From bd6b3cdaf3a14dd31f2031301a10ec187eb92397 Mon Sep 17 00:00:00 2001 From: microshine Date: Tue, 30 Aug 2016 20:46:29 +0300 Subject: [PATCH 001/382] Add ERROR_STATE flag --- graphene-pk11/graphene-pk11.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/graphene-pk11/graphene-pk11.d.ts b/graphene-pk11/graphene-pk11.d.ts index 0405b4c6df..2a4d8aad0c 100644 --- a/graphene-pk11/graphene-pk11.d.ts +++ b/graphene-pk11/graphene-pk11.d.ts @@ -2131,6 +2131,7 @@ declare module "graphene-pk11" { SO_PIN_FINAL_TRY, SO_PIN_LOCKED, SO_PIN_TO_BE_CHANGED, + ERROR_STATE, } class Token extends HandleObject { From 7c50d2c7a7d11b0e6e76508b59b359b4ae4e558c Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Thu, 15 Sep 2016 10:20:57 -0700 Subject: [PATCH 002/382] added prop options and func timeFormatter added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } From dda378990181cd75523afaddaf8d453c18e74276 Mon Sep 17 00:00:00 2001 From: microshine Date: Sat, 24 Sep 2016 16:18:53 +0300 Subject: [PATCH 003/382] Fix type errors --- pkcs11js/pkcs11js.d.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/pkcs11js/pkcs11js.d.ts b/pkcs11js/pkcs11js.d.ts index dcbdb401cb..676dce6555 100644 --- a/pkcs11js/pkcs11js.d.ts +++ b/pkcs11js/pkcs11js.d.ts @@ -210,7 +210,7 @@ declare module "pkcs11js" { * @param {Handle} slot ID of token's slot * @returns {Handle[]} Gets mech. array */ - C_GetMechanismList(slot: Handle): number[]; + C_GetMechanismList(slot: Handle): Handle[]; /** * Obtains information about a particular mechanism possibly supported by a token * @@ -218,7 +218,7 @@ declare module "pkcs11js" { * @param {Handle} mech Type of mechanism * @returns {MechanismInfo} Receives mechanism info */ - C_GetMechanismInfo(slot: Handle, mech: number): MechanismInfo; + C_GetMechanismInfo(slot: Handle, mech: Handle): MechanismInfo; /* Session management */ @@ -1173,11 +1173,11 @@ declare module "pkcs11js" { const CKM_RSA_PKCS_TPM_1_1: number; const CKM_RSA_PKCS_OAEP_TPM_1_1: number; const CKM_VENDOR_DEFINED: number; - + // Session flags const CKF_RW_SESSION: number; const CKF_SERIAL_SESSION: number; - + // Follows const CKF_HW: number; const CKF_ENCRYPT: number; @@ -1192,6 +1192,7 @@ declare module "pkcs11js" { const CKF_WRAP: number; const CKF_UNWRAP: number; const CKF_DERIVE: number; + const CKF_CLOCK_ON_TOKEN: number; // Certificates const CKC_X_509: number; @@ -1223,4 +1224,4 @@ declare module "pkcs11js" { const CK_PARAMS_RSA_OAEP: number; const CK_PARAMS_RSA_PSS: number; const CK_PARAMS_EC_DH: number; -} \ No newline at end of file +} From e277344c14a3660e20e4645525c50b59c9756e1d Mon Sep 17 00:00:00 2001 From: Cedric van Putten Date: Sat, 24 Sep 2016 21:18:16 +0200 Subject: [PATCH 004/382] Added typings for css-modules-require-hook --- .../css-modules-require-hook-tests.ts | 174 ++++++++++++++++++ .../css-modules-require-hook.d.ts | 47 +++++ 2 files changed, 221 insertions(+) create mode 100644 css-modules-require-hook/css-modules-require-hook-tests.ts create mode 100644 css-modules-require-hook/css-modules-require-hook.d.ts diff --git a/css-modules-require-hook/css-modules-require-hook-tests.ts b/css-modules-require-hook/css-modules-require-hook-tests.ts new file mode 100644 index 0000000000..8fde182571 --- /dev/null +++ b/css-modules-require-hook/css-modules-require-hook-tests.ts @@ -0,0 +1,174 @@ +/// +/// + +import * as hook from 'css-modules-require-hook'; +import * as path from 'path'; + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#usage +// + +hook({ generateScopedName: '[name]__[local]___[hash:base64:5]' }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#adding-custom-postcss-plugins +// + +hook({ + prepend: [ + () => { + // my prepender + }, + ], +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#specify-custom-pattern-to-build-generic-names +// + +hook({ generateScopedName: '[name]__[local]___[hash:base64:5]' }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#using-stylus-as-a-preprocessor +// + +hook({ + extensions: ['.styl'], + preprocessCss: (css: string, filepath: string) => { + // my preprocesser + }, +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#tuning-options +// + +hook({ /* my option */ }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#devmode-boolean +// + +hook({ devMode: false }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#extensions-array +// + +hook({ extensions: ['.scss', '.sass'] }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#ignore-functionregexstring +// + +hook({ ignore: (file: string) => false }); +hook({ ignore: 'unused' }); +hook({ ignore: /\.test\.(css|scss|sass)/$ }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#preprocesscss-function +// + +hook({ preprocessCss: (css: string, filepath: string) => css }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#processcss-function +// + +hook({ processCss: (css: string, filepath: string) => css }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#processoropts-object +// + +hook({ + extensions: '.scss', + processorOpts: { + parser: () => { + // my parser + }, + }, +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#camelcase-boolean +// + +hook({ camelCase: true }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#append-array +// + +hook({ + append: [ + () => { + // another plugin + }, + ], +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#prepend-array +// + +hook({ + prepend: [ + () => { + // again, another plugin + }, + ], +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#use-array +// + +hook({ + use: [ + () => { + // they like plugins very much + }, + ], +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#createimportedname-function +// + +hook({ + createImportedName: (css: string, filepath: string) => { + // my import name creator + }, +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#generatescopedname-stringfunction +// + +hook({ generateScopedName: '[name]__[local]___[hash:base64:5]' }); +hook({ + generateScopedName: () => { + // should generate something + }, +}); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#hashprefix-string +// + +hook({ hashPrefix: 'awesome_' }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#mode-string +// + +hook({ mode: 'global' }); +hook({ mode: 'local' }); +hook({ mode: 'pure' }); + +// +// https://github.com/css-modules/css-modules-require-hook/blob/master/README.md#rootdir-string +// + +hook({ rootDir: path.resolve('./my-folder') }); diff --git a/css-modules-require-hook/css-modules-require-hook.d.ts b/css-modules-require-hook/css-modules-require-hook.d.ts new file mode 100644 index 0000000000..3777cf1fc2 --- /dev/null +++ b/css-modules-require-hook/css-modules-require-hook.d.ts @@ -0,0 +1,47 @@ +// Type definitions for css-modules-require-hook +// Project: https://github.com/css-modules/css-modules-require-hook +// Definitions by: Cedric van Putten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'css-modules-require-hook' { + interface Options { + /** Helps you to invalidate cache of all require calls. */ + devMode?: boolean; + /** Attach the require hook to additional file extensions. */ + extensions?: string | string[]; + /** Provides possibility to exclude particular files from processing. */ + ignore?: string | RegExp | Function; + /** In rare cases you may want to precompile styles, before they will be passed to the PostCSS pipeline. */ + preprocessCss?: Function; + /** In rare cases you may want to get compiled styles in runtime, so providing this option helps. */ + processCss?: Function; + /** Provides possibility to pass custom options to the LazyResult instance. */ + processorOpts?: Object; + /** Camelizes exported class names. */ + camelCase?: boolean; + /** Appends custom plugins to the end of the PostCSS pipeline. */ + append?: Array; + /** Prepends custom plugins to the beginning of the PostCSS pipeline. */ + prepend?: Array; + /** Provides the full list of PostCSS plugins to the pipeline. */ + use?: Array; + /** Short alias for the postcss-modules-extract-imports plugin's createImportedName option. */ + createImportedName?: Function; + /** Short alias for the postcss-modules-scope plugin's option. */ + generateScopedName?: string | Function; + /** Short alias for the generic-names helper option. */ + hashPrefix?: string; + /** Short alias for the postcss-modules-local-by-default plugin's option. */ + mode?: string; + /** Provides absolute path to the project directory. */ + rootDir?: string; + } + + interface RequireHook { + (options?: Options): void; + } + + var requireHook: RequireHook; + + export = requireHook; +} From 53a729cd0973d20549cf7bc320bc95932c7c0f7d Mon Sep 17 00:00:00 2001 From: microshine Date: Sun, 25 Sep 2016 01:33:59 +0300 Subject: [PATCH 005/382] Remove spaces --- pkcs11js/pkcs11js.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkcs11js/pkcs11js.d.ts b/pkcs11js/pkcs11js.d.ts index 676dce6555..d1b5314878 100644 --- a/pkcs11js/pkcs11js.d.ts +++ b/pkcs11js/pkcs11js.d.ts @@ -1173,11 +1173,11 @@ declare module "pkcs11js" { const CKM_RSA_PKCS_TPM_1_1: number; const CKM_RSA_PKCS_OAEP_TPM_1_1: number; const CKM_VENDOR_DEFINED: number; - + // Session flags const CKF_RW_SESSION: number; const CKF_SERIAL_SESSION: number; - + // Follows const CKF_HW: number; const CKF_ENCRYPT: number; From 9215c3e845e3b03882b5c7fd45644eb5f3b17cf8 Mon Sep 17 00:00:00 2001 From: Cedric van Putten Date: Sun, 25 Sep 2016 02:22:40 +0200 Subject: [PATCH 006/382] Added semver, added explicit ignore callback, unified array definition and removed one time interface --- .../css-modules-require-hook.d.ts | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/css-modules-require-hook/css-modules-require-hook.d.ts b/css-modules-require-hook/css-modules-require-hook.d.ts index 3777cf1fc2..b990ffb90f 100644 --- a/css-modules-require-hook/css-modules-require-hook.d.ts +++ b/css-modules-require-hook/css-modules-require-hook.d.ts @@ -1,4 +1,4 @@ -// Type definitions for css-modules-require-hook +// Type definitions for css-modules-require-hook 4.0.3 // Project: https://github.com/css-modules/css-modules-require-hook // Definitions by: Cedric van Putten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ declare module 'css-modules-require-hook' { /** Attach the require hook to additional file extensions. */ extensions?: string | string[]; /** Provides possibility to exclude particular files from processing. */ - ignore?: string | RegExp | Function; + ignore?: string | RegExp | ((filepath: string) => boolean); /** In rare cases you may want to precompile styles, before they will be passed to the PostCSS pipeline. */ preprocessCss?: Function; /** In rare cases you may want to get compiled styles in runtime, so providing this option helps. */ @@ -20,11 +20,11 @@ declare module 'css-modules-require-hook' { /** Camelizes exported class names. */ camelCase?: boolean; /** Appends custom plugins to the end of the PostCSS pipeline. */ - append?: Array; + append?: any[]; /** Prepends custom plugins to the beginning of the PostCSS pipeline. */ - prepend?: Array; + prepend?: any[]; /** Provides the full list of PostCSS plugins to the pipeline. */ - use?: Array; + use?: any[]; /** Short alias for the postcss-modules-extract-imports plugin's createImportedName option. */ createImportedName?: Function; /** Short alias for the postcss-modules-scope plugin's option. */ @@ -37,11 +37,7 @@ declare module 'css-modules-require-hook' { rootDir?: string; } - interface RequireHook { - (options?: Options): void; - } - - var requireHook: RequireHook; + var requireHook: (options?: Options) => void; export = requireHook; } From 6b5e394f6f408b50a1fff4d8734fcf9c0585d76c Mon Sep 17 00:00:00 2001 From: Andrea Zucchini Date: Sun, 25 Sep 2016 02:50:36 +0200 Subject: [PATCH 007/382] Overwriting method signature --- method-override/method-override.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts index 572a9226f8..73e2956cd2 100644 --- a/method-override/method-override.d.ts +++ b/method-override/method-override.d.ts @@ -20,8 +20,10 @@ declare module "method-override" { } } - function e(getter?: string, options?: e.MethodOverrideOptions): express.RequestHandler; - function e(getter?: (req: express.Request, res: express.Response) => string, options?: e.MethodOverrideOptions): express.RequestHandler; + + type stringType = string; + type functionType = (req: express.Request, res: express.Response) => string; + function e(getter?: stringType | functionType, options?: e.MethodOverrideOptions): express.RequestHandler; export = e; } From 34ff2d1550fa30142966b1f5fa3a5cb8ca60c9e4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sun, 25 Sep 2016 12:39:15 +0800 Subject: [PATCH 008/382] Correct parameter type --- validator/validator.d.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/validator/validator.d.ts b/validator/validator.d.ts index c2289cf169..48fce17ff8 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -17,7 +17,7 @@ declare namespace ValidatorJS { contains(str: string, elem: any): boolean; // check if the string matches the comparison. - equals(str: string, comparison: any): boolean; + equals(str: string, comparison: string): boolean; // check if the string is a date that's after the specified date (defaults to now). isAfter(str: string, date?: string): boolean; @@ -152,7 +152,7 @@ declare namespace ValidatorJS { isURL(str: string, options?: IsURLOptions): boolean; // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. - isUUID(str: string, version?: string|number): boolean; + isUUID(str: string, version?: string | number): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; @@ -161,10 +161,10 @@ declare namespace ValidatorJS { isVariableWidth(str: string): boolean; // checks characters if they appear in the whitelist. - isWhitelisted(str: string, chars: string|string[]): boolean; + isWhitelisted(str: string, chars: string | string[]): boolean; // check if string matches the pattern. - matches(str: string, pattern: RegExp|string, modifiers?: string): boolean; + matches(str: string, pattern: RegExp | string, modifiers?: string): boolean; // ************** // * Sanitizers * @@ -181,13 +181,13 @@ declare namespace ValidatorJS { unescape(input: string): string; // trim characters from the left-side of the input. - ltrim(input: any, chars?: string): string; + ltrim(input: string, chars?: string): string; // canonicalize an email address. normalizeEmail(email: string, options?: NormalizeEmailOptions): string; // trim characters from the right-side of the input. - rtrim(input: any, chars?: string): string; + rtrim(input: string, chars?: string): string; // remove characters with a numerical value < 32 and 127, mostly control characters. If keep_new_lines is true, // newline characters are preserved (\n and \r, hex 0xA and 0xD). Unicode-safe in JavaScript. @@ -195,19 +195,19 @@ declare namespace ValidatorJS { // convert the input to a boolean. Everything except for '0', 'false' and '' returns true. In strict mode only '1' // and 'true' return true. - toBoolean(input: any, strict?: boolean): boolean; + toBoolean(input: string, strict?: boolean): boolean; // convert the input to a date, or null if the input is not a date. - toDate(input: any): Date; // Date or null + toDate(input: string): Date; // Date or null // convert the input to a float, or NaN if the input is not a float. - toFloat(input: any): number; // number or NaN + toFloat(input: string): number; // number or NaN // convert the input to an integer, or NaN if the input is not an integer. - toInt(input: any, radix?: number): number; // number or NaN + toInt(input: string, radix?: number): number; // number or NaN // trim characters (whitespace by default) from both sides of the input. - trim(input: any, chars?: string): string; + trim(input: string, chars?: string): string; // remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will // need to escape some chars, e.g. whitelist(input, '\\[\\]'). @@ -284,8 +284,8 @@ declare namespace ValidatorJS { require_host: boolean; require_valid_protocol?: boolean; allow_underscores?: boolean; - host_whitelist?: (string|RegExp)[]; - host_blacklist?: (string|RegExp)[]; + host_whitelist?: (string | RegExp)[]; + host_blacklist?: (string | RegExp)[]; allow_trailing_dot?: boolean; allow_protocol_relative_urls?: boolean; } @@ -304,7 +304,7 @@ declare module "validator" { } // deprecated interfaces for backward compatibility, please use ValidatorJS.* instead the ones -interface IValidatorStatic extends ValidatorJS.ValidatorStatic {} -interface IURLoptions extends ValidatorJS.IsURLOptions {} -interface IFQDNoptions extends ValidatorJS.IsFQDNOptions {} -interface IEmailoptions extends ValidatorJS.NormalizeEmailOptions {} +interface IValidatorStatic extends ValidatorJS.ValidatorStatic { } +interface IURLoptions extends ValidatorJS.IsURLOptions { } +interface IFQDNoptions extends ValidatorJS.IsFQDNOptions { } +interface IEmailoptions extends ValidatorJS.NormalizeEmailOptions { } From ac3aa50a8dff706e9f7495e19dfab96c32925a89 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sun, 25 Sep 2016 12:53:48 +0800 Subject: [PATCH 009/382] Add MobilePhoneLocale --- validator/validator.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/validator/validator.d.ts b/validator/validator.d.ts index c2289cf169..dc69ff1c54 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -6,7 +6,8 @@ declare namespace ValidatorJS { type AlphaLocale = "ar" | "ar-AE" | "ar-BH" | "ar-DZ" | "ar-EG" | "ar-IQ" | "ar-JO" | "ar-KW" | "ar-LB" | "ar-LY" | "ar-MA" | "ar-QA" | "ar-QM" | "ar-SA" | "ar-SD" | "ar-SY" | "ar-TN" | "ar-YE" | "cs-CZ" | "de-DE" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-ZA" | "en-ZM" | "es-ES" | "fr-FR" | "hu-HU" | "nl-NL" | "pl-PL" | "pt-BR" | "pt-PT" | "ru-RU" | "sr-RS" | "sr-RS@latin" | "tr-TR"; type AlphanumericLocale = "ar" | "ar-AE" | "ar-BH" | "ar-DZ" | "ar-EG" | "ar-IQ" | "ar-JO" | "ar-KW" | "ar-LB" | "ar-LY" | "ar-MA" | "ar-QA" | "ar-QM" | "ar-SA" | "ar-SD" | "ar-SY" | "ar-TN" | "ar-YE" | "cs-CZ" | "de-DE" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-ZA" | "en-ZM" | "es-ES" | "fr-FR" | "fr-BE" | "hu-HU" | "nl-BE" | "nl-NL" | "pl-PL" | "pt-BR" | "pt-PT" | "ru-RU" | "sr-RS" | "sr-RS@latin" | "tr-TR"; - + type MobilePhoneLocale = "ar-DZ" | "ar-SA" | "ar-SY" | "cs-CZ" | "de-DE" | "da-DK" | "el-GR" | "en-AU" | "en-GB" | "en-HK" | "en-IN" | "en-NZ" | "en-US" | "en-CA" | "en-ZA" | "en-ZM" | "es-ES" | "fi-FI" | "fr-FR" | "hu-HU" | "it-IT" | "ja-JP" | "ms-MY" | "nb-NO" | "nn-NO" | "pl-PL" | "pt-PT" | "ru-RU" | "sr-RS" | "tr-TR" | "vi-VN" | "zh-CN" | "zh-TW" + interface ValidatorStatic { // ************** @@ -130,7 +131,7 @@ declare namespace ValidatorJS { // 'en-IN', 'en-NZ', 'en-US', 'en-CA', 'en-ZA', 'en-ZM', 'es-ES', 'fi-FI', 'fr-FR', 'hu-HU', // 'it-IT', 'ja-JP', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'ru-RU', 'sr-RS', 'tr-TR', // 'vi-VN', 'zh-CN', 'zh-TW']). - isMobilePhone(str: string, locale: string): boolean; + isMobilePhone(str: string, locale: MobilePhoneLocale): boolean; // check if the string is a valid hex-encoded representation of a MongoDB ObjectId // (http://docs.mongodb.org/manual/reference/object-id/). From bf8640709e1ba72ed387b5f80970f60734bfe054 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sun, 25 Sep 2016 12:56:19 +0800 Subject: [PATCH 010/382] Add isMobilePhone tests --- validator/validator-tests.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index 748a6bf340..cc857121bb 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -178,7 +178,39 @@ let any: any; result = validator.isMD5('sample'); + result = validator.isMobilePhone('sample', 'ar-DZ'); + result = validator.isMobilePhone('sample', 'ar-SA'); + result = validator.isMobilePhone('sample', 'ar-SY'); + result = validator.isMobilePhone('sample', 'cs-CZ'); + result = validator.isMobilePhone('sample', 'de-DE'); + result = validator.isMobilePhone('sample', 'da-DK'); + result = validator.isMobilePhone('sample', 'el-GR'); + result = validator.isMobilePhone('sample', 'en-AU'); + result = validator.isMobilePhone('sample', 'en-GB'); + result = validator.isMobilePhone('sample', 'en-HK'); + result = validator.isMobilePhone('sample', 'en-IN'); + result = validator.isMobilePhone('sample', 'en-NZ'); result = validator.isMobilePhone('sample', 'en-US'); + result = validator.isMobilePhone('sample', 'en-CA'); + result = validator.isMobilePhone('sample', 'en-ZA'); + result = validator.isMobilePhone('sample', 'en-ZM'); + result = validator.isMobilePhone('sample', 'es-ES'); + result = validator.isMobilePhone('sample', 'fi-FI'); + result = validator.isMobilePhone('sample', 'fr-FR'); + result = validator.isMobilePhone('sample', 'hu-HU'); + result = validator.isMobilePhone('sample', 'it-IT'); + result = validator.isMobilePhone('sample', 'ja-JP'); + result = validator.isMobilePhone('sample', 'ms-MY'); + result = validator.isMobilePhone('sample', 'nb-NO'); + result = validator.isMobilePhone('sample', 'nn-NO'); + result = validator.isMobilePhone('sample', 'pl-PL'); + result = validator.isMobilePhone('sample', 'pt-PT'); + result = validator.isMobilePhone('sample', 'ru-RU'); + result = validator.isMobilePhone('sample', 'sr-RS'); + result = validator.isMobilePhone('sample', 'tr-TR'); + result = validator.isMobilePhone('sample', 'vi-VN'); + result = validator.isMobilePhone('sample', 'zh-CN'); + result = validator.isMobilePhone('sample', 'zh-TW'); result = validator.isMongoId('sample'); From 9e563f461278090424447a065809149f017cd182 Mon Sep 17 00:00:00 2001 From: mudkip Date: Sun, 25 Sep 2016 14:34:01 +0800 Subject: [PATCH 011/382] Type definitions for bit-array --- bit-array/bit-array-tests.ts | 10 ++++ bit-array/bit-array.d.ts | 106 +++++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 bit-array/bit-array-tests.ts create mode 100644 bit-array/bit-array.d.ts diff --git a/bit-array/bit-array-tests.ts b/bit-array/bit-array-tests.ts new file mode 100644 index 0000000000..9337c2afa9 --- /dev/null +++ b/bit-array/bit-array-tests.ts @@ -0,0 +1,10 @@ +/// + +import * as BitArray from "bit-array"; + +const a = new BitArray(32); +a.set(0, true); +a.set(31, true); +a.toString(); // "10000000000000000000000000000001" +a.get(1); // false +a.get(31); // true \ No newline at end of file diff --git a/bit-array/bit-array.d.ts b/bit-array/bit-array.d.ts new file mode 100644 index 0000000000..e9ee31339e --- /dev/null +++ b/bit-array/bit-array.d.ts @@ -0,0 +1,106 @@ +// Type definitions for bit-array v0.2.2 +// Project: https://github.com/bramstein/bit-array +// Definitions by: Mudkip +// Definitions: https://github.com/mudkipme/DefinitelyTyped + +declare module "bit-array" { + + class BitArray { + /** + * Creates a new empty BitArray with the given length or initialises the BitArray with the given hex representation. + */ + constructor(size: number, hex?: string); + + /** + * Returns the total number of bits in this BitArray. + */ + size(): number; + + /** + * Sets the bit at index to a value (boolean.) + */ + set(index: number, value: boolean): BitArray; + + /** + * Toggles the bit at index. If the bit is on, it is turned off. Likewise, if the bit is off it is turned on. + */ + toggle(index: number): BitArray; + + /** + * Returns the value of the bit at index (boolean.) + */ + get(index: number): boolean; + + /** + * Resets the BitArray so that it is empty and can be re-used. + */ + reset(): BitArray; + + /** + * Returns a copy of this BitArray. + */ + copy(): BitArray; + + /** + * Returns true if this BitArray equals another. Two BitArrays are considered + * equal if both have the same length and bit pattern. + */ + equals(x: BitArray): boolean; + + /** + * Returns the JSON representation of this BitArray. + */ + toJSON(): string; + + /** + * Returns a string representation of the BitArray with bits + * in mathemetical order. + */ + toBinaryString(): string; + + /** + * Returns a hexadecimal string representation of the BitArray + * with bits in logical order. + */ + toHexString(): string; + + /** + * Returns a string representation of the BitArray with bits + * in logical order. + */ + toString(): string; + + /** + * Convert the BitArray to an Array of boolean values (slow). + */ + toArray(): boolean[]; + + /** + * Returns the total number of bits set to one in this BitArray. + */ + count(): number; + + /** + * Inverts this BitArray. + */ + not(): BitArray; + + /** + * Bitwise OR on the values of this BitArray using BitArray x. + */ + or(x: BitArray): BitArray; + + /** + * Bitwise AND on the values of this BitArray using BitArray x. + */ + and(x: BitArray): BitArray; + + /** + * Bitwise XOR on the values of this BitArray using BitArray x. + */ + xor(x: BitArray): BitArray; + } + + namespace BitArray {} + export = BitArray; +} \ No newline at end of file From cc8a36678692b28eeea4e5f8dcc17fc3de21e4b6 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Sun, 25 Sep 2016 15:03:32 +0800 Subject: [PATCH 012/382] Add emit for cluster --- node/node.d.ts | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index f3657db4a5..5b807cb5b2 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -797,6 +797,14 @@ declare module "cluster" { addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. addListener(event: "online", listener: () => void): this; + emit(event: string, listener: Function): boolean + emit(event: "disconnect", listener: () => void): boolean + emit(event: "error", listener: (code: number, signal: string) => void): boolean + emit(event: "exit", listener: (code: number, signal: string) => void): boolean + emit(event: "listening", listener: (address: Address) => void): boolean + emit(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): boolean + emit(event: "online", listener: () => void): boolean + on(event: string, listener: Function): this; on(event: "disconnect", listener: () => void): this; on(event: "error", listener: (code: number, signal: string) => void): this; @@ -863,6 +871,15 @@ declare module "cluster" { addListener(event: "online", listener: (worker: Worker) => void): this; addListener(event: "setup", listener: (settings: any) => void): this; + emit(event: string, listener: Function): boolean; + emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + emit(event: "fork", listener: (worker: Worker) => void): boolean; + emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + emit(event: "online", listener: (worker: Worker) => void): boolean; + emit(event: "setup", listener: (settings: any) => void): boolean; + on(event: string, listener: Function): this; on(event: "disconnect", listener: (worker: Worker) => void): this; on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; @@ -932,6 +949,15 @@ declare module "cluster" { export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + export function emit(event: string, listener: Function): boolean; + export function emit(event: "disconnect", listener: (worker: Worker) => void): boolean; + export function emit(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): boolean; + export function emit(event: "fork", listener: (worker: Worker) => void): boolean; + export function emit(event: "listening", listener: (worker: Worker, address: Address) => void): boolean; + export function emit(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): boolean; + export function emit(event: "online", listener: (worker: Worker) => void): boolean; + export function emit(event: "setup", listener: (settings: any) => void): boolean; + export function on(event: string, listener: Function): Cluster; export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; @@ -955,7 +981,6 @@ declare module "cluster" { export function setMaxListeners(n: number): Cluster; export function getMaxListeners(): number; export function listeners(event: string): Function[]; - export function emit(event: string, ...args: any[]): boolean; export function listenerCount(type: string): number; export function prependListener(event: string, listener: Function): Cluster; From 1dc78748609a0d41e1dd2cbef975f2b2dbfba7d9 Mon Sep 17 00:00:00 2001 From: Andrea Zucchini Date: Sun, 25 Sep 2016 11:46:06 +0200 Subject: [PATCH 013/382] To use the definition inline --- method-override/method-override.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/method-override/method-override.d.ts b/method-override/method-override.d.ts index 73e2956cd2..e201c5434a 100644 --- a/method-override/method-override.d.ts +++ b/method-override/method-override.d.ts @@ -21,9 +21,8 @@ declare module "method-override" { } - type stringType = string; - type functionType = (req: express.Request, res: express.Response) => string; - function e(getter?: stringType | functionType, options?: e.MethodOverrideOptions): express.RequestHandler; + function e(getter?: string | ((req: express.Request, res: express.Response) => string), options?: e.MethodOverrideOptions): express.RequestHandler; + export = e; } From b6dd4429d8e87574882fa3c9cf205943d4627336 Mon Sep 17 00:00:00 2001 From: Vikash Kumar Date: Sun, 25 Sep 2016 18:07:43 +0530 Subject: [PATCH 014/382] [logat.d.ts] Type definition for node module 'logat' (#11485) * Create logat.d.ts * Create logat-tests.ts * Update logat-tests.ts * Update logat-tests.ts * Update logat.d.ts * updated logat test * updated type definiton --- logat/logat-tests.ts | 19 +++++++++++++++++++ logat/logat.d.ts | 26 ++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 logat/logat-tests.ts create mode 100644 logat/logat.d.ts diff --git a/logat/logat-tests.ts b/logat/logat-tests.ts new file mode 100644 index 0000000000..58a7333342 --- /dev/null +++ b/logat/logat-tests.ts @@ -0,0 +1,19 @@ +/// + +import logat = require('logat'); + +logat.on('LogConfigError', function(err: any){ +}) + +logat.error('This is error'); +logat.error( new Error('This is error instance') ); +logat.error( String('object1'), String('object2') ); +logat.warn('This is warn'); +logat.info('This is info'); +logat.debug('This is debug'); + +logat.setOptions( { + logLevel: 4, + logMethod: 1 +}); +logat.getOptions(); diff --git a/logat/logat.d.ts b/logat/logat.d.ts new file mode 100644 index 0000000000..f36adb3dfb --- /dev/null +++ b/logat/logat.d.ts @@ -0,0 +1,26 @@ +// Type definitions for logat 1.x.x +// Project: https://github.com/krvikash35/logat +// Definitions by: Vikash +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'logat'{ + + interface LogOptionsI { + logLevel?: number, + logMethod?: number, + logFileName?: string + } + + class Logger extends NodeJS.EventEmitter { + error(...args: any[]): void; + warn(...args: any[]): void; + info(...args: any[]): void; + debug(...args: any[]): void; + getOptions(): LogOptionsI; + setOptions(options: LogOptionsI): void; + } + + export = new Logger(); +} From 1d3de94f5077de90ec0d0a765c3887bab07399bd Mon Sep 17 00:00:00 2001 From: Kombu Date: Tue, 20 Sep 2016 10:23:29 +0800 Subject: [PATCH 015/382] [dateformat.d.ts] Add definitions for dateformat --- dateformat/dateformat-tests.ts | 58 +++++++++++++++++++++++++ dateformat/dateformat.d.ts | 77 ++++++++++++++++++++++++++++++++++ 2 files changed, 135 insertions(+) create mode 100644 dateformat/dateformat-tests.ts create mode 100644 dateformat/dateformat.d.ts diff --git a/dateformat/dateformat-tests.ts b/dateformat/dateformat-tests.ts new file mode 100644 index 0000000000..95d642b922 --- /dev/null +++ b/dateformat/dateformat-tests.ts @@ -0,0 +1,58 @@ +/// + +/** + * https://github.com/felixge/node-dateformat#usage + */ + +import * as dateFormat from 'dateformat' +const now = new Date() + +// Basic usage +dateFormat(now, 'dddd, mmmm dS, yyyy, h:MM:ss TT') +// Saturday, June 9th, 2007, 5:46:21 PM + +// You can use one of several named masks +dateFormat(now, 'isoDateTime') +// 2007-06-09T17:46:21 + +// ...Or add your own +dateFormat.masks['hammerTime'] = `HH:MM! "Can't touch this!"` +dateFormat(now, 'hammerTime') +// 17:46! Can't touch this! + +// When using the standalone dateFormat function, +// you can also provide the date as a string +dateFormat('Jun 9 2007', 'fullDate') +// Saturday, June 9, 2007 + +// Note that if you don't include the mask argument, +// dateFormat.masks.default is used +dateFormat(now) +// Sat Jun 09 2007 17:46:21 + +// And if you don't include the date argument, +// the current date and time is used +dateFormat() +// Sat Jun 09 2007 17:46:22 + +// You can also skip the date argument (as long as your mask doesn't +// contain any numbers), in which case the current date/time is used +dateFormat('longTime') +// 5:46:22 PM EST + +// And finally, you can convert local time to UTC time. Simply pass in +// true as an additional argument (no argument skipping allowed in this case): +dateFormat(now, 'longTime', true) +// 10:46:21 PM UTC + +// ...Or add the prefix 'UTC:' or 'GMT:' to your mask. +dateFormat(now, 'UTC:h:MM:ss TT Z') +// 10:46:21 PM UTC + +// You can also get the ISO 8601 week of the year: +dateFormat(now, 'W') +// 42 + +// and also get the ISO 8601 numeric representation of the day of the week: +dateFormat(now, 'N') +// 6 diff --git a/dateformat/dateformat.d.ts b/dateformat/dateformat.d.ts new file mode 100644 index 0000000000..9a97ba620f --- /dev/null +++ b/dateformat/dateformat.d.ts @@ -0,0 +1,77 @@ +// Type definitions for dateformat v1.0.12 +// Project: https://github.com/felixge/node-dateformat +// Definitions by: Kombu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * dateFormat.masks + * + * Predefined Formats + * + * https://github.com/felixge/node-dateformat/blob/master/lib/dateformat.js#L107 + */ +interface DateFormatMasks { + default: string; + shortDate: string; + mediumDate: string; + longDate: string; + fullDate: string; + shortTime: string; + mediumTime: string; + longTime: string; + isoDate: string; + isoTime: string; + isoDateTime: string; + isoUtcDateTime: string; + expiresHeaderFormat: string; + [key: string]: string; +} + +/** + * dateFormat.i18n + * + * Internationalization strings + * + * Example: + * + * ``` + * dateFormat.i18n = { + * dayNames: [ + * 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', + * 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' + * ], + * monthNames: [ + * 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', + * 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + * ] + * } + * ``` + * + * https://github.com/felixge/node-dateformat/blob/master/lib/dateformat.js#L124 + */ +interface DateFormatI18n { + dayNames: string[]; + monthNames: string[]; +} + +/** + * dateFormat() + * + * Accepts a date, a mask, or a date and a mask. + * Returns a formatted version of the given date. + * The date defaults to the current date/time. + * The mask defaults to dateFormat.masks.default. + * + * https://github.com/felixge/node-dateformat/blob/master/lib/dateformat.js#L18 + */ +interface DateFormatStatic { + (date?: Date | string | number, mask?: string, utc?: boolean, gmt?: boolean): string; + (mask?: string, utc?: boolean, gmt?: boolean): string; + masks: DateFormatMasks; + i18n: DateFormatI18n; +} + +declare module 'dateformat' { + const dateFormat: DateFormatStatic; + export = dateFormat; +} From df45fdf0af7a829a74e86e04f94413c6cadebac1 Mon Sep 17 00:00:00 2001 From: mudkip Date: Sun, 25 Sep 2016 22:43:40 +0800 Subject: [PATCH 016/382] Remove the ES6 module hack --- bit-array/bit-array-tests.ts | 2 +- bit-array/bit-array-tests.ts.tscparams | 1 + bit-array/bit-array.d.ts | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 bit-array/bit-array-tests.ts.tscparams diff --git a/bit-array/bit-array-tests.ts b/bit-array/bit-array-tests.ts index 9337c2afa9..20310b2208 100644 --- a/bit-array/bit-array-tests.ts +++ b/bit-array/bit-array-tests.ts @@ -1,6 +1,6 @@ /// -import * as BitArray from "bit-array"; +import BitArray = require("bit-array"); const a = new BitArray(32); a.set(0, true); diff --git a/bit-array/bit-array-tests.ts.tscparams b/bit-array/bit-array-tests.ts.tscparams new file mode 100644 index 0000000000..85542607d1 --- /dev/null +++ b/bit-array/bit-array-tests.ts.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs diff --git a/bit-array/bit-array.d.ts b/bit-array/bit-array.d.ts index e9ee31339e..bab3d98a46 100644 --- a/bit-array/bit-array.d.ts +++ b/bit-array/bit-array.d.ts @@ -101,6 +101,5 @@ declare module "bit-array" { xor(x: BitArray): BitArray; } - namespace BitArray {} export = BitArray; } \ No newline at end of file From 3ab295950ca3106cb1bf90d13fd1c7a1e9c5e6fa Mon Sep 17 00:00:00 2001 From: David Wood Date: Sun, 25 Sep 2016 16:21:10 +0100 Subject: [PATCH 017/382] Yayson definitions (#11484) * Add yayson Store typings * Add yayson Store tests * Improve yayson coverage * Specify version in yayson definition * Remove yayson generics and tidy --- yayson/yayson-tests.ts | 116 +++++++++++++++++++++++++++++++++++++++++ yayson/yayson.d.ts | 64 +++++++++++++++++++++++ 2 files changed, 180 insertions(+) create mode 100644 yayson/yayson-tests.ts create mode 100644 yayson/yayson.d.ts diff --git a/yayson/yayson-tests.ts b/yayson/yayson-tests.ts new file mode 100644 index 0000000000..7ae86c541f --- /dev/null +++ b/yayson/yayson-tests.ts @@ -0,0 +1,116 @@ +/// + +import * as Yayson from "yayson"; + +const yayson = Yayson({ adapter: 'default' }) || Yayson({ adapter: 'sequelize' }) || Yayson(); +const Adapter = yayson.Adapter; +const Store = yayson.Store; +const Presenter = yayson.Presenter; + +interface Thing { + hello: 'world' | 'you'; +} + +function test_store() { + const store = new Store(); + + store.sync('some string').toString(); + store.sync(1234).toString(); + store.sync({ any: 'thing' }).toString(); + + store.find('mytype', '1234').toString(); + <[]> store.findAll('mytype'); + + store.remove('mytype', '1234'); + store.remove('mytype'); + + store.reset(); + + store.records; + store.records[0].attributes.toString(); + store.records[0].id.toString(); + store.records[0].relationships.toString(); + store.records[0].type; + + store.relations['something']; +} + +function test_presenter_static() { + Presenter.render('something').toString(); + Presenter.render({}).toString(); + Presenter.render({}, { meta: {} }).toString(); + + <[]> Presenter.render([]); + <[]> Presenter.render([], { meta: {} }); + + const promiseNum: PromiseLike = null; + + Presenter.render(promiseNum).then(data => data.toExponential()); + Presenter.render(promiseNum, { meta: { so: 'meta' } }).then(data => data.toExponential()); + + Presenter.toJSON({ any: 'thing' }).toString(); + Presenter.toJSON({ other: 'thing' }, { meta: { so: 'meta' } }).toString(); +} + +function test_presenter_instance() { + const presenter = new Presenter(); + + presenter.render({}).toString(); + presenter.render({}, { meta: {} }).toString(); + + <[]> presenter.render([]); + <[]> presenter.render([], { meta: {} }); + + const promiseNum: PromiseLike = null; + + presenter.render(promiseNum).then(data => data.toExponential()); + presenter.render(promiseNum, { meta: { so: 'meta' } }).then(data => data.toExponential()); + + presenter.toJSON({ any: 'thing' }).toString(); + presenter.toJSON({ other: 'thing' }, { meta: { so: 'meta' } }).toString(); +} + +function test_presenter_inheritance() { + class MotorPresenter extends Presenter { + type = 'motors'; + relationships() { + return { car: CarPresenter } + }; + selfLinks(instance: any) { + return '/cars/' + this.id(instance); + }; + } + + class CarPresenter extends Presenter { + type = 'cars' + relationships() { + return { motor: MotorPresenter } + }; + } + + const motor: { id: any; car: any } = { + id: 2, + car: null + } + + const car = { + id: 1, + motor: motor + } + + motor.car = car; + + CarPresenter.toJSON(car).toString(); + CarPresenter.toJSON(car, { meta: { so: 'meta' } }).toString(); + + CarPresenter.render({ id: 3 }).toString(); + CarPresenter.render({ id: 3 }, { meta: { so: 'meta' } }).toString(); + CarPresenter.render({ id: 3 }, { car: { id: 3 } }).toString(); +} + +function test_adapter() { + Adapter.get({ name: 'Abraham' }).toString(); + Adapter.get({ name: 'Abraham' }, 'name').toString(); + + Adapter.id({ id: 5 }); +} diff --git a/yayson/yayson.d.ts b/yayson/yayson.d.ts new file mode 100644 index 0000000000..1ee0eda777 --- /dev/null +++ b/yayson/yayson.d.ts @@ -0,0 +1,64 @@ +// Type definitions for yayson v2.0.1 +// Project: https://github.com/confetti/yayson +// Definitions by: David Wood +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'yayson' { + class Store { + sync(obj: {}): any; + find(type: string, id: string): any; + findAll(type: string): any[]; + remove(type: string, id?: string): void; + reset(): void; + + records: y.Record[]; + relations: { [key: string]: any }; + } + + interface Adapter { + get(model: {}, key?: string): any; + id(model: {}): string; + } + + class Presenter { + static adapter: string; + + static render(instanceOrCollection: PromiseLike, options?: y.JsonOptions): PromiseLike; + static render(instanceOrCollection: {}, options?: y.JsonOptions): any; + static toJSON(instanceOrCollection: {}, options?: y.JsonOptions): any; + + render(instanceOrCollection: PromiseLike, options?: y.JsonOptions): PromiseLike; + render(instanceOrCollection: {}, options?: y.JsonOptions): any; + toJSON(instanceOrCollection: {}, options?: y.JsonOptions): any; + id(instance: {}): string; + + type: string; + } + + interface Yayson { + Store: typeof Store; + Presenter: typeof Presenter; + Adapter: Adapter; + } + + interface YaysonOptions { + adapter?: 'default' | 'sequelize'; + } + + function y(arg?: YaysonOptions): Yayson; + + namespace y { + interface JsonOptions { + [key: string]: any; + meta?: {}; + } + interface Record { + id: any; + type: string; + attributes: any; + relationships: any; + } + } + + export = y; +} From 8ca204242d6b56ec6c79ef663f7c0eaf14ac483e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20Kova=C4=8Di=C4=8D?= Date: Sun, 25 Sep 2016 19:57:26 +0200 Subject: [PATCH 018/382] Changed namespace from angularTouchspin to angular.touchspin (#11414) --- angular-touchspin/angular-touchspin-tests.ts | 6 +++--- angular-touchspin/angular-touchspin.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/angular-touchspin/angular-touchspin-tests.ts b/angular-touchspin/angular-touchspin-tests.ts index c6e229c7f5..c69c6b3140 100644 --- a/angular-touchspin/angular-touchspin-tests.ts +++ b/angular-touchspin/angular-touchspin-tests.ts @@ -2,9 +2,9 @@ /// angular - .module('touchspin-tests', ['lm.touchspin']) - .config(function(touchspinConfigProvider: angularTouchSpin.ITouchSpinConfigProvider) { - touchspinConfigProvider.defaults({ + .module('touchspin-tests', ['nk.touchspin']) + .config(function(touchspinConfigProvider: angular.touchspin.ITouchSpinConfigProvider) { + touchspinConfigProvider.defaults({ min: 0, max: 0, step: 0, diff --git a/angular-touchspin/angular-touchspin.d.ts b/angular-touchspin/angular-touchspin.d.ts index 5423b17e55..adae8cc92c 100644 --- a/angular-touchspin/angular-touchspin.d.ts +++ b/angular-touchspin/angular-touchspin.d.ts @@ -11,7 +11,7 @@ declare module "angular-touchspin" { export = _; } -declare namespace angularTouchSpin { +declare namespace angular.touchspin { interface ITouchSpinOptions { min?: number; max?: number; From a1769ac42af931b508ae94b7a833a2654594e815 Mon Sep 17 00:00:00 2001 From: Kombu Date: Mon, 26 Sep 2016 02:01:26 +0800 Subject: [PATCH 019/382] [perfect-scrollbar.d.ts] Add definitions for perfect-scrollbar (#11486) --- perfect-scrollbar/perfect-scrollbar-tests.ts | 42 ++++++ perfect-scrollbar/perfect-scrollbar.d.ts | 134 +++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 perfect-scrollbar/perfect-scrollbar-tests.ts create mode 100644 perfect-scrollbar/perfect-scrollbar.d.ts diff --git a/perfect-scrollbar/perfect-scrollbar-tests.ts b/perfect-scrollbar/perfect-scrollbar-tests.ts new file mode 100644 index 0000000000..2036d19f0f --- /dev/null +++ b/perfect-scrollbar/perfect-scrollbar-tests.ts @@ -0,0 +1,42 @@ +/// +/// + +/** + * https://github.com/noraesae/perfect-scrollbar#how-to-use + */ + +import * as Ps from 'perfect-scrollbar' +const container = document.body + +// To initialise the plugin, `Ps.initialize` is used. +Ps.initialize(container) + +// It can be initialised with optional parameters. +Ps.initialize(container, { + wheelSpeed: 2, + wheelPropagation: true, + minScrollbarLength: 20 +}) + +// If the size of your container or content changes, call `update`. +Ps.update(container) + +// If you want to destroy the scrollbar, use `destroy`. +Ps.destroy(container) + +// If you want to scroll to somewhere, just use a `scrollTop` property and update. +container.scrollTop = 0 +Ps.update(container) + +/** + * https://github.com/noraesae/perfect-scrollbar#jquery + */ + +import * as $ from 'jquery' +import mountJQuery = require('perfect-scrollbar/jquery') +mountJQuery($) + +$('#container').perfectScrollbar() // Initialize +$('#container').perfectScrollbar({ /*...*/ }) // with options +$('#container').perfectScrollbar('update') // Update +$('#container').perfectScrollbar('destroy') // Destroy diff --git a/perfect-scrollbar/perfect-scrollbar.d.ts b/perfect-scrollbar/perfect-scrollbar.d.ts new file mode 100644 index 0000000000..85155ea3cd --- /dev/null +++ b/perfect-scrollbar/perfect-scrollbar.d.ts @@ -0,0 +1,134 @@ +// Type definitions for perfect-scrollbar v0.6.12 +// Project: https://github.com/noraesae/perfect-scrollbar +// Definitions by: Kombu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/default-setting.js#L3 + * https://github.com/noraesae/perfect-scrollbar#optional-parameters + */ +interface PerfectScrollbarSettings { + + /** + * It is a list of handlers to use to scroll the element. + * https://github.com/noraesae/perfect-scrollbar#handlers + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L9 + */ + handlers?: ('click-rail' | + 'drag-scrollbar' | + 'keyboard' | + 'wheel' | + 'touch' | + 'selection')[]; + + /** + * When set to an integer value, the thumb part of the scrollbar will not expand over that number of pixels. + * https://github.com/noraesae/perfect-scrollbar#maxscrollbarlength + */ + maxScrollbarLength?: number; + + /** + * When set to an integer value, the thumb part of the scrollbar will not shrink below that number of pixels. + * https://github.com/noraesae/perfect-scrollbar#minscrollbarlength + */ + minScrollbarLength?: number; + + /** + * The number of pixels the content width can surpass the container width without enabling the X axis scroll bar. + * Allows some "wiggle room" or "offset break", so that X axis scroll bar is not enabled just because of a few pixels. + * https://github.com/noraesae/perfect-scrollbar#scrollxmarginoffset + */ + scrollXMarginOffset?: number; + + /** + * The number of pixels the content height can surpass the container height without enabling the Y axis scroll bar. + * Allows some "wiggle room" or "offset break", so that Y axis scroll bar is not enabled just because of a few pixels. + * https://github.com/noraesae/perfect-scrollbar#scrollymarginoffset + */ + scrollYMarginOffset?: number; + + /** + * When set to false, when clicking on a rail, the click event will be allowed to propagate. + * https://github.com/noraesae/perfect-scrollbar#stoppropagationonclick + */ + stopPropagationOnClick?: boolean; + + /** + * When set to true, the scroll bar in X axis will not be available, regardless of the content width. + * https://github.com/noraesae/perfect-scrollbar#suppressscrollx + */ + suppressScrollX?: boolean; + + /** + * When set to true, the scroll bar in Y axis will not be available, regardless of the content height. + * https://github.com/noraesae/perfect-scrollbar#suppressscrolly + */ + suppressScrollY?: boolean; + + /** + * If this option is true, when the scroll reaches the end of the side, touch scrolling will be propagated to parent element. + * https://github.com/noraesae/perfect-scrollbar#swipepropagation + */ + swipePropagation?: boolean; + + /** + * When set to true, and only one (vertical or horizontal) scrollbar is visible then both vertical and horizontal scrolling will affect the scrollbar. + * https://github.com/noraesae/perfect-scrollbar#usebothwheelaxes + */ + useBothWheelAxes?: boolean; + + /** + * If this option is true, when the scroll reaches the end of the side, mousewheel event will be propagated to parent element. + * https://github.com/noraesae/perfect-scrollbar#wheelpropagation + */ + wheelPropagation?: boolean; + + /** + * The scroll speed applied to mousewheel event. + * https://github.com/noraesae/perfect-scrollbar#wheelspeed + */ + wheelSpeed?: number; + + /** + * A string. + * It's a class name added to the container element. + * The class name is prepended with `ps-theme-`. + * So default theme class name is `ps-theme-default`. + * In order to create custom themes with scss use `ps-container($theme)` mixin, where `$theme` is a scss map. + * https://github.com/noraesae/perfect-scrollbar#theme + */ + theme?: string; +} + +declare module 'perfect-scrollbar' { + + /** + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/initialize.js#L19 + */ + export function initialize(element: HTMLElement, settings?: PerfectScrollbarSettings): void; + + /** + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/update.js#L9 + */ + export function update(element: HTMLElement): void; + + /** + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/plugin/destroy.js#L7 + */ + export function destroy(element: HTMLElement): void; +} + +interface JQuery { + + /** + * https://github.com/noraesae/perfect-scrollbar/blob/master/src/js/adaptor/jquery.js#L6 + */ + perfectScrollbar(settingOrCommand?: PerfectScrollbarSettings | 'update' | 'destroy'): JQuery; +} + +declare module 'perfect-scrollbar/jquery' { + function mountJQuery(jQuery: JQueryStatic): void; + export = mountJQuery; +} From f82ccb560ec3b966fa571384047e27152cfed391 Mon Sep 17 00:00:00 2001 From: Matthew McEachen Date: Sun, 25 Sep 2016 16:22:47 -0700 Subject: [PATCH 020/382] Added types for klaw (#11492) * Added types for klaw * addressed pr comments and `tsfmt -r klaw/*.ts` --- klaw/klaw-tests.ts | 46 ++++++++++++++++++++++++++++++++++++++++++++++ klaw/klaw.d.ts | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 klaw/klaw-tests.ts create mode 100644 klaw/klaw.d.ts diff --git a/klaw/klaw-tests.ts b/klaw/klaw-tests.ts new file mode 100644 index 0000000000..5e7ecdebf7 --- /dev/null +++ b/klaw/klaw-tests.ts @@ -0,0 +1,46 @@ +/// +/// + +import * as klaw from "klaw"; +const path = require('path'); + +// README.md: Streams 1 (push) example: + +let items: klaw.Item[] = [] // files, directories, symlinks, etc + +klaw('/some/dir') + .on('data', function(item: klaw.Item) { + items.push(item) + }) + .on('end', function() { + console.dir(items) // => [ ... array of files] + }) + +// README.md: Streams 2 & 3 (pull) with error handling + +klaw('/some/dir') + .on('readable', function() { + let item: klaw.Item; + while (item = this.read()) { + items.push(item) + } + }) + .on('error', function(err: Error, item: klaw.Item) { + console.log(err.message) + console.log(item.path) // the file the error occurred on + }) + .on('end', function() { + console.log(items) // => [ ... array of files] + }) + +// README.md: Example (ignore hidden directories): + +var filterFunc = function(item: klaw.Item): boolean { + var basename = path.basename(item.path) + return basename === '.' || basename[0] !== '.' +} + +klaw('/some/dir', { filter: filterFunc }) + .on('data', function(item: klaw.Item) { + // only items of none hidden folders will reach here + }) diff --git a/klaw/klaw.d.ts b/klaw/klaw.d.ts new file mode 100644 index 0000000000..e2b641f546 --- /dev/null +++ b/klaw/klaw.d.ts @@ -0,0 +1,44 @@ +// Type definitions for klaw v1.3.0 +// Project: https://github.com/jprichardson/node-klaw +// Definitions by: Matthew McEachen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "klaw" { + + import * as fs from "fs" + import { Readable, ReadableOptions } from 'stream' + + function K(root: string, options?: K.Options): K.Walker + + namespace K { + interface Item { + path: string + stats: fs.Stats + } + + type QueueMethod = "shift" | "pop" + + interface Options extends ReadableOptions { + queueMethod?: QueueMethod + pathSorter?: (a: Array) => Array + fs?: any // fs or mock-fs + filter?: (a: Item) => boolean + } + + type Event = "close" | "data" | "end" | "readable" | "error" + + interface Walker { + on(event: Event, listener: Function): this + on(event: "close", listener: () => void): this + on(event: "data", listener: (item: Item) => void): this + on(event: "end", listener: () => void): this + on(event: "readable", listener: () => void): this + on(event: "error", listener: (err: Error) => void): this + read(): Item + } + } + + export = K +} From d0a34b8791e95a0f17314c8754e3b0a96e812be7 Mon Sep 17 00:00:00 2001 From: Hisham A Date: Mon, 26 Sep 2016 08:33:32 -0600 Subject: [PATCH 021/382] add typings for onselected and onunselected methods, refs #11493 (#11496) --- c3/c3.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index e815b44391..83ccf85853 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -385,10 +385,10 @@ declare namespace c3 { * - d is the data where mouse cursor moves out. In this callback, this will be the Chart object. */ onmouseout?: (d: any, element?: any) => void; - // onselected?: any; - // onunselected?: any; - // ondragstart?: any; - // ondragend?: any; + + onselected?: (d: any, element?: any) => void; + + onunselected?: (d: any, element?: any) => void; } interface Axis { From 55d9114bbd68142c1afb846732cfaae002aca27c Mon Sep 17 00:00:00 2001 From: Ben Chauvette Date: Mon, 26 Sep 2016 07:52:03 -0700 Subject: [PATCH 022/382] Improve through2 declarations (#11499) * [through2] Fix typos * [through2] Change return types to stream.Transform `through2` creates `stream.Transform`-flavored streams, so switching the return types to `stream.Transform` gives us richer typing information than using `NodeJS.ReadWriteStream`, which is missing methods (e.g. `stream.Transform#push`) and the ability to use object mode. * [through2] Add through2.ctor method * [through2] Update header and docs --- through2/through2-tests.ts | 49 +++++++++++++++++++++++++++++++++++++- through2/through2.d.ts | 28 +++++++++++++++------- 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/through2/through2-tests.ts b/through2/through2-tests.ts index e6f97fb712..94d60e0bff 100644 --- a/through2/through2-tests.ts +++ b/through2/through2-tests.ts @@ -1,9 +1,11 @@ /// /// +import stream = require('stream'); import through2 = require('through2'); -var rws: NodeJS.ReadWriteStream; +var rws: stream.Transform; +var Rws: through2.Through2Constructor; rws = through2({ objectMode: true, @@ -53,3 +55,48 @@ rws = through2.obj(function (entry: any, enc: string, callback: (err: any) => vo }, (flashCallback) => { flashCallback(); }); + +// ctor +Rws = through2.ctor({ + objectMode: true, + allowHalfOpen: true +}, function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}, () => { + +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: (error: any, data?: any) => void) { + callback(null, 'foo'); +}, (flushCallback: () => void) => { + flushCallback(); +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); + +Rws = through2.ctor(function (entry: any, enc: string, callback: () => void) { + this.push('foo'); + callback(); +}); + +rws = Rws(); +rws = new Rws(); +rws = new Rws({ objectMode: true, allowHalfOpen: true }); diff --git a/through2/through2.d.ts b/through2/through2.d.ts index 77cc817caa..27b8a93178 100644 --- a/through2/through2.d.ts +++ b/through2/through2.d.ts @@ -1,6 +1,6 @@ // Type definitions for through2 v 2.0.0 // Project: https://github.com/rvagg/through2 -// Definitions by: Bart van der Schoor , jedmao , Georgios Valotasios +// Definitions by: Bart van der Schoor , jedmao , Georgios Valotasios , Ben Chauvette // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,20 +9,30 @@ declare module 'through2' { import stream = require('stream'); - type TransfofmCallback = (err?: any, data?: any) => void; - type TransformFunction = (chunk: any, enc: string, callback: TransfofmCallback) => void; - type FlashCallback = (flushCallback: () => void) => void; + type TransformCallback = (err?: any, data?: any) => void; + type TransformFunction = (chunk: any, enc: string, callback: TransformCallback) => void; + type FlushCallback = (flushCallback: () => void) => void; - function through2(transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; + function through2(transform?: TransformFunction, flush?: FlushCallback): stream.Transform; - function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; + function through2(opts?: stream.DuplexOptions, transform?: TransformFunction, flush?: FlushCallback): stream.Transform; namespace through2 { + export interface Through2Constructor extends stream.Transform { + new(opts?: stream.DuplexOptions): stream.Transform; + (opts?: stream.DuplexOptions): stream.Transform; + } - export function obj(transform?: TransformFunction, flush?: FlashCallback): NodeJS.ReadWriteStream; - - export function push(data: any): void; + /** + * Convenvience method for creating object streams + */ + export function obj(transform?: TransformFunction, flush?: FlushCallback): stream.Transform; + /** + * Creates a constructor for a custom Transform. This is useful when you + * want to use the same transform logic in multiple instances. + */ + export function ctor(opts?: stream.DuplexOptions, transfrom?: TransformFunction, flush?: FlushCallback): Through2Constructor; } export = through2; From d907b02638bf6c56ae3f632ca5c151cb869df5b4 Mon Sep 17 00:00:00 2001 From: Izaak Baker Date: Mon, 26 Sep 2016 14:01:45 -0700 Subject: [PATCH 023/382] Add module declaration to crossfilter so that it can be explicitly imported (#11521) --- crossfilter/crossfilter.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crossfilter/crossfilter.d.ts b/crossfilter/crossfilter.d.ts index 646d8abeb0..ed888f6959 100644 --- a/crossfilter/crossfilter.d.ts +++ b/crossfilter/crossfilter.d.ts @@ -1,6 +1,6 @@ // Type definitions for CrossFilter // Project: https://github.com/square/crossfilter -// Definitions by: Schmulik Raskin +// Definitions by: Schmulik Raskin , Izaak Baker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace CrossFilter { @@ -111,3 +111,8 @@ declare namespace CrossFilter { } declare var crossfilter: CrossFilter.CrossFilterStatic; +declare module "crossfilter" { + var crossfilter: CrossFilter.CrossFilterStatic; + export = crossfilter; +} + From 22a311bd60be06c92d4b9a6646e30b3180627158 Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:44:22 -0500 Subject: [PATCH 024/382] Add typings for murmurhash3js --- murmurhash3js/murmurhash3js-tests.ts | 12 ++++++++++++ murmurhash3js/murmurhash3js.d.ts | 15 +++++++++++++++ 2 files changed, 27 insertions(+) create mode 100644 murmurhash3js/murmurhash3js-tests.ts create mode 100644 murmurhash3js/murmurhash3js.d.ts diff --git a/murmurhash3js/murmurhash3js-tests.ts b/murmurhash3js/murmurhash3js-tests.ts new file mode 100644 index 0000000000..297adcbc67 --- /dev/null +++ b/murmurhash3js/murmurhash3js-tests.ts @@ -0,0 +1,12 @@ +/// + +import murmurhash3js = require('murmurhash3js'); + +murmurhash3js.x86.hash32('string'); +murmurhash3js.x86.hash32('string with seed', 1337); + +murmurhash3js.x86.hash128('string'); +murmurhash3js.x86.hash128('string with seed', 1337); + +murmurhash3js.x64.hash128('string'); +murmurhash3js.x64.hash128('string with seed', 1337); diff --git a/murmurhash3js/murmurhash3js.d.ts b/murmurhash3js/murmurhash3js.d.ts new file mode 100644 index 0000000000..f43deeaa37 --- /dev/null +++ b/murmurhash3js/murmurhash3js.d.ts @@ -0,0 +1,15 @@ +// Type definitions for murmurhash3js v3.0.1 +// Project: https://github.com/pid/murmurHash3js +// Definitions by: Dave Lee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'murmurhash3js' { + export module x86 { + function hash32(val: string, seed?: number): string; + function hash128(val: string, seed?: number): string; + } + + export module x64 { + function hash128(val: string, seed?: number): string; + } +} \ No newline at end of file From 5143d60f3790c68c23ebbaf8f78951316a32322e Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:46:34 -0500 Subject: [PATCH 025/382] fix module import to be ES6 compliant --- murmurhash3js/murmurhash3js-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/murmurhash3js/murmurhash3js-tests.ts b/murmurhash3js/murmurhash3js-tests.ts index 297adcbc67..f9a40619d6 100644 --- a/murmurhash3js/murmurhash3js-tests.ts +++ b/murmurhash3js/murmurhash3js-tests.ts @@ -1,6 +1,6 @@ /// -import murmurhash3js = require('murmurhash3js'); +import * as murmurhash3js from 'murmurhash3js'; murmurhash3js.x86.hash32('string'); murmurhash3js.x86.hash32('string with seed', 1337); From 7e08a4492cabd1e022f488d3be9ebe9d238c06fe Mon Sep 17 00:00:00 2001 From: David Lee Date: Mon, 26 Sep 2016 17:47:40 -0500 Subject: [PATCH 026/382] newline at EOF --- murmurhash3js/murmurhash3js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/murmurhash3js/murmurhash3js.d.ts b/murmurhash3js/murmurhash3js.d.ts index f43deeaa37..2193085d5b 100644 --- a/murmurhash3js/murmurhash3js.d.ts +++ b/murmurhash3js/murmurhash3js.d.ts @@ -12,4 +12,4 @@ declare module 'murmurhash3js' { export module x64 { function hash128(val: string, seed?: number): string; } -} \ No newline at end of file +} From 5ac67c6749dd84d45b091ef1b991f5cbb1171536 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:40:01 -0700 Subject: [PATCH 027/382] [rethinkdb] Adds missing promise methods to Cursor and Connection --- rethinkdb/rethinkdb-tests.ts | 6 ++++-- rethinkdb/rethinkdb.d.ts | 23 ++++++++++++++--------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/rethinkdb/rethinkdb-tests.ts b/rethinkdb/rethinkdb-tests.ts index a6911e3021..4dbd7ab638 100644 --- a/rethinkdb/rethinkdb-tests.ts +++ b/rethinkdb/rethinkdb-tests.ts @@ -15,8 +15,10 @@ r.connect({host:"localhost", port: 28015}, function(err, conn) { }) .between("james", "beth") .limit(4) - .run(conn, function() { - + .run(conn, function(err, cursor) { + cursor.toArray().then(rows => { + console.log(rows); + }); }) }) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index 7161e42060..0b4d6b54b9 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -35,11 +35,13 @@ declare module "rethinkdb" { export class Cursor { hasNext():boolean; - each(cb:(err:Error, row:any)=>void, done?:()=>void); - each(cb:(err:Error, row:any)=>boolean, done?:()=>void); // returning false stops iteration - next(cb:(err:Error, row:any) => void); - toArray(cb:(err:Error, rows:any[]) => void); - close(); + each(cb:(err:Error, row:any)=>void, done?:()=>void): void; + each(cb:(err:Error, row:any)=>boolean, done?:()=>void): void; // returning false stops iteration + next(cb:(err:Error, row:any) => void): void; + toArray(cb:(err:Error, rows:any[]) => void): void; + toArray(): Promise; + close(cb: (err: Error) => void): void; + close(): Promise; } interface ConnectionOptions { @@ -50,11 +52,14 @@ declare module "rethinkdb" { } interface Connection { - close(); + close(cb: (err: Error) => void): void; + close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; + close(): Promise; + close(opts: { noreplyWait: boolean }): Promise; reconnect(cb?:(err:Error, conn:Connection)=>void):Promise; - use(dbName:string); - addListener(event:string, cb:Function); - on(event:string, cb:Function); + use(dbName:string): void; + addListener(event:string, cb:Function): void; + on(event:string, cb:Function): void; } interface Db { From 87a03f83ce8a03188424ca2126f4d1c70e17f0b4 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:41:08 -0700 Subject: [PATCH 028/382] [rethinkdb] Applied TypeScript formatting to the file --- rethinkdb/rethinkdb.d.ts | 368 +++++++++++++++++++-------------------- 1 file changed, 184 insertions(+), 184 deletions(-) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index 0b4d6b54b9..dc251b2a8e 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -8,234 +8,234 @@ declare module "rethinkdb" { - export function connect(host:ConnectionOptions, cb?:(err:Error, conn:Connection)=>void):Promise; + export function connect(host: ConnectionOptions, cb?: (err: Error, conn: Connection) => void): Promise; - export function dbCreate(name:string):Operation; - export function dbDrop(name:string):Operation; - export function dbList():Operation; + export function dbCreate(name: string): Operation; + export function dbDrop(name: string): Operation; + export function dbList(): Operation; - export function db(name:string):Db; - export function table(name:string, options?:{useOutdated:boolean}):Table; + export function db(name: string): Db; + export function table(name: string, options?: { useOutdated: boolean }): Table; - export function asc(property:string):Sort; - export function desc(property:string):Sort; + export function asc(property: string): Sort; + export function desc(property: string): Sort; - export var count:Aggregator; - export function sum(prop:string):Aggregator; - export function avg(prop:string):Aggregator; + export var count: Aggregator; + export function sum(prop: string): Aggregator; + export function avg(prop: string): Aggregator; - export function row(name:string):Expression; - export function expr(stuff:any):Expression; + export function row(name: string): Expression; + export function expr(stuff: any): Expression; - export function now():Time; + export function now(): Time; - // Control Structures - export function branch(test:Expression, trueBranch:Expression, falseBranch:Expression):Expression; + // Control Structures + export function branch(test: Expression, trueBranch: Expression, falseBranch: Expression): Expression; - export class Cursor { - hasNext():boolean; - each(cb:(err:Error, row:any)=>void, done?:()=>void): void; - each(cb:(err:Error, row:any)=>boolean, done?:()=>void): void; // returning false stops iteration - next(cb:(err:Error, row:any) => void): void; - toArray(cb:(err:Error, rows:any[]) => void): void; - toArray(): Promise; - close(cb: (err: Error) => void): void; - close(): Promise; - } + export class Cursor { + hasNext(): boolean; + each(cb: (err: Error, row: any) => void, done?: () => void): void; + each(cb: (err: Error, row: any) => boolean, done?: () => void): void; // returning false stops iteration + next(cb: (err: Error, row: any) => void): void; + toArray(cb: (err: Error, rows: any[]) => void): void; + toArray(): Promise; + close(cb: (err: Error) => void): void; + close(): Promise; + } - interface ConnectionOptions { - host:string; - port:number; - db?:string; - authKey?:string; - } + interface ConnectionOptions { + host: string; + port: number; + db?: string; + authKey?: string; + } - interface Connection { - close(cb: (err: Error) => void): void; - close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; - close(): Promise; - close(opts: { noreplyWait: boolean }): Promise; - reconnect(cb?:(err:Error, conn:Connection)=>void):Promise; - use(dbName:string): void; - addListener(event:string, cb:Function): void; - on(event:string, cb:Function): void; - } + interface Connection { + close(cb: (err: Error) => void): void; + close(opts: { noreplyWait: boolean }, cb: (err: Error) => void): void; + close(): Promise; + close(opts: { noreplyWait: boolean }): Promise; + reconnect(cb?: (err: Error, conn: Connection) => void): Promise; + use(dbName: string): void; + addListener(event: string, cb: Function): void; + on(event: string, cb: Function): void; + } - interface Db { - tableCreate(name:string, options?:TableOptions):Operation; - tableDrop(name:string):Operation; - tableList():Operation; - table(name:string, options?:GetTableOptions):Table; - } + interface Db { + tableCreate(name: string, options?: TableOptions): Operation; + tableDrop(name: string): Operation; + tableList(): Operation; + table(name: string, options?: GetTableOptions): Table; + } - interface TableOptions { - primary_key?:string; // 'id' - durability?:string; // 'soft' - cache_size?:number; - datacenter?:string; - } + interface TableOptions { + primary_key?: string; // 'id' + durability?: string; // 'soft' + cache_size?: number; + datacenter?: string; + } - interface GetTableOptions { - useOutdated: boolean; - } + interface GetTableOptions { + useOutdated: boolean; + } - interface Writeable { - update(obj:Object, options?:UpdateOptions):Operation; - replace(obj:Object, options?:UpdateOptions):Operation; - replace(expr:ExpressionFunction):Operation; - delete(options?:UpdateOptions):Operation; - } + interface Writeable { + update(obj: Object, options?: UpdateOptions): Operation; + replace(obj: Object, options?: UpdateOptions): Operation; + replace(expr: ExpressionFunction): Operation; + delete(options?: UpdateOptions): Operation; + } - interface Table extends Sequence { - indexCreate(name:string, index?:ExpressionFunction):Operation; - indexDrop(name:string):Operation; - indexList():Operation; + interface Table extends Sequence { + indexCreate(name: string, index?: ExpressionFunction): Operation; + indexDrop(name: string): Operation; + indexList(): Operation; - insert(obj:any[], options?:InsertOptions):Operation; - insert(obj:any, options?:InsertOptions):Operation; + insert(obj: any[], options?: InsertOptions): Operation; + insert(obj: any, options?: InsertOptions): Operation; - get(key:string):Sequence; // primary key - getAll(key:string, index?:Index):Sequence; // without index defaults to primary key - getAll(...keys:string[]):Sequence; - } + get(key: string): Sequence; // primary key + getAll(key: string, index?: Index): Sequence; // without index defaults to primary key + getAll(...keys: string[]): Sequence; + } - interface Sequence extends Operation, Writeable { + interface Sequence extends Operation, Writeable { - between(lower:any, upper:any, index?:Index):Sequence; - filter(rql:ExpressionFunction):Sequence; - filter(rql:Expression):Sequence; - filter(obj:{[key:string]:any}):Sequence; + between(lower: any, upper: any, index?: Index): Sequence; + filter(rql: ExpressionFunction): Sequence; + filter(rql: Expression): Sequence; + filter(obj: { [key: string]: any }): Sequence; - // Join - // these return left, right - innerJoin(sequence:Sequence, join:JoinFunction):Sequence; - outerJoin(sequence:Sequence, join:JoinFunction):Sequence; - eqJoin(leftAttribute:string, rightSequence:Sequence, index?:Index):Sequence; - eqJoin(leftAttribute:ExpressionFunction, rightSequence:Sequence, index?:Index):Sequence; - zip():Sequence; + // Join + // these return left, right + innerJoin(sequence: Sequence, join: JoinFunction): Sequence; + outerJoin(sequence: Sequence, join: JoinFunction): Sequence; + eqJoin(leftAttribute: string, rightSequence: Sequence, index?: Index): Sequence; + eqJoin(leftAttribute: ExpressionFunction, rightSequence: Sequence, index?: Index): Sequence; + zip(): Sequence; - // Transform - map(transform:ExpressionFunction):Sequence; - withFields(...selectors:any[]):Sequence; - concatMap(transform:ExpressionFunction):Sequence; - orderBy(...keys:string[]):Sequence; - orderBy(...sorts:Sort[]):Sequence; - skip(n:number):Sequence; - limit(n:number):Sequence; - slice(start:number, end?:number):Sequence; - nth(n:number):Expression; - indexesOf(obj:any):Sequence; - isEmpty():Expression; - union(sequence:Sequence):Sequence; - sample(n:number):Sequence; + // Transform + map(transform: ExpressionFunction): Sequence; + withFields(...selectors: any[]): Sequence; + concatMap(transform: ExpressionFunction): Sequence; + orderBy(...keys: string[]): Sequence; + orderBy(...sorts: Sort[]): Sequence; + skip(n: number): Sequence; + limit(n: number): Sequence; + slice(start: number, end?: number): Sequence; + nth(n: number): Expression; + indexesOf(obj: any): Sequence; + isEmpty(): Expression; + union(sequence: Sequence): Sequence; + sample(n: number): Sequence; - // Aggregate - reduce(r:ReduceFunction, base?:any):Expression; - count():Expression; - distinct():Sequence; - groupedMapReduce(group:ExpressionFunction, map:ExpressionFunction, reduce:ReduceFunction, base?:any):Sequence; - groupBy(...aggregators:Aggregator[]):Expression; // TODO: reduction object - contains(prop:string):Expression; + // Aggregate + reduce(r: ReduceFunction, base?: any): Expression; + count(): Expression; + distinct(): Sequence; + groupedMapReduce(group: ExpressionFunction, map: ExpressionFunction, reduce: ReduceFunction, base?: any): Sequence; + groupBy(...aggregators: Aggregator[]): Expression; // TODO: reduction object + contains(prop: string): Expression; - // Manipulation - pluck(...props:string[]):Sequence; - without(...props:string[]):Sequence; - } + // Manipulation + pluck(...props: string[]): Sequence; + without(...props: string[]): Sequence; + } - interface ExpressionFunction { - (doc:Expression):Expression; - } + interface ExpressionFunction { + (doc: Expression): Expression; + } - interface JoinFunction { - (left:Expression, right:Expression):Expression; - } + interface JoinFunction { + (left: Expression, right: Expression): Expression; + } - interface ReduceFunction { - (acc:Expression, val:Expression):Expression; - } + interface ReduceFunction { + (acc: Expression, val: Expression): Expression; + } - interface InsertOptions { - upsert: boolean; // true - durability: string; // 'soft' - return_vals: boolean; // false - } + interface InsertOptions { + upsert: boolean; // true + durability: string; // 'soft' + return_vals: boolean; // false + } - interface UpdateOptions { - non_atomic: boolean; - durability: string; // 'soft' - return_vals: boolean; // false - } + interface UpdateOptions { + non_atomic: boolean; + durability: string; // 'soft' + return_vals: boolean; // false + } - interface WriteResult { - inserted: number; - replaced: number; - unchanged: number; - errors: number; - deleted: number; - skipped: number; - first_error: Error; - generated_keys: string[]; // only for insert - } + interface WriteResult { + inserted: number; + replaced: number; + unchanged: number; + errors: number; + deleted: number; + skipped: number; + first_error: Error; + generated_keys: string[]; // only for insert + } - interface JoinResult { - left:any; - right:any; - } + interface JoinResult { + left: any; + right: any; + } - interface CreateResult { - created: number; - } + interface CreateResult { + created: number; + } - interface DropResult { - dropped: number; - } + interface DropResult { + dropped: number; + } - interface Index { - index: string; - left_bound?: string; // 'closed' - right_bound?: string; // 'open' - } + interface Index { + index: string; + left_bound?: string; // 'closed' + right_bound?: string; // 'open' + } - interface Expression extends Writeable, Operation { - (prop:string):Expression; - merge(query:Expression):Expression; - append(prop:string):Expression; - contains(prop:string):Expression; + interface Expression extends Writeable, Operation { + (prop: string): Expression; + merge(query: Expression): Expression; + append(prop: string): Expression; + contains(prop: string): Expression; - and(b:boolean):Expression; - or(b:boolean):Expression; - eq(v:any):Expression; - ne(v:any):Expression; - not():Expression; + and(b: boolean): Expression; + or(b: boolean): Expression; + eq(v: any): Expression; + ne(v: any): Expression; + not(): Expression; - gt(value:T):Expression; - ge(value:T):Expression; - lt(value:T):Expression; - le(value:T):Expression; + gt(value: T): Expression; + ge(value: T): Expression; + lt(value: T): Expression; + le(value: T): Expression; - add(n:number):Expression; - sub(n:number):Expression; - mul(n:number):Expression; - div(n:number):Expression; - mod(n:number):Expression; + add(n: number): Expression; + sub(n: number): Expression; + mul(n: number): Expression; + div(n: number): Expression; + mod(n: number): Expression; - hasFields(...fields:string[]):Expression; + hasFields(...fields: string[]): Expression; - default(value:T):Expression; - } + default(value: T): Expression; + } - interface Operation { - run(conn:Connection, cb?:(err:Error, result:T)=>void):Promise; - } + interface Operation { + run(conn: Connection, cb?: (err: Error, result: T) => void): Promise; + } - interface Aggregator {} - interface Sort {} + interface Aggregator { } + interface Sort { } - interface Time {} + interface Time { } - // http://www.rethinkdb.com/api/#js - // TODO control structures + // http://www.rethinkdb.com/api/#js + // TODO control structures } From 317be6bc69da5f69b9517f1ff4c7908745dd5592 Mon Sep 17 00:00:00 2001 From: Alex Gorbatchev Date: Mon, 26 Sep 2016 19:59:32 -0700 Subject: [PATCH 029/382] [rethinkdb] Adds types to Cursor methods --- rethinkdb/rethinkdb.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rethinkdb/rethinkdb.d.ts b/rethinkdb/rethinkdb.d.ts index dc251b2a8e..7babd42fe2 100644 --- a/rethinkdb/rethinkdb.d.ts +++ b/rethinkdb/rethinkdb.d.ts @@ -36,10 +36,15 @@ declare module "rethinkdb" { export class Cursor { hasNext(): boolean; each(cb: (err: Error, row: any) => void, done?: () => void): void; + each(cb: (err: Error, row: T) => void, done?: () => void): void; each(cb: (err: Error, row: any) => boolean, done?: () => void): void; // returning false stops iteration + each(cb: (err: Error, row: T) => boolean, done?: () => void): void; // returning false stops iteration next(cb: (err: Error, row: any) => void): void; + next(cb: (err: Error, row: T) => void): void; toArray(cb: (err: Error, rows: any[]) => void): void; + toArray(cb: (err: Error, rows: T[]) => void): void; toArray(): Promise; + toArray(): Promise; close(cb: (err: Error) => void): void; close(): Promise; } From b5979947c9bec28a35a1c4189ec21cea12d5dc3d Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Mon, 26 Sep 2016 20:45:56 -0700 Subject: [PATCH 030/382] webpack - HotModuleReplacementPlugin has opts arg --- webpack/webpack.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack/webpack.d.ts b/webpack/webpack.d.ts index 96a7c710df..42dbc81e05 100644 --- a/webpack/webpack.d.ts +++ b/webpack/webpack.d.ts @@ -404,7 +404,7 @@ declare module "webpack" { } interface HotModuleReplacementPluginStatic { - new(): Plugin; + new(options?: any): Plugin; } interface ExtendedAPIPluginStatic { From 3a517142892532ae628f98d23990742bf212e34f Mon Sep 17 00:00:00 2001 From: stonio Date: Tue, 27 Sep 2016 09:55:51 +0200 Subject: [PATCH 031/382] [openlayers] forEachFeatureAtPixel can return a value See doc http://openlayers.org/en/latest/apidoc/ol.Map.html#forEachFeatureAtPixel --- openlayers/openlayers.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 0b9e1b41f4..36026fa70d 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -2131,7 +2131,7 @@ declare namespace ol { * @param ref2 Value to use as this when executing layerFilter. * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. */ - forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): any; /** * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. From 6aff001e47fada0f16768ee435ddcc9eb7c521c1 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Tue, 27 Sep 2016 09:23:13 +0100 Subject: [PATCH 032/382] Update react.d.ts Added myself as an author so I get notifications of PRs / updates from GitHub. --- react/react.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index 2f762e0974..c13cdac082 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1,6 +1,6 @@ // Type definitions for React v0.14 // Project: http://facebook.github.io/react/ -// Definitions by: Asana , AssureSign , Microsoft +// Definitions by: Asana , AssureSign , Microsoft , John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace __React { From f70bcf9a0ef640915ad4324b23396f28e2803ddc Mon Sep 17 00:00:00 2001 From: Christian Kittelmann Date: Tue, 27 Sep 2016 12:54:43 +0200 Subject: [PATCH 033/382] vue: fixed definition for activate() in ComponentOption --- vue/vue-tests.ts | 5 +++++ vue/vue.d.ts | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/vue/vue-tests.ts b/vue/vue-tests.ts index 48d8d91683..a15c3e49c1 100644 --- a/vue/vue-tests.ts +++ b/vue/vue-tests.ts @@ -88,6 +88,11 @@ namespace TestGlobalAPI { }, init: function() {} }); + Vue.component("component", { + activate: function(callback: Function) { + callback(); + } + }); var transition = Vue.transition("transition"); Vue.transition("transition", transition); Vue.transition("transition", { diff --git a/vue/vue.d.ts b/vue/vue.d.ts index a335ee63d1..d65a50da63 100644 --- a/vue/vue.d.ts +++ b/vue/vue.d.ts @@ -96,7 +96,7 @@ declare namespace vuejs { detached?(): void; beforeDestroy?(): void; destroyed?(): void; - activate?(): void; + activate?(callback: Function): void; directives?: { [key: string]: (DirectiveOption | Function) }; elementDirectives?: { [key: string]: (DirectiveOption | Function) }; filters?: { [key: string]: (Function | FilterOption) }; From 29a2eb800b4cb7ecc5218fd222001c641bdb8258 Mon Sep 17 00:00:00 2001 From: Passakorn Suppakityothin Date: Tue, 27 Sep 2016 17:56:23 +0700 Subject: [PATCH 034/382] Fix error that came using typescript 2 This error come when try compile with typescript 2 kue.d.ts(13,3): error TS2440: Import declaration conflicts with local declaration of 'redis' --- kue/kue.d.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/kue/kue.d.ts b/kue/kue.d.ts index baca094200..ee3571db0d 100644 --- a/kue/kue.d.ts +++ b/kue/kue.d.ts @@ -10,7 +10,7 @@ declare module "kue" { import events = require('events'); import express = require('express'); - import redis = require('redis'); + import redisClientFactory = require('redis'); export class Queue extends events.EventEmitter { name: string; @@ -18,7 +18,7 @@ declare module "kue" { promoter: any; workers: Worker[]; shuttingDown: boolean; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; testMode: TestMode; static singleton: Queue; @@ -63,7 +63,7 @@ declare module "kue" { public id: number; public type: string; public data: any; - public client: redis.RedisClient; + public client: redisClientFactory.RedisClient; private _max_attempts; static priorities: Priorities; @@ -109,7 +109,7 @@ declare module "kue" { class Worker extends events.EventEmitter { queue: Queue; type: string; - client: redis.RedisClient; + client: redisClientFactory.RedisClient; job: Job; constructor(queue: Queue, type: string); @@ -127,10 +127,10 @@ declare module "kue" { interface Redis { configureFactory(options: Object, queue: Queue): void; - createClient(): redis.RedisClient; - createClientFactory(options: Object): redis.RedisClient; - client(): redis.RedisClient; - pubsubClient(): redis.RedisClient; + createClient(): redisClientFactory.RedisClient; + createClientFactory(options: Object): redisClientFactory.RedisClient; + client(): redisClientFactory.RedisClient; + pubsubClient(): redisClientFactory.RedisClient; reset(): void; } From 262f69018bce7a7a11bfbd0bc663c29cd501bb6d Mon Sep 17 00:00:00 2001 From: Erik Mogensen Date: Tue, 27 Sep 2016 13:48:39 +0200 Subject: [PATCH 035/382] path can be string or a hash of options As per http://restify.com/#client-api it states: > Note that all further documentation refers to the "short-hand" > form of methods like get/put/del which take a string path. You > can also pass in an object to any of those methods with extra > params (notably headers): So the path can be either a string or a hash of options. --- restify/restify.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index 65b3f44d47..a1b933f419 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -470,12 +470,12 @@ declare module "restify" { } interface Client { - get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - patch: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any; + get: (opts: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + patch: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; } From 1e7454173b2d2cf76545b361456df7fb42683ce0 Mon Sep 17 00:00:00 2001 From: ryutamaki Date: Tue, 27 Sep 2016 23:17:03 +0900 Subject: [PATCH 036/382] Add CognitoIdentity into aws-sdk --- aws-sdk/aws-sdk.d.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 2a92a4bcc4..d30b3af305 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -22,6 +22,27 @@ declare module "aws-sdk" { constructor(profile: string); } + export module CognitoIdentity { + export interface CognitoIdentityCredentialsParams { + IdentityPoolId?: string; + AccountId?: string; + Logins?: {[k: string]: any}; + + RoleArn?: string; + RoleSessionName?: string; + WebIdentityToken?: string; + ProviderId?: string; + Policy?: string; + DurationSeconds?: number; + + IdentityId?: string; + } + } + + export class CognitoIdentityCredentials extends Credentials { + constructor(params: CognitoIdentity.CognitoIdentityCredentialsParams); + } + export interface Logger { write?: (chunk: any, encoding?: string, callback?: () => void) => void; log?: (...messages: any[]) => void; From 1545f5cd9193d38e465637ad35d38ba620a007af Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Tue, 27 Sep 2016 22:46:12 +0300 Subject: [PATCH 037/382] Font advanced config options added (for v2.0.6+) --- canvas-gauges/canvas-gauges-tests.ts | 6 ++++-- canvas-gauges/canvas-gauges.d.ts | 14 +++++++++++++- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts index d0f04e1082..015bdfd7e2 100644 --- a/canvas-gauges/canvas-gauges-tests.ts +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -8,10 +8,12 @@ import { } from 'canvas-gauges'; let linearOptions: LinearGaugeOptions = { - renderTo: document.createElement('canvas') + renderTo: document.createElement('canvas'), + fontNumbersStyle: 'italic' }; let radialOptions: RadialGaugeOptions = { - renderTo: 'gauge-id' + renderTo: 'gauge-id', + fontNumbersWeight: 'bold' }; new LinearGauge(linearOptions); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts index 2b67c7f76f..b330726f55 100644 --- a/canvas-gauges/canvas-gauges.d.ts +++ b/canvas-gauges/canvas-gauges.d.ts @@ -4,6 +4,10 @@ // Definitions: https://github.com/Mikhus/DefinitelyTyped declare namespace CanvasGauges { + export type FontStyle = 'normal' | 'italic' | 'oblique'; + export type FontWeight = 'normal' | 'bold' | 'bolder' | 'lighter' | + '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'; + export type RenderTarget = string|HTMLElement; export interface AnimationRule { @@ -86,7 +90,15 @@ declare namespace CanvasGauges { fontTitleSize?: number, fontValueSize?: number, fontUnitsSize?: number, - fontNumbersSize?: number + fontNumbersSize?: number, + fontTitleStyle?: FontStyle, + fontValueStyle?: FontStyle, + fontUnitsStyle?: FontStyle, + fontNumbersStyle?: FontStyle, + fontTitleWeight?: FontWeight, + fontValueWeight?: FontWeight, + fontUnitsWeight?: FontWeight, + fontNumbersWeight?: FontWeight } export interface RadialGaugeOptions extends GenericOptions { From fd8fdb5cf992e09f0a12da758c1099bcba75cf86 Mon Sep 17 00:00:00 2001 From: Frank Gambino Date: Tue, 27 Sep 2016 18:04:58 -0400 Subject: [PATCH 038/382] Add missing slider parameters --- flexSlider/flexSlider.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/flexSlider/flexSlider.d.ts b/flexSlider/flexSlider.d.ts index c8fa3f949c..276bb35e84 100644 --- a/flexSlider/flexSlider.d.ts +++ b/flexSlider/flexSlider.d.ts @@ -78,10 +78,10 @@ interface FlexSliderOptions { // Callback API start?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider loads the first slide before?: (slider: SliderObject) => any; //Callback: function(slider) - Fires asynchronously with each slider animation - after?: () => any; //Callback: function(slider) - Fires after each slider animation completes - end?: () => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) - added?: () => any; //{NEW} Callback: function(slider) - Fires after a slide is added - removed?: () => any; + after?: (slider: SliderObject) => any; //Callback: function(slider) - Fires after each slider animation completes + end?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous) + added?: (slider: SliderObject) => any; //{NEW} Callback: function(slider) - Fires after a slide is added + removed?: (slider: SliderObject) => any; } From dc0093e464a1a31a0659b776daee83e68a7320df Mon Sep 17 00:00:00 2001 From: Vipul Shekhawat Date: Tue, 27 Sep 2016 16:03:49 -0700 Subject: [PATCH 039/382] Add backspaceToRemoveMessage prop --- react-select/react-select.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts index 701d5efc4a..8011122fed 100644 --- a/react-select/react-select.d.ts +++ b/react-select/react-select.d.ts @@ -87,6 +87,12 @@ declare namespace ReactSelect { * @default true */ backspaceRemoves?: boolean; + /** + * Message to use for screenreaders to press backspace to remove the current item + * {label} is replaced with the item label + * @default "Press backspace to remove..." + */ + backspaceToRemoveMessage?: string; /** * CSS className for the outer element */ From 4c73343ec113a863b7c66f0f1e8e2a1e435c3eaf Mon Sep 17 00:00:00 2001 From: Erik Mogensen Date: Wed, 28 Sep 2016 12:36:05 +0200 Subject: [PATCH 040/382] fixup! path can be string or a hash of options --- restify/restify.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index a1b933f419..eb4f5b5702 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -470,24 +470,24 @@ declare module "restify" { } interface Client { - get: (opts: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - head: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; - post: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - put: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - patch: (opts: any, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; - del: (opts: any, callback?: (err: any, req: Request, res: Response) => any) => any; + get: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + head: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; + post: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + put: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + patch: (opts: string | { path?: string; [name: string]: any }, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any; + del: (opts: string | { path?: string; [name: string]: any }, callback?: (err: any, req: Request, res: Response) => any) => any; basicAuth: (username: string, password: string) => any; } interface HttpClient extends Client { - get: (path?: any, callback?: Function) => any; - head: (path?:any, callback?: Function) => any; - post: (opts?: any, callback?: Function) => any; - put: (opts?: any, callback?: Function) => any; - patch: (opts?: any, callback?: Function) => any; - del: (opts?: any, callback?: Function) => any; + get: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + head: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + post: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + put: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + patch: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; + del: (opts?: string | { path?: string; [name: string]: any }, callback?: Function) => any; } - + interface ThrottleOptions { burst?: number; rate?: number; From 27986da0aa5f78c596bd8068b3e617b9c55b7137 Mon Sep 17 00:00:00 2001 From: Chen Zhutian Date: Wed, 28 Sep 2016 20:24:41 +0800 Subject: [PATCH 041/382] add request.body (#11395) * add request.body * Update koa-bodyparser.d.ts According to the documentation of `koa-bodyparser`: ```javascript // the parsed body will store in this.request.body // if nothing was parsed, body will be an empty object {} ctx.body = ctx.request.body; ``` Therefore the `body` property will exit in the `request` object. Changing the `body` property from optional to required can also fix the conflict problem in Koa's declaration file: ```ts class Koa extend Request, Response {} ``` --- koa-bodyparser/koa-bodyparser.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/koa-bodyparser/koa-bodyparser.d.ts b/koa-bodyparser/koa-bodyparser.d.ts index f8e1b25aae..0daf7cdb2a 100644 --- a/koa-bodyparser/koa-bodyparser.d.ts +++ b/koa-bodyparser/koa-bodyparser.d.ts @@ -18,6 +18,11 @@ declare module "koa-bodyparser" { import * as Koa from "koa"; + module "koa" { + interface Request { + body: any; + } + } function bodyParser(opts?: { /** From 02aed91b3d7e1b0d4226609ac2453f8555491206 Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 28 Sep 2016 08:27:39 -0400 Subject: [PATCH 042/382] Implement tilebelt definition (#11495) --- tilebelt/tilebelt-tests.ts | 29 ++++++ tilebelt/tilebelt.d.ts | 189 +++++++++++++++++++++++++++++++++++++ 2 files changed, 218 insertions(+) create mode 100644 tilebelt/tilebelt-tests.ts create mode 100644 tilebelt/tilebelt.d.ts diff --git a/tilebelt/tilebelt-tests.ts b/tilebelt/tilebelt-tests.ts new file mode 100644 index 0000000000..90c0923f36 --- /dev/null +++ b/tilebelt/tilebelt-tests.ts @@ -0,0 +1,29 @@ +/// +import * as tilebelt from 'tilebelt' + +const lon = 30.5 +const lat = 50.5 +const z = 15 +const tile = [5, 10, 10] +const tiles = [ + [0, 0, 5], + [0, 1, 5], + [1, 1, 5], + [1, 0, 5] +] +const quadkey = '00001033' +const bbox = [ -178.24, 84.70, -177.89, 84.73 ] + +tilebelt.tileToQuadkey(tile) +tilebelt.tileToBBOX(tile) +tilebelt.tileToGeoJSON(tile) +tilebelt.getParent(tile) +tilebelt.getSiblings(tile) +tilebelt.tileToQuadkey(tile) +tilebelt.pointToTile(lon, lat, z) +tilebelt.quadkeyToTile(quadkey) +tilebelt.bboxToTile(bbox) +tilebelt.pointToTileFraction(lon, lat, z) +tilebelt.hasSiblings(tile, tiles) +tilebelt.hasTile(tiles, tile) +tilebelt.tilesEqual(tiles[0], tiles[1]) \ No newline at end of file diff --git a/tilebelt/tilebelt.d.ts b/tilebelt/tilebelt.d.ts new file mode 100644 index 0000000000..c35a803228 --- /dev/null +++ b/tilebelt/tilebelt.d.ts @@ -0,0 +1,189 @@ +// Type definitions for tilebelt 1.0.1 +// Project: https://github.com/mapbox/tilebelt +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const tilebelt: tilebelt.TilebeltStatic; +declare namespace tilebelt { + interface TilebeltStatic { + /** + * Get a geojson representation of a tile + * + * @name tileToGeoJSON + * @param {Array} tile + * @returns {Feature} + * @example + * var poly = tileToGeoJSON([5, 10, 10]) + * //=poly + */ + tileToGeoJSON(tile: Array): GeoJSON.Feature + + /** + * Get the bbox of a tile + * + * @name tileToBBOX + * @param {Array} tile + * @returns {Array} bbox + * @example + * var bbox = tileToBBOX([5, 10, 10]) + * //=bbox + */ + tileToBBOX(tile: Array): Array + + /** + * Get the tile for a point at a specified zoom level + * + * @name pointToTile + * @param {number} lon + * @param {number} lat + * @param {number} z + * @returns {Array} tile + * @example + * var tile = pointToTile(1, 1, 20) + * //=tile + */ + pointToTile(lon: number, lat: number, z: number): Array + + /** + * Get the 4 tiles one zoom level higher + * + * @name getChildren + * @param {Array} tile + * @returns {Array>} tiles + * @example + * var tiles = getChildren([5, 10, 10]) + * //=tiles + */ + getChildren(tile: Array): Array> + + /** + * Get the tile one zoom level lower + * + * @name getParent + * @param {Array} tile + * @returns {Array} tile + * @example + * var tile = getParent([5, 10, 10]) + * //=tile + */ + getParent(tile: Array): Array + + /** + * Get the 3 sibling tiles for a tile + * + * @name getSiblings + * @param {Array} tile + * @returns {Array>} tiles + * @example + * var tiles = getSiblings([5, 10, 10]) + * //=tiles + */ + getSiblings(tile: Array): Array> + + /** + * Check to see if an array of tiles contains a tiles siblings + * + * @name hasSiblings + * @param {Array} tile + * @param {Array>} tiles + * @returns {boolean} + * @example + * var tiles = [ + * [0, 0, 5], + * [0, 1, 5], + * [1, 1, 5], + * [1, 0, 5] + * ] + * hasSiblings([0, 0, 5], tiles) + * //=boolean + */ + hasSiblings(tile: Array, tiles: Array>): boolean + + /** + * Check to see if an array of tiles contains a particular tile + * + * @name hasTile + * @param {Array>} tiles + * @param {Array} tile + * @returns {boolean} + * @example + * var tiles = [ + * [0, 0, 5], + * [0, 1, 5], + * [1, 1, 5], + * [1, 0, 5] + * ] + * hasTile(tiles, [0, 0, 5]) + * //=boolean + */ + hasTile(tiles: Array>, tile: Array): boolean + + /** + * Check to see if two tiles are the same + * + * @name tilesEqual + * @param {Array} tile1 + * @param {Array} tile2 + * @returns {boolean} + * @example + * tilesEqual([0, 1, 5], [0, 0, 5]) + * //=boolean + */ + tilesEqual(tile1: Array, tile2: Array): boolean + + /** + * Get the quadkey for a tile + * + * @name tileToQuadkey + * @param {Array} tile + * @returns {string} quadkey + * @example + * var quadkey = tileToQuadkey([0, 1, 5]) + * //=quadkey + */ + tileToQuadkey(tile: Array): string + + /** + * Get the tile for a quadkey + * + * @name quadkeyToTile + * @param {string} quadkey + * @returns {Array} tile + * @example + * var tile = quadkeyToTile('00001033') + * //=tile + */ + quadkeyToTile(quadkey: string): Array + + /** + * Get the smallest tile to cover a bbox + * + * @name bboxToTile + * @param {Array} bbox + * @returns {Array} tile + * @example + * var tile = bboxToTile([ -178, 84, -177, 85 ]) + * //=tile + */ + bboxToTile(bbox: Array): Array + + /** + * Get the precise fractional tile location for a point at a zoom level + * + * @name pointToTileFraction + * @param {number} lon + * @param {number} lat + * @param {number} z + * @returns {Array} tile fraction + * var tile = pointToTileFraction(30.5, 50.5, 15) + * //=tile + */ + pointToTileFraction(lon: number, lat: number, z: number): Array + } +} + +declare module "tilebelt" { + export = tilebelt +} \ No newline at end of file From 7b9c3257214af878d92693308cd7686cbe1f1384 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:29:10 +0800 Subject: [PATCH 043/382] Add import test (#11476) --- validator/validator-tests.ts | 252 +++++++++++++++++++++++++++++++++++ 1 file changed, 252 insertions(+) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index cc857121bb..fa2f72439f 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -2,6 +2,258 @@ import * as validator from 'validator'; + +/************************************************ +* * +* IMPORT TESTS * +* * +************************************************/ +import { + blacklist as blacklistFunc, + contains as containsFunc, + equals as equalsFunc, + escape as escapeFunc, + isAfter as isAfterFunc, + isAlpha as isAlphaFunc, + isAlphanumeric as isAlphanumericFunc, + isAscii as isAsciiFunc, + isBase64 as isBase64Func, + isBefore as isBeforeFunc, + isBoolean as isBooleanFunc, + isByteLength as isByteLengthFunc, + isCreditCard as isCreditCardFunc, + isCurrency as isCurrencyFunc, + isDataURI as isDataURIFunc, + isDate as isDateFunc, + isDecimal as isDecimalFunc, + isDivisibleBy as isDivisibleByFunc, + isEmail as isEmailFunc, + isFQDN as isFQDNFunc, + isFloat as isFloatFunc, + isFullWidth as isFullWidthFunc, + isHalfWidth as isHalfWidthFunc, + isHexColor as isHexColorFunc, + isHexadecimal as isHexadecimalFunc, + isIP as isIPFunc, + isISBN as isISBNFunc, + isISIN as isISINFunc, + isISO8601 as isISO8601Func, + isIn as isInFunc, + isInt as isIntFunc, + isJSON as isJSONFunc, + isLength as isLengthFunc, + isLowercase as isLowercaseFunc, + isMACAddress as isMACAddressFunc, + isMD5 as isMD5Func, + isMobilePhone as isMobilePhoneFunc, + isMongoId as isMongoIdFunc, + isMultibyte as isMultibyteFunc, + isNull as isNullFunc, + isNumeric as isNumericFunc, + isSurrogatePair as isSurrogatePairFunc, + isURL as isURLFunc, + isUUID as isUUIDFunc, + isUppercase as isUppercaseFunc, + isVariableWidth as isVariableWidthFunc, + isWhitelisted as isWhitelistedFunc, + ltrim as ltrimFunc, + matches as matchesFunc, + normalizeEmail as normalizeEmailFunc, + rtrim as rtrimFunc, + stripLow as stripLowFunc, + toBoolean as toBooleanFunc, + toDate as toDateFunc, + toFloat as toFloatFunc, + toInt as toIntFunc, + trim as trimFunc, + unescape as unescapeFunc, + whitelist as whitelistFunc, +} from 'validator' + +namespace import_tests { + let _blacklist = validator.blacklist; + _blacklist = blacklistFunc; + + let _contains = validator.contains; + _contains = containsFunc; + + let _equals = validator.equals; + _equals = equalsFunc; + + let _escape = validator.escape; + _escape = escapeFunc; + + let _isAfter = validator.isAfter; + _isAfter = isAfterFunc; + + let _isAlpha = validator.isAlpha; + _isAlpha = isAlphaFunc; + + let _isAlphanumeric = validator.isAlphanumeric; + _isAlphanumeric = isAlphanumericFunc; + + let _isAscii = validator.isAscii; + _isAscii = isAsciiFunc; + + let _isBase64 = validator.isBase64; + _isBase64 = isBase64Func; + + let _isBefore = validator.isBefore; + _isBefore = isBeforeFunc; + + let _isBoolean = validator.isBoolean; + _isBoolean = isBooleanFunc; + + let _isByteLength = validator.isByteLength; + _isByteLength = isByteLengthFunc; + + let _isCreditCard = validator.isCreditCard; + _isCreditCard = isCreditCardFunc; + + let _isCurrency = validator.isCurrency; + _isCurrency = isCurrencyFunc; + + let _isDataURI = validator.isDataURI; + _isDataURI = isDataURIFunc; + + let _isDate = validator.isDate; + _isDate = isDateFunc; + + let _isDecimal = validator.isDecimal; + _isDecimal = isDecimalFunc; + + let _isDivisibleBy = validator.isDivisibleBy; + _isDivisibleBy = isDivisibleByFunc; + + let _isEmail = validator.isEmail; + _isEmail = isEmailFunc; + + let _isFQDN = validator.isFQDN; + _isFQDN = isFQDNFunc; + + let _isFloat = validator.isFloat; + _isFloat = isFloatFunc; + + let _isFullWidth = validator.isFullWidth; + _isFullWidth = isFullWidthFunc; + + let _isHalfWidth = validator.isHalfWidth; + _isHalfWidth = isHalfWidthFunc; + + let _isHexColor = validator.isHexColor; + _isHexColor = isHexColorFunc; + + let _isHexadecimal = validator.isHexadecimal; + _isHexadecimal = isHexadecimalFunc; + + let _isIP = validator.isIP; + _isIP = isIPFunc; + + let _isISBN = validator.isISBN; + _isISBN = isISBNFunc; + + let _isISIN = validator.isISIN; + _isISIN = isISINFunc; + + let _isISO8601 = validator.isISO8601; + _isISO8601 = isISO8601Func; + + let _isIn = validator.isIn; + _isIn = isInFunc; + + let _isInt = validator.isInt; + _isInt = isIntFunc; + + let _isJSON = validator.isJSON; + _isJSON = isJSONFunc; + + let _isLength = validator.isLength; + _isLength = isLengthFunc; + + let _isLowercase = validator.isLowercase; + _isLowercase = isLowercaseFunc; + + let _isMACAddress = validator.isMACAddress; + _isMACAddress = isMACAddressFunc; + + let _isMD5 = validator.isMD5; + _isMD5 = isMD5Func; + + let _isMobilePhone = validator.isMobilePhone; + _isMobilePhone = isMobilePhoneFunc; + + let _isMongoId = validator.isMongoId; + _isMongoId = isMongoIdFunc; + + let _isMultibyte = validator.isMultibyte; + _isMultibyte = isMultibyteFunc; + + let _isNull = validator.isNull; + _isNull = isNullFunc; + + let _isNumeric = validator.isNumeric; + _isNumeric = isNumericFunc; + + let _isSurrogatePair = validator.isSurrogatePair; + _isSurrogatePair = isSurrogatePairFunc; + + let _isURL = validator.isURL; + _isURL = isURLFunc; + + let _isUUID = validator.isUUID; + _isUUID = isUUIDFunc; + + let _isUppercase = validator.isUppercase; + _isUppercase = isUppercaseFunc; + + let _isVariableWidth = validator.isVariableWidth; + _isVariableWidth = isVariableWidthFunc; + + let _isWhitelisted = validator.isWhitelisted; + _isWhitelisted = isWhitelistedFunc; + + let _ltrim = validator.ltrim; + _ltrim = ltrimFunc; + + let _matches = validator.matches; + _matches = matchesFunc; + + let _normalizeEmail = validator.normalizeEmail; + _normalizeEmail = normalizeEmailFunc; + + let _rtrim = validator.rtrim; + _rtrim = rtrimFunc; + + let _stripLow = validator.stripLow; + _stripLow = stripLowFunc; + + let _toBoolean = validator.toBoolean; + _toBoolean = toBooleanFunc; + + let _toDate = validator.toDate; + _toDate = toDateFunc; + + let _toFloat = validator.toFloat; + _toFloat = toFloatFunc; + + let _toInt = validator.toInt; + _toInt = toIntFunc; + + let _trim = validator.trim; + _trim = trimFunc; + + let _unescape = validator.unescape; + _unescape = unescapeFunc; + + let _whitelist = validator.whitelist; + _whitelist = whitelistFunc; +} + +/************************************************ +* * +* API TESTS * +* * +************************************************/ let any: any; // ************** From f597aadbe9227b84dcd231c0396d6a93d271621f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:29:27 +0800 Subject: [PATCH 044/382] [validator] Add new stuff which document not mentioned (#11498) * Add new stuff which document not mentioned * Add related test --- validator/validator-tests.ts | 10 ++++++++++ validator/validator.d.ts | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index fa2f72439f..a0ee4a4cbf 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -551,6 +551,16 @@ let any: any; result = validator.whitelist('sample', 'abc'); } +{ + let str: string; + str = validator.toString([123, 456, '123', '456', true, false]); +} + +{ + let ver: string; + ver = validator.version; +} + // ************** // * Extensions * // ************** diff --git a/validator/validator.d.ts b/validator/validator.d.ts index eb09d12b95..02e8eba732 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -213,6 +213,10 @@ declare namespace ValidatorJS { // remove characters that do not appear in the whitelist. The characters are used in a RegExp and so you will // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; + + toString(input: any | any[]): string; + + version: string; // ************** // * Extensions * From bbf7d433237a5e8eb455e74bbd561f614eea9f15 Mon Sep 17 00:00:00 2001 From: Samuel Marks Date: Wed, 28 Sep 2016 22:42:23 +1000 Subject: [PATCH 045/382] http.ServerRequest => http.IncomingMessage (#11500) --- acl/acl.d.ts | 2 +- applicationinsights/applicationinsights.d.ts | 8 ++++---- browser-sync/browser-sync.d.ts | 4 ++-- bufferstream/bufferstream.d.ts | 2 +- busboy/busboy-tests.ts | 2 +- express-serve-static-core/express-serve-static-core.d.ts | 2 +- formidable/formidable-tests.ts | 2 +- multiparty/multiparty-tests.ts | 2 +- multiparty/multiparty.d.ts | 2 +- on-headers/on-headers-tests.ts | 2 +- restify/restify.d.ts | 2 +- urlrouter/urlrouter.d.ts | 2 +- ws/ws-tests.ts | 2 +- 13 files changed, 17 insertions(+), 17 deletions(-) diff --git a/acl/acl.d.ts b/acl/acl.d.ts index d222f9ebb6..eaa728cb2c 100644 --- a/acl/acl.d.ts +++ b/acl/acl.d.ts @@ -20,7 +20,7 @@ declare module "acl" { type Callback = (err: Error) => any; type AnyCallback = (err: Error, obj: any) => any; type AllowedCallback = (err: Error, allowed: boolean) => any; - type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value; + type GetUserId = (req: http.IncomingMessage, res: http.ServerResponse) => Value; interface AclStatic { new (backend: Backend, logger: Logger, options: Option): Acl; diff --git a/applicationinsights/applicationinsights.d.ts b/applicationinsights/applicationinsights.d.ts index 96d5773fa5..45c89556a6 100644 --- a/applicationinsights/applicationinsights.d.ts +++ b/applicationinsights/applicationinsights.d.ts @@ -346,24 +346,24 @@ interface Client { * Log an incoming http request to your server. The request data will be tracked during the response "finish" event if it is successful or the request "error" * event if it fails. The request duration is automatically calculated as the timespan between when the trackRequest method was called, and when the response "finish" * or request "error" events were fired. - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. */ - trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: { + trackRequest(request: any /* http.IncomingMessage */, response: any /* http.ServerResponse */, properties?: { [key: string]: string; }): void; /** * Log an incoming http request to your server. The request data is tracked synchronously rather than waiting for the response "finish"" or request "error"" events. * Use this if you need your request telemetry to respect custom app insights operation and user context (for example if you set any appInsights.client.context.tags). - * @param request The http.ServerRequest object to track + * @param request The http.IncomingMessage object to track * @param response The http.ServerResponse object for this request * @param ellapsedMilliseconds The duration for this request. Defaults to 0. * @param properties map[string, string] - additional data used to filter requests in the portal. Defaults to empty. * @param error An error that was returned for this request if it was unsuccessful. Defaults to null. */ - trackRequestSync(request: any /*http.ServerRequest */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { + trackRequestSync(request: any /*http.IncomingMessage */, response: any /*http.ServerResponse */, ellapsedMilliseconds?: number, properties?: { [key: string]: string;}, error?: any) : void; /** diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 00d234f958..54b42aff4a 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -288,11 +288,11 @@ declare module "browser-sync" { middleware?: MiddlewareHandler; ws: boolean; reqHeaders: (config: any) => Hash; - proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any; + proxyRes: (res: http.ServerResponse, req: http.IncomingMessage, next: Function) => any; } interface MiddlewareHandler { - (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; + (req: http.IncomingMessage, res: http.ServerResponse, next: Function): any; } interface PerRouteMiddleware { diff --git a/bufferstream/bufferstream.d.ts b/bufferstream/bufferstream.d.ts index ee115d0ab5..c43a716d4b 100644 --- a/bufferstream/bufferstream.d.ts +++ b/bufferstream/bufferstream.d.ts @@ -104,7 +104,7 @@ declare module 'bufferstream/postbuffer' { http client buffer */ - constructor(req: http.ServerRequest); + constructor(req: http.IncomingMessage); /* set a callback to get all post data from a http server request */ diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts index 058b5c92d3..11e8b6c9ad 100644 --- a/busboy/busboy-tests.ts +++ b/busboy/busboy-tests.ts @@ -5,7 +5,7 @@ import * as Busboy from 'busboy'; import * as http from 'http'; import * as util from 'util'; -function serverFn(req: http.ServerRequest, res: http.ServerResponse) { +function serverFn(req: http.IncomingMessage, res: http.ServerResponse) { if (req.method === 'POST') { var busboy = new Busboy({ headers: req.headers }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 0371c2bb6a..648f1447a5 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -130,7 +130,7 @@ declare module "express-serve-static-core" { interface Errback { (err: Error): void; } - interface Request extends http.ServerRequest, Express.Request { + interface Request extends http.IncomingMessage, Express.Request { /** * Return request header. diff --git a/formidable/formidable-tests.ts b/formidable/formidable-tests.ts index a0f70a713c..4fdc5ba4cf 100644 --- a/formidable/formidable-tests.ts +++ b/formidable/formidable-tests.ts @@ -48,7 +48,7 @@ if (form.bytesReceived > 100) { if (form.bytesExpected > 100) { } -var req: http.ServerRequest; +var req: http.IncomingMessage; form.parse(req); form.parse(req, (err: any, fields: formidable.Fields, files: formidable.Files) => { diff --git a/multiparty/multiparty-tests.ts b/multiparty/multiparty-tests.ts index 47e6a62f71..e84320ca46 100644 --- a/multiparty/multiparty-tests.ts +++ b/multiparty/multiparty-tests.ts @@ -4,7 +4,7 @@ import multiparty = require('multiparty'); import http = require('http'); import util = require('util'); -http.createServer(function (req: http.ServerRequest, res: http.ServerResponse) { +http.createServer(function (req: http.IncomingMessage, res: http.ServerResponse) { if (req.url === '/upload' && req.method === 'POST') { var count = 0; var form = new multiparty.Form(); diff --git a/multiparty/multiparty.d.ts b/multiparty/multiparty.d.ts index a280c366f8..b0977ff034 100644 --- a/multiparty/multiparty.d.ts +++ b/multiparty/multiparty.d.ts @@ -18,7 +18,7 @@ declare module "multiparty" { * @param request * @param callback */ - parse(request: http.ServerRequest, callback?: (error: Error, fields: any, files: any) => any): void; + parse(request: http.IncomingMessage, callback?: (error: Error, fields: any, files: any) => any): void; } export interface File { diff --git a/on-headers/on-headers-tests.ts b/on-headers/on-headers-tests.ts index 11f33c4ef0..35b62764ed 100644 --- a/on-headers/on-headers-tests.ts +++ b/on-headers/on-headers-tests.ts @@ -6,7 +6,7 @@ import onHeaders = require('on-headers') http.createServer(onRequest) .listen(3000); -function onRequest(req: http.ServerRequest, res: http.ServerResponse) { +function onRequest(req: http.IncomingMessage, res: http.ServerResponse) { onHeaders(res, addPoweredBy); res.setHeader('Content-Type', 'text/plain') res.end('hello!'); diff --git a/restify/restify.d.ts b/restify/restify.d.ts index 65b3f44d47..5f6ca472b1 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -35,7 +35,7 @@ declare module "restify" { } } - interface Request extends http.ServerRequest { + interface Request extends http.IncomingMessage { /** * builds an absolute URI for the request. * @private diff --git a/urlrouter/urlrouter.d.ts b/urlrouter/urlrouter.d.ts index c7a741ac90..0a1fff0d4c 100644 --- a/urlrouter/urlrouter.d.ts +++ b/urlrouter/urlrouter.d.ts @@ -13,7 +13,7 @@ declare module "urlrouter" { namespace UrlRouterInternal { - interface ServerRequest extends http.ServerRequest { + interface ServerRequest extends http.IncomingMessage { params: any; } diff --git a/ws/ws-tests.ts b/ws/ws-tests.ts index 3c85d678cb..4afa12bfe8 100644 --- a/ws/ws-tests.ts +++ b/ws/ws-tests.ts @@ -66,7 +66,7 @@ var WebSocketServer = WebSocket.Server; info: { origin: string secure: boolean - req: http.ServerRequest + req: http.IncomingMessage } , callback: (res: boolean) => void ): void { From 7315e9e81faa9d6e940561f5b25a72762b9719e5 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:44:55 +0800 Subject: [PATCH 046/382] [node] Add events for dgram (#11501) * Add events for dgram * Add tests for dgram * Correct dgram.RemoteInfo interface * Correct emit * Correct emit --- node/node-tests.ts | 88 +++++++++++++++++++++++++++++++++++++++++----- node/node.d.ts | 45 +++++++++++++++++++++++- 2 files changed, 124 insertions(+), 9 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 30ea4bcaa3..623d31c1f9 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -659,14 +659,86 @@ namespace tty_tests { //////////////////////////////////////////////////// namespace dgram_tests { - var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { - }); - ds.bind(); - ds.bind(41234); - var ai: dgram.AddressInfo = ds.address(); - ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { - }); - ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + { + var ds: dgram.Socket = dgram.createSocket("udp4", (msg: Buffer, rinfo: dgram.RemoteInfo): void => { + }); + ds.bind(); + ds.bind(41234); + var ai: dgram.AddressInfo = ds.address(); + ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => { + }); + ds.send(new Buffer("hello"), 5000, "127.0.0.1"); + } + + { + let _socket: dgram.Socket; + let _boolean: boolean; + let _err: Error; + let _str: string; + let _rinfo: dgram.AddressInfo; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + + _socket = _socket.addListener("close", () => {}); + _socket = _socket.addListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.addListener("listening", () => {}); + _socket = _socket.addListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _boolean = _socket.emit("close") + _boolean = _socket.emit("error", _err); + _boolean = _socket.emit("listening"); + _boolean = _socket.emit("message", _str, _rinfo); + + _socket = _socket.on("close", () => {}); + _socket = _socket.on("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.on("listening", () => {}); + _socket = _socket.on("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.once("close", () => {}); + _socket = _socket.once("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.once("listening", () => {}); + _socket = _socket.once("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.prependListener("close", () => {}); + _socket = _socket.prependListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.prependListener("listening", () => {}); + _socket = _socket.prependListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + + _socket = _socket.prependOnceListener("close", () => {}); + _socket = _socket.prependOnceListener("error", (err) => { + let _err: Error = err; + }) + _socket = _socket.prependOnceListener("listening", () => {}); + _socket = _socket.prependOnceListener("message", (msg, rinfo) => { + let _msg: string = msg; + let _rinfo: dgram.AddressInfo = rinfo; + }) + } } //////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 5b807cb5b2..3473ab3281 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1855,8 +1855,8 @@ declare module "dgram" { interface RemoteInfo { address: string; + family: string; port: number; - size: number; } interface AddressInfo { @@ -1894,6 +1894,49 @@ declare module "dgram" { dropMembership(multicastAddress: string, multicastInterface?: string): void; ref(): void; unref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: string, rinfo: AddressInfo): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: string, rinfo: AddressInfo) => void): this; } } From c48f9b3fd516a74fd38c51818b0eae6e98c63d38 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 20:46:43 +0800 Subject: [PATCH 047/382] [node] Add events for tls.Server and tls.TLSSocket (#11502) * Add events for tls.Server * Add tests for tls.Server * Add tests for TLSSocket * Add events for TLSSocket --- node/node-tests.ts | 199 ++++++++++++++++++++++++++++++++++++++++++--- node/node.d.ts | 79 ++++++++++++++++++ 2 files changed, 268 insertions(+), 10 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 623d31c1f9..433435ee13 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -558,17 +558,196 @@ namespace crypto_tests { ////////////////////////////////////////////////// namespace tls_tests { - var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", - }); - var blah = ctx.context; + { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; - var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 - }; - var tlsSocket = tls.connect(connOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); + } + + { + let _server: tls.Server; + let _boolean: boolean; + let _func1 = function(err: Error, resp: Buffer){}; + let _func2 = function(err: Error, sessionData: any){}; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + + _server = _server.addListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.addListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.addListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.addListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.addListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + let _err: Error; + let _tlsSocket: tls.TLSSocket; + let _any: any; + let _func: Function; + let _buffer: Buffer; + _boolean = _server.emit("tlsClientError", _err, _tlsSocket); + _boolean = _server.emit("newSession", _any, _any, _func1); + _boolean = _server.emit("OCSPRequest", _buffer, _buffer, _func); + _boolean = _server.emit("resumeSession", _any, _func2); + _boolean = _server.emit("secureConnection", _tlsSocket); + + _server = _server.on("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.on("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.on("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.on("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.on("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.once("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.once("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.once("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.once("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.once("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.prependListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.prependListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.prependListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.prependListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.prependListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + + _server = _server.prependOnceListener("tlsClientError", (err, tlsSocket) => { + let _err: Error = err; + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + _server = _server.prependOnceListener("newSession", (sessionId, sessionData, callback) => { + let _sessionId: any = sessionId; + let _sessionData: any = sessionData; + let _func1 = callback; + }) + _server = _server.prependOnceListener("OCSPRequest", (certificate, issuer, callback) => { + let _certificate: Buffer = certificate; + let _issuer: Buffer = issuer; + let _callback: Function = callback; + }) + _server = _server.prependOnceListener("resumeSession", (sessionId, callback) => { + let _sessionId: any = sessionId; + let _func2 = callback; + }) + _server = _server.prependOnceListener("secureConnection", (tlsSocket) => { + let _tlsSocket: tls.TLSSocket = tlsSocket; + }) + } + + { + let _TLSSocket: tls.TLSSocket; + let _boolean: boolean; + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + **/ + + _TLSSocket = _TLSSocket.addListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.addListener("secureConnect", () => { }); + + let _buffer: Buffer; + _boolean = _TLSSocket.emit("OCSPResponse", _buffer); + _boolean = _TLSSocket.emit("secureConnect"); + + _TLSSocket = _TLSSocket.on("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.on("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.once("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.once("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.prependListener("secureConnect", () => { }); + + _TLSSocket = _TLSSocket.prependOnceListener("OCSPResponse", (response) => { + let _response: Buffer = response; + }) + _TLSSocket = _TLSSocket.prependOnceListener("secureConnect", () => { }); + } } //////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 3473ab3281..5c016af3fd 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2628,6 +2628,35 @@ declare module "tls" { * @returns {boolean} - Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + **/ + addListener(event: string, listener: Function): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + + on(event: string, listener: Function): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; } export interface TlsOptions { @@ -2686,6 +2715,56 @@ declare module "tls" { }): void; maxConnections: number; connections: number; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + **/ + addListener(event: string, listener: Function): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + addListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: Function): boolean; + emit(event: "resumeSession", sessionId: any, callback: (err: Error, sessionData: any) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: Function): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + on(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: Function): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + once(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: any, sessionData: any, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: Function) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: any, callback: (err: Error, sessionData: any) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } export interface ClearTextStream extends stream.Duplex { From ce70e15ee4639ce8648acfd4b0a81b021e4c7998 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Wed, 28 Sep 2016 16:02:02 +0300 Subject: [PATCH 048/382] [react-router] Update getComponents signatures (#11319) Update `getComponent(s)` all over the place. See #9530 for more info. --- react-router/react-router.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 1a68cc89a5..321adf9bb7 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -169,8 +169,8 @@ declare namespace ReactRouter { path?: RoutePattern component?: RouteComponent components?: RouteComponents - getComponent?: (location: H.Location, cb: (error: any, component?: RouteComponent) => void) => void - getComponents?: (location: H.Location, cb: (error: any, components?: RouteComponents) => void) => void + getComponent?: (nextState: RouterState, cb: (error: any, component?: RouteComponent) => void) => void + getComponents?: (nextState: RouterState, cb: (error: any, components?: RouteComponents) => void) => void onEnter?: EnterHook onLeave?: LeaveHook indexRoute?: PlainRoute @@ -195,8 +195,8 @@ declare namespace ReactRouter { interface IndexRouteProps extends React.Props { component?: RouteComponent components?: RouteComponents - getComponent?: (location: H.Location, cb: (error: any, component?: RouteComponent) => void) => void - getComponents?: (location: H.Location, cb: (error: any, components?: RouteComponents) => void) => void + getComponent?: (nextState: RouterState, cb: (error: any, component?: RouteComponent) => void) => void + getComponents?: (nextState: RouterState, cb: (error: any, components?: RouteComponents) => void) => void onEnter?: EnterHook onLeave?: LeaveHook } From 3518ba75e124a9afae1f18df34043e4a982047eb Mon Sep 17 00:00:00 2001 From: Craig Boland Date: Wed, 28 Sep 2016 08:05:50 -0500 Subject: [PATCH 049/382] Updated jquery.dataTables for 1.10.7. (#11408) * Updated jquery.dataTables for 1.10.7. Version release notes: https://cdn.datatables.net/1.10.7/ * Added any() * Added i18n() Note: selector-modifier support currently exists with interface ObjectSelectorModifier. * Added strong variable typing in jquery.dataTables-tests.ts * For parameter 'def', replaced 'Object' data type with 'any' per TypeScript declaration file guidance. --- jquery.dataTables/jquery.dataTables-tests.ts | 5 +++++ jquery.dataTables/jquery.dataTables.d.ts | 18 +++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 6329861604..09014f39f4 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -311,6 +311,9 @@ $(document).ready(function () { var initSettings = dt.init(); + var i18n: string = dt.i18n('buttons.copy', 'Copy to clipboard'); + i18n = dt.i18n('select.rows', { _: '%d rows selected', 1: '1 row selected' }, 0); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -901,5 +904,7 @@ $(document).ready(function () { //#region "Methods-Util" + var util_1: boolean = dt.any(); + //#endregion "Methods-Util" }); diff --git a/jquery.dataTables/jquery.dataTables.d.ts b/jquery.dataTables/jquery.dataTables.d.ts index 459676f87d..70c72b8570 100644 --- a/jquery.dataTables/jquery.dataTables.d.ts +++ b/jquery.dataTables/jquery.dataTables.d.ts @@ -1,4 +1,4 @@ -// Type definitions for JQuery DataTables 1.10.6 +// Type definitions for JQuery DataTables 1.10.7 // Project: http://www.datatables.net // Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -188,6 +188,17 @@ declare namespace DataTables { */ draw(reset?: boolean): DataTable; + /* + * Look up a language token that was defined in the DataTables' language initialisation object. + * + * @param token The language token to lookup from the language object. + * @param def The default value to use if the DataTables initialisation has not specified a value. + * @param numeric If handling numeric output, the number to be presented should be given in this parameter. If not numeric operator is required (for example button label text) this parameter is not required. + * + * @returns Resulting internationalised string. + */ + i18n(token: string, def: any | string, numeric?: number): string; + /* * Get the initialisation options used for the table. Since: DataTables 1.10.6 */ @@ -412,6 +423,11 @@ declare namespace DataTables { //#region "util-methods" interface UtilityMethods { + /* + * Get a boolean value to indicate if there are any entries in the API instance's result set (i.e. any data, selected rows, etc). + */ + any(): boolean; + /** * Concatenate two or more API instances together * From 3929fe1b6762a5380c717a52f296af3d55740ede Mon Sep 17 00:00:00 2001 From: AKFish Date: Wed, 28 Sep 2016 21:41:30 +0800 Subject: [PATCH 050/382] [HAPI] Add `IStrictSessionHandler` (#11523) * Fix #11519 --- hapi/hapi-8.2.0.d.ts | 8 ++++++-- hapi/hapi-tests-8.2.0.ts | 10 ++++++++++ hapi/hapi-tests.ts | 10 ++++++++++ hapi/hapi.d.ts | 8 ++++++-- 4 files changed, 32 insertions(+), 4 deletions(-) diff --git a/hapi/hapi-8.2.0.d.ts b/hapi/hapi-8.2.0.d.ts index ef81b4fba3..a789915965 100644 --- a/hapi/hapi-8.2.0.d.ts +++ b/hapi/hapi-8.2.0.d.ts @@ -300,8 +300,12 @@ declare module "hapi" { } export interface ISessionHandler { (request: Request, reply: IReply): void; + } + + export interface IStrictSessionHandler{ (request: Request, reply: IStrictReply): void; } + export interface IRequestHandler { (request: Request): T; } @@ -464,7 +468,7 @@ declare module "hapi" { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** an optional unique identifier used to look up the route using server.lookup(). */ id?: number; /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ @@ -834,7 +838,7 @@ declare module "hapi" { /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ vhost?: string; /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler: ISessionHandler | string | IRouteHandlerConfig; + handler: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } diff --git a/hapi/hapi-tests-8.2.0.ts b/hapi/hapi-tests-8.2.0.ts index e26ce193bc..012e913432 100644 --- a/hapi/hapi-tests-8.2.0.ts +++ b/hapi/hapi-tests-8.2.0.ts @@ -124,5 +124,15 @@ server.route([{ } }]); +// Implict handler +server.route({ + method: 'GET', + path: '/hello6', + handler: function (request, reply) { + request.log('info', { route: '/hello' }, Date.now()); + reply('hello world'); + } +}); + // Start the server server.start(); diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index 3288618816..c33e934611 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -112,6 +112,16 @@ server.route([{ } }]); +// Implict handler +server.route({ + method: 'GET', + path: '/hello6', + handler: function (request, reply) { + request.log('info', { route: '/hello' }, Date.now()); + reply('hello world'); + } +}); + // config.validate parameters should be optional server.route([{ method: 'GET', diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index ff5e1d9fe8..9c01eb741d 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -330,8 +330,12 @@ declare module "hapi" { export interface ISessionHandler { (request: Request, reply: IReply): void; + } + + export interface IStrictSessionHandler { (request: Request, reply: IStrictReply): void; } + export interface IRequestHandler { (request: Request): T; } @@ -495,7 +499,7 @@ declare module "hapi" { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** an optional unique identifier used to look up the route using server.lookup(). */ id?: number; /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ @@ -894,7 +898,7 @@ declare module "hapi" { /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ vhost?: string; /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler?: ISessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } From 351b4c7598c689337b8ce2c82543f902f8b30045 Mon Sep 17 00:00:00 2001 From: nkovacic Date: Wed, 28 Sep 2016 15:47:15 +0200 Subject: [PATCH 051/382] Added FileResizeOptions for the changed resize function call --- ng-file-upload/ng-file-upload-tests.ts | 12 +++++++++++- ng-file-upload/ng-file-upload.d.ts | 21 +++++++++++++++++---- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/ng-file-upload/ng-file-upload-tests.ts b/ng-file-upload/ng-file-upload-tests.ts index f7fdcf1015..ff3044977a 100644 --- a/ng-file-upload/ng-file-upload-tests.ts +++ b/ng-file-upload/ng-file-upload-tests.ts @@ -78,7 +78,17 @@ class UploadController { fileWithNewName = this.Upload.rename(files[0], "newName.jpg"); this.Upload - .resize(files[0], 1024, 1024, 0.7, 'image/jpeg', 0.9, true) + .resize(files[0], { + height: 1024, + width: 1024, + quality: 0.7, + ratio: 0.9, + centerCrop: true, + restoreExif: true, + resizeIf: (width, height) => { + return true; + } + }) .then((resizedFile) => { console.log(resizedFile); }); diff --git a/ng-file-upload/ng-file-upload.d.ts b/ng-file-upload/ng-file-upload.d.ts index 41b0331dbe..2700a5d206 100644 --- a/ng-file-upload/ng-file-upload.d.ts +++ b/ng-file-upload/ng-file-upload.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular File Upload 11.1.1 +// Type definitions for Angular File Upload 12.2.12 // Project: https://github.com/danialfarid/ng-file-upload // Definitions by: John Reilly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -92,6 +92,20 @@ declare namespace angular.angularFileUpload { ngfValidateForce?: boolean; } + interface ResizeIfFunction { + (width: number, height: number): boolean; + } + + interface FileResizeOptions { + centerCrop?: boolean; + height?: number; + ratio?: number; + resizeIf?: ResizeIfFunction; + restoreExif?: boolean; + quality?: number; + width?: number; + } + interface IUploadService { /** * Convert a single file or array of files to a single or array of @@ -166,7 +180,7 @@ declare namespace angular.angularFileUpload { * @param {string} newName * @return {File} */ - rename(file: File, newName: string): File; + rename(file: File, newName: string): Blob; /** * Resizes an image. Returns a promise * @@ -179,8 +193,7 @@ declare namespace angular.angularFileUpload { * @param {boolean} [centerCrop] * @return {angular.IPromise} */ - resize(file: File, width?: number, height?: number, quality?: number, type?: string, - ratio?: number | string, centerCrop?: boolean): angular.IPromise; + resize(file: File, options: FileResizeOptions): angular.IPromise; /** * Set the default values for ngf-select and ngf-drop directives * From 462850812b7b471d6d8d01223accb3ca282b8731 Mon Sep 17 00:00:00 2001 From: Maux Date: Wed, 28 Sep 2016 23:49:22 +1000 Subject: [PATCH 052/382] getEvent should not be set to void it should return a value (#11135) * getEvent should not be set to void it should return a value * Add type to getActionData for testing * pnotify Add type fpr notice styling and state * fix pnotify test * Remove Generics and replaces by return any * convert space tp tabs --- dhtmlxscheduler/dhtmlxscheduler.d.ts | 60 +++++++++++++------------- jquery.pnotify/jquery.pnotify-tests.ts | 4 +- jquery.pnotify/jquery.pnotify.d.ts | 14 +++--- 3 files changed, 37 insertions(+), 41 deletions(-) diff --git a/dhtmlxscheduler/dhtmlxscheduler.d.ts b/dhtmlxscheduler/dhtmlxscheduler.d.ts index 40123827ca..3f075861ab 100644 --- a/dhtmlxscheduler/dhtmlxscheduler.d.ts +++ b/dhtmlxscheduler/dhtmlxscheduler.d.ts @@ -3,12 +3,12 @@ // Definitions by: Maksim Kozhukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface SchedulerCallback { (...args: any[]) : any } +interface SchedulerCallback { (...args: any[]): any } interface SchedulerFilterCallback { (id: string | number, event: any): boolean } -type SchedulerEventName ='onAfterEventDisplay'|'onAfterFolderToggle'|'onAfterLightbox'|'onAfterSchedulerResize'|'onBeforeCollapse'|'onBeforeDrag'|'onBeforeEventChanged'|'onBeforeEventCreated'|'onBeforeEventDelete'|'onBeforeEventDisplay'|'onBeforeEventDragIn'|'onBeforeEventDragOut'|'onBeforeExpand'|'onBeforeExternalDragIn'|'onBeforeFolderToggle'|'onBeforeLightbox'|'onBeforeSectionRender'|'onBeforeTodayDisplayed'|'onBeforeTooltip'|'onBeforeViewChange'|'onCellClick'|'onCellDblClick'|'onClearAll'|'onClick'|'onCollapse'|'onConfirmedBeforeEventDelete'|'onContextMenu'|'onDblClick'|'onDragEnd'|'onEmptyClick'|'onEventAdded'|'onEventCancel'|'onEventChanged'|'onEventCollision'|'onEventCopied'|'onEventCreated'|'onEventCut'|'onEventDeleted'|'onEventDrag'|'onEventDragIn'|'onEventDragOut'|'onEventDropOut'|'onEventIdChange'|'onEventLoading'|'onEventPasted'|'onEventSave'|'onExpand'|'onExternalDragIn'|'onLightbox'|'onLightboxButton'|'onLimitViolation'|'onLoadError'|'onLocationError'|'onMouseDown'|'onMouseMove'|'onOptionsLoad'|'onOptionsLoadFinal'|'onOptionsLoadStart'|'onSaveError'|'onScaleAdd'|'onScaleDblClick'|'onSchedulerReady'|'onSchedulerResize'|'onTemplatesReady'|'onTimelineCreated'|'onViewChange'|'onViewMoreClick'|'onXLE'|'onXLS'|'onXScaleClick'|'onXScaleDblClick'|'onYScaleClick'|'onYScaleDblClick'; +type SchedulerEventName = 'onAfterEventDisplay' | 'onAfterFolderToggle' | 'onAfterLightbox' | 'onAfterSchedulerResize' | 'onBeforeCollapse' | 'onBeforeDrag' | 'onBeforeEventChanged' | 'onBeforeEventCreated' | 'onBeforeEventDelete' | 'onBeforeEventDisplay' | 'onBeforeEventDragIn' | 'onBeforeEventDragOut' | 'onBeforeExpand' | 'onBeforeExternalDragIn' | 'onBeforeFolderToggle' | 'onBeforeLightbox' | 'onBeforeSectionRender' | 'onBeforeTodayDisplayed' | 'onBeforeTooltip' | 'onBeforeViewChange' | 'onCellClick' | 'onCellDblClick' | 'onClearAll' | 'onClick' | 'onCollapse' | 'onConfirmedBeforeEventDelete' | 'onContextMenu' | 'onDblClick' | 'onDragEnd' | 'onEmptyClick' | 'onEventAdded' | 'onEventCancel' | 'onEventChanged' | 'onEventCollision' | 'onEventCopied' | 'onEventCreated' | 'onEventCut' | 'onEventDeleted' | 'onEventDrag' | 'onEventDragIn' | 'onEventDragOut' | 'onEventDropOut' | 'onEventIdChange' | 'onEventLoading' | 'onEventPasted' | 'onEventSave' | 'onExpand' | 'onExternalDragIn' | 'onLightbox' | 'onLightboxButton' | 'onLimitViolation' | 'onLoadError' | 'onLocationError' | 'onMouseDown' | 'onMouseMove' | 'onOptionsLoad' | 'onOptionsLoadFinal' | 'onOptionsLoadStart' | 'onSaveError' | 'onScaleAdd' | 'onScaleDblClick' | 'onSchedulerReady' | 'onSchedulerResize' | 'onTemplatesReady' | 'onTimelineCreated' | 'onViewChange' | 'onViewMoreClick' | 'onXLE' | 'onXLS' | 'onXScaleClick' | 'onXScaleDblClick' | 'onYScaleClick' | 'onYScaleDblClick'; -interface SchedulerTemplates{ +interface SchedulerTemplates { /** * specifies the date in the header of the view * @param start the start date of the view @@ -458,7 +458,7 @@ interface SchedulerTemplates{ } -interface SchedulerConfigOptions{ +interface SchedulerConfigOptions { /** * 'says' to present the numbers of days in the Month view as clickable links that open the related day in the specified view */ @@ -477,12 +477,12 @@ interface SchedulerConfigOptions{ /** * specifies how to display the default error notification in case the XML data loading failed */ - ajax_error: string|boolean; + ajax_error: string | boolean; /** * 'says' to show multi-day events in the regular way (as one-day events are displayed) */ - all_timed: boolean|string; + all_timed: boolean | string; /** * sets the date format that will be used by the addEvent() method to parse the start_date, end_date properties in case they are specified as strings @@ -812,7 +812,7 @@ interface SchedulerConfigOptions{ /** * sets the height of the area that displays multi-day events */ - multi_day_height_limit: number|boolean; + multi_day_height_limit: number | boolean; /** * enables the possibility to render the same events in several sections of the Timeline or Units view @@ -942,12 +942,12 @@ interface SchedulerConfigOptions{ /** * enables/disables the touch support in the scheduler */ - touch: boolean|string; + touch: boolean | string; /** * defines the time period in milliseconds that is used to differ the long touch gesture from the scroll gesture */ - touch_drag: number|boolean; + touch_drag: number | boolean; /** * enables/disables prompting messages in the right top corner of the screen @@ -996,7 +996,7 @@ interface SchedulerConfigOptions{ } -interface SchedulerDateHelpers{ +interface SchedulerDateHelpers { add(origin: Date, count: number, unit: string): Date; copy(origin: Date): Date; @@ -1017,19 +1017,19 @@ interface SchedulerDateHelpers{ to_fixed(value: number): string; } -interface SchedulerHotkeys{ +interface SchedulerHotkeys { edit_save: number; edit_cancel: number; } -interface SchedulerLocaleDate{ +interface SchedulerLocaleDate { month_full: string[]; month_short: string[]; day_full: string[]; day_short: string[]; } -interface SchedulerLocaleLabels{ +interface SchedulerLocaleLabels { dhx_cal_today_button: string; day_tab: string; week_tab: string; @@ -1046,13 +1046,13 @@ interface SchedulerLocaleLabels{ section_time: string; } -interface SchedulerLocale{ +interface SchedulerLocale { date: SchedulerLocaleDate; labels: SchedulerLocaleLabels; } -interface SchedulerSizes{ +interface SchedulerSizes { /** * the height of day cells in the month view */ @@ -1124,14 +1124,14 @@ interface SchedulerSizes{ scroll_width: number; } -interface SchedulerEnterprise{ +interface SchedulerEnterprise { /** * Creates a new instance of Scheduler */ getSchedulerInstance(): SchedulerStatic; } -interface SchedulerStatic{ +interface SchedulerStatic { templates: SchedulerTemplates; config: SchedulerConfigOptions; date: SchedulerDateHelpers; @@ -1238,7 +1238,7 @@ interface SchedulerStatic{ * @param time_points an array [start_minute,end_minute,..,start_minute_N,end_minute_N],
where each pair sets a certain limit range. The array can have any number of
such pairs * @param items defines specific items of view(s) to block */ - blockTime(date: Date|number, time_points: any[], items?: any): void; + blockTime(date: Date | number, time_points: any[], items?: any): void; /** * calls an inner event @@ -1327,7 +1327,7 @@ interface SchedulerStatic{ * deletes the specified event * @param id the event's id */ - deleteEvent(id: string|number): void; + deleteEvent(id: string | number): void; /** * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods @@ -1393,39 +1393,39 @@ interface SchedulerStatic{ * returns the event object by its id * @param event_id the event's id */ - getEvent(event_id: string|number): void; + getEvent(event_id: string | number): any; /** * gets the event's end date * @param id the event's id */ - getEventEndDate(id: string): Date; + getEventEndDate(id: string | number): Date; /** * gets the event's start date * @param id the event's id */ - getEventStartDate(id: string): Date; + getEventStartDate(id: string | number): Date; /** * gets the event's text * @param id the event's id */ - getEventText(id: string): string; + getEventText(id: string | number): string; /** * returns a collection of events which occur during the specified period * @param from the start date of the period * @param to the end date of the period */ - getEvents(from?: Date, to?: Date): void; + getEvents(from?: Date, to?: Date): any; /** * gets the label of a select control in the lightbox * @param property the name of a data property that the control is mapped to * @param key the option's id. This parameter is compared with the event's data property
to assign the select's option to an event */ - getLabel(property: string, key: string|number): void; + getLabel(property: string, key: string | number): any; /** * gets the lightbox's HTML object element @@ -1486,7 +1486,7 @@ interface SchedulerStatic{ * @param date the initial date of the scheduler (by default, the current date) * @param view the name of the initial view (by default, "week") */ - init(container: string|HTMLElement, date?: Date, view?: string): void; + init(container: string | HTMLElement, date?: Date, view?: string): void; /** * inverts the specified time zones @@ -1497,7 +1497,7 @@ interface SchedulerStatic{ /** * checks whether the calendar is currently opened in the scheduler */ - isCalendarVisible(): boolean|HTMLElement; + isCalendarVisible(): boolean | HTMLElement; /** * checks whether the specified event one-day or multi-day @@ -1607,7 +1607,7 @@ interface SchedulerStatic{ * @param id the event's id * @param event the event object */ - setEvent(id: string|number, event: any): void; + setEvent(id: string | number, event: any): void; /** * sets the event's end date @@ -1739,7 +1739,7 @@ interface SchedulerStatic{ * removes marking/blocking set by the markTimespan() method * @param divs a timespan to remove marking/blocking from (or an array of timespans) */ - unmarkTimespan(divs: HTMLElement|any[]): void; + unmarkTimespan(divs: HTMLElement | any[]): void; /** * unselects the specified event @@ -1776,7 +1776,5 @@ interface SchedulerStatic{ } - - declare var scheduler: SchedulerStatic; declare var Scheduler: SchedulerEnterprise; \ No newline at end of file diff --git a/jquery.pnotify/jquery.pnotify-tests.ts b/jquery.pnotify/jquery.pnotify-tests.ts index 8704da19f3..d0f2c4475e 100644 --- a/jquery.pnotify/jquery.pnotify-tests.ts +++ b/jquery.pnotify/jquery.pnotify-tests.ts @@ -223,7 +223,7 @@ function test_pnotify() { }); var type = "error"; - var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25}; + var stack_bottomright = { "dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25 }; var opts = { title: "Over Here", @@ -233,8 +233,8 @@ function test_pnotify() { width: "100%", stack: stack_bottomright, type: "error" + } as PNotifyOptions; - }; new PNotify(opts); new PNotify({ diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index 8daee5da1e..03a1e91c1c 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -4,11 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// - -// could not pass the Travis Test if enabled -//type NoticeTypeOptions = "notice" | "info" | "success" | "error"; -//type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; -//type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; +type NoticeTypeOptions = "notice" | "info" | "success" | "error"; +type StylingOptions = "brighttheme" | "jqueryui" | "bootstrap2" | "bootstrap3" | "fontawesome"; +type StateOptions = "initializing" | "opening" | "open" | "closing" | "closed"; interface PNotifyStack { dir1?: string; @@ -137,7 +135,7 @@ interface PNotifyOptions { /** * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ - styling?: string; + styling?: StylingOptions; /** * Additional classes to be added to the notice. (For custom styling.) */ @@ -182,7 +180,7 @@ interface PNotifyOptions { /** * Type of the notice. "notice", "info", "success", or "error". */ - type?: string; + type?: NoticeTypeOptions; /** * Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. */ @@ -263,7 +261,7 @@ interface PNotify { /** * The state can be "initializing", "opening", "open", "closing", and "closed" */ - state?: string; + state?: StateOptions; /** * This function is for updating the notice. From f65b3822d91e01e95d80e9f1e02bf21468709256 Mon Sep 17 00:00:00 2001 From: Yvo Date: Wed, 28 Sep 2016 09:52:20 -0400 Subject: [PATCH 053/382] Add barTintColor to NavigatorIOS (#11522) --- react-native/react-native.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index 4973fa08f9..e3e0cf0209 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -1591,7 +1591,11 @@ declare namespace __React { export interface NavigatorIOSProperties extends React.Props { - + /** + * The background color of the navigation bar + */ + barTintColor?: string + /** * NavigatorIOS uses "route" objects to identify child views, their props, and navigation bar configuration. * "push" and all the other navigation operations expect routes to be like this From 750936896bacf9027eccc80228822f4f131a77a5 Mon Sep 17 00:00:00 2001 From: lucap86 Date: Wed, 28 Sep 2016 15:52:35 +0200 Subject: [PATCH 054/382] GreenSock TweenMax TweenLite config Object typed refs #11265 (#11310) * refs #9944 * refs #11265 * refs #11265 --- greensock/greensock.d.ts | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/greensock/greensock.d.ts b/greensock/greensock.d.ts index a3b3801775..004ec79dab 100644 --- a/greensock/greensock.d.ts +++ b/greensock/greensock.d.ts @@ -13,7 +13,38 @@ interface IDispatcher { declare type Tween = TweenLite | TweenMax; declare type Timeline = SimpleTimeline | TimelineLite | TimelineMax; - +declare type TweenConfig = { + [tweenProp: string]: any; + delay?: number; + ease?: Ease; + repeat?: number; + repeatDelay?: number; + yoyo?: boolean; + paused?: boolean; + overwrite?: string|number; + onComplete?: Function; + immediateRender?: boolean; + onCompleteParams?: any[]; + onCompleteScope?: Object; + onRepeat?: Function; + onRepeatScope?: Object; + onReverseComplete?: Function; + onReverseCompleteParams?: any[]; + onReverseCompleteScope?: Object; + onStart?: Function; + onStartParams?: any[]; + onStartScope?: Object; + onUpdate?: Function; + onUpdateParams?: any[]; + onUpdateScope?: Object; + startAt?: Object; + useFrames?: boolean; + lazy?: boolean; + onOverwrite?: Function; + autoCSS?: boolean; + callbackScope?: Object; +} + //com.greensock.core declare class Animation { static ticker: IDispatcher; @@ -86,7 +117,7 @@ declare class TweenLite extends Animation { static killTweensOf(target: Object, onlyActive?: boolean, vars?: Object): void; static lagSmoothing(threshold: number, adjustedLag: number): void; static set(target: Object, vars: Object): TweenLite; - static to(target: Object, duration: number, vars: Object): TweenLite; + static to(target: Object, duration: number, vars: TweenConfig): TweenLite; } declare class TweenMax extends TweenLite { @@ -112,7 +143,7 @@ declare class TweenMax extends TweenLite { static staggerFrom(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; static staggerFromTo(targets: any, duration: number, fromVars: Object, toVars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; static staggerTo(targets: any, duration: number, vars: Object, stagger: number, onCompleteAll?: Function, onCompleteAllParams?: any[], onCompleteAllScope?: any): any[]; - static to(target:Object, duration:number, vars:Object):TweenMax; + static to(target:Object, duration:number, vars:TweenConfig):TweenMax; updateTo(vars: Object, resetDuration?: boolean): TweenMax; yoyo(): boolean; yoyo(value?: boolean): TweenMax; From 881408c91909383843f7cf10de4f39fcd71baa06 Mon Sep 17 00:00:00 2001 From: Prashant Tiwari Date: Wed, 28 Sep 2016 19:24:45 +0530 Subject: [PATCH 055/382] Call strategy with only mode or options (#11466) * Call strategy with only mode or options * Refactor `server.auth.strategy` --- hapi/hapi.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 9c01eb741d..a25ecff38d 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1876,7 +1876,9 @@ declare module "hapi" { } } });*/ - strategy(name: string, scheme: any, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string): void; + strategy(name: string, scheme: string, options?:any): void; /** server.auth.test(strategy, request, next) Tests a request against an authentication strategy where: From 15345f88562b77cbf03013382581838bf97813d3 Mon Sep 17 00:00:00 2001 From: panoti Date: Wed, 28 Sep 2016 21:01:54 +0700 Subject: [PATCH 056/382] - add client.exists([params, [callback]]) (#11515) --- elasticsearch/elasticsearch.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index 2816a0dee0..26a9a1e880 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -15,6 +15,8 @@ declare module Elasticsearch { create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; + exists(params: ExistsParams): PromiseLike; + exists(params: ExistsParams, callback: (error: any, response: any, status?: any) => void): void; get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; @@ -95,6 +97,7 @@ declare module Elasticsearch { method?: string; body?: any; ignore?: number | number[]; + filterPath?: string | string[]; } export interface BulkIndexDocumentsParams extends GenericParams { @@ -205,6 +208,17 @@ declare module Elasticsearch { _source: T; } + export interface ExistsParams extends GenericParams { + id: string; + index: string; + parent?: string; + preference?: string; + realtime?: boolean; + refresh?: boolean; + routing?: string; + type: string; + } + export interface IndexDocumentParams extends GenericParams { index: string; type: string; From 32b5d0a12c4a8e5be4e51c82d8636de022b6b4ec Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Wed, 28 Sep 2016 07:23:24 -0700 Subject: [PATCH 057/382] Update to Electron 1.4.1 (#11481) --- github-electron/github-electron.d.ts | 62 ++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 64b7cf6a02..9541d64ac6 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.6 +// Type definitions for Electron v1.4.1 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -176,7 +176,7 @@ declare namespace Electron { /** * Emitted when the gpu process crashes. */ - on(event: 'gpu-process-crashed', listener: Function): this; + on(event: 'gpu-process-crashed', listener: (event: Event, killed: boolean) => void): this; /** * Emitted when Chrome's accessibility support changes. * @@ -841,6 +841,11 @@ declare namespace Electron { * 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. @@ -2589,6 +2594,7 @@ declare namespace Electron { 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; /** @@ -2769,8 +2775,18 @@ declare namespace Electron { referrer: string; method: string; uploadData?: { + /** + * Content being sent. + */ bytes: Buffer, - file: string + /** + * Path of file being uploaded. + */ + file: string, + /** + * UUID of blob data. Use session.getBlobData method to retrieve the data. + */ + blobUUID: string; }[]; } @@ -3016,6 +3032,10 @@ declare namespace Electron { * @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. */ @@ -3317,6 +3337,10 @@ declare namespace Electron { * 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 { @@ -3495,6 +3519,11 @@ declare namespace Electron { * Get system preferences. */ interface SystemPreferences { + /** + * Note: This is only implemented on Windows. + */ + on(event: 'accent-color-changed', listener: (event: Event, newColor: string) => void): this; + on(event: string, listener: Function): this; /** * @returns If the system is in Dark Mode. * @@ -3549,13 +3578,17 @@ declare namespace Electron { */ getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url' | 'array' | 'dictionary'): any; /** - * This method returns true if DWM composition (Aero Glass) is enabled, - * and false otherwise. You can use it to determine if you should create - * a transparent window or not (transparent windows won’t work correctly when DWM composition is disabled). + * @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; } // https://github.com/electron/electron/blob/master/docs/api/tray.md @@ -3822,7 +3855,7 @@ declare namespace Electron { /** * Emitted when the renderer process has crashed. */ - on(event: 'crashed', listener: Function): this; + on(event: 'crashed', listener: (event: Event, killed: boolean) => void): this; /** * Emitted when a plugin process has crashed. */ @@ -4237,6 +4270,10 @@ declare namespace Electron { * 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. */ @@ -4438,7 +4475,7 @@ declare namespace Electron { [key: string]: string; } - type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'other'; + type NewWindowDisposition = 'default' | 'foreground-tab' | 'background-tab' | 'new-window' | 'save-to-disk' | 'other'; /** * Specifies the action to take place when ending webContents.findInPage request. @@ -4881,6 +4918,15 @@ declare namespace Electron { * 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://. */ From 7be68adbdff4bea14f33f54f27d3bdb5822e3b10 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 28 Sep 2016 22:34:18 +0800 Subject: [PATCH 058/382] Correct fs.createWriteStream (#11560) --- node/node.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 5c016af3fd..0f2374ae10 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2321,6 +2321,8 @@ declare module "fs" { encoding?: string; fd?: number; mode?: number; + autoClose?: boolean; + start?: number; }): WriteStream; export function fdatasync(fd: number, callback: Function): void; export function fdatasyncSync(fd: number): void; From b8cdd448dd9bc6236fef31a11aa6bd1daf074739 Mon Sep 17 00:00:00 2001 From: vargeek Date: Wed, 28 Sep 2016 23:11:03 +0800 Subject: [PATCH 059/382] add declaration file for weapp (#11554) * add declaration file of weapp * rename "weapp" to "weapp-api" rename "weapp" to "weapp-api" to avoid naming conflicts --- weapp-api/weapp-api-tests.ts | 678 ++++++++++++++++++++ weapp-api/weapp-api.d.ts | 1135 ++++++++++++++++++++++++++++++++++ 2 files changed, 1813 insertions(+) create mode 100644 weapp-api/weapp-api-tests.ts create mode 100644 weapp-api/weapp-api.d.ts diff --git a/weapp-api/weapp-api-tests.ts b/weapp-api/weapp-api-tests.ts new file mode 100644 index 0000000000..0b249701c6 --- /dev/null +++ b/weapp-api/weapp-api-tests.ts @@ -0,0 +1,678 @@ +/// + + +App({ + onLaunch: function () { + //调用API从本地缓存中获取数据 + var logs = wx.getStorageSync('logs') as Array || [] + logs.unshift(Date.now()) + wx.setStorageSync('logs', logs) + }, + getUserInfo: function (cb: Function) { + var that = this; + if (this.globalData.userInfo) { + typeof cb == "function" && cb(this.globalData.userInfo) + } else { + //调用登录接口 + wx.login({ + success: function () { + wx.getUserInfo({ + success: function (res) { + that.globalData.userInfo = res.userInfo; + typeof cb == "function" && cb(that.globalData.userInfo) + } + }) + } + }); + } + }, + globalData: { + userInfo: null + } +}) + + +let app = getApp(); +let page = app.getCurrentPage(); +page.setData({ 'foo': 'bar' }); +Page({ + data: { + foo: 'bar' + }, + onLoad: function (options) { + console.log(options.title); + } +}) + + +wx.request({ + url: 'test.php', + data: { + x: '', + y: '' + }, + header: { + 'Content-Type': 'application/json' + }, + success: function (res) { + console.log(res.data) + } +}) + +wx.chooseImage({ + success: function (res) { + var tempFilePaths = res.tempFilePaths + wx.uploadFile({ + url: 'http://example.com/upload', + filePath: tempFilePaths[0], + name: 'file', + formData: { + 'user': 'test' + } + }) + } +}) + +wx.downloadFile({ + url: 'http://example.com/audio/123', + type: 'audio', + success: function (res) { + wx.playVoice({ + filePath: res.tempFilePath + }) + } +}) + +wx.connectSocket({ + url: 'test.php', + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + method: "GET", +}) + +wx.connectSocket({ + url: 'test.php' +}) +wx.onSocketOpen(function (res) { + console.log('WebSocket连接已打开!') +}) + +wx.connectSocket({ + url: 'test.php' +}) +wx.onSocketOpen(function (res) { + console.log('WebSocket连接已打开!') +}) +wx.onSocketError(function (res) { + console.log('WebSocket连接打开失败,请检查!') +}) + +var socketOpen = false +var socketMsgQueue: Array = [] +wx.connectSocket({ + url: 'test.php' +}) + +wx.onSocketOpen(function (res) { + socketOpen = true + for (var i = 0; i < socketMsgQueue.length; i++) { + sendSocketMessage(socketMsgQueue[i]) + } + socketMsgQueue = [] +}) + +function sendSocketMessage(msg: string) { + if (socketOpen) { + wx.sendSocketMessage({ + data: msg + }) + } else { + socketMsgQueue.push(msg) + } +} + +wx.connectSocket({ + url: 'test.php' +}) + +wx.onSocketMessage(function (res) { + console.log('收到服务器内容:' + res.data) +}) + +wx.connectSocket({ + url: 'test.php' +}) + +//注意这里有时序问题, +//如果 wx.connectSocket 还没回调 wx.onSocketOpen,而先调用 wx.closeSocket,那么就做不到关闭 WebSocket 的目的。 +//必须在 WebSocket 打开期间调用 wx.closeSocket 才能关闭。 +wx.onSocketOpen(function () { + wx.closeSocket() +}) + +wx.onSocketClose(function (res) { + console.log('WebSocket 已关闭!') +}) + +wx.chooseImage({ + count: 1, // 默认9 + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success: function (res) { + // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 + var tempFilePaths = res.tempFilePaths + } +}) + +wx.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [] // 需要预览的图片http链接列表 +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + }, + fail: function (res) { + //录音失败 + } +}) +setTimeout(function () { + //结束录音 + wx.stopRecord() +}, 10000) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath, + complete: function () { + } + }) + } +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath + }) + + setTimeout(function () { + //暂停播放 + wx.pauseVoice() + }, 5000) + } +}) + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.playVoice({ + filePath: tempFilePath + }) + + setTimeout(function () { + wx.stopVoice() + }, 5000) + } +}) + +wx.getBackgroundAudioPlayerState({ + success: function (res) { + var status = res.status + var dataUrl = res.dataUrl + var currentPosition = res.currentPosition + var duration = res.duration + var downloadPercent = res.downloadPercent + } +}) + +wx.playBackgroundAudio({ + dataUrl: '', + title: '', + coverImgUrl: '' +}) + +wx.pauseBackgroundAudio() + +wx.seekBackgroundAudio({ + position: 30 +}) +wx.stopBackgroundAudio() + +wx.startRecord({ + success: function (res) { + var tempFilePath = res.tempFilePath + wx.saveFile({ + tempFilePath: tempFilePath, + success: function (res) { + var savedFilePath = res.savedFilePath + } + }) + } +}) + + +Page({ + bindButtonTap: function () { + var that = this + wx.chooseVideo({ + sourceType: ['album', 'camera'], + maxDuration: 60, + camera: ['front', 'back'], + success: function (res) { + that.setData({ + src: res.tempFilePath + }) + } + }) + } +}) + +wx.setStorage({ + key: "key", + data: "value" +}) + +try { + wx.setStorageSync('key', 'value') +} catch (e) { +} + +wx.getStorage({ + key: 'key', + success: function (res) { + console.log(res.data) + } +}) + + +var value = wx.getStorageSync('key') +if (value) { + // Do something with return value +} + + +wx.clearStorage() + + +try { + wx.clearStorageSync() +} catch (e) { +} + + +wx.getLocation({ + type: 'wgs84', + success: function (res) { + var latitude = res.latitude + var longitude = res.longitude + var speed = res.speed + var accuracy = res.accuracy + } +}) + +wx.getLocation({ + type: 'gcj02', //返回可以用于wx.openLocation的经纬度 + success: function(res) { + var latitude = res.latitude + var longitude = res.longitude + wx.openLocation({ + latitude: latitude, + longitude: longitude, + scale: 28 + }) + } +}) + +wx.getNetworkType({ + success: function(res) { + var networkType = res.networkType // 返回网络类型2g,3g,4g,wifi + } +}) + +wx.getSystemInfo({ + success: function(res) { + console.log(res.model) + console.log(res.pixelRatio) + console.log(res.windowWidth) + console.log(res.windowHeight) + console.log(res.language) + console.log(res.version) + } +}) + +wx.onAccelerometerChange(function(res) { + console.log(res.x) + console.log(res.y) + console.log(res.z) +}) + +wx.onCompassChange(function (res) { + console.log(res.direction) +}) + +wx.setNavigationBarTitle({ + title: '当前页面' +}) + +wx.navigateTo({ + url: 'test?id=1' +}) + +wx.redirectTo({ + url: 'test?id=1' +}) + + +var animation = wx.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 +}) + + +Page({ + data: { + animationData: {} + }, + onShow: function(){ + var animation = wx.createAnimation({ + duration: 1000, + timingFunction: 'ease', + }) + + this.animation = animation + + animation.scale(2,2).rotate(45).step() + + this.setData({ + animationData:animation.export() + }) + + setTimeout(function() { + animation.translate(30).step() + this.setData({ + animationData:animation.export() + }) + }.bind(this), 1000) + }, + rotateAndScale: function () { + // 旋转同时放大 + this.animation.rotate(45).scale(2, 2).step() + this.setData({ + animationData:animation.export() + }) + }, + rotateThenScale: function () { + // 先旋转后放大 + this.animation.rotate(45).step() + this.animation.scale(2, 2).step() + this.setData({ + animationData:animation.export() + }) + }, + rotateAndScaleThenTranslate: function () { + // 先旋转同时放大,然后平移 + this.animation.rotate(45).scale(2, 2).step() + this.animation.translate(100, 100).step({ duration: 1000 }) + this.setData({ + animationData:animation.export() + }) + } +}) + +// 假设页面上有3个画布 +var canvas1Id = 3001 +var canvas2Id = 3002 +var canvas3Id = 3003 + +var context = wx.createContext(); + +[canvas1Id, canvas2Id, canvas3Id].forEach(function (id) { + context.clearActions() + // 在context上调用方法 + wx.drawCanvas({ + canvasId: id, + actions: context.getActions() + }) +}) + + +Page({ + onReady: function() { + var context = wx.createContext() + context.rect(5, 5, 25, 15) + context.stroke() + context.scale(2, 2) //再放大2倍 + context.rect(5, 5, 25, 15) + context.stroke() + context.scale(2, 2) //再放大2倍 + context.rect(5, 5, 25, 15) + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + + +Page({ + onReady: function() { + var context = wx.createContext() + context.rect(50, 50, 200, 200) + context.stroke() + context.rotate(5 * Math.PI / 180) + context.rect(50, 50, 200, 200) + context.stroke() + context.rotate(5 * Math.PI / 180) + context.rect(50, 50, 200, 200) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.rect(50, 50, 200, 200) + context.stroke() + context.translate(50, 50) + context.rect(50, 50, 200, 200) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.rect(50, 50, 200, 200) + context.fill() + context.clearRect(100, 100, 50, 50) + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + wx.chooseImage({ + success: function(res) { + context.drawImage(res.tempFilePaths[0], 0, 0) + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }) + } + }) + } +}) + +Page({ + onReady:function(){ + var context = wx.createContext() + + context.setFontSize(14) + context.fillText("MINA", 50, 50) + context.moveTo(0, 50) + context.lineTo(100, 50) + context.stroke() + + context.setFontSize(20) + context.fillText("MINA", 100, 100) + context.moveTo(0, 100) + context.lineTo(200, 100) + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.setFillStyle("#ff00ff") + context.setStrokeStyle("#00ffff") + + context.rect(50, 50, 100, 100) + context.fill() + context.stroke() + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) + +Page({ + onReady: function() { + var context = wx.createContext() + + context.setLineWidth(10) + context.setLineCap("round") + context.setLineJoin("miter") + context.setMiterLimit(10) + context.moveTo(20, 20) + context.lineTo(150, 27) + context.lineTo(20, 54) + context.stroke() + + context.beginPath() + + context.setMiterLimit(3) + context.moveTo(20, 70) + context.lineTo(150, 77) + context.lineTo(20, 104) + context.stroke() + + wx.drawCanvas({ + canvasId: 1, + actions: context.getActions() + }); + } +}) +Page({ + canvasIdErrorCallback: function (e:any) { + console.error(e.detail.errMsg) + }, + onReady: function() { + //使用wx.createContext获取绘图上下文context + var context = wx.createContext() + + context.setStrokeStyle("#00ff00") + context.setLineWidth(5) + context.rect(0, 0, 200, 200) + context.stroke() + context.setStrokeStyle("#ff0000") + context.setLineWidth(2) + context.moveTo(160, 100) + context.arc(100, 100, 60, 0,2 * Math.PI, true) + context.moveTo(140, 100) + context.arc(100, 100, 40, 0, Math.PI, false) + context.moveTo(85, 80) + context.arc(80, 80, 5, 0,2 * Math.PI, true) + context.moveTo(125, 80) + context.arc(120, 80, 5, 0, 2 * Math.PI, true) + context.stroke() + + // 调用 wx.drawCanvas,通过 canvasId 指定在哪张画布上绘制,通过 actions 指定绘制行为 + wx.drawCanvas({ + canvasId: 'firstCanvas', + actions: context.getActions() // 获取绘图动作数组 + }) + } +}) + + +App({ + onLaunch: function() { + wx.login({ + success: function(res) { + if (res.code) { + //发起网络请求 + wx.request({ + url: 'https://test.com/onLogin', + data: { + code: res.code + } + }) + } else { + console.log('获取用户登录态失败!' + res.errMsg) + } + } + }); + } +}) + + +wx.getUserInfo({ + success: function(res) { + var userInfo = res.userInfo + var nickName = userInfo.nickName + var avatarUrl = userInfo.avatarUrl + var gender = userInfo.gender //性别 0:未知、1:男、2:女 + var province = userInfo.province + var city = userInfo.city + var country = userInfo.country + } +}) + +wx.requestPayment({ + 'timeStamp': '', + 'nonceStr': '', + 'package': '', + 'signType': 'MD5', + 'paySign': '', + 'success':function(res){ + }, + 'fail':function(res){ + } +}) diff --git a/weapp-api/weapp-api.d.ts b/weapp-api/weapp-api.d.ts new file mode 100644 index 0000000000..cb9d00383d --- /dev/null +++ b/weapp-api/weapp-api.d.ts @@ -0,0 +1,1135 @@ +// Type definitions for weapp +// Project: https://mp.weixin.qq.com/debug/wxadoc/dev/index.html +// Definitions by: vargeek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace wx { + type NoneParamCallback = () => void; + type OneParamCallback = (data: any) => void; + type ResponseCallback = (res: any) => void; + type DataResponseCallback = (res: DataResponse) => void; + type TempFileResponseCallback = (res: TempFileResponse) => void; + type ErrorCallback = (error: any) => void; + type EventCallback = (event: any) => void; + + interface DataResponse { + /** 回调函数返回的内容 */ + data: any; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + } + + interface PageOptions { + /** 页面的初始数据 */ + data?: any; + /** 生命周期函数--监听页面加载 */ + onLoad?: (options: any) => void; + /** 生命周期函数--监听页面渲染完成 */ + onReady?: NoneParamCallback; + /** 生命周期函数--监听页面显示 */ + onShow?: NoneParamCallback; + /** 生命周期函数--监听页面隐藏 */ + onHide?: NoneParamCallback; + /** 生命周期函数--监听页面卸载 */ + onUnload?: NoneParamCallback; + [key: string]: any; + } + + interface AppOptions { + /** + * 生命周期函数--监听小程序初始化 + * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) + */ + onLaunch?: NoneParamCallback; + /** + * 生命周期函数--监听小程序显示 + * 当小程序启动,或从后台进入前台显示,会触发 onShow + */ + onShow?: NoneParamCallback; + /** + * 生命周期函数--监听小程序隐藏 + * 当小程序从前台进入后台,会触发 onHide + */ + onHide?: NoneParamCallback; + [key: string]: any + } + + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | any; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?: DataResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * wx.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): void; + + + interface UploadFileOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): void; + + + interface DownloadFileOptions { + /** 下载资源的 url */ + url: string; + /** 下载资源的类型,用于客户端识别处理,有效值:image/audio/video */ + type?: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?: TempFileResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): void; + + + interface ConnectSocketOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** 请求的数据 */ + data?: any; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + + + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: OneParamCallback): void; + + /** 监听WebSocket错误。 */ + function onSocketError(callback: ErrorCallback): void; + + interface SendSocketMessageOptions { + /** 需要发送的内容 */ + data: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 通过 WebSocket 连接发送数据,需要先 wx.connectSocket, + * 并在 wx.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + + + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: DataResponseCallback): void; + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(): void; + + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: ResponseCallback): void; + + type ImageSizeType = 'original' | 'compressed'; + type ImageSourceType = 'album' | 'camera'; + type VideoSourceType = 'album' | 'camera'; + type CameraDevice = 'front' | 'back'; + + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + } + interface ChooseImageOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: Array; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: Array; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success: (res: TempFilesData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + + interface PreviewImageOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: Array; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + + interface StartRecordOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?: TempFileResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 开始录音。当主动调用wx.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用wx.saveFile,在小程序下次启动时才能访问得到。 + */ + function startRecord(options: StartRecordOptions): void; + + /** + * ​ 主动调用停止录音。 + */ + function stopRecord(): void; + + interface PlayVoiceOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + */ + function playVoice(options: PlayVoiceOptions): void; + + /** + * 暂停正在播放的语音。 + * 再次调用wx.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 wx.stopVoice。 + */ + function pauseVoice(): void; + + /** + * 结束播放语音。 + */ + function stopVoice(): void; + + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration?: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition?: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent?: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl?: string; + } + type GetBackgroundAudioPlayerStateSuccessCallback = (state: BackgroundAudioPlayerState) => void; + interface GetBackgroundAudioPlayerStateOptions { + /** 接口调用成功的回调函数 */ + success?: GetBackgroundAudioPlayerStateSuccessCallback; + /** 接口调用失败的回调函数 */ + fail?: NoneParamCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: NoneParamCallback; + } + /** 获取音乐播放状态。 */ + function getBackgroundAudioPlayerState(options: GetBackgroundAudioPlayerStateOptions): void; + + interface PlayBackgroundAudioOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + + } + /** 播放音乐,同时只能有一首音乐正在播放。 */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + + /** 暂停播放音乐。 */ + function pauseBackgroundAudio(): void; + + interface SeekBackgroundAudioOptions { + /** 音乐位置,单位:秒 */ + position: number; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 控制音乐播放进度。 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + + /** + * 停止播放音乐。 + */ + function stopBackgroundAudio(): void; + + /** 监听音乐播放。 */ + function onBackgroundAudioPlay(callback: NoneParamCallback): void; + + /** 监听音乐暂停。 */ + function onBackgroundAudioPause(callback: NoneParamCallback): void; + + /** 监听音乐停止。 */ + function onBackgroundAudioStop(callback: NoneParamCallback): void; + + interface SavedFileData { + /** 文件的保存路径 */ + savedFilePath: string; + } + interface SaveFileOptions { + /** 需要保存的文件的临时路径 */ + tempFilePath: string; + /** 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'} */ + success?: (res: SavedFileData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 保存文件到本地。 + */ + function saveFile(options: SaveFileOptions): void; + + interface VideoData { + /** 选定视频的临时文件路径 */ + tempFilePath: string; + /** 选定视频的时间长度 */ + duration: number; + /** 选定视频的数据量大小 */ + size: number; + /** 返回选定视频的长 */ + height: number; + /** 返回选定视频的宽 */ + width: number; + } + interface ChooseVideoOptions { + /** album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera'] */ + sourceType?: Array; + /** 拍摄视频最长拍摄时间,单位秒。最长支持60秒 */ + maxDuration?: number; + /** 前置或者后置摄像头,默认为前后都有,即:['front', 'back'] */ + camera?: Array; + /** 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明 */ + success?: (res: VideoData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。 + */ + function chooseVideo(options: ChooseVideoOptions): void; + + interface SetStorageOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 需要存储的内容 */ + data: any | string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 将数据存储在本地缓存中指定的 key 中, + * 会覆盖掉原来该 key 对应的内容,这是一个异步接口。 + */ + function setStorage(options: SetStorageOptions): void; + /** + * 将 data 存储在本地缓存中指定的 key 中, + * 会覆盖掉原来该 key 对应的内容,这是一个同步接口。 + * + * @param {string} key 本地缓存中的指定的 key + * @param {(Object | string)} data 需要存储的内容 + */ + function setStorageSync(key: string, data: any | string): void; + + interface GetStorageOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 接口调用的回调函数,res = {data: key对应的内容} */ + success: DataResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 从本地缓存中异步获取指定 key 对应的内容。 + */ + function getStorage(options: GetStorageOptions): void; + + /** + * 从本地缓存中同步获取指定 key 对应的内容。 + * + * @param {string} key + * @returns {(Object | string)} + */ + function getStorageSync(key: string): any | string; + + /** + * 清理本地数据缓存。 + */ + function clearStorage(): void; + /** + * 同步清理本地数据缓存 + */ + function clearStorageSync(): void; + + interface LocationData { + /** 纬度,浮点数,范围为-90~90,负数表示南纬 */ + latitude: number; + /** 经度,浮点数,范围为-180~180,负数表示西经 */ + longitude: number; + /** 速度,浮点数,单位m/s */ + speed: number; + /** 位置的精确度 */ + accuracy: number; + } + + interface GetLocationOptions { + /** 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于wx.openLocation的坐标 */ + type?: 'wgs84' | 'gcj02'; + /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ + success: (res: LocationData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取当前的地理位置、速度。 + */ + function getLocation(options: GetLocationOptions): void; + + interface OpenLocationOptions { + /** 纬度,范围为-90~90,负数表示南纬 */ + latitude: number; + /** 经度,范围为-180~180,负数表示西经 */ + longitude: number; + /** 缩放比例,范围1~28,默认为28 */ + scale?: number; + /** 位置名 */ + name?: string; + /** 地址的详细说明 */ + address?: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 使用微信内置地图查看位置 + */ + function openLocation(options: OpenLocationOptions): void; + + interface NetworkTypeData { + /** 返回网络类型2g,3g,4g,wifi */ + networkType: '2g' | '3g' | '4g' | 'wifi'; + } + interface GetNetworkTypeOptions { + /** 接口调用成功,返回网络类型 networkType */ + success: (res: NetworkTypeData) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取网络类型。 + */ + function getNetworkType(options: GetNetworkTypeOptions): void; + + + interface SystemInfo { + /** 手机型号 */ + model: string; + /** 设备像素比 */ + pixelRatio: number; + /** 窗口宽度 */ + windowWidth: number; + /** 窗口高度 */ + windowHeight: number; + /** 微信设置的语言 */ + language: string; + /** 微信版本号 */ + version: string; + } + interface GetSystemInfoOptions { + /** 成功获取系统信息的回调 */ + success: (res: SystemInfo) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取系统信息。 + */ + function getSystemInfo(options: GetSystemInfoOptions): void; + + interface AccelerometerData { + /** X 轴 */ + x: number; + /** Y 轴 */ + y: number; + /** Z 轴 */ + z: number; + } + type AccelerometerChangeCallback = (res: AccelerometerData) => void; + /** + * 监听重力感应数据,频率:5次/秒 + */ + function onAccelerometerChange(callback: AccelerometerChangeCallback): void; + + interface CompassData { + /** 面对的方向度数 */ + direction: number; + } + type CompassChangeCallback = (res: CompassData) => void; + function onCompassChange(callback: CompassChangeCallback): void; + + interface SetNavigationBarTitleOptions { + /** 页面标题 */ + title?: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 动态设置当前页面的标题。 + */ + function setNavigationBarTitle(options: SetNavigationBarTitleOptions): void; + + /** + * 在当前页面显示导航条加载动画。 + */ + function showNavigationBarLoading(): void; + /** + * 隐藏导航条加载动画。 + */ + function hideNavigationBarLoading(): void; + + interface NavigateToOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 + * + * 注意:为了不让用户在使用小程序时造成困扰, + * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 + */ + function navigateTo(options: NavigateToOptions): void; + + interface RedirectToOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + /** 成功获取系统信息的回调 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 关闭当前页面,跳转到应用内的某个页面。 + */ + function redirectTo(options: RedirectToOptions): void; + + /** + * 关闭当前页面,回退前一页面。 + */ + function navigateBack(): void; + + type TimingFunction = 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; + + interface CreateAnimationOptions { + /** 动画持续时间,单位ms,默认值 400 */ + duration?: number; + /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ + timingFunction?: TimingFunction; + /** 动画持续时间,单位 ms,默认值 0 */ + delay?: number; + /** 设置transform-origin,默认为"50% 50% 0" */ + transformOrigin?: string; + } + + interface Animator { + actions: Array; + } + interface AnimationAction { + animates: Array; + option: AnimationActionOption; + } + interface AnimationActionOption { + transformOrigin: string; + transition: AnimationTransition; + } + interface AnimationTransition { + delay: number; + duration: number; + timingFunction: TimingFunction; + } + interface Animate { + type: string; + args: Array; + } + + /** + * 创建一个动画实例animation。调用实例的方法来描述动画。 + * 最后通过动画实例的export方法导出动画数据传递给组件的animation属性。 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + function createAnimation(options?: CreateAnimationOptions): Animation; + /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ + interface Animation { + /** + * 调用动画操作方法后要调用 step() 来表示一组动画完成, + * 可以在一组动画中调用任意多个动画方法, + * 一组动画中的所有动画会同时开始, + * 一组动画完成后才会进行下一组动画。 + * @param {CreateAnimationOptions} options 指定当前组动画的配置 + */ + step(options?: CreateAnimationOptions): void; + /** + * 导出动画操作 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + export(): Animator; + + /** 透明度,参数范围 0~1 */ + opacity(value: number): Animation; + /** 颜色值 */ + backgroundColor(color: string): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + width(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + height(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + top(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + left(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + bottom(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + right(length: number): Animation; + + /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ + rotate(deg: number): Animation; + /** deg的范围-180~180,在X轴旋转一个deg角度 */ + rotateX(deg: number): Animation; + /** deg的范围-180~180,在Y轴旋转一个deg角度 */ + rotateY(deg: number): Animation; + /** deg的范围-180~180,在Z轴旋转一个deg角度 */ + rotateZ(deg: number): Animation; + /** 同transform-function rotate3d */ + rotate3d(x: number, y: number, z: number, deg: number): Animation; + + /** + * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; + * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 + */ + scale(sx: number, sy?: number): Animation; + /** 在X轴缩放sx倍数 */ + scaleX(sx: number): Animation; + /** 在Y轴缩放sy倍数 */ + scaleY(sy: number): Animation; + /** 在Z轴缩放sy倍数 */ + scaleZ(sz: number): Animation; + /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ + scale3d(sx: number, sy: number, sz: number): Animation; + + /** + * 一个参数时,表示在X轴偏移tx,单位px; + * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 + */ + translate(tx: number, ty?: number): Animation; + /** + * 在X轴偏移tx,单位px + */ + translateX(tx: number): Animation; + /** + * 在Y轴偏移tx,单位px + */ + translateY(ty: number): Animation; + /** + * 在Z轴偏移tx,单位px + */ + translateZ(tz: number): Animation; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px + */ + translate3d(tx: number, ty: number, tz: number): Animation; + + /** + * 参数范围-180~180; + * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; + * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 + */ + skew(ax: number, ay?: number): Animation; + /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ + skewX(ax: number): Animation; + /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ + skewY(ay: number): Animation; + + /** + * 同transform-function matrix + */ + matrix(a: number, b: number, c: number, d: number, tx: number, ty: number): Animation; + /** 同transform-function matrix3d */ + matrix3d(a1: number, b1: number, c1: number, d1: number, a2: number, b2: number, c2: number, d2: number, a3: number, b3: number, c3: number, d3: number, a4: number, b4: number, c4: number, d4: number): Animation; + } + + interface CanvasAction { + method: string; + data: Array | Array + } + type LineCapType = 'butt' | 'round' | 'square'; + type LineJoinType = 'bevel' | 'round' | 'miter'; + /** + * context只是一个记录方法调用的容器,用于生成记录绘制行为的actions数组。context跟不存在对应关系,一个context生成画布的绘制动作数组可以应用于多个。 + */ + interface CanvasContext { + /** 获取当前context上存储的绘图动作 */ + getActions(): Array + /** 清空当前的存储绘图动作 */ + clearActions(): void; + /** + * 对横纵坐标进行缩放 + * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。 + * 多次调用scale,倍数会相乘。 + * + * @param {number} scaleWidth 横坐标缩放的倍数 + * @param {number} scaleHeight 纵坐标轴缩放的倍数 + */ + scale(scaleWidth: number, scaleHeight?: number): void; + /** + * 对坐标轴进行顺时针旋转 + * 以原点为中心,原点可以用 translate方法修改。 + * 顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 + * + * @param {number} rotate 旋转角度,以弧度计。 + */ + rotate(rotate: number): void; + /** + * 对坐标原点进行缩放 + * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 + * + * @param {number} x 水平坐标平移量 + * @param {number} y 竖直坐标平移量 + */ + translate(x: number, y: number): void; + /** + * 保存当前坐标轴的缩放、旋转、平移信息 + */ + save(): void; + /** + * 恢复之前保存过的坐标轴的缩放、旋转、平移信息 + */ + restore(): void; + /** + * 在给定的矩形区域内,清除画布上的像素 + * 清除画布上在该矩形区域内的内容。 + * + * @param {number} x 矩形区域左上角的x坐标 + * @param {number} y 矩形区域左上角的y坐标 + * @param {number} width 矩形区域的宽度 + * @param {number} height 矩形区域的高度 + */ + clearRect(x: number, y: number, width: number, height: number): void; + /** + * 在画布上绘制被填充的文本 + * + * @param {string} text 在画布上输出的文本 + * @param {number} x 绘制文本的左上角x坐标位置 + * @param {number} y 绘制文本的左上角y坐标位置 + */ + fillText(text: string, x: number, y: number): void; + /** + * 在画布上绘制图像 + * 绘制图像,图像保持原始尺寸。 + * + * @param {string} imageResource 所要绘制的图片资源。 通过chooseImage得到一个文件路径或者一个项目目录内的图片 + * @param {number} x 图像左上角的x坐标 + * @param {number} y 图像左上角的y坐标 + */ + drawImage(imageResource: string, x: number, y: number): void; + /** + * 对当前路径进行填充 + */ + fill(): void; + /** + * 对当前路径进行描边 + */ + stroke(): void; + /** + * 开始一个路径 + * 开始创建一个路径,需要调用fill或者stroke才会使用路径进行填充或描边。 + * 同一个路径内的多次setFillStyle、setStrokeStyle、setLineWidth等设置, + * 以最后一次设置为准。 + */ + beginPath(): void; + /** + * 关闭一个路径 + */ + closePath(): void; + /** + * 把路径移动到画布中的指定点,但不创建线条。 + * + * @param {number} x 目标位置的x坐标 + * @param {number} y 目标位置的y坐标 + */ + moveTo(x: number, y: number): void; + /** + * 在当前位置添加一个新点,然后在画布中创建从该点到最后指定点的路径。 + * + * @param {number} x 目标位置的x坐标 + * @param {number} y 目标位置的y坐标 + */ + lineTo(x: number, y: number): void; + /** + * 添加一个矩形路径到当前路径。 + * + * @param {number} x 矩形路径左上角的x坐标 + * @param {number} y 矩形路径左上角的y坐标 + * @param {number} width 矩形路径的宽度 + * @param {number} height 矩形路径的高度 + */ + rect(x: number, y: number, width: number, height: number): void; + /** + * 添加一个弧形路径到当前路径,顺时针绘制。 + * + * @param {number} x 矩形路径左上角的x坐标 + * @param {number} y 矩形路径左上角的y坐标 + * @param {number} radius 矩形路径左上角的y坐标 + * @param {number} startAngle 起始弧度 + * @param {number} endAngle 结束弧度 + * @param {boolean} sweepAngle 从起始弧度开始,扫过的弧度 + */ + arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, sweepAngle: boolean): void; + /** + * 创建二次方贝塞尔曲线 + * + * @param {number} cpx 贝塞尔控制点的x坐标 + * @param {number} cpy 贝塞尔控制点的y坐标 + * @param {number} x 结束点的x坐标 + * @param {number} y 结束点的y坐标 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + /** + * 创建三次方贝塞尔曲线 + * + * @param {number} cp1x 第一个贝塞尔控制点的 x 坐标 + * @param {number} cp1y 第一个贝塞尔控制点的 y 坐标 + * @param {number} cp2x 第二个贝塞尔控制点的 x 坐标 + * @param {number} cp2y 第二个贝塞尔控制点的 y 坐标 + * @param {number} x 结束点的x坐标 + * @param {number} y 结束点的y坐标 + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + /** + * 设置填充样式 + * + * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setFillStyle(color: string): void; + /** + * 设置线条样式 + * + * @param {string} color 设置为填充样式的颜色。'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setStrokeStyle(color: string): void; + /** + * 设置阴影 + * + * @param {number} offsetX 阴影相对于形状在水平方向的偏移 + * @param {number} offsetY 阴影相对于形状在竖直方向的偏移 + * @param {number} blur 阴影的模糊级别,数值越大越模糊 0~100 + * @param {string} color 阴影的颜色。 'rgb(255, 0, 0)'或'rgba(255, 0, 0, 0.6)'或'#ff0000'格式的颜色字符串 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: string): void; + /** + * 设置字体大小 + * + * @param {number} fontSize 字体的字号 + */ + setFontSize(fontSize: number): void; + /** + * 设置线条端点的样式 + * + * @param {LineCapType} lineCap 线条的结束端点样式。 'butt'、'round'、'square' + */ + setLineCap(lineCap: LineCapType): void; + /** + * 设置两线相交处的样式 + * @param {LineJoinType} lineJoin 两条线相交时,所创建的拐角类型 + */ + setLineJoin(lineJoin: LineJoinType): void; + /** + * 设置线条宽度 + * + * @param {number} lineWidth 线条的宽度 + */ + setLineWidth(lineWidth: number): void; + /** 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 + * 当 setLineJoin为 miter 时才有效。 + * 超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 + * + * @param {number} miterLimit 最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + } + /** + * 创建并返回绘图上下文context对象。 + * context只是一个记录方法调用的容器, + * 用于生成记录绘制行为的actions数组。c + * ontext跟不存在对应关系, + * 一个context生成画布的绘制动作数组可以应用于多个。 + */ + function createContext(): CanvasContext; + + interface DrawCanvasOptions { + /** 画布标识,传入 的 cavas-id */ + canvasId: number | string; + /** + * 绘图动作数组,由 wx.createContext 创建的 context, + * 调用 getActions 方法导出绘图动作数组。 + */ + actions: Array; + } + /** + * 绘制画布 + */ + function drawCanvas(options: DrawCanvasOptions): void; + + /** + * 收起键盘。 + */ + function hideKeyboard(): void; + + interface LoginResponse { + /** 调用结果 */ + errMsg: string; + /** 用户允许登录后,回调内容会带上 code(有效期五分钟), + * 开发者需要将 code 发送到开发者服务器后台, + * 使用code 换取 session_key api, + * 将 code 换成 openid 和 session_key */ + code: string; + } + interface LoginOptions { + /** 接口调用成功的回调函数 */ + success?: (res: LoginResponse) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + + /** + * 调用接口获取登录凭证(code)进而换取用户登录态信息, + * 包括用户的唯一标识(openid) 及本次登录的 会话密钥(session_key)。 + * 用户数据的加解密通讯需要依赖会话密钥完成。 + */ + function login(option: LoginOptions): void; + + interface UserInfo { + nickName: string; + avatarUrl: string; + gender: number; + province: string; + city: string; + country: string; + } + interface UserInfoResponse { + /** 用户信息对象,不包含 openid 等敏感信息 */ + userInfo: UserInfo; + /** 不包括敏感信息的原始数据字符串,用于计算签名。 */ + rawData: string; + /** 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息。 */ + signature: string; + /** 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法 */ + encryptData: string; + } + interface GetUserInfoOptions { + /** 接口调用成功的回调函数 */ + success?: (res: UserInfoResponse) => void; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 获取用户信息,需要先调用 wx.login 接口。 + */ + function getUserInfo(options: GetUserInfoOptions): void; + + type PaymentSignType = 'MD5'; + interface RequestPaymentOptions { + /** 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间 */ + timeStamp: string|number; + /** 随机字符串,长度为32个字符以下。 */ + nonceStr: string; + /** 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=* */ + package: string; + /** 签名算法,暂支持 MD5 */ + signType: PaymentSignType; + /** 签名,具体签名方案参见微信公众号支付帮助文档; */ + paySign: string; + /** 接口调用成功的回调函数 */ + success?: ResponseCallback; + /** 接口调用失败的回调函数 */ + fail?: ResponseCallback; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?: ResponseCallback; + } + /** + * 发起微信支付。 + */ + function requestPayment(options: RequestPaymentOptions): void; +} + + +interface Page { + /** + * setData 函数用于将数据从逻辑层发送到视图层, + * 同时改变对应的 this.data 的值。 + * 注意: + * 1. 直接修改 this.data 无效,无法改变页面的状态,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + */ + setData(data: any): void; +} +interface PageConstructor { + /** + * Page() 函数用来注册一个页面。 + * 接受一个 object 参数,其指定页面的初始数据、生命周期函数、事件处理函数等。 + */ + (options: wx.PageOptions): void; +} +declare var Page: PageConstructor; + + +interface App { + /** + * getCurrentPage() 函数用户获取当前页面的实例。 + */ + getCurrentPage(): Page; +} +interface AppConstructor { + /** + * App() 函数用来注册一个小程序。 + * 接受一个 object 参数,其指定小程序的生命周期函数等。 + */ + (options: wx.AppOptions): void; +} +declare var App: AppConstructor; + +/** + * 我们提供了全局的 getApp() 函数,可以获取到小程序实例。 + */ +declare function getApp(): App; From 727c305d5e32c5dec79b8f407013aad6d8cf4abd Mon Sep 17 00:00:00 2001 From: Denis Date: Wed, 28 Sep 2016 11:11:29 -0400 Subject: [PATCH 060/382] Added more methods to Turf (#11558) * Added more methods to Turf - circle - geojsonType - propReduce - coordAll - tesselate * Replace Object with GeoJSON --- turf/turf-tests.ts | 20 +++++- turf/turf.d.ts | 166 ++++++++++++++++++++++++++++++++------------- 2 files changed, 139 insertions(+), 47 deletions(-) diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index 31462adc51..0e887e2e3e 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -499,8 +499,26 @@ turf.collect(polygons, points, 'population', 'values') /////////////////////////////////////////// // Tests Assertions /////////////////////////////////////////// +// -- Test bbox -- turf.bbox(polygon1) turf.bbox(point1) turf.bbox(lineString1) turf.bbox(multiLineString1) -turf.bbox(multiPolygon1) \ No newline at end of file +turf.bbox(multiPolygon1) + +// -- Test circle -- +turf.circle(point1, 10) +turf.circle(point1, 10, 32) +turf.circle(point1, 10, 64, 'miles') + +// -- Test geojsonType -- +turf.geojsonType(point1, 'point', 'Test') + +// -- Test propReduce -- +turf.propReduce(point1, (memo, coord) => {}, 'point') + +// -- Test coordAll -- +turf.coordAll(polygon1) + +// -- Test tesselate -- +turf.tesselate(polygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index e90cf69276..773802a103 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -80,16 +80,22 @@ ASSERTIONS - [ ] featureOf - [ ] collectionOf - [x] bbox -- [ ] circle -- [ ] geojsonType -- [ ] propReduce -- [ ] coordAll -- [ ] tesselate +- [x] circle +- [x] geojsonType +- [x] propReduce +- [x] coordAll +- [x] tesselate */ declare const turf: turf.TurfStatic; declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' +declare interface OptionsRandom { + bbox?: Array + num_vertices?: number + max_radial_length?: number +} +declare type PropReduceCallback = (memo: any, coord: GeoJSON.Feature | GeoJSON.FeatureCollection) => any declare module turf { interface TurfStatic { ////////////////////////////////////////////////////// @@ -169,11 +175,79 @@ declare module turf { * var bboxPolygon = turf.bboxPolygon(bbox); * * //=bbox - * + * * //=bboxPolygon */ bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + /** + * Takes a {@link Point} and calculates the circle polygon given a radius in degrees, radians, miles, or kilometers; and steps for precision. + * + * @name circle + * @param {Feature} center center point + * @param {number} radius radius of the circle + * @param {number} [steps=64] number of steps + * @param {string} [units=kilometers] miles, kilometers, degrees, or radians + * @returns {Feature} circle polygon + * @example + * var center = point([-75.343, 39.984]); + * var radius = 5; + * var steps = 10; + * var units = 'kilometers'; + * + * var circle = turf.circle(center, radius, steps, units); + * + * //=circle + */ + circle(center: GeoJSON.Feature, radius: number, steps?: number, units?: typeof TemplateUnits): GeoJSON.Feature; + + + /** + * Enforce expectations about types of GeoJSON objects for Turf. + * + * @name geojsonType + * @param {GeoJSON} value any GeoJSON object + * @param {string} type expected GeoJSON type + * @param {string} name name of calling function + * @throws {Error} if value is not the expected type. + */ + geojsonType(value: GeoJSON.Feature | GeoJSON.FeatureCollection, type: string, name: string): void + + /** + * Reduce properties in any GeoJSON object into a single value, similar to how Array.reduce works. However, in this case we lazily run the reduction, so an array of all properties is unnecessary. + * + * @name propReduce + * @param {GeoJSON} layer any GeoJSON object + * @param {Function} callback a method that takes (memo, coord) and returns a new memo + * @param {*} memo the starting value of memo: can be any type. + * @return {*} combined value + */ + propReduce(layer: GeoJSON.Feature | GeoJSON.FeatureCollection, callback: PropReduceCallback, memo: any): any + + /** + * Get all coordinates from any GeoJSON object, returning an array of coordinate arrays. + * + * @name coordAll + * @param {GeoJSON} layer any GeoJSON object + * @returns {Array>} coordinate position array + */ + coordAll(layer: GeoJSON.Feature | GeoJSON.FeatureCollection): Array> + + /** + * Tesselates a {@link Feature} into a {@link FeatureCollection} of triangles using [earcut](https://github.com/mapbox/earcut). + * + * @name tesselate + * @param {Feature} polygon the polygon to tesselate + * @returns {FeatureCollection} a geometrycollection feature + * @example + * var polygon = turf.random('polygon').features[0]; + * + * var triangles = turf.tesselate(polygon); + * + * //=triangles + */ + tesselate(poly: GeoJSON.Feature): GeoJSON.FeatureCollection + /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] @@ -298,7 +372,7 @@ declare module turf { */ buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; - buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; @@ -343,7 +417,7 @@ declare module turf { * If they share a border, returns the border if they don't intersect, returns undefined. * * @name [intersect](http://turfjs.org/docs/#intersect) - * @param {Feature} poly1 + * @param {Feature} poly1 * @param {Feature} poly2 * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. * @example @@ -456,7 +530,7 @@ declare module turf { /** * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. - * + * * @name [featureCollection](http://turfjs.org/docs/#featurecollection) * @param {Feature[]} features input features * @returns {FeatureCollection} a FeatureCollection of input features @@ -497,7 +571,7 @@ declare module turf { /** * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. - * + * * @name [lineString](http://turfjs.org/docs/#linestring) * @param {Array>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties @@ -525,7 +599,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiLineString](http://turfjs.org/docs/#multilinestring) * @param {Array>>} coordinates an array of LineStrings * @param {Object=} properties an Object of key-value pairs to add as properties @@ -541,7 +615,7 @@ declare module turf { /** * Takes coordinates and properties (optional) and returns a new {@link Point} feature. - * + * * @name [point](http://turfjs.org/docs/#point) * @param {Array} coordinates longitude, latitude position (each in decimal degrees) * @param {Object=} properties an Object that is used as the {@link Feature}'s @@ -556,7 +630,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiPoint](http://turfjs.org/docs/#multipoint) * @param {Array>} coordinates an array of Positions * @param {Object=} properties an Object of key-value pairs to add as properties @@ -572,7 +646,7 @@ declare module turf { /** * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. - * + * * @name [polygon](http://turfjs.org/docs/#polygon) * @param {Array>>} coordinates an array of LinearRings * @param {Object=} properties a properties object @@ -595,7 +669,7 @@ declare module turf { /** * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. - * + * * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) * @param {Array>>>} coordinates an array of Polygons * @param {Object=} properties an Object of key-value pairs to add as properties @@ -664,15 +738,15 @@ declare module turf { * * //=polygons */ - random(type?: typeof TemplateType, count?: number, options?: { - bbox?: Array - num_vertices?: number - max_radial_length?: number - }): GeoJSON.FeatureCollection; + random(type?: 'point', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'points', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'polygon', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: 'polygons', count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; + random(type?: typeof TemplateType, count?: number, options?: OptionsRandom): GeoJSON.FeatureCollection; /** * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. - * + * * @name [sample](http://turfjs.org/docs/#sample) * @param {FeatureCollection} featurecollection set of input features * @param {number} num number of features to select @@ -694,7 +768,7 @@ declare module turf { /** * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). - * + * * @name [hexGrid](http://turfjs.org/docs/#hexgrid) * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order * @param {number} cellSize dimension of cell in specified units @@ -737,7 +811,7 @@ declare module turf { pointGrid( bbox: Array, cellSize: number, - units?: typeof TemplateUnits + units?: typeof TemplateUnits ): GeoJSON.FeatureCollection; /** @@ -835,7 +909,7 @@ declare module turf { * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) * * var isInside = turf.inside(pt, poly) - * + * * //=isInside */ inside( @@ -857,10 +931,10 @@ declare module turf { * var pt2 = point([-77, 38]) * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) - * + * * var points = featureCollection([pt1, pt2]) * var polygons = featureCollection([poly1, poly2]) - * + * * var tagged = turf.tag(points, polygons, 'pop', 'population') * //=tagged */ @@ -1181,27 +1255,27 @@ declare module "@turf/bbox" { export = bbox; } -// declare module "@turf/circle" { -// const circle: typeof turf.circle; -// export = circle; -// } +declare module "@turf/circle" { + const circle: typeof turf.circle; + export = circle; +} -// declare module "@turf/geojsonType" { -// const geojsonType: typeof turf.geojsonType; -// export = geojsonType; -// } +declare module "@turf/geojsonType" { + const geojsonType: typeof turf.geojsonType; + export = geojsonType; +} -// declare module "@turf/propReduce" { -// const propReduce: typeof turf.propReduce; -// export = propReduce; -// } +declare module "@turf/propReduce" { + const propReduce: typeof turf.propReduce; + export = propReduce; +} -// declare module "@turf/coordAll" { -// const coordAll: typeof turf.coordAll; -// export = coordAll; -// } +declare module "@turf/coordAll" { + const coordAll: typeof turf.coordAll; + export = coordAll; +} -// declare module "@turf/tesselate" { -// const tesselate: typeof turf.tesselate; -// export = tesselate; -// } +declare module "@turf/tesselate" { + const tesselate: typeof turf.tesselate; + export = tesselate; +} From 9fadbac5f835d7ad1b0b2d7241e25bf2c8c33d72 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:28:19 -0400 Subject: [PATCH 061/382] Implemented cheap-ruler definition --- cheap-ruler/cheap-ruler-tests.ts | 60 ++++++++ cheap-ruler/cheap-ruler.d.ts | 226 +++++++++++++++++++++++++++++++ 2 files changed, 286 insertions(+) create mode 100644 cheap-ruler/cheap-ruler-tests.ts create mode 100644 cheap-ruler/cheap-ruler.d.ts diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts new file mode 100644 index 0000000000..67388e52fd --- /dev/null +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -0,0 +1,60 @@ +/// + +import * as cheapRuler from 'cheap-ruler' + +// -- Fixtures -- +const unit = 'miles' +const lineString: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +} +const line = lineString.geometry.coordinates +const polygon = [[ + [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534], + [-66.929, 50.458], [-67.031, 50.458] +]] +const points = [ + [-67.031, 50.458], [-67.031, 50.534], + [-66.929, 50.534], [-66.929, 50.458] +] + +// -- Test initiators -- +cheapRuler(35.05) +cheapRuler(35.05, 'miles') +cheapRuler(35.05, unit) +cheapRuler.fromTile(1567, 12) +cheapRuler.fromTile(1567, 12, 'miles') +cheapRuler.fromTile(1567, 12, unit) + +// -- Test units -- +cheapRuler.units +cheapRuler.units.miles +cheapRuler.units.kilometers +50 * cheapRuler.units.yards / cheapRuler.units.meters + +// -- Test cheapRuler -- +const ruler = cheapRuler(35.05, 'kilometers') + +console.log(ruler.distance([30.5, 50.5], [30.51, 50.49])) +ruler.bearing([30.5, 50.5], [30.51, 50.49]) +ruler.destination([30.5, 50.5], 0.1, 90) +ruler.lineDistance(points) +ruler.area(polygon) +ruler.along(line, 2.5) +ruler.pointOnLine(line, [-67.04, 50.5]).point +ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line) +ruler.lineSliceAlong(10, 20, line) +ruler.bufferPoint([30.5, 50.5], 0.01) +ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2) +ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]) \ No newline at end of file diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts new file mode 100644 index 0000000000..97ad51730e --- /dev/null +++ b/cheap-ruler/cheap-ruler.d.ts @@ -0,0 +1,226 @@ +// Type definitions for cheap-ruler 2.4.1 +// Project: https://github.com/mapbox/cheap-ruler +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "cheap-ruler" { + interface TemplateUnits { + kilometers: number + miles: number + nauticalmiles: number + meters: number + metres: number + yards: number + feet: number + inches: number + } + interface InterfacePointOnLine { + point: Array + index: number + t: number + } + class CheapRuler { + /** + * Given two points of the form [longitude, latitude], returns the distance. + * + * @name distance + * @param {Array} a point [longitude, latitude] + * @param {Array} b point [longitude, latitude] + * @returns {number} distance + * @example + * var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); + * //=distance + */ + distance(a: Array, b: Array): number; + + /** + * Returns the bearing between two points in angles. + * + * @name bearing + * @param {Array} a point [longitude, latitude] + * @param {Array} b point [longitude, latitude] + * @returns {number} bearing + * @example + * var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]); + * //=bearing + */ + bearing(a: Array, b: Array): number; + + /** + * Returns a new point given distance and bearing from the starting point. + * + * @name destination + * @param {Array} p point [longitude, latitude] + * @param {number} dist distance + * @param {number} bearing + * @returns {Array} point [longitude, latitude] + * @example + * var point = ruler.destination([30.5, 50.5], 0.1, 90); + * //=point + */ + destination(p: Array, dist: number, bearing: number): Array; + + /** + * Given a line (an array of points), returns the total line distance. + * + * @name lineDistance + * @param {Array>} points [longitude, latitude] + * @returns {number} total line distance + * @example + * var length = ruler.lineDistance([ + * [-67.031, 50.458], [-67.031, 50.534], + * [-66.929, 50.534], [-66.929, 50.458] + * ]); + * //=length + */ + lineDistance(points: Array>): number; + + /** + * Given a polygon (an array of rings, where each ring is an array of points), returns the area. + * + * @name area + * @param {Array>>} polygon + * @returns {number} area value in the specified units (square kilometers by default) + * @example + * var area = ruler.area([[ + * [-67.031, 50.458], [-67.031, 50.534], [-66.929, 50.534], + * [-66.929, 50.458], [-67.031, 50.458] + * ]]); + * //=area + */ + area(polygon: Array>>): number; + + /** + * Returns the point at a specified distance along the line. + * + * @name along + * @param {Array>} line + * @param {number} dist distance + * @returns {Array} point [longitude, latitude] + * @example + * var point = ruler.along(line, 2.5); + * //=point + */ + along(line: Array>, dist: number): Array + + /** + * Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point. + * + * @pointOnLine + * @param {Array>} line + * @param {Array} p point [longitude, latitude] + * @returns {Object} {point, index} + * @example + * var point = ruler.pointOnLine(line, [-67.04, 50.5]).point; + * //=point + */ + pointOnLine(line: Array>, p: Array): InterfacePointOnLine + + /** + * Returns a part of the given line between the start and the stop points (or their closest points on the line). + * + * @name lineSlice + * @param {Array} start point [longitude, latitude] + * @param {Array} stop point [longitude, latitude] + * @param {Array>} line + * @returns {Array>} line part of a line + * @example + * var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1); + * //=line2 + */ + lineSlice(start: Array, stop: Array, line: Array>): Array> + + /** + * Returns a part of the given line between the start and the stop points indicated by distance along the line. + * + * @name lineSliceAlong + * @param {number} start distance + * @param {number} stop distance + * @param {Array>} line + * @returns {Array>} line part of a line + * @example + * var line2 = ruler.lineSliceAlong(10, 20, line1); + * //=line2 + */ + lineSliceAlong(start: number, stop: number, line: Array>): Array> + + /** + * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. + * + * @name bufferPoint + * @param {Array} p point [longitude, latitude] + * @param {number} buffer + * @returns {Array} box object ([w, s, e, n]) + * @example + * var bbox = ruler.bufferPoint([30.5, 50.5], 0.01); + * //=bbox + */ + bufferPoint(p: Array, buffer: number): Array + + /** + * Given a bounding box, returns the box buffered by a given distance. + * + * @name bufferBBox + * @param {Array} box object ([w, s, e, n]) + * @param {number} buffer + * @returns {Array} box object ([w, s, e, n]) + * @example + * var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2); + * //=bbox + */ + bufferBBox(bbox: Array, buffer: number): Array + + /** + * Returns true if the given point is inside in the given bounding box, otherwise false. + * + * @name insideBBox + * @param {Array} p point [longitude, latitude] + * @param {Array} box object ([w, s, e, n]) + * @returns {boolean} + * @example + * var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]); + * //=inside + */ + insideBBox(p: Array, bbox: Array): boolean + } + /** + * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. + * + * @name cheapRuler + * @param {number} lat latitude + * @param {string} [units='kilometers'] + * @returns {Object} CheapRuler + * @example + * var ruler = cheapRuler(35.05, 'miles'); + * //=ruler + */ + function cheapRuler(lat: number, units?: string): CheapRuler; + namespace cheapRuler { + /** + * Multipliers for converting between units. + * + * @name units + * @example + * // convert 50 meters to yards + * 50 * cheapRuler.units.yards / cheapRuler.units.meters; + */ + const units: TemplateUnits + + /** + * Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts. + * + * @name fromTile + * @param {number} y + * @param {number} z + * @param {string} [units='kilometers'] + * @returns {Object} CheapRuler + * @example + * var ruler = cheapRuler.fromTile(1567, 12); + * //=ruler + */ + function fromTile(y: number, z: number, units?: string) + } + export = cheapRuler +} \ No newline at end of file From 7898c8c4fabe1dc79bc68066478697f00f516f7e Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:29:48 -0400 Subject: [PATCH 062/382] Remove GeoJSON dependency --- cheap-ruler/cheap-ruler.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 97ad51730e..dd0dcb9dbc 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -3,8 +3,6 @@ // Definitions by: Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "cheap-ruler" { interface TemplateUnits { kilometers: number From 4f3c8528c27c42684adea93d5608bc9f90e9ac76 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:38:10 -0400 Subject: [PATCH 063/382] Cheap-ruler fixes - Removed GeoJSON from tests - Added return-type to fromTile --- cheap-ruler/cheap-ruler-tests.ts | 6 +++--- cheap-ruler/cheap-ruler.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts index 67388e52fd..2a1bf6521d 100644 --- a/cheap-ruler/cheap-ruler-tests.ts +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -4,7 +4,7 @@ import * as cheapRuler from 'cheap-ruler' // -- Fixtures -- const unit = 'miles' -const lineString: GeoJSON.Feature = { +const lineString = { "type": "Feature", "properties": {}, "geometry": { @@ -44,9 +44,9 @@ cheapRuler.units.kilometers 50 * cheapRuler.units.yards / cheapRuler.units.meters // -- Test cheapRuler -- -const ruler = cheapRuler(35.05, 'kilometers') +const ruler = cheapRuler(35.05) -console.log(ruler.distance([30.5, 50.5], [30.51, 50.49])) +ruler.distance([30.5, 50.5], [30.51, 50.49]) ruler.bearing([30.5, 50.5], [30.51, 50.49]) ruler.destination([30.5, 50.5], 0.1, 90) ruler.lineDistance(points) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index dd0dcb9dbc..300af9ee5d 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -218,7 +218,7 @@ declare module "cheap-ruler" { * var ruler = cheapRuler.fromTile(1567, 12); * //=ruler */ - function fromTile(y: number, z: number, units?: string) + function fromTile(y: number, z: number, units?: string): CheapRuler; } export = cheapRuler } \ No newline at end of file From bf34b77b69fbba586273d101a3fb2538b1c080ea Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Wed, 28 Sep 2016 11:59:07 -0400 Subject: [PATCH 064/382] Update JSDocs cheap-ruler Update based on comments https://github.com/mapbox/cheap-ruler/pull/20 - Removed `{@name}` - Changed {Object} to {CheapRuler} --- cheap-ruler/cheap-ruler.d.ts | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 300af9ee5d..187b27ea82 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -23,7 +23,6 @@ declare module "cheap-ruler" { /** * Given two points of the form [longitude, latitude], returns the distance. * - * @name distance * @param {Array} a point [longitude, latitude] * @param {Array} b point [longitude, latitude] * @returns {number} distance @@ -36,7 +35,6 @@ declare module "cheap-ruler" { /** * Returns the bearing between two points in angles. * - * @name bearing * @param {Array} a point [longitude, latitude] * @param {Array} b point [longitude, latitude] * @returns {number} bearing @@ -49,7 +47,6 @@ declare module "cheap-ruler" { /** * Returns a new point given distance and bearing from the starting point. * - * @name destination * @param {Array} p point [longitude, latitude] * @param {number} dist distance * @param {number} bearing @@ -63,7 +60,6 @@ declare module "cheap-ruler" { /** * Given a line (an array of points), returns the total line distance. * - * @name lineDistance * @param {Array>} points [longitude, latitude] * @returns {number} total line distance * @example @@ -78,7 +74,6 @@ declare module "cheap-ruler" { /** * Given a polygon (an array of rings, where each ring is an array of points), returns the area. * - * @name area * @param {Array>>} polygon * @returns {number} area value in the specified units (square kilometers by default) * @example @@ -93,7 +88,6 @@ declare module "cheap-ruler" { /** * Returns the point at a specified distance along the line. * - * @name along * @param {Array>} line * @param {number} dist distance * @returns {Array} point [longitude, latitude] @@ -119,7 +113,6 @@ declare module "cheap-ruler" { /** * Returns a part of the given line between the start and the stop points (or their closest points on the line). * - * @name lineSlice * @param {Array} start point [longitude, latitude] * @param {Array} stop point [longitude, latitude] * @param {Array>} line @@ -133,7 +126,6 @@ declare module "cheap-ruler" { /** * Returns a part of the given line between the start and the stop points indicated by distance along the line. * - * @name lineSliceAlong * @param {number} start distance * @param {number} stop distance * @param {Array>} line @@ -147,7 +139,6 @@ declare module "cheap-ruler" { /** * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. * - * @name bufferPoint * @param {Array} p point [longitude, latitude] * @param {number} buffer * @returns {Array} box object ([w, s, e, n]) @@ -160,7 +151,6 @@ declare module "cheap-ruler" { /** * Given a bounding box, returns the box buffered by a given distance. * - * @name bufferBBox * @param {Array} box object ([w, s, e, n]) * @param {number} buffer * @returns {Array} box object ([w, s, e, n]) @@ -173,7 +163,6 @@ declare module "cheap-ruler" { /** * Returns true if the given point is inside in the given bounding box, otherwise false. * - * @name insideBBox * @param {Array} p point [longitude, latitude] * @param {Array} box object ([w, s, e, n]) * @returns {boolean} @@ -186,10 +175,9 @@ declare module "cheap-ruler" { /** * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. * - * @name cheapRuler * @param {number} lat latitude * @param {string} [units='kilometers'] - * @returns {Object} CheapRuler + * @returns {CheapRuler} * @example * var ruler = cheapRuler(35.05, 'miles'); * //=ruler @@ -199,7 +187,6 @@ declare module "cheap-ruler" { /** * Multipliers for converting between units. * - * @name units * @example * // convert 50 meters to yards * 50 * cheapRuler.units.yards / cheapRuler.units.meters; @@ -209,11 +196,10 @@ declare module "cheap-ruler" { /** * Creates a ruler object from tile coordinates (y and z). Convenient in tile-reduce scripts. * - * @name fromTile * @param {number} y * @param {number} z * @param {string} [units='kilometers'] - * @returns {Object} CheapRuler + * @returns {CheapRuler} * @example * var ruler = cheapRuler.fromTile(1567, 12); * //=ruler From a4a33e265cf12ce775a9a0e54897fdabf2f6b3ce Mon Sep 17 00:00:00 2001 From: Artur Eshenbrener Date: Wed, 28 Sep 2016 19:20:57 +0300 Subject: [PATCH 065/382] [bluebird] document .suppressUnhandledRejections http://bluebirdjs.com/docs/api/suppressunhandledrejections.html --- bluebird/bluebird.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 35b506542a..3dc66b78f0 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -317,6 +317,13 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { */ cancel(): void; + /** + * Basically sugar for doing: somePromise.catch(function(){}); + * + * Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting. + */ + suppressUnhandledRejections(): void; + /** * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. * From b8abf4a0e491270df1369d953fdb0af63379947f Mon Sep 17 00:00:00 2001 From: Sean Kelley Date: Wed, 28 Sep 2016 12:20:33 -0700 Subject: [PATCH 066/382] Add typings for shallowequal. --- shallowequal/shallowequal-tests.ts | 12 ++++++++++++ shallowequal/shallowequal.d.ts | 9 +++++++++ 2 files changed, 21 insertions(+) create mode 100644 shallowequal/shallowequal-tests.ts create mode 100644 shallowequal/shallowequal.d.ts diff --git a/shallowequal/shallowequal-tests.ts b/shallowequal/shallowequal-tests.ts new file mode 100644 index 0000000000..73c644c770 --- /dev/null +++ b/shallowequal/shallowequal-tests.ts @@ -0,0 +1,12 @@ +/// + +import shallowEqual = require('shallowequal'); + +const a = {}, b = {}; +function compare(a: any, b: any, indexOrKey?: number | string) { + return false; +} + +shallowEqual(a, b); +shallowEqual(a, b, compare); +shallowEqual(a, b, compare, {}); diff --git a/shallowequal/shallowequal.d.ts b/shallowequal/shallowequal.d.ts new file mode 100644 index 0000000000..d3971e15c9 --- /dev/null +++ b/shallowequal/shallowequal.d.ts @@ -0,0 +1,9 @@ +// Type definitions for shallowequal v0.2.2 +// Project: https://github.com/dashed/shallowequal +// Definitions by: Sean Kelley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'shallowequal' { + function shallowEqual(objA: any, objB: any, compare?: (objA: any, objB: any, indexOrKey?: number | string) => boolean, compareContext?: any): boolean; + export = shallowEqual; +} From cfdd3db404999e24047ccd0d74a71c411f02ca3b Mon Sep 17 00:00:00 2001 From: Matt Rohr Date: Wed, 28 Sep 2016 17:33:47 -0400 Subject: [PATCH 067/382] URIjs fix .joinPaths() the .joinPaths function is on URIStatic, not an instance of URI https://medialize.github.io/URI.js/docs.html#static-joinPaths --- urijs/URIjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/urijs/URIjs.d.ts b/urijs/URIjs.d.ts index 8d784ad1ac..79a65dbb55 100644 --- a/urijs/URIjs.d.ts +++ b/urijs/URIjs.d.ts @@ -52,8 +52,6 @@ declare namespace uri { is(qry: string): boolean; iso8859(): URI; - joinPaths(...paths: (string | URI)[]): URI; - normalize(): URI; normalizeFragment(): URI; normalizeHash(): URI; @@ -190,6 +188,8 @@ declare namespace uri { expand(template: string, vals: Object): URI; iso8859(): void; + + joinPaths(...paths: (string | URI)[]): URI; parse(url: string): { protocol: string; From 4bf0e3eec34fba697afb966879fffe33fd903de1 Mon Sep 17 00:00:00 2001 From: Simon Date: Wed, 28 Sep 2016 18:07:02 -0400 Subject: [PATCH 068/382] set document id property to be optional --- mongoose/mongoose.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 24664cc350..631e9c9581 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -871,7 +871,7 @@ declare module "mongoose" { /** Hash containing current validation errors. */ errors: Object; /** The string version of this documents _id. */ - id: string; + id?: string; /** This documents _id. */ _id: any; /** Boolean flag specifying if the document is new. */ From f58fded0a8cf5deb7fb1b136685c49ec310e9a57 Mon Sep 17 00:00:00 2001 From: Sahin Kureta Date: Thu, 29 Sep 2016 05:17:54 +0300 Subject: [PATCH 069/382] Fixed type of onchallenge --- autobahn/autobahn.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index bb7a0c86ae..496738875e 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -211,7 +211,7 @@ declare namespace autobahn { retry_delay_jitter?: number; url?: string; protocols?: string[]; - onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + onchallenge?: OnChallengeHandler; realm?: string; authmethods?: string[]; authid?: string; From 50d20cf6e684b76f26c55eff966735e2db985cd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adrien=20Verg=C3=A9?= Date: Wed, 28 Sep 2016 16:46:08 +0200 Subject: [PATCH 070/382] feat(CKEditor): Add missing typings for `focusManager` --- ckeditor/ckeditor-tests.ts | 19 +++++++++++++++++++ ckeditor/ckeditor.d.ts | 13 ++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/ckeditor/ckeditor-tests.ts b/ckeditor/ckeditor-tests.ts index f7deb67069..bcf2a7807b 100644 --- a/ckeditor/ckeditor-tests.ts +++ b/ckeditor/ckeditor-tests.ts @@ -300,3 +300,22 @@ function test_adding_widget() { }); } } + +function test_focusManager() { + var textarea = document.createElement('textarea'); + var instance = CKEDITOR.replace(textarea); + var element = CKEDITOR.document.getById('myElement'); + + instance.focusManager.focus(); + instance.focusManager.focus(element); + instance.focusManager.lock(); + instance.focusManager.unlock(); + instance.focusManager.blur(); + instance.focusManager.blur(true); + instance.focusManager.add(element, true); + instance.focusManager.remove(element); + + var focusManager = new CKEDITOR.focusManager(instance); + var object: CKEDITOR.dom.domObject = focusManager.currentActive; + var bool: boolean = focusManager.hasFocus; +} diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index 60b6491407..b5009fa031 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -544,8 +544,19 @@ declare namespace CKEDITOR { } - interface focusManager { + class focusManager { + // Properties + currentActive: dom.domObject; + hasFocus: boolean; + // Methods + constructor(editor: editor); + focus(currentActive?: dom.element): void; + lock(): void; + unlock(): void; + blur(noDelay?: boolean): void; + add(element: dom.element, isCapture: boolean): void; + remove(element: dom.element): void; } interface keystrokeHandler { From 119234be457b9a7a12cf0e796c909e5bdf0e2e32 Mon Sep 17 00:00:00 2001 From: TANAKA Koichi Date: Thu, 29 Sep 2016 17:05:58 +0900 Subject: [PATCH 071/382] sequelize: fix return value type of Model.findOrXXX methods http://docs.sequelizejs.com/en/latest/api/model/#findorinitialize-promiseinstance-initialized --- sequelize/sequelize-tests.ts | 25 +++++++++++++------------ sequelize/sequelize.d.ts | 6 +++--- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 5a1dfe4def..80e009f8a2 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -962,22 +962,23 @@ User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Ha User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); -User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); -User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); -User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +let findOrRetVal: Promise<[AnyInstance, boolean]>; +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' } } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); +findOrRetVal = User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); */ -User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); -User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); -User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); -User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); -User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); -User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -User.findOrCreate( { where : 'c', defaults : {} } ); +findOrRetVal = User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); +findOrRetVal = User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); +findOrRetVal = User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); +findOrRetVal = User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); +findOrRetVal = User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); +findOrRetVal = User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); +findOrRetVal = User.findOrCreate( { where : 'c', defaults : {} } ); User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 76c5f46490..27885d0d66 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -3809,8 +3809,8 @@ declare module "sequelize" { * Find a row that matches the query, or build (but don't save) the row if none is found. * The successfull result of the promise will be (instance, initialized) - Make sure to use .spread() */ - findOrInitialize( options : FindOrInitializeOptions ) : Promise; - findOrBuild( options : FindOrInitializeOptions ) : Promise; + findOrInitialize( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; + findOrBuild( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; /** * Find a row that matches the query, or build and save the row if none is found @@ -3823,7 +3823,7 @@ declare module "sequelize" { * an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint * will be created instead, and any unique constraint violation will be handled internally. */ - findOrCreate( options : FindOrInitializeOptions ) : Promise; + findOrCreate( options : FindOrInitializeOptions ) : Promise<[TInstance, boolean]>; /** * A more performant findOrCreate that will not work under a transaction (at least not in postgres) From 2b7104bab0b653ebd2f247b01d51c9a210e33198 Mon Sep 17 00:00:00 2001 From: Denis Carriere Date: Thu, 29 Sep 2016 07:57:54 -0400 Subject: [PATCH 072/382] Added type Point for simplicity Comments from @vladima --- cheap-ruler/cheap-ruler-tests.ts | 19 ++++---- cheap-ruler/cheap-ruler.d.ts | 80 +++++++++++++++++--------------- 2 files changed, 54 insertions(+), 45 deletions(-) diff --git a/cheap-ruler/cheap-ruler-tests.ts b/cheap-ruler/cheap-ruler-tests.ts index 2a1bf6521d..6e2a2d45e7 100644 --- a/cheap-ruler/cheap-ruler-tests.ts +++ b/cheap-ruler/cheap-ruler-tests.ts @@ -3,6 +3,9 @@ import * as cheapRuler from 'cheap-ruler' // -- Fixtures -- +const bbox = [30.5, 50.5, 31, 51] +const point1 = [30.5, 50.5] +const point2 = [30.51, 50.49] const unit = 'miles' const lineString = { "type": "Feature", @@ -46,15 +49,15 @@ cheapRuler.units.kilometers // -- Test cheapRuler -- const ruler = cheapRuler(35.05) -ruler.distance([30.5, 50.5], [30.51, 50.49]) -ruler.bearing([30.5, 50.5], [30.51, 50.49]) -ruler.destination([30.5, 50.5], 0.1, 90) +ruler.distance(point1, point2) +ruler.bearing(point1, point2) +ruler.destination(point1, 0.1, 90) ruler.lineDistance(points) ruler.area(polygon) ruler.along(line, 2.5) -ruler.pointOnLine(line, [-67.04, 50.5]).point -ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line) +ruler.pointOnLine(line, point1).point +ruler.lineSlice(point1, point2, line) ruler.lineSliceAlong(10, 20, line) -ruler.bufferPoint([30.5, 50.5], 0.01) -ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2) -ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]) \ No newline at end of file +ruler.bufferPoint(point1, 0.01) +ruler.bufferBBox(bbox, 0.2) +ruler.insideBBox(point1, bbox) \ No newline at end of file diff --git a/cheap-ruler/cheap-ruler.d.ts b/cheap-ruler/cheap-ruler.d.ts index 187b27ea82..91f417d490 100644 --- a/cheap-ruler/cheap-ruler.d.ts +++ b/cheap-ruler/cheap-ruler.d.ts @@ -4,6 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "cheap-ruler" { + type BBox = [number, number, number, number] | number[] + type Point = [number, number] | number[] + type Line = Array + type Points = Array + type Polygon = Array> + interface TemplateUnits { kilometers: number miles: number @@ -15,7 +21,7 @@ declare module "cheap-ruler" { inches: number } interface InterfacePointOnLine { - point: Array + point: Point index: number t: number } @@ -23,44 +29,44 @@ declare module "cheap-ruler" { /** * Given two points of the form [longitude, latitude], returns the distance. * - * @param {Array} a point [longitude, latitude] - * @param {Array} b point [longitude, latitude] + * @param {Point} a point [longitude, latitude] + * @param {Point} b point [longitude, latitude] * @returns {number} distance * @example * var distance = ruler.distance([30.5, 50.5], [30.51, 50.49]); * //=distance */ - distance(a: Array, b: Array): number; + distance(a: Point, b: Point): number; /** * Returns the bearing between two points in angles. * - * @param {Array} a point [longitude, latitude] - * @param {Array} b point [longitude, latitude] + * @param {Point} a point [longitude, latitude] + * @param {Point} b point [longitude, latitude] * @returns {number} bearing * @example * var bearing = ruler.bearing([30.5, 50.5], [30.51, 50.49]); * //=bearing */ - bearing(a: Array, b: Array): number; + bearing(a: Point, b: Point): number; /** * Returns a new point given distance and bearing from the starting point. * - * @param {Array} p point [longitude, latitude] + * @param {Point} p point [longitude, latitude] * @param {number} dist distance * @param {number} bearing - * @returns {Array} point [longitude, latitude] + * @returns {Point} point [longitude, latitude] * @example * var point = ruler.destination([30.5, 50.5], 0.1, 90); * //=point */ - destination(p: Array, dist: number, bearing: number): Array; + destination(p: Point, dist: number, bearing: number): Point; /** * Given a line (an array of points), returns the total line distance. * - * @param {Array>} points [longitude, latitude] + * @param {Points} points [longitude, latitude] * @returns {number} total line distance * @example * var length = ruler.lineDistance([ @@ -69,12 +75,12 @@ declare module "cheap-ruler" { * ]); * //=length */ - lineDistance(points: Array>): number; + lineDistance(points: Points): number; /** * Given a polygon (an array of rings, where each ring is an array of points), returns the area. * - * @param {Array>>} polygon + * @param {Polygon} polygon * @returns {number} area value in the specified units (square kilometers by default) * @example * var area = ruler.area([[ @@ -83,94 +89,94 @@ declare module "cheap-ruler" { * ]]); * //=area */ - area(polygon: Array>>): number; + area(polygon: Polygon): number; /** * Returns the point at a specified distance along the line. * - * @param {Array>} line + * @param {Line} line * @param {number} dist distance - * @returns {Array} point [longitude, latitude] + * @returns {Point} point [longitude, latitude] * @example * var point = ruler.along(line, 2.5); * //=point */ - along(line: Array>, dist: number): Array + along(line: Line, dist: number): Point /** * Returns an object of the form {point, index} where point is closest point on the line from the given point, and index is the start index of the segment with the closest point. * * @pointOnLine - * @param {Array>} line - * @param {Array} p point [longitude, latitude] + * @param {Line} line + * @param {Point} p point [longitude, latitude] * @returns {Object} {point, index} * @example * var point = ruler.pointOnLine(line, [-67.04, 50.5]).point; * //=point */ - pointOnLine(line: Array>, p: Array): InterfacePointOnLine + pointOnLine(line: Line, p: Point): InterfacePointOnLine /** * Returns a part of the given line between the start and the stop points (or their closest points on the line). * - * @param {Array} start point [longitude, latitude] - * @param {Array} stop point [longitude, latitude] - * @param {Array>} line - * @returns {Array>} line part of a line + * @param {Point} start point [longitude, latitude] + * @param {Point} stop point [longitude, latitude] + * @param {Line} line + * @returns {Line} line part of a line * @example * var line2 = ruler.lineSlice([-67.04, 50.5], [-67.05, 50.56], line1); * //=line2 */ - lineSlice(start: Array, stop: Array, line: Array>): Array> + lineSlice(start: Point, stop: Point, line: Line): Line /** * Returns a part of the given line between the start and the stop points indicated by distance along the line. * * @param {number} start distance * @param {number} stop distance - * @param {Array>} line - * @returns {Array>} line part of a line + * @param {Line} line + * @returns {Line} line part of a line * @example * var line2 = ruler.lineSliceAlong(10, 20, line1); * //=line2 */ - lineSliceAlong(start: number, stop: number, line: Array>): Array> + lineSliceAlong(start: number, stop: number, line: Line): Line /** * Given a point, returns a bounding box object ([w, s, e, n]) created from the given point buffered by a given distance. * - * @param {Array} p point [longitude, latitude] + * @param {Point} p point [longitude, latitude] * @param {number} buffer - * @returns {Array} box object ([w, s, e, n]) + * @returns {BBox} box object ([w, s, e, n]) * @example * var bbox = ruler.bufferPoint([30.5, 50.5], 0.01); * //=bbox */ - bufferPoint(p: Array, buffer: number): Array + bufferPoint(p: Point, buffer: number): BBox /** * Given a bounding box, returns the box buffered by a given distance. * - * @param {Array} box object ([w, s, e, n]) + * @param {BBox} box object ([w, s, e, n]) * @param {number} buffer - * @returns {Array} box object ([w, s, e, n]) + * @returns {BBox} box object ([w, s, e, n]) * @example * var bbox = ruler.bufferBBox([30.5, 50.5, 31, 51], 0.2); * //=bbox */ - bufferBBox(bbox: Array, buffer: number): Array + bufferBBox(bbox: BBox, buffer: number): BBox /** * Returns true if the given point is inside in the given bounding box, otherwise false. * - * @param {Array} p point [longitude, latitude] - * @param {Array} box object ([w, s, e, n]) + * @param {Point} p point [longitude, latitude] + * @param {Point} box object ([w, s, e, n]) * @returns {boolean} * @example * var inside = ruler.insideBBox([30.5, 50.5], [30, 50, 31, 51]); * //=inside */ - insideBBox(p: Array, bbox: Array): boolean + insideBBox(p: Point, bbox: BBox): boolean } /** * A collection of very fast approximations to common geodesic measurements. Useful for performance-sensitive code that measures things on a city scale. From f3c98e74a04b199ca4c6acc6ceeec5691dc2cb70 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 29 Sep 2016 08:59:12 -0400 Subject: [PATCH 073/382] add interface for mongoose document optional properties --- mongoose/mongoose.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 631e9c9581..9e5600e696 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -715,7 +715,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - class MongooseDocument { + class MongooseDocument implements MongooseDocumentOptionals { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; @@ -870,8 +870,6 @@ declare module "mongoose" { /** Hash containing current validation errors. */ errors: Object; - /** The string version of this documents _id. */ - id?: string; /** This documents _id. */ _id: any; /** Boolean flag specifying if the document is new. */ @@ -880,6 +878,11 @@ declare module "mongoose" { schema: Schema; } + interface MongooseDocumentOptionals { + /** The string version of this documents _id. */ + id?: string; + } + interface DocumentToObjectOptions { /** apply all getters (path and virtual getters) */ getters?: boolean; From 2f74c100a1b567675c9cb374fc7039d5a5ce8f13 Mon Sep 17 00:00:00 2001 From: George Edwards Date: Thu, 29 Sep 2016 16:17:37 +0100 Subject: [PATCH 074/382] optional constructor for RecurrenceRule --- node-schedule/node-schedule.d.ts | 56 ++++++++++++++++---------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/node-schedule/node-schedule.d.ts b/node-schedule/node-schedule.d.ts index 5127eafb40..1b15f9c34c 100644 --- a/node-schedule/node-schedule.d.ts +++ b/node-schedule/node-schedule.d.ts @@ -13,7 +13,7 @@ declare module 'node-schedule' { * The callback executed by a Job */ export interface JobCallback { - ():void; + (): void; } /** @@ -25,7 +25,7 @@ declare module 'node-schedule' { /** * This Job's name. read-only. */ - name:string; + name: string; /** * Use the function scheduleJob() to create new Job objects. @@ -36,7 +36,7 @@ declare module 'node-schedule' { * @param {JobCallback|Function} job either this Job's callback or an optional callback function * @param {Function} callback optional callback that is executed right before the JobCallback */ - constructor(name: string|JobCallback, job?: JobCallback|Function, callback?: Function); + constructor(name: string | JobCallback, job?: JobCallback | Function, callback?: Function); /** * Adds an Invocation to this job. For internal use. @@ -44,7 +44,7 @@ declare module 'node-schedule' { * @param {Invocation} invokation * @return {boolean} whether the invocation could be added */ - trackInvocation(invokation:Invocation):boolean; + trackInvocation(invokation: Invocation): boolean; /** * removes an Invocation from this Job's tracking list. For internal use. @@ -52,69 +52,69 @@ declare module 'node-schedule' { * @param invocation {Invocation} * @return boolean whether the invocation was successful. Removing an Invocation that doesn't exist, returns false. */ - stopTrackingInvocation(invocation:Invocation):boolean; + stopTrackingInvocation(invocation: Invocation): boolean; /** * @internal * @return {number} the number of currently running instances of this Job. */ - triggeredJobs():number; + triggeredJobs(): number; /** * set the number of currently running Jobs. * @internal * @param triggeredJobs */ - setTriggeredJobs(triggeredJobs:number):void; + setTriggeredJobs(triggeredJobs: number): void; /** * cancel all pending Invocations of this Job. * @param reschedule {boolean} whether to reschedule the canceled Invocations. */ - cancel(reschedule?:boolean):boolean; + cancel(reschedule?: boolean): boolean; /** * cancel the next Invocation of this Job. * @param reschedule {boolean} whether to reschedule the canceled Invocation. * @return {boolean} whether cancelation was successful */ - cancelNext(reschedule?:boolean):boolean; + cancelNext(reschedule?: boolean): boolean; /** * Changes the scheduling information for this Job. * @param spec {RecurrenceRule|string|number} the * @return {boolean} whether the reschedule was successful */ - reschedule(spec:RecurrenceRule|string|number):boolean; + reschedule(spec: RecurrenceRule | string | number): boolean; /** * Returns the Date on which this Job will be run next. * @return {Date} */ - nextInvocation():Date; + nextInvocation(): Date; /** * @return Invocation[] a list of all pending Invocations */ - pendingInvocations():Invocation[]; + pendingInvocations(): Invocation[]; /** * run this Job immediately. */ - invoke():void; + invoke(): void; /** * schedule this Job to be run on the specified date. * @param date {Date} */ - runOnDate(date:Date): void; + runOnDate(date: Date): void; /** * set scheduling information * @param {Date|string|number} date * @public */ - schedule(date: Date|string|number): boolean; + schedule(date: Date | string | number): boolean; } /** @@ -160,7 +160,7 @@ declare module 'node-schedule' { * @public * @type {number|Array} */ - dayOfWeek: number|Array; + dayOfWeek: number | Array; /** * Hour. @@ -202,15 +202,15 @@ declare module 'node-schedule' { */ year: number; - constructor(year:number, - month:number, - date:number, - dayOfWeek:number|Array, - hour:number, - minute:number, - second:number); + constructor(year?: number, + month?: number, + date?: number, + dayOfWeek?: number | Array, + hour?: number, + minute?: number, + second?: number); - nextInvocationDate(base:Date):Date; + nextInvocationDate(base: Date): Date; } /** @@ -269,7 +269,7 @@ declare module 'node-schedule' { * @param {RecurrenceRule|Date|string} rule either the scheduling info or the JobCallback * @param {JobCallback} callback The callback to be executed on each invocation. */ - export function scheduleJob(name:string|RecurrenceRule|Date, rule: RecurrenceRule|Date|string|JobCallback, callback?: JobCallback): Job; + export function scheduleJob(name: string | RecurrenceRule | Date, rule: RecurrenceRule | Date | string | JobCallback, callback?: JobCallback): Job; /** * Changes the timing of a Job, canceling all pending invocations. @@ -278,12 +278,12 @@ declare module 'node-schedule' { * @param spec {JobCallback} the new timing for this Job * @return {Job} if the job could be rescheduled, {null} otherwise. */ - export function rescheduleJob(job:Job|string, spec:RecurrenceRule|Date|string):Job; + export function rescheduleJob(job: Job | string, spec: RecurrenceRule | Date | string): Job; /** * Dictionary of all Jobs, accessible by name. */ - export let scheduledJobs:{[jobName:string]:Job}; + export let scheduledJobs: { [jobName: string]: Job }; /** * Cancels the job. @@ -291,5 +291,5 @@ declare module 'node-schedule' { * @param {Job} job The job. * @returns {boolean} {true} if the job has been cancelled with success, otherwise, {false}. */ - export function cancelJob(job: Job|string): boolean; + export function cancelJob(job: Job | string): boolean; } From dee341230c59586a132f045eee7eefbdd88ca542 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:14:43 +0800 Subject: [PATCH 075/382] fix the framework type --- passport/passport-tests.ts | 55 +++++++++++++++++++++++++------------- passport/passport.d.ts | 12 ++++++--- 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/passport/passport-tests.ts b/passport/passport-tests.ts index 423d925b4c..8b02c96c76 100644 --- a/passport/passport-tests.ts +++ b/passport/passport-tests.ts @@ -7,19 +7,34 @@ import passport = require('passport'); class TestStrategy implements passport.Strategy { public name: string = 'test'; - constructor() {} - authenticate(req: express.Request) {} + constructor() { } + authenticate(req: express.Request) { } } +const newFramework:passport.Framework = { + initialize: function () { + return function () { }; + }, + authenticate: function (passport, name, options) { + return function () { + return 'authenticate(): ' + name + ' ' + options; + }; + }, + authorize: function (passport, name, options) { + return function () { + return 'authorize(): ' + name + ' ' + options; + } + } +}; passport.use(new TestStrategy()); -passport.framework('test'); -passport.serializeUser((user, done) => {}); -passport.deserializeUser((id, done) => {}); +passport.framework(newFramework); +passport.serializeUser((user, done) => { }); +passport.deserializeUser((id, done) => { }); passport.use(new TestStrategy()) .unuse('test') .use(new TestStrategy()) - .framework('test-fw'); + .framework(newFramework); var app = express(); @@ -28,27 +43,27 @@ app.configure(() => { app.use(passport.session()); }); -app.post('/login', +app.post('/login', passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), - function(req, res) { + function (req, res) { res.redirect('/'); }); -app.post('/login', function(req, res, next) { - passport.authenticate('local', function(err: any, user: { username: string; }, info: { message: string; }) { +app.post('/login', function (req, res, next) { + passport.authenticate('local', function (err: any, user: { username: string; }, info: { message: string; }) { if (err) { return next(err) } if (!user) { req.session['error'] = info.message; return res.redirect('/login') } - req.logIn(user, function(err) { + req.logIn(user, function (err) { if (err) { return next(err); } return res.redirect('/users/' + user.username); }); })(req, res, next); }); -app.get('/logout', function(req, res) { +app.get('/logout', function (req, res) { req.logout(); res.redirect('/'); }); @@ -66,20 +81,22 @@ function authSetting(): void { }; app.get('/auth/facebook', - passport.authenticate('facebook')); + passport.authenticate('facebook')); app.get('/auth/facebook/callback', - passport.authenticate('facebook', authOption), successCallback); + passport.authenticate('facebook', authOption), successCallback); app.get('/auth/twitter', - passport.authenticate('twitter')); + passport.authenticate('twitter')); app.get('/auth/twitter/callback', - passport.authenticate('twitter', authOption)); + passport.authenticate('twitter', authOption)); app.get('/auth/google', - passport.authenticate('google', { scope: - [ 'https://www.googleapis.com/auth/userinfo.profile' ] })); + passport.authenticate('google', { + scope: + ['https://www.googleapis.com/auth/userinfo.profile'] + })); app.get('/auth/google/callback', - passport.authenticate('google', authOption), successCallback); + passport.authenticate('google', authOption), successCallback); } diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 470c0dc79c..3723176970 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -30,7 +30,7 @@ declare module 'passport' { function use(strategy: Strategy): Passport; function use(name: string, strategy: Strategy): Passport; function unuse(name: string): Passport; - function framework(fw: string): Passport; + function framework(fw: Framework): Passport; function initialize(options?: { userProperty: string; }): express.Handler; function session(options?: { pauseStream: boolean; }): express.Handler; @@ -50,7 +50,7 @@ declare module 'passport' { use(strategy: Strategy): Passport; use(name: string, strategy: Strategy): Passport; unuse(name: string): Passport; - framework(fw: string): Passport; + framework(fw: Framework): Passport; initialize(options?: { userProperty: string; }): express.Handler; session(options?: { pauseStream: boolean; }): express.Handler; @@ -76,7 +76,7 @@ declare module 'passport' { provider: string; id: string; displayName: string; - name? : { + name?: { familyName: string; givenName: string; middleName?: string; @@ -89,4 +89,10 @@ declare module 'passport' { value: string; }[]; } + + interface Framework { + initialize(): Function; + authenticate(passport: Passport, name: string, options?: Object):Function; + authorize(passport: Passport, name: string, options?: Object):Function; + } } From 6a78378d1722551c35ba0584261963b572b288cd Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:47:32 +0800 Subject: [PATCH 076/382] add parameter support in initialize() --- passport/passport.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 3723176970..6c3e755974 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -91,8 +91,8 @@ declare module 'passport' { } interface Framework { - initialize(): Function; - authenticate(passport: Passport, name: string, options?: Object):Function; - authorize(passport: Passport, name: string, options?: Object):Function; + initialize(passport: Passport, options?: Object): Function; + authenticate(passport: Passport, name: string, options?: Object): Function; + authorize(passport: Passport, name: string, options?: Object): Function; } } From 30e0200d506cd785c971680d80bc8eb11b296b49 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Thu, 29 Sep 2016 23:50:04 +0800 Subject: [PATCH 077/382] add callback parameter --- passport/passport.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 6c3e755974..536cb27d3b 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -92,7 +92,7 @@ declare module 'passport' { interface Framework { initialize(passport: Passport, options?: Object): Function; - authenticate(passport: Passport, name: string, options?: Object): Function; - authorize(passport: Passport, name: string, options?: Object): Function; + authenticate(passport: Passport, name: string, options?: Object, callback?: Function): Function; + authorize(passport: Passport, name: string, options?: Object, callback?: Function): Function; } } From c8a69b0b0c71cc00d4ada94a4420fb037b3cc9cd Mon Sep 17 00:00:00 2001 From: dan-def Date: Thu, 29 Sep 2016 17:29:22 +0100 Subject: [PATCH 078/382] Added promise() to the JQueryPromise interface jQuery allows calling a promise() function on a Promise object. Updated the interface to reflect this. --- jquery/jquery.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index b08598cc53..f8af62caba 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -344,6 +344,13 @@ interface JQueryPromise extends JQueryGenericPromise { // Deprecated - given no typings pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; } /** From 819954b127f4aa5abfad43965270858a0ec5ea93 Mon Sep 17 00:00:00 2001 From: unHealthy Date: Fri, 30 Sep 2016 02:10:29 +0800 Subject: [PATCH 079/382] optional authorize --- passport/passport.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/passport/passport.d.ts b/passport/passport.d.ts index 536cb27d3b..088156b2d3 100644 --- a/passport/passport.d.ts +++ b/passport/passport.d.ts @@ -93,6 +93,6 @@ declare module 'passport' { interface Framework { initialize(passport: Passport, options?: Object): Function; authenticate(passport: Passport, name: string, options?: Object, callback?: Function): Function; - authorize(passport: Passport, name: string, options?: Object, callback?: Function): Function; + authorize?(passport: Passport, name: string, options?: Object, callback?: Function): Function; } } From 71ae898a05164dc2a583ab75541ee67bee697b1d Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 22:56:24 +0300 Subject: [PATCH 080/382] add contains fn --- ip/ip.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ip/ip.d.ts b/ip/ip.d.ts index 0542ae0785..1c00f1320e 100644 --- a/ip/ip.d.ts +++ b/ip/ip.d.ts @@ -14,6 +14,7 @@ interface SubnetInfo { subnetMaskLength: number; numHosts: number; length: number; + contains(ip: string): boolean; } declare module "ip" { @@ -112,4 +113,4 @@ declare module "ip" { * @param cidr CIDR address. */ export function cidrSubnet(cidr: string): SubnetInfo; -} \ No newline at end of file +} From 43d17ebbfe625e339cdf4b30dcca5dc2cef51292 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 22:57:17 +0300 Subject: [PATCH 081/382] Update ip-tests.ts --- ip/ip-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/ip/ip-tests.ts b/ip/ip-tests.ts index 338c2bc040..3210871ee0 100644 --- a/ip/ip-tests.ts +++ b/ip/ip-tests.ts @@ -19,3 +19,4 @@ var buff:any = ip.toBuffer(myIP); ip.toString(buff); ip.subnet('192.168.1.134', '255.255.255.192'); ip.cidrSubnet('192.168.1.134/26'); +ip.cidrSubnet('192.168.1.134/26').contains('192.168.1.134'); From c4e9d77c1899652d9ed320f35ccd85bd7b6f5e29 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 29 Sep 2016 23:48:42 +0300 Subject: [PATCH 082/382] add id --- express-session/express-session.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 90e1ed07cc..0320ff1aed 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,11 +10,14 @@ declare namespace Express { export interface Request { session?: Session; + readonly sessionId: string; } export interface Session { [key: string]: any; + readonly id: string; + regenerate: (callback: (err: any) => void) => void; destroy: (callback: (err: any) => void) => void; reload: (callback: (err: any) => void) => void; From 9c8c07801e8c65631d9dc563d3ef1604ac009d4d Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 00:00:15 +0300 Subject: [PATCH 083/382] remove readonly --- express-session/express-session.d.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 0320ff1aed..c685c8a1bb 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,13 +10,12 @@ declare namespace Express { export interface Request { session?: Session; - readonly sessionId: string; + sessionId?: string; } export interface Session { [key: string]: any; - - readonly id: string; + id: string; regenerate: (callback: (err: any) => void) => void; destroy: (callback: (err: any) => void) => void; From 5a0b946a42315f58b3f5fdd3de6dc70e9f24cfea Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 01:16:45 +0300 Subject: [PATCH 084/382] add touch after --- connect-mongo/connect-mongo.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/connect-mongo/connect-mongo.d.ts b/connect-mongo/connect-mongo.d.ts index 49f93e2d46..7c779e2d07 100644 --- a/connect-mongo/connect-mongo.d.ts +++ b/connect-mongo/connect-mongo.d.ts @@ -78,6 +78,12 @@ declare module "connect-mongo" { * (Default: 10) */ autoRemoveInterval?: number; + + + /** + * don't save session if unmodified + */ + touchAfter?: number; } export interface MongoUrlOptions extends DefaultOptions { From 30b38b4e5a16967e9f4c07b4be5da58c04213700 Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Fri, 30 Sep 2016 06:49:17 +0300 Subject: [PATCH 085/382] fix typo --- express-session/express-session.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index c685c8a1bb..9af409ddc5 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -10,7 +10,7 @@ declare namespace Express { export interface Request { session?: Session; - sessionId?: string; + sessionID?: string; } export interface Session { From 10940d2b423df0e8f5d32402dddea000fb492a1c Mon Sep 17 00:00:00 2001 From: dan-def Date: Fri, 30 Sep 2016 08:49:00 +0100 Subject: [PATCH 086/382] Added tests for the promise() method on jqXHR Ensures that the jqXHR object exposes a standard promise because it implements the JQueryPromise interface. --- jquery/jquery-tests.ts | 44 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/jquery/jquery-tests.ts b/jquery/jquery-tests.ts index d031535184..c5ee51df15 100644 --- a/jquery/jquery-tests.ts +++ b/jquery/jquery-tests.ts @@ -209,6 +209,50 @@ function test_ajax() { url: "test.js" }); jqXHR.abort('aborting because I can'); + + //Test the promise exposed by the jqXHR object + + // done method + $.ajax({ + url: "test.js" + }).promise().done((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // fail method + $.ajax({ + url: "test.js" + }).promise().fail((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // always method with successful request + $.ajax({ + url: "test.js" + }).promise().always((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }); + + // always method with failed request + $.ajax({ + url: "test.js" + }).promise().always((jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // then method (as of 1.8) + $.ajax({ + url: "test.js" + }).promise().then((data, textStatus, jqXHR) => { + console.log(data, textStatus, jqXHR); + }, (jqXHR, textStatus, errorThrown) => { + console.log(jqXHR, textStatus, errorThrown); + }); + + // generic then method + var p: JQueryPromise = $.ajax({ url: "test.js" }).promise() + .then(() => "Hello") + .then((x) => x.length); } function test_ajaxComplete() { From 62566b86d7e7f23ab88cd3ec8ede5448c57b94c0 Mon Sep 17 00:00:00 2001 From: JulienBourgain Date: Fri, 30 Sep 2016 14:05:41 +0200 Subject: [PATCH 087/382] angular-dynamic-local Add "storageKey" definition (#11566) Add "storageKey" definition cf : https://github.com/lgalfaso/angular-dynamic-locale/blob/master/src/tmhDynamicLocale.js#L197 --- angular-dynamic-locale/angular-dynamic-locale.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/angular-dynamic-locale/angular-dynamic-locale.d.ts b/angular-dynamic-locale/angular-dynamic-locale.d.ts index 4b7a1f9656..210a50f4aa 100644 --- a/angular-dynamic-locale/angular-dynamic-locale.d.ts +++ b/angular-dynamic-locale/angular-dynamic-locale.d.ts @@ -20,6 +20,7 @@ declare namespace angular.dynamicLocale { interface tmhDynamicLocaleProvider extends angular.IServiceProvider { localeLocationPattern(location: string): tmhDynamicLocaleProvider; localeLocationPattern(): string; + storageKey(storageKey: string): void; useStorage(storageName: string): void; useCookieStorage(): void; } From 67205ae0907a7bd1e9e11259c6c18abb0d71e8b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niko=20Kova=C4=8Di=C4=8D?= Date: Fri, 30 Sep 2016 14:05:53 +0200 Subject: [PATCH 088/382] Added declare module for easier including. (#11562) --- angular-signalr-hub/angular-signalr-hub-tests.ts | 2 +- angular-signalr-hub/angular-signalr-hub.d.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index d20457bcdc..1e7c90c962 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -1,5 +1,5 @@ -/// /// +/// angular .module('app', ['SignalR']) diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts index 03fa6427eb..8d331ffd75 100644 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -3,8 +3,14 @@ // Definitions by: Adam Santaniello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /// +declare module "angular-signalr-hub" { + let _: string; + export = _; +} + declare namespace ngSignalr { interface HubFactory { /** From 96e0dfcf7c1d7328eb9c3c1a210358fd2c6086f9 Mon Sep 17 00:00:00 2001 From: iskandersierra Date: Fri, 30 Sep 2016 14:07:58 +0200 Subject: [PATCH 089/382] Adding recompose@0.20.2 typings (#11577) * Added typings for change-emitter@0.1.2 * Adding recompose@0.20.2 typings --- recompose/recompose-tests.tsx | 171 +++++++++++++++++ recompose/recompose.d.ts | 334 ++++++++++++++++++++++++++++++++++ 2 files changed, 505 insertions(+) create mode 100644 recompose/recompose-tests.tsx create mode 100644 recompose/recompose.d.ts diff --git a/recompose/recompose-tests.tsx b/recompose/recompose-tests.tsx new file mode 100644 index 0000000000..714ce83d66 --- /dev/null +++ b/recompose/recompose-tests.tsx @@ -0,0 +1,171 @@ +/// + +import * as React from "react"; +import { + Component, + // Higher-order components + mapProps, withProps, withPropsOnChange, withHandlers, + defaultProps, renameProp, renameProps, flattenProp, + withState, withReducer, branch, renderComponent, + renderNothing, shouldUpdate, pure, onlyUpdateForKeys, + onlyUpdateForPropTypes, withContext, getContext, + lifecycle, toClass, + // Static property helpers + setStatic, setPropTypes, setDisplayName, + // Utilities + compose, getDisplayName, wrapDisplayName, shallowEqual, + isClassComponent, createEagerElement, createEagerFactory, + createSink, componentFromProp, nest, hoistStatics, + // Observable utilities + componentFromStream, mapPropsStream, createEventHandler, + setObservableConfig, +} from "recompose"; +import rxjsconfig from "recompose/rxjsObservableConfig"; +import rxjs4config from "recompose/rxjs4ObservableConfig"; +import mostConfig from "recompose/mostObservableConfig"; +import xstreamConfig from "recompose/xstreamObservableConfig"; +import baconConfig from "recompose/baconObservableConfig"; +import kefirConfig from "recompose/kefirObservableConfig"; + +function testMapProps() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = mapProps((props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testWithProps() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = withProps((props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withProps({ inn: 123 } as InnerProps); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithPropsOnChange() { + interface InnerProps { inn: number } + interface OutterProps { out: string } + const innerComponent = ({inn}: InnerProps) =>
{inn}
; + + const enhancer = withPropsOnChange( + (props: OutterProps, nextProps: OutterProps) => true, + (props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withPropsOnChange( + [ "out" ], + (props: OutterProps) => ({ inn: 123 } as InnerProps)); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithHandlers() { + interface InnerProps { onSubmit: Function; onChange: Function; } + interface OutterProps { out: string } + const innerComponent = ({onChange, onSubmit}: InnerProps) => +
; + + const enhancer = withHandlers({ + onChange: (props: OutterProps) => (e: any) => {}, + onSubmit: (props: OutterProps) => (e: any) => {}, + }); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testDefaultProps() { + interface Props { a?: string; b?: number; } + const innerComponent = ({a, b}: Props) =>
{a}, {b}
; + + const enhancer = defaultProps({ a: "answer", b: 42 }); + const enhanced: React.StatelessComponent = enhancer(innerComponent); +} + +function testRenameProp() { + interface InnerProps { c: string; b: number; } + interface OutterProps { a: string; b: number; } + const innerComponent: React.StatelessComponent = ({c, b}: InnerProps) =>
{c}, {b}
; + + const enhancer = renameProp("a", "c"); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testRenameProps() { + interface InnerProps { c: string; d: number; } + interface OutterProps { a: string; b: number; } + const innerComponent: React.StatelessComponent = ({c, d}: InnerProps) =>
{c}, {d}
; + + const enhancer = renameProps({ a:"c", b: "d" }); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testFlattenProp() { + interface InnerProps { a: string; b: string; y: {c: string; d: number;} } + interface OutterProps { x: {a: string; b: number;}; y: {c: string; d: number;} } + const innerComponent: React.StatelessComponent = (props: InnerProps) =>
; + + const enhancer = flattenProp("x"); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testWithState() { + interface InnerProps { count: number; setCount: (count: number) => void } + interface OutterProps { title: string } + const innerComponent: React.StatelessComponent = (props) => +
props.setCount(0)}>
; + + const enhancer = withState("count", "setCount", 0); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withState("count", "setCount", + (p: OutterProps) => p.title.length); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testWithReducer() { + interface State { count: number } + interface Action { type: string } + interface InnerProps { title: string; count: number; dispatch: (a: Action) => void; } + interface OutterProps { title: string; } + const innerComponent: React.StatelessComponent = (props: InnerProps) => +
props.dispatch({type: "INCREMENT"})}>
; + + const enhancer = withReducer("count", "dispatch", + (s: number, a: Action) => s + 1, 0); + const enhanced: React.ComponentClass = enhancer(innerComponent); + + const enhancer2 = withReducer("count", "dispatch", + (s: number, a: Action) => s + 1, + (props: OutterProps) => props.title.length); + const enhanced2: React.ComponentClass = enhancer2(innerComponent); +} + +function testBranch() { + interface InnerProps { count: number; update: () => void; } + interface OutterProps { toggled: boolean } + + const innerComponent: React.StatelessComponent = (props: InnerProps) => +
props.update()}>{props.count}
; + + const enhancer = branch( + (props: OutterProps) => props.toggled, + withState("count", "update", 0), + withState("count", "update", 100) + ); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + +function testRenderComponent() { + interface InnerProps { count: number; update: () => void; } + interface OutterProps { toggled: boolean } + + const innerComponent = () =>
Hello
; + + const enhancer = renderComponent(() => Nop!); + const enhanced: React.ComponentClass = enhancer(innerComponent); +} + diff --git a/recompose/recompose.d.ts b/recompose/recompose.d.ts new file mode 100644 index 0000000000..cef352dc7c --- /dev/null +++ b/recompose/recompose.d.ts @@ -0,0 +1,334 @@ +// Type definitions for Recompose v0.20.2 +// Project: https://github.com/acdlite/recompose +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'recompose' { + + import * as React from 'react'; + import { ComponentClass, StatelessComponent, ValidationMap } from 'react'; + + type Component

= ComponentClass

| StatelessComponent

; + type mapper = (input: TInner) => TOutter; + type predicate = mapper; + type predicateDiff = (current: T, next: T) => boolean + interface Subscribable { + subscribe: Function; + } + + interface ComponentEnhancer { + (component: Component): ComponentClass; + } + interface InferableComponentEnhancer { + )>(component: TComp): TComp; + } + + + // Higher-order components: https://github.com/acdlite/recompose/blob/master/docs/API.md#higher-order-components + + // mapProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#mapprops + export function mapProps( + propsMapper: mapper + ): ComponentEnhancer; + + // withProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#withprops + export function withProps( + createProps: TInner | mapper + ): ComponentEnhancer; + + // withPropsOnChange: https://github.com/acdlite/recompose/blob/master/docs/API.md#withpropsonchange + export function withPropsOnChange( + shouldMapOrKeys: string[] | predicateDiff, + createProps: mapper + ): ComponentEnhancer; + + // withHandlers: https://github.com/acdlite/recompose/blob/master/docs/API.md#withhandlers + type EventHandler = Function; + type HandleCreators = { + [handlerName: string]: mapper; + }; + export function withHandlers( + handlerCreators: HandleCreators + ): ComponentEnhancer; + + // defaultProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#defaultprops + export function defaultProps( + props: Object + ): InferableComponentEnhancer; + + // renameProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#renameProp + export function renameProp( + outterName: string, innerName: string + ): ComponentEnhancer; + + // renameProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#renameProps + type NameMap = { + [outterName: string]: string; + }; + export function renameProps( + nameMap: NameMap + ): ComponentEnhancer; + + // flattenProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#flattenProp + export function flattenProp( + propName: string + ): ComponentEnhancer; + + // withState: https://github.com/acdlite/recompose/blob/master/docs/API.md#withState + export function withState( + stateName: string, + stateUpdaterName: string, + initialState: any | mapper + ): ComponentEnhancer void }*/, TOutter>; + + // withReducer: https://github.com/acdlite/recompose/blob/master/docs/API.md#withReducer + type reducer = (s: TState, a: TAction) => TState; + export function withReducer( + stateName: string, + dispatchName: string, + reducer: reducer, + initialState: TState + ): ComponentEnhancer; + export function withReducer( + stateName: string, + dispatchName: string, + reducer: reducer, + initialState: (props: TOutter) => TState + ): ComponentEnhancer; + + // branch: https://github.com/acdlite/recompose/blob/master/docs/API.md#branch + export function branch( + test: predicate, + trueEnhancer: InferableComponentEnhancer, + falseEnhancer: InferableComponentEnhancer + ): ComponentEnhancer; + + // renderComponent: https://github.com/acdlite/recompose/blob/master/docs/API.md#renderComponent + export function renderComponent( + component: string | Component + ): ComponentEnhancer; + + // renderNothing: https://github.com/acdlite/recompose/blob/master/docs/API.md#renderNothing + export const renderNothing: InferableComponentEnhancer; + + // shouldUpdate: https://github.com/acdlite/recompose/blob/master/docs/API.md#shouldUpdate + export function shouldUpdate( + test: predicateDiff + ): InferableComponentEnhancer; + + // pure: https://github.com/acdlite/recompose/blob/master/docs/API.md#pure + export function pure)> + (component: TComp): TComp; + + // onlyUpdateForKeys: https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyUpdateForKeys + export function onlyUpdateForKeys( + propKeys: Array + ) : InferableComponentEnhancer; + + // onlyUpdateForPropTypes: https://github.com/acdlite/recompose/blob/master/docs/API.md#onlyUpdateForPropTypes + export const onlyUpdateForPropTypes: InferableComponentEnhancer; + + // withContext: https://github.com/acdlite/recompose/blob/master/docs/API.md#withContext + export function withContext( + childContextTypes: ValidationMap, + getChildContext: mapper + ) : InferableComponentEnhancer; + + // getContext: https://github.com/acdlite/recompose/blob/master/docs/API.md#getContext + export function getContext( + contextTypes: ValidationMap + ) : InferableComponentEnhancer; + + // lifecycle: https://github.com/acdlite/recompose/blob/master/docs/API.md#lifecycle + interface ReactLifeCycleFunctions { + componentWillMount?: Function; + componentDidMount?: Function; + componentWillReceiveProps?: Function; + shouldComponentUpdate?: Function; + componentWillUpdate?: Function; + componentDidUpdate?: Function; + componentWillUnmount?: Function; + } + export function lifecycle( + spec: ReactLifeCycleFunctions + ): InferableComponentEnhancer; + + // toClass: https://github.com/acdlite/recompose/blob/master/docs/API.md#toClass + export const toClass: InferableComponentEnhancer; + + + // Static property helpers: https://github.com/acdlite/recompose/blob/master/docs/API.md#static-property-helpers + + // setStatic: https://github.com/acdlite/recompose/blob/master/docs/API.md#setStatic + export function setStatic( + key: string, value: any + ): ComponentEnhancer; + + // setPropTypes: https://github.com/acdlite/recompose/blob/master/docs/API.md#setPropTypes + export function setPropTypes( + propTypes: ValidationMap + ): ComponentEnhancer; + + // setDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#setDisplayName + export function setDisplayName( + displayName: string + ): ComponentEnhancer; + + + // Utilities: https://github.com/acdlite/recompose/blob/master/docs/API.md#utilities + + // compose: https://github.com/acdlite/recompose/blob/master/docs/API.md#compose + export function compose( + ...functions: Function[] + ): ComponentEnhancer; + // export function compose( + // ...functions: Array + // ): ComponentEnhancer; + // export function compose( + // ...functions: Array + // ): ComponentEnhancer; + + // getDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#getDisplayName + export function getDisplayName( + component: Component + ): string; + + // wrapDisplayName: https://github.com/acdlite/recompose/blob/master/docs/API.md#wrapDisplayName + export function wrapDisplayName( + component: Component, + wrapperName: string + ): string; + + // shallowEqual: https://github.com/acdlite/recompose/blob/master/docs/API.md#shallowEqual + export function shallowEqual( + a: Object, b: Object + ): boolean; + + // isClassComponent: https://github.com/acdlite/recompose/blob/master/docs/API.md#isClassComponent + export function isClassComponent( + value: any + ): boolean; + + // createEagerElement: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEagerElement + export function createEagerElement( + type: Component | string, + props?: Object, + children?: React.ReactNode + ): React.ReactElement; + + // createEagerFactory: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEagerFactory + type componentFactory = (props?: Object, children?: React.ReactNode) => React.ReactElement; + export function createEagerFactory( + type: Component | string + ): componentFactory; + + // createSink: https://github.com/acdlite/recompose/blob/master/docs/API.md#createSink + export function createSink( + callback: (props: Object) => void + ): React.ComponentClass; // ??? + + // componentFromProp: https://github.com/acdlite/recompose/blob/master/docs/API.md#componentFromProp + export function componentFromProp( + propName: string + ): StatelessComponent; + + // nest: https://github.com/acdlite/recompose/blob/master/docs/API.md#nest + export function nest( + ...Components: (string | Component)[] + ): React.ComponentClass; // ??? + + // hoistStatics: https://github.com/acdlite/recompose/blob/master/docs/API.md#hoistStatics + export function hoistStatics( + hoc: InferableComponentEnhancer + ): InferableComponentEnhancer; + + + + // Observable utilities: https://github.com/acdlite/recompose/blob/master/docs/API.md#observable-utilities + + // componentFromStream: https://github.com/acdlite/recompose/blob/master/docs/API.md#componentFromStream + export function componentFromStream( + propsToReactNode: mapper, Subscribable> + ): Component; // ??? + + // mapPropsStream: https://github.com/acdlite/recompose/blob/master/docs/API.md#mapPropsStream + export function mapPropsStream( + transform: mapper, Subscribable> + ): ComponentEnhancer; + + // createEventHandler: https://github.com/acdlite/recompose/blob/master/docs/API.md#createEventHandler + type EventHandlerOf> = { + handler: (value: T) => void; + stream: TSubs; + }; + export function createEventHandler>(): EventHandlerOf; + + // setObservableConfig: https://github.com/acdlite/recompose/blob/master/docs/API.md#setObservableConfig + type ObservableConfig = { + fromESObservable?: (observable: Subscribable) => any; + toESObservable?: (stream: any) => Subscribable; + }; + export function setObservableConfig(config: ObservableConfig): void; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#rxjs +declare module 'recompose/rxjsObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const rxjsconfig: ObservableConfig; + + export default rxjsconfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#rxjs-4-legacy +declare module 'recompose/rxjs4ObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const rxjs4config: ObservableConfig; + + export default rxjs4config; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#most +declare module 'recompose/mostObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const mostConfig: ObservableConfig; + + export default mostConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#xstream +declare module 'recompose/xstreamObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const xstreamConfig: ObservableConfig; + + export default xstreamConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#bacon +declare module 'recompose/baconObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const baconConfig: ObservableConfig; + + export default baconConfig; +} + +// https://github.com/acdlite/recompose/blob/master/docs/API.md#kefir +declare module 'recompose/kefirObservableConfig' { + + import { ObservableConfig } from 'recompose'; + + const kefirConfig: ObservableConfig; + + export default kefirConfig; +} From 07453cbf8e99a21f978f9cc35d8eb3fa648f2c93 Mon Sep 17 00:00:00 2001 From: Natalie Date: Fri, 30 Sep 2016 14:09:56 +0200 Subject: [PATCH 090/382] Update typescript definition for selectize to 0.12.13 (#11570) --- selectize/selectize.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/selectize/selectize.d.ts b/selectize/selectize.d.ts index b593fa73dd..cea529e07f 100644 --- a/selectize/selectize.d.ts +++ b/selectize/selectize.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selectize 0.11.2 +// Type definitions for Selectize 0.12.13 // Project: https://github.com/brianreavis/selectize.js -// Definitions by: Adi Dahiya +// Definitions by: Adi Dahiya , Natalie Bausch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -562,6 +562,11 @@ declare namespace Selectize { * Clears the render cache. Takes an optional template argument (e.g. "option", "item") to clear only that cache. */ clearCache(template?: string): void; + + /** + * When the `settings.placeholder` value is changed, the new placeholder will be displayed. + */ + updatePlaceholder(): void; } interface ISearchToken { @@ -609,4 +614,3 @@ interface JQuery { interface HTMLElement { selectize: Selectize.IApi; } - From da9bf4d701ded823f1a98fce9b7d2fcc2ef98922 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 30 Sep 2016 15:11:07 +0300 Subject: [PATCH 091/382] [react-router-redux] Update action payload type (#11559) The payload for React Redux Router action is a location object. For more information look at the source code [here](https://github.com/reactjs/react-router-redux/blob/master/src/sync.js#L95) --- react-router-redux/react-router-redux.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-router-redux/react-router-redux.d.ts b/react-router-redux/react-router-redux.d.ts index 6a9d499b1f..a781fed663 100644 --- a/react-router-redux/react-router-redux.d.ts +++ b/react-router-redux/react-router-redux.d.ts @@ -29,7 +29,7 @@ declare namespace ReactRouterRedux { type RouterAction = { type: string - payload?: any + payload?: LocationDescriptor } interface RouteActions { From 2b68598bb60edab2a65c60c3efcae9552aa1fcbc Mon Sep 17 00:00:00 2001 From: osechet Date: Fri, 30 Sep 2016 14:15:16 +0200 Subject: [PATCH 092/382] [openlayers] Rewrite for openlayers 3.18.2 (#11339) --- openlayers/openlayers-3.6.0-tests.ts | 563 + openlayers/openlayers-3.6.0.d.ts | 5403 +++++++ openlayers/openlayers-tests.ts | 286 +- openlayers/openlayers.d.ts | 18792 ++++++++++++++++++------- 4 files changed, 19740 insertions(+), 5304 deletions(-) create mode 100644 openlayers/openlayers-3.6.0-tests.ts create mode 100644 openlayers/openlayers-3.6.0.d.ts diff --git a/openlayers/openlayers-3.6.0-tests.ts b/openlayers/openlayers-3.6.0-tests.ts new file mode 100644 index 0000000000..52d7535710 --- /dev/null +++ b/openlayers/openlayers-3.6.0-tests.ts @@ -0,0 +1,563 @@ +/// + +// Basic type variables for test functions +var voidValue: void; +var numberValue: number; +var booleanValue: boolean; +var stringValue: string; +var jsonValue: JSON; + +// Callback predefinitions for OpenLayers +var preRenderFunction: ol.PreRenderFunction; +var transformFunction: ol.TransformFunction; +var coordinateFormatType: ol.CoordinateFormatType; +var featureStyleFunction: ol.FeatureStyleFunction; +var featureLoader: ol.FeatureLoader; +var easingFunction: (t: number) => number; + +// Type variables for OpenLayers +var circle: ol.geom.Circle; +var color: ol.Color; +var coordinate: ol.Coordinate; +var coordinatesArray: Array; +var coordinatesArrayDim2: Array>; +var extent: ol.Extent; +var boundingCoordinates: Array; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var feature: ol.Feature; +var featureArray: Array; +var graticule: ol.Graticule +var geometry: ol.geom.Geometry; +var geometriesArray: Array; +var feature: ol.Feature; +var featureArray: Array; +var featureFormat: ol.format.Feature; +var geometry: ol.geom.Geometry; +var geometryCollection: ol.geom.GeometryCollection; +var geometryLayout: ol.geom.GeometryLayout; +var geometryType: ol.geom.GeometryType; +var linearRing: ol.geom.LinearRing; +var lineString: ol.geom.LineString; +var loadingstrategy: ol.LoadingStrategy; +var multiLineString: ol.geom.MultiLineString; +var multiPoint: ol.geom.MultiPoint; +var multiPolygon: ol.geom.MultiPolygon; +var point: ol.geom.Point; +var polygon: ol.geom.Polygon; +var simpleGeometry: ol.geom.SimpleGeometry; +var tilegrid: ol.tilegrid.TileGrid; +var vector: ol.source.Vector; +var projection: ol.proj.Projection; +var projectionLike: ol.proj.ProjectionLike; +var transformFn: ol.TransformFunction; + +// +// ol.Attribution +// + +var attribution: ol.Attribution = new ol.Attribution({ + html: stringValue, +}); + +// +// ol.color +// +color = ol.color.asArray(color); +color = ol.color.asArray(stringValue); +stringValue = ol.color.asString(color); +stringValue = ol.color.asString(stringValue); + +// +// ol.extent +// +transformFunction = function (input: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[], dimension: number) { + var returnData: number[]; + return returnData; +} +extent = ol.extent.applyTransform(extent, transformFunction); +ol.extent.applyTransform(extent, transformFunction, extent); +extent = ol.extent.boundingExtent(boundingCoordinates) +extent = ol.extent.buffer(extent, numberValue); +ol.extent.buffer(extent, numberValue, extent); +booleanValue = ol.extent.containsCoordinate(extent, coordinate); +booleanValue = ol.extent.containsExtent(extent, extent); +booleanValue = ol.extent.containsXY(extent, numberValue, numberValue); +extent = ol.extent.createEmpty(); +booleanValue = ol.extent.equals(extent, extent); +extent = ol.extent.extend(extent, extent); +coordinate = ol.extent.getBottomLeft(extent); +coordinate = ol.extent.getBottomRight(extent); +coordinate = ol.extent.getCenter(extent); +numberValue = ol.extent.getHeight(extent); +extent = ol.extent.getIntersection(extent, extent); +ol.extent.getIntersection(extent, extent, extent); +size = ol.extent.getSize(extent); +coordinate = ol.extent.getTopLeft(extent); +coordinate = ol.extent.getTopRight(extent); +numberValue = ol.extent.getWidth(extent); +booleanValue = ol.extent.intersects(extent, extent); +booleanValue = ol.extent.isEmpty(extent); + +// +// ol.featureloader +// +featureLoader = ol.featureloader.xhr(stringValue, featureFormat); + +// +// ol.loadingstrategy +// +loadingstrategy = ol.loadingstrategy.all; +loadingstrategy = ol.loadingstrategy.bbox; +loadingstrategy = ol.loadingstrategy.tile(tilegrid); + +// +// +// ol.geom.Circle +// +booleanValue = circle.intersectsExtent(extent); +circle = circle.transform(projectionLike, projectionLike); + +// +// +// ol.geom.Geometry +// +var geometryResult: ol.geom.Geometry; +coordinate = geometryResult.getClosestPoint(coordinate); +geometryResult.getClosestPoint(coordinate, coordinate); +extent = geometryResult.getExtent(); +geometryResult.getExtent(extent); +geometryResult.transform(projection, projection); + +// +// +// ol.geom.GeometryCollection +// +geometryCollection = new ol.geom.GeometryCollection(geometriesArray) +geometryCollection = new ol.geom.GeometryCollection(); +voidValue = geometryCollection.applyTransform(transformFn); +geometryCollection = geometryCollection.clone(); +geometriesArray = geometryCollection.getGeometries(); +geometryType = geometryCollection.getType(); +booleanValue = geometryCollection.intersectsExtent(extent); +voidValue = geometryCollection.setGeometries(geometriesArray); + +// +// +// ol.geom.LinearRing +// +linearRing = new ol.geom.LinearRing(coordinatesArray); +linearRing = new ol.geom.LinearRing(coordinatesArray, geometryLayout); +linearRing = linearRing.clone(); +numberValue = linearRing.getArea(); +coordinatesArray = linearRing.getCoordinates(); +geometryType = linearRing.getType(); +voidValue = linearRing.setCoordinates(coordinatesArray); +voidValue = linearRing.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.LineString +// +lineString = new ol.geom.LineString(coordinatesArray); +lineString = new ol.geom.LineString(coordinatesArray, geometryLayout); +voidValue = lineString.appendCoordinate(coordinate); +lineString = lineString.clone(); +coordinate = lineString.getCoordinateAtM(numberValue); +coordinate = lineString.getCoordinateAtM(numberValue, booleanValue); +coordinatesArray = lineString.getCoordinates(); +numberValue = lineString.getLength(); +geometryType = lineString.getType(); +booleanValue = lineString.intersectsExtent(extent); +voidValue = lineString.setCoordinates(coordinatesArray); +voidValue = lineString.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiLineString +// +var lineStringsArray: Array; + +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2); +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2, geometryLayout); +voidValue = multiLineString.appendLineString(lineString); +multiLineString = multiLineString.clone(); +coordinate = multiLineString.getCoordinateAtM(numberValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue, booleanValue); +coordinatesArrayDim2 = multiLineString.getCoordinates(); +lineString = multiLineString.getLineString(numberValue); +lineStringsArray = multiLineString.getLineStrings(); +geometryType = multiLineString.getType(); +booleanValue = multiLineString.intersectsExtent(extent); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2, geometryLayout); + +// +// +// ol.geom.MultiPoint +// +var pointsArray: Array; + +multiPoint = new ol.geom.MultiPoint(coordinatesArray); +multiPoint = new ol.geom.MultiPoint(coordinatesArray, geometryLayout); +voidValue = multiPoint.appendPoint(point); +multiPoint = multiPoint.clone(); +coordinatesArray = multiPoint.getCoordinates(); +point = multiPoint.getPoint(numberValue); +pointsArray = multiPoint.getPoints(); +geometryType = multiPoint.getType(); +booleanValue = multiPoint.intersectsExtent(extent); +voidValue = multiPoint.setCoordinates(coordinatesArray); +voidValue = multiPoint.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiPolygon +// +var coordinatesArrayDim3: Array>>; +var polygonsArray: Array; + +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3); +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3, geometryLayout); +voidValue = multiPolygon.appendPolygon(polygon); +multiPolygon = multiPolygon.clone(); +numberValue = multiPolygon.getArea(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(booleanValue); +multiPoint = multiPolygon.getInteriorPoints(); +polygon = multiPolygon.getPolygon(numberValue); +polygonsArray = multiPolygon.getPolygons(); +geometryType = multiPolygon.getType(); +booleanValue = multiPolygon.intersectsExtent(extent); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3, geometryLayout); + +// +// +// ol.geom.Point +// +point = new ol.geom.Point(coordinate); +point = new ol.geom.Point(coordinate, geometryLayout); +point = point.clone(); +coordinate = point.getCoordinates(); +geometryType = point.getType(); +booleanValue = point.intersectsExtent(extent); +voidValue = point.setCoordinates(coordinate); +voidValue = point.setCoordinates(coordinate, geometryLayout); + +// +// +// ol.geom.Polygon +// +var localSphere: ol.Sphere; +var linearRingsArray: Array; + +polygon = new ol.geom.Polygon(coordinatesArrayDim2); +polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +voidValue = polygon.appendLinearRing(linearRing); +polygon = polygon.clone(); +numberValue = polygon.getArea(); +coordinatesArrayDim2 = polygon.getCoordinates(); +coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); +point = polygon.getInteriorPoint(); +linearRing = polygon.getLinearRing(numberValue); +linearRingsArray = polygon.getLinearRings(); +geometryType = polygon.getType(); +booleanValue = polygon.intersectsExtent(extent); + +// +// +// ol.geom.SimpleGeometry +// +simpleGeometry.applyTransform(transformFn); +coordinate = simpleGeometry.getFirstCoordinate(); +coordinate = simpleGeometry.getLastCoordinate(); +geometryLayout = simpleGeometry.getLayout(); +voidValue = simpleGeometry.translate(numberValue, numberValue); + +// +// ol.source +// +vector = new ol.source.Vector({ + features: [feature] +}); + +// +// ol.Feature +// +feature = new ol.Feature(); +feature = new ol.Feature(geometry); +feature = new ol.Feature({ + geometry: geometry +}); +feature = feature.clone(); +geometry = feature.getGeometry(); +stringValue = feature.getGeometryName(); +var featureGetId: string | number = feature.getId(); +var featureGetStyle: ol.style.Style | Array | ol.FeatureStyleFunction = feature.getStyle(); +featureStyleFunction = feature.getStyleFunction(); +voidValue = feature.setGeometry(geometry); +voidValue = feature.setGeometryName(stringValue); +voidValue = feature.setId(stringValue); +voidValue = feature.setId(numberValue); +voidValue = feature.setStyle(style); +voidValue = feature.setStyle(styleArray); +voidValue = feature.setStyle(featureStyleFunction); + +// +// ol.View +// + +var view: ol.View = new ol.View({ + center: [0, 0], + zoom: numberValue, +}); + +// +// ol.layer.Tile +// +var tileLayer: ol.layer.Tile = new ol.layer.Tile({ + source: new ol.source.MapQuest({ layer: 'osm' }) +}); + +// +// ol.proj +// +projection = new ol.proj.Projection({ + code:stringValue, +}); +projection.setExtent(projection.getExtent()); + +// +// ol.Map +// + +var map: ol.Map = new ol.Map({ + view: view, + layers: [tileLayer], + target: stringValue +}); +map.beforeRender(preRenderFunction); + +// +// ol.source.ImageWMS +// +var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + serverType: stringValue, + url:stringValue +}); + +// +// ol.source.Source +// +const source = imageWMS as ol.source.Source; +voidValue = source.refresh(); +projection = source.getProjection(); + +// +// ol.source.TileWMS +// +var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ + params: {}, + serverType: stringValue, + url:stringValue +}); + +tileWMS.updateParams(tileWMS.getParams()); +stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); + +// +// ol.source.WMTS +// +var wmts: ol.source.WMTS = new ol.source.WMTS({ + tileGrid: new ol.tilegrid.WMTS({}), + layer: "", + style: "", + matrixSet: "", + wrapX: true +}); + +// +// ol.animation +// +var bounceOptions: olx.animation.BounceOptions; +bounceOptions.duration = numberValue; +bounceOptions.start = numberValue; +bounceOptions.resolution = numberValue; +bounceOptions.easing = easingFunction; +preRenderFunction = ol.animation.bounce(bounceOptions); + +var panOptions: olx.animation.PanOptions; +panOptions.duration = numberValue; +panOptions.start = numberValue; +panOptions.source = coordinate; +panOptions.easing = easingFunction; +preRenderFunction = ol.animation.pan(panOptions); + +var rotateOptions: olx.animation.RotateOptions; +rotateOptions.duration = numberValue; +rotateOptions.start = numberValue; +rotateOptions.anchor = coordinate; +rotateOptions.rotation = numberValue; +rotateOptions.easing = easingFunction; +preRenderFunction = ol.animation.rotate(rotateOptions); + +var zoomOptions: olx.animation.ZoomOptions; +zoomOptions.duration = numberValue; +zoomOptions.start = numberValue; +zoomOptions.resolution = numberValue; +zoomOptions.easing = easingFunction; +preRenderFunction = ol.animation.zoom(zoomOptions); +map.beforeRender(preRenderFunction); + +// +// ol.coordinate +// +coordinate = ol.coordinate.add(coordinate, coordinate); +coordinateFormatType = ol.coordinate.createStringXY(); +coordinateFormatType = ol.coordinate.createStringXY(numberValue); +stringValue = ol.coordinate.format(coordinate, stringValue); +stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); +coordinate = ol.coordinate.rotate(coordinate, numberValue); +stringValue = ol.coordinate.toStringHDMS(); +stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringXY(); +stringValue = ol.coordinate.toStringXY(coordinate); +stringValue = ol.coordinate.toStringXY(coordinate, numberValue); + +// +// ol.easing +// +easingFunction = ol.easing.easeIn; +easingFunction = ol.easing.easeOut; +easingFunction = ol.easing.inAndOut; +easingFunction = ol.easing.linear; +easingFunction = ol.easing.upAndDown; + +// +// ol.Geolocation +// +var geolocation: ol.Geolocation = new ol.Geolocation({ + projection: projection +}); +geolocation.on('change', function (evt) { + window.console.log(geolocation.getPosition()); +}); + +// +// ol.Graticule +// + +graticule = new ol.Graticule(); +graticule = new ol.Graticule({ + map: map, +}); +var graticuleMap: ol.Map = graticule.getMap(); +var graticuleMeridians: Array = graticule.getMeridians(); +var graticuleParallels: Array = graticule.getParallels(); +graticule.setMap(graticuleMap); + +// +// ol.DeviceOrientation +// + +var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ + tracking: true, +}); +deviceOrientation.on('change', function (evt) { + window.console.log(deviceOrientation.getHeading()); +}); + +// +// ol.Overlay +// + +var popup: ol.Overlay = new ol.Overlay({ + element: document.getElementById('popup') +}); +map.addOverlay(popup); +var popupElement: Element = popup.getElement(); +var popupMap: ol.Map = popup.getMap(); +var popupOffset: Array = popup.getOffset(); +coordinate = popup.getPosition(); +var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); +popup.setElement(popupElement); +popup.setMap(popupMap); +popup.setOffset(popupOffset); +popup.setPosition(coordinate); +popup.setPositioning(popupPositioning); + + +// +// ol.format.GeoJSON +// + +var geojsonOptions: olx.format.GeoJSONOptions; +geojsonOptions.defaultDataProjection = "EPSG"; +geojsonOptions.defaultDataProjection = projection; +geojsonOptions.geometryName = "geom"; + +var geojsonFormat: ol.format.GeoJSON; +geojsonFormat = new ol.format.GeoJSON(); +geojsonFormat = new ol.format.GeoJSON(geojsonOptions); + +// Test options +var readOptions: olx.format.ReadOptions; +readOptions.dataProjection = "EPSG"; +readOptions.dataProjection = projection; +readOptions.featureProjection = "EPSG"; +readOptions.featureProjection = projection; + +var writeOptions: olx.format.WriteOptions; +writeOptions.dataProjection = "EPSG"; +writeOptions.dataProjection = projection; +writeOptions.featureProjection = "EPSG"; +writeOptions.featureProjection = projection; +writeOptions.rightHanded = false; + +// Test functions +feature = geojsonFormat.readFeature("json"); +feature = geojsonFormat.readFeature("json", readOptions); +featureArray = geojsonFormat.readFeatures("json"); +featureArray = geojsonFormat.readFeatures("json", readOptions); +geometry = geojsonFormat.readGeometry("geometry"); +geometry = geojsonFormat.readGeometry("geometry", readOptions); +stringValue = geojsonFormat.writeFeature(feature); +stringValue = geojsonFormat.writeFeature(feature, writeOptions); +stringValue = geojsonFormat.writeFeatures(featureArray); +stringValue = geojsonFormat.writeFeatures(featureArray, writeOptions); +stringValue = geojsonFormat.writeGeometry(geometry); +stringValue = geojsonFormat.writeGeometry(geometry, writeOptions); +jsonValue = geojsonFormat.writeFeatureObject(feature); +jsonValue = geojsonFormat.writeFeatureObject(feature, writeOptions); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray, writeOptions); +jsonValue = geojsonFormat.writeGeometryObject(geometry); +jsonValue = geojsonFormat.writeGeometryObject(geometry, writeOptions); + +// +// ol.interactions +// +var modify: ol.interaction.Modify = new ol.interaction.Modify({ + features: new ol.Collection(featureArray) +}); + +var draw: ol.interaction.Draw = new ol.interaction.Draw({ + type: "Point" +}) + +const select: ol.interaction.Select = new ol.interaction.Select({ + layers: (layer: ol.layer.Layer) => true, +}); diff --git a/openlayers/openlayers-3.6.0.d.ts b/openlayers/openlayers-3.6.0.d.ts new file mode 100644 index 0000000000..91b822d6b6 --- /dev/null +++ b/openlayers/openlayers-3.6.0.d.ts @@ -0,0 +1,5403 @@ +// Type definitions for OpenLayers v3.6.0 +// Project: http://openlayers.org/ +// Definitions by: Wouter Goedhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace olx { + interface StaticImageOptions { + + /** Attributions */ + attributions?: Array + + /*** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string + + /*** Extent of the image in map coordinates. This is the [left, bottom, right, top] map coordinates of your image.*/ + imageExtent: ol.Extent; + + /*** Size of the image in pixels.*/ + imageSize?: ol.Size; + + /*** experimental Optional function to load an image given a URL.*/ + imageLoadFunction?: ol.TileLoadFunctionType; + + /*** Optional logo.*/ + logo?: olx.LogoOptions; + + /*** experimental Projection.*/ + projection: ol.proj.Projection; + + /*** Image URL.*/ + url: string; + } + + interface ZoomToExtentOptions { + /*** Class name. Default is ol-zoom-extent.*/ + className?: string; + + /*** Target.*/ + target?: Element; + + /*** Text label to use for the button. Default is E. Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Node; + + /*** Text label to use for the button tip. Default is Zoom to extent.*/ + tipLabel?: string; + + /*** The extent to zoom to. If undefined the validity extent of the view projection is used.*/ + extent: ol.Extent; + } + + interface OverviewMapOptions { + /*** Whether the control should start collapsed or not (expanded). Default to true.*/ + collapsed?: boolean; + /*** Text label to use for the expanded overviewmap button. Default is «. Instead of text, also a Node (e.g. a span element) can be used.*/ + collapseLabel? :string | Node; + /*** Whether the control can be collapsed or not. Default to true.*/ + collapsible?: boolean; + /*** Text label to use for the collapsed overviewmap button. Default is ». Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Node; + /*** Layers for the overview map. If not set, then all main map layers are used instead.*/ + layers?: ol.layer.Layer[] | ol.Collection; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Specify a target if you want the control to be rendered outside of the map's viewport.*/ + target?: Element; + /*** Text label to use for the button tip. Default is Overview map*/ + tipLabel?: string; + /*** Custom view for the overview map. If not provided, a default view with an EPSG:3857 projection will be used.*/ + view?: ol.View; + } + + interface RotateOptions { + /*** CSS class name. Default is ol-rotate.*/ + className?: string; + /*** Text label to use for the rotate button. Default is ⇧. Instead of text, also a Node (e.g. a span element) can be used.*/ + label?: string | Element; + /*** Text label to use for the rotate tip. Default is Reset rotation.*/ + tipLabel?: string; + /*** Animation duration in milliseconds. Default is 250.*/ + duration?: number; + /*** Hide the control when rotation is 0. Default is true.*/ + autoHide?: boolean; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + /*** Function called when the control is clicked. This will override the default resetNorth.*/ + resetNorth?: Function; + /*** Target.*/ + target?: Element; + } + + interface AttributionOptions { + + /** HTML markup for this attribution. */ + html: string; + } + + interface DeviceOrientationOptions { + + /** + * Start tracking. Default is false. + */ + tracking?: boolean; + } + + interface FrameState { + + /** + * + */ + pixelRatio: number; + + /** + * + */ + time: number; + + /** + * + */ + viewState: olx.ViewState; + } + + interface FeatureOverlayOptions { + + /** + * Features + */ + features?: Array | ol.Collection | ol.style.StyleFunction; + + /** + * Map + */ + map: ol.Map; + + /** + * Style + */ + style: ol.style.Style | Array; + } + + interface GeolocationOptions { + + /** + * Start Tracking. Default is false. + */ + tracking?: boolean; + + /** + * Tracking options. See http://www.w3.org/TR/geolocation-API/#position_options_interface. + */ + trackingOptions?: PositionOptions; + + /** + * The projection the position is reported in. + */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface GraticuleOptions { + + /** Reference to an ol.Map object. */ + map?: ol.Map; + + /** The maximum number of meridians and parallels from the center of the map. The default value is 100, which means that at most 200 meridians and 200 parallels will be displayed. The default value is appropriate for conformal projections like Spherical Mercator. If you increase the value more lines will be drawn and the drawing performance will decrease. */ + maxLines?: number; + + /** The stroke style to use for drawing the graticule. If not provided, the lines will be drawn with rgba(0,0,0,0.2), a not fully opaque black. */ + strokeStyle?: ol.style.Stroke; + + /** The target size of the graticule cells, in pixels. Default value is 100 pixels. */ + targetSize?: number; + } + + interface BaseWMSOptions { + + /** Attributions. */ + attributions?: Array; + + /** WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. */ + params?: any; + + /** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string; + + /** experimental Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true. */ + hidpi?: boolean; + + /** experimental The type of the remote WMS server: mapserver, geoserver or qgis. Only needed if hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** WMS service URL. */ + url?: string; + + /** Logo. */ + logo?: olx.LogoOptions; + + /** experimental Projection. */ + projection?: ol.proj.ProjectionLike; + } + + interface ImageWMSOptions extends BaseWMSOptions { + + /** experimental Optional function to load an image given a URL. */ + imageLoadFunction?: ol.ImageLoadFunctionType; + + /** Ratio. 1 means image requests are the size of the map viewport, 2 means twice the width and height of the map viewport, and so on. Must be 1 or higher. Default is 1.5. */ + ratio?: number; + + /** Resolutions. If specified, requests will be made for these resolutions only. */ + resolutions?: Array; + } + + interface TileWMSOptions { + + attributions?: Array; + + /**WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. Required.*/ + params: Object; + /**The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.*/ + crossOrigin?: string; + + /** The size in pixels of the gutter around image tiles to ignore. By setting this property to a non-zero value, images will be requested that are wider and taller than the tile size by a value of 2 x gutter. Defaults to zero. Using a non-zero value allows artifacts of rendering at tile edges to be ignored. If you control the WMS service it is recommended to address "artifacts at tile edges" issues by properly configuring the WMS service. For example, MapServer has a tile_map_edge_buffer configuration parameter for this. See http://mapserver.org/output/tile_mode.html. */ + gutter?: number; + + /** Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true.*/ + hidpi?: boolean; + + logo?: string | olx.LogoOptions; + + /** Tile grid. Base this on the resolutions, tilesize and extent supported by the server. If this is not defined, a default grid will be used: if there is a projection extent, the grid will be based on that; if not, a grid based on a global extent with origin at 0,0 will be used. */ + tileGrid?: ol.tilegrid.TileGrid; + + /** experimental Maximum zoom. */ + maxZoom?: number; + + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + + /** experimental Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + + /** WMS service URL. */ + url?: string; + + /** WMS service urls. Use this instead of url when the WMS supports multiple urls for GetMap requests. */ + urls?: Array; + + /** experimental The type of the remote WMS server. Currently only used when hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */ + wrapX?: boolean; + } + interface OSMOptions { + /** Attributions */ + attributions?: ol.AttributionLike; + /** Cache size. Default is 2048. */ + cacheSize?: number; + /** + * The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL + * renderer or if you want to access pixel data with the Canvas renderer. + * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. Default is anonymous. + */ + crossOrigin?: string; + /** Max zoom. Default is 19. */ + maxZoom?: number; + /** Whether the layer is opaque. Default is true. */ + opaque?: boolean; + /** Maximum allowed reprojection error (in pixels). Default is 0.5. Higher values can increase reprojection performance, but decrease precision. */ + reprojectionErrorThreshold?: number; + /** Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + /** URL template. Must include {x}, {y} or {-y}, and {z} placeholders. Default is https://{a-c}.tile.openstreetmap.org/{z}/{x}/{y}.png. */ + url?: string; + /** Whether to wrap the world horizontally. Default is true. */ + wrapX?: boolean; + } + /** + * Object literal with config options for the map logo. + */ + interface LogoOptions { + /** + * Link url for the logo. Will be followed when the logo is clicked. + */ + href: string; + + /** + * Image src for the logo + */ + src: string; + + } + + interface MapOptions { + + /** Controls initially added to the map. If not specified, ol.control.defaults() is used. */ + controls?: any; + + /** The ratio between physical pixels and device-independent pixels (dips) on the device. If undefined then it gets set by using window.devicePixelRatio. */ + pixelRatio?: number; + + /** Interactions that are initially added to the map. If not specified, ol.interaction.defaults() is used. */ + interactions?: any; + + /** The element to listen to keyboard events on. This determines when the KeyboardPan and KeyboardZoom interactions trigger. For example, if this option is set to document the keyboard interactions will always trigger. If this option is not specified, the element the library listens to keyboard events on is the map target (i.e. the user-provided div for the map). If this is not document the target element needs to be focused for key events to be emitted, requiring that the target element has a tabindex attribute. */ + keyboardEventTarget?: any; + + /** Layers. If this is not defined, a map with no layers will be rendered. Note that layers are rendered in the order supplied, so if you want, for example, a vector layer to appear on top of a tile layer, it must come after the tile layer. */ + layers?: Array + + /** When set to true, tiles will be loaded during animations. This may improve the user experience, but can also make animations stutter on devices with slow memory. Default is false. */ + loadTilesWhileAnimating?: boolean; + + /** When set to true, tiles will be loaded while interacting with the map. This may improve the user experience, but can also make map panning and zooming choppy on devices with slow memory. Default is false. */ + loadTilesWhileInteracting?: boolean; + + /** The map logo. A logo to be displayed on the map at all times. If a string is provided, it will be set as the image source of the logo. If an object is provided, the src property should be the URL for an image and the href property should be a URL for creating a link. To disable the map logo, set the option to false. By default, the OpenLayers 3 logo is shown. */ + logo?: any; + + /** Overlays initially added to the map. By default, no overlays are added. */ + overlays?: any; + + /** Renderer. By default, Canvas, DOM and WebGL renderers are tested for support in that order, and the first supported used. Specify a ol.RendererType here to use a specific renderer. Note that at present only the Canvas renderer supports vector data. */ + renderer?: any; + + /** The container for the map, either the element itself or the id of the element. If not specified at construction time, ol.Map#setTarget must be called for the map to be rendered. */ + target?: any; + + /** The map's view. No layer sources will be fetched unless this is specified at construction time or through ol.Map#setView. */ + view?: ViewOptions; + } + + interface OverlayOptions { + + /** + * The overlay element. + */ + element?: Element; + + /** + * Offsets in pixels used when positioning the overlay. The fist element in the array is the horizontal offset. A positive value shifts the overlay right. The second element in the array is the vertical offset. A positive value shifts the overlay down. Default is [0, 0]. + */ + offset?: Array; + + /** + * The overlay position in map projection. + */ + position?: ol.Coordinate; + + /** + * Defines how the overlay is actually positioned with respect to its position property. Possible values are 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', and 'top-right'. Default is 'top-left'. + */ + positioning?: ol.OverlayPositioning; + + /** + * Whether event propagation to the map viewport should be stopped. Default is true. If true the overlay is placed in the same container as that of the controls (CSS class name ol-overlaycontainer-stopevent); if false it is placed in the container with CSS class name ol-overlaycontainer. + */ + stopEvent?: boolean; + + /** + * Whether the overlay is inserted first in the overlay container, or appended. Default is true. If the overlay is placed in the same container as that of the controls (see the stopEvent option) you will probably set insertFirst to true so the overlay is displayed below the controls. + */ + insertFirst?: boolean; + + /** + * If set to true the map is panned when calling setPosition, so that the overlay is entirely visible in the current viewport. The default is false. + */ + autoPan?: boolean; + + /** + * The options used to create a ol.animation.pan animation. This animation is only used when autoPan is enabled. By default the default options for ol.animation.pan are used. If set to null the panning is not animated. + */ + autoPanAnimation?: olx.animation.PanOptions; + + /** + * The margin (in pixels) between the overlay and the borders of the map when autopanning. The default is 20. + */ + autoPanMargin?: number; + } + + interface ViewOptions { + + /** The initial center for the view. The coordinate system for the center is specified with the projection option. Default is undefined, and layer sources will not be fetched if this is not set. */ + center?: ol.Coordinate; + + /** Rotation constraint. false means no constraint. true means no constraint, but snap to zero near zero. A number constrains the rotation to that number of values. For example, 4 will constrain the rotation to 0, 90, 180, and 270 degrees. The default is true. */ + constrainRotation?: boolean; + + /** Enable rotation. Default is true. If false a rotation constraint that always sets the rotation to zero is used. The constrainRotation option has no effect if enableRotation is false. */ + enableRotation?: boolean; + + /**The extent that constrains the center, in other words, center cannot be set outside this extent. Default is undefined. */ + extent?: ol.Extent; + + /** The maximum resolution used to determine the resolution constraint. It is used together with minResolution (or maxZoom) and zoomFactor. If unspecified it is calculated in such a way that the projection's validity extent fits in a 256x256 px tile. If the projection is Spherical Mercator (the default) then maxResolution defaults to 40075016.68557849 / 256 = 156543.03392804097. */ + maxResolution?: number; + + /** The minimum resolution used to determine the resolution constraint. It is used together with maxResolution (or minZoom) and zoomFactor. If unspecified it is calculated assuming 29 zoom levels (with a factor of 2). If the projection is Spherical Mercator (the default) then minResolution defaults to 40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253. */ + minResolution?: number; + + /** The maximum zoom level used to determine the resolution constraint. It is used together with minZoom (or maxResolution) and zoomFactor. Default is 28. Note that if minResolution is also provided, it is given precedence over maxZoom. */ + maxZoom?: number; + + /** The minimum zoom level used to determine the resolution constraint. It is used together with maxZoom (or minResolution) and zoomFactor. Default is 0. Note that if maxResolution is also provided, it is given precedence over minZoom. */ + minZoom?: number; + + /** The projection. Default is EPSG:3857 (Spherical Mercator). */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** The initial resolution for the view. The units are projection units per pixel (e.g. meters per pixel). An alternative to setting this is to set zoom. Default is undefined, and layer sources will not be fetched if neither this nor zoom are defined. */ + resolution?: number; + + /** Resolutions to determine the resolution constraint. If set the maxResolution, minResolution, minZoom, maxZoom, and zoomFactor options are ignored. */ + resolutions?: Array; + + /** The initial rotation for the view in radians (positive rotation clockwise). Default is 0. */ + rotation?: number; + + /** Only used if resolution is not defined. Zoom level used to calculate the initial resolution for the view. The initial resolution is determined using the ol.View#constrainResolution method. */ + zoom?: number; + + /** The zoom factor used to determine the resolution constraint. Default is 2. */ + zoomFactor?: number; + } + + interface ViewState { + + /** + * + */ + center: ol.Coordinate; + + /** + * + */ + projection: ol.proj.Projection; + + /** + * + */ + resolution: number; + + /** + * + */ + rotation: number; + } + + interface Projection { + /** + * The SRS identifier code, e.g. EPSG:4326. + */ + code: string; + + /** + * Units. Required unless a proj4 projection is defined for code. + */ + units?: ol.proj.Units; + + /** + * The validity extent for the SRS. + */ + extent?: Array; + + /** + * The axis orientation as specified in Proj4. The default is enu. + */ + axisOrientation?: string; + + /** + * Whether the projection is valid for the whole globe. Default is false. + */ + global?: boolean; + + /** + * experimental The world extent for the SRS. + */ + worldExtent?: ol.Extent; + + /** + * experimental Function to determine resolution at a point. The function is called with + * a {number} view resolution and an {ol.Coordinate} as arguments, and returns the {number} + * resolution at the passed coordinate. + */ + getPointResolution?: (resolution: number, coordinate: ol.Coordinate) => number; + } + + namespace animation { + + interface BounceOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface PanOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + source: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface RotateOptions { + + /** + * The rotation value (in radians) to begin rotating from, typically map.getView().getRotation(). If undefined then 0 is assumed. + */ + rotation?: number; + + /** + * The rotation center/anchor. The map rotates around the center of the view if unspecified. + */ + anchor?: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + + interface ZoomOptions { + + /** + * The resolution to begin zooming from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + } + + namespace control { + + interface DefaultsOptions { + + /** + * Attribution. Default is true. + */ + attribution?: boolean; + + /** + * Attribution options. + */ + //TODO: Replace with olx.control.AttributionOptions + attributionOptions?: any; + + /** + * Rotate. Default is true; + */ + rotate?: boolean; + + /** + * Rotate options + */ + //TODO: Replace with olx.control.RotateOptions + rotateOptions?: any; + + /** + * Zoom. Default is true + */ + zoom?: boolean; + + /** + * + */ + //TODO: Replace with olx.control.ZoomOptions + zoomOptions?: any; + } + } + + namespace interaction { + interface DefaultsOptions { + /*** Whether Alt-Shift-drag rotate is desired. Default is true.*/ + altShiftDragRotate?: boolean; + /*** Whether double click zoom is desired. Default is true.*/ + doubleClickZoom?: boolean; + /*** Whether keyboard interaction is desired. Default is true.*/ + keyboard?: boolean; + /*** Whether mousewheel zoom is desired. Default is true.*/ + mouseWheelZoom?: boolean; + /*** Whether Shift-drag zoom is desired. Default is true.*/ + shiftDragZoom?: boolean; + /*** Whether drag pan is desired. Default is true.*/ + dragPan?: boolean; + /*** Whether pinch rotate is desired. Default is true.*/ + pinchRotate?: boolean; + /*** Whether pinch zoom is desired. Default is true.*/ + pinchZoom?: boolean; + /*** Zoom delta*/ + zoomDelta?: number; + /*** Zoom duration*/ + zoomDuration?: number; + } + interface InteractionOptions { + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in + * the map's interactions chain. Required. + */ + handleEvent: Function; + } + interface ModifyOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event will + * be considered to add or move a vertex to the sketch. Default is ol.events.condition.primaryAction. + */ + condition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should + * be handled. By default, ol.events.condition.singleClick with ol.events.condition.noModifierKeys results + * in a vertex deletion. + */ + deleteCondition?: ol.events.ConditionType; + /*** Pixel tolerance for considering the pointer close enough to a segment or vertex for editing. Default is 10.*/ + pixelTolerance?: number; + /*** Style used for the features being modified. By default the default edit style is used (see ol.style).*/ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /*** The features the interaction works on. Required.*/ + features: ol.Collection; + /*** Wrap the world horizontally on the sketch overlay. Default is false.*/ + wrapX?: boolean; + } + interface DragBoxOptions { + /*** CSS class name for styling the box. The default is ol-dragbox.*/ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.always. + */ + condition?: ol.events.ConditionType; + /*** A function that takes a ol.MapBrowserEvent and two ol.Pixels to indicate whether a boxend event should be fired.*/ + boxEndCondition?: ol.interaction.DragBoxEndConditionType; + } + interface DrawOptions { + /** + * The maximum distance in pixels between "down" and "up" for a "up" event to be considered a "click" event and actually + * add a point/vertex to the geometry being drawn. Default is 6 pixels. That value was chosen for the draw interaction + * to behave correctly on mouse as well as on touch devices. + */ + clickTolerance?: number; + /** + * Destination collection for the drawn features. + */ + features?: ol.Collection; + /** + * Destination source for the drawn features. + */ + source?: ol.source.Vector; + /** + * Pixel distance for snapping to the drawing finish. Default is 12. + */ + snapTolerance?: number; + /** + * Drawing type ('Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString', 'MultiPolygon' or 'Circle'). Required. + */ + type: ol.geom.GeometryType; + /** + * The number of points that can be drawn before a polygon ring or line string is finished. The default is no restriction. + */ + maxPoints?: number; + /** + * The number of points that must be drawn before a polygon ring or line string can be finished. Default is 3 for polygon + * rings and 2 for line strings. + */ + minPoints?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether the drawing can be finished. + */ + finishCondition?: ol.events.ConditionType; + /** + * Style for sketch features. + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * Function that is called when a geometry's coordinates are updated. + */ + geometryFunction?: ol.interaction.DrawGeometryFunctionType; + /** + * Geometry name to use for features created by the draw interaction. + */ + geometryName?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default ol.events.condition.noModifierKeys, i.e. a click, adds a vertex or deactivates freehand drawing. + */ + condition?: ol.events.ConditionType; + /** + * Condition that activates freehand drawing for lines and polygons. This function takes an ol.MapBrowserEvent and returns + * a boolean to indicate whether that event should be handled. The default is ol.events.condition.shiftKeyOnly, meaning that + * the Shift key activates freehand drawing. + */ + freehandCondition?: ol.events.ConditionType; + /** + * Wrap the world horizontally on the sketch overlay. Default is false. + */ + wrapX?: boolean; + } + interface DoubleClickZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * The zoom delta applied on each double click, default is 1. + */ + delta?: number; + } + interface DragAndDropOptions { + /** + * Format constructors. + */ + formatConstructors?: Array; + /** + * Target projection. By default, the map's view's projection is used. + */ + projection: ol.proj.ProjectionLike; + /** + * The element that is used as the drop target, default is the viewport element. + */ + target?: Element; + } + interface DragPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys. + */ + condition?: ol.events.ConditionType; + /** + * Kinetic inertia to apply to the pan. + */ + kinetic?: ol.Kinetic; + } + interface DragRotateOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.altShiftKeysOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + } + interface DragRotateAndZoomOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface DragZoomOptions { + /** + * CSS class name for styling the box. The default is ol-dragzoom. + */ + className?: string; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.shiftKeyOnly. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 200. + */ + duration?: number; + /** + * Use interaction for zooming out. Default is false. + */ + out?: boolean; + } + interface KeyboardPanOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.noModifierKeys and ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * Pixel The amount to pan on each key press. Default is 128 pixels. + */ + pixelDelta?: number; + } + interface KeyboardZoomOptions { + /** + * Animation duration in milliseconds. Default is 100. + */ + duration?: number; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * Default is ol.events.condition.targetNotEditable. + */ + condition?: ol.events.ConditionType; + /** + * The amount to zoom on each key press. Default is 1. + */ + delta?: number; + } + interface MouseWheelZoomOptions { + /** + * Animation duration in milliseconds. Default is 250. + */ + duration?: number; + /** + * Enable zooming using the mouse's location as the anchor. Default is true. + * When set to false, zooming in and out will zoom to the center of the screen instead of zooming on the mouse's location. + */ + useAnchor?: boolean; + } + interface PinchRotateOptions { + /** + * The duration of the animation in milliseconds. Default is 250. + */ + duration?: number; + /** + * Minimal angle in radians to start a rotation. Default is 0.3. + */ + threshold?: number; + } + interface PinchZoomOptions { + /** + * Animation duration in milliseconds. Default is 400. + */ + duration?: number; + } + interface PointerOptions { + /** + * Function handling "down" events. If the function returns true then a drag sequence is started. + */ + handleDownEvent?: Function; + /** + * Function handling "drag" events. This function is called on "move" events during a drag sequence. + */ + handleDragEvent?: Function; + /** + * Method called by the map to notify the interaction that a browser event was dispatched to the map. + * The function may return false to prevent the propagation of the event to other interactions in the map's interactions chain. + */ + handleEvent?: Function; + /** + * Function handling "move" events. This function is called on "move" events, also during a drag sequence + * (so during a drag sequence both the handleDragEvent function and this function are called). + */ + handleMoveEvent?: Function; + /** + * Function handling "up" events. If the function returns false then the current drag sequence is stopped. + */ + handleUpEvent?: Function; + } + interface SnapOptions { + /** + * Snap to these features. Either this option or source should be provided. + */ + features?: ol.Collection; + /** + * Snap to edges. Default is true. + */ + edge?: boolean; + /** + * Snap to vertices. Default is true. + */ + vertex?: boolean; + /** + * Pixel tolerance for considering the pointer close enough to a segment or vertex for snapping. Default is 10 pixels. + */ + pixelTolerance?: number; + /** + * Snap to features from this source. Either this option or features should be provided. + */ + source?: ol.source.Vector; + } + interface SelectOptions { + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + addCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is the event for the selected features as a whole. By default, this is ol.events.condition.singleClick. + * Clicking on a feature selects that feature and removes any that were in the selection. + * Clicking outside any feature removes all from the selection. + * See toggle, add, remove options for adding/removing extra features to/ from the selection. + */ + condition?: ol.events.ConditionType; + /** + * A list of layers from which features should be selected. Alternatively, a filter function can be provided. + * The function will be called for each layer in the map and should return true for layers that you want to be selectable. + * If the option is absent, all visible layers will be considered selectable. + */ + layers?: Array | ((layer: ol.layer.Layer) => boolean); + /** + * Style for the selected features. By default the default edit style is used (see ol.style). + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * By default, this is ol.events.condition.never. + * Use this if you want to use different events for add and remove instead of toggle. + */ + removeCondition?: ol.events.ConditionType; + /** + * A function that takes an ol.MapBrowserEvent and returns a boolean to indicate whether that event should be handled. + * This is in addition to the condition event. By default, ol.events.condition.shiftKeyOnly, + * i.e. pressing shift as well as the condition event, adds that feature to the current selection if it is not currently + * selected, and removes it if it is. See add and remove if you want to use different events instead of a toggle. + */ + toggleCondition?: ol.events.ConditionType; + /** + * A boolean that determines if the default behaviour should select only single features or all (overlapping) + * features at the clicked map position. Default is false i.e single select + */ + multi?: boolean; + /** + * Collection where the interaction will place selected features. Optional. If not set the interaction will create a collection. + * In any case the collection used by the interaction is returned by ol.interaction.Select#getFeatures. + */ + features?: ol.Collection; + /** + * A function that takes an ol.Feature and an ol.layer.Layer and returns true if the feature may be selected or false otherwise. + */ + filter?: ol.interaction.SelectFilterFunction; + /** + * Wrap the world horizontally on the selection overlay. Default is true. + */ + wrapX?: boolean; + } + } + + namespace layer { + + interface BaseOptions { + /** + * Opacity (0, 1). Default is 1. + */ + opacity?: number; + + /** + * Visibility. Default is true. + */ + visible?: boolean; + + /** + * The bounding extent for layer rendering. The layer will not be rendered outside of this extent. + */ + extent?: ol.Extent; + + zIndex?: number; + /** + * The minimum resolution (inclusive) at which this layer will be visible. + */ + minResolution?: number; + + /** + * The maximum resolution (exclusive) below which this layer will be visible. + */ + maxResolution?: number; + } + + interface GroupOptions extends BaseOptions { + + /** + * Child layers + */ + layers?: Array | ol.Collection; + } + + interface HeatmapOptions extends VectorOptions { + + /** + * The color gradient of the heatmap, specified as an array of CSS color strings. Default is ['#00f', '#0ff', '#0f0', '#ff0', '#f00']. + */ + gradient?: Array; + + /** + * Radius size in pixels. Default is 8. + */ + radius?: number; + + /** + * Blur size in pixels. Default is 15. + */ + blur?: number; + + /** + * Shadow size in pixels. Default is 250. + */ + shadow?: number; + } + + interface ImageOptions extends LayerOptions { + } + + interface LayerOptions extends BaseOptions { + + /** + * The layer source (or null if not yet set). + */ + source?: ol.source.Source; + } + + interface TileOptions extends LayerOptions { + + /** + * Preload. Load low-resolution tiles up to preload levels. By default preload is 0, which means no preloading. + */ + preload?: number; + + /** + * Source for this layer. + */ + source?: ol.source.Tile; + + /** + * Use interim tiles on error. Default is true. + */ + useInterimTilesOnError?: boolean; + } + + interface VectorOptions extends LayerOptions { + + /** + * When set to true, feature batches will be recreated during animations. This means that no vectors will be shown clipped, but the setting will have a performance impact for large amounts of vector data. When set to false, batches will be recreated when no animation is active. Default is false. + */ + updateWhileAnimating?: boolean; + + /** + * When set to true, feature batches will be recreated during interactions. See also updateWhileInteracting. Default is false. + */ + updateWhileInteracting?: boolean; + + /** + * Render order. Function to be used when sorting features before rendering. By default features are drawn in the order that they are created. Use null to avoid the sort, but get an undefined draw order. + */ + // TODO: replace any with the expected function, unclear in documentation what the parameters are + renderOrder?: any; + + /** + * The buffer around the viewport extent used by the renderer when getting features from the vector source for the rendering or hit-detection. Recommended value: the size of the largest symbol, line width or label. Default is 100 pixels. + */ + renderBuffer?: number; + + /** + * Source. + */ + source?: ol.source.Vector; + + /** + * Layer style. See ol.style for default style which will be used if this is not defined. + */ + style?: ol.style.Style | Array | any; + } + } + + namespace source { + + interface VectorOptions { + /** + * Attributions. + */ + attributions?: Array; + + /** + * Features. If provided as {@link ol.Collection}, the features in the source + * and the collection will stay in sync. + */ + features?: Array | ol.Collection; + + /** + * The feature format used by the XHR feature loader when `url` is set. + * Required if `url` is set, otherwise ignored. Default is `undefined`. + */ + format?: ol.format.Feature; + + /** + * The loader function used to load features, from a remote source for example. + * Note that the source will create and use an XHR feature loader when `url` is + * set. + */ + loader?: ol.FeatureLoader; + + /** + * Logo. + */ + logo?: string | olx.LogoOptions; + + /** + * The loading strategy to use. By default an {@link ol.loadingstrategy.all} + * strategy is used, a one-off strategy which loads all features at once. + */ + strategy?: ol.LoadingStrategy; + + /** + * Setting this option instructs the source to use an XHR loader (see + * {@link ol.featureloader.xhr}) and an {@link ol.loadingstrategy.all} for a + * one-off download of all features from that URL. + * Requires `format` to be set as well. + */ + url?: string; + + /** + * By default, an RTree is used as spatial index. When features are removed and + * added frequently, and the total number of features is low, setting this to + * `false` may improve performance. + */ + useSpatialIndex?: boolean; + + /** + * Wrap the world horizontally. Default is `true`. For vector editing across the + * -180° and 180° meridians to work properly, this should be set to `false`. The + * resulting geometry coordinates will then exceed the world bounds. + */ + wrapX?: boolean; + } + + interface ClusterOptions extends VectorOptions{ + + /** + * Minimum distance in pixels between clusters. Default is 20. + */ + distance?: number; + + extent?: ol.Extent; + + geometryFunction?: any; + + projection?: ol.proj.ProjectionLike; + + source: ol.source.Vector; + + } + + interface WMTSOptions { + attributions?: Array; + crossOrigin?: string; + logo?: string | olx.LogoOptions; + tileGrid: ol.tilegrid.WMTS; // REQUIRED ! + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + requestEncoding?: ol.source.WMTSRequestEncoding; + layer: string; //REQUIRED + style: string; //REQUIRED + tileClass?: Function; + tilePixelRatio?: number; + version?: string; + format?: string; + matrixSet: string; //REQUIRED + dimensions?: Object; + url?: string; + maxZoom?: number; + tileLoadFunction?: ol.TileLoadFunctionType; + urls?: Array; + wrapX: boolean; + } + } + + namespace style { + + interface FillOptions { + color?: ol.Color | string; + } + + interface StyleOptions { + geometry?: string | ol.geom.Geometry | ol.style.GeometryFunction; + fill?: ol.style.Fill; + image?: ol.style.Image; + stroke?: ol.style.Stroke; + text?: ol.style.Text; + zIndex?: number; + } + + interface TextOptions { + font?: string; + offsetX?: number; + offsetY?: number; + scale?: number; + rotation?: number; + text?: string; + textAlign?: string; + textBaseline?: string; + fill?: ol.style.Fill; + stroke?: ol.style.Stroke; + } + interface StrokeOptions { + color?: ol.Color | string; + lineCap?: string; + lineJoin?: string; + lineDash?: Array; + miterLimit?: number; + width?: number; + } + interface IconOptions { + anchor?: Array; + anchorOrigin?: string; + anchorXUnits?: string; + anchorYUnits?: string; + crossOrigin?: string; + img?: ol.Image | HTMLCanvasElement; + offset?: Array; + offsetOrigin?: string; + opacity?: number; + scale?: number; + snapToPixel?: boolean; + rotateWithView?: boolean; + rotation?: number; + size?: ol.Size; + imgSize?: ol.Size; + src?: string; + } + interface CircleOptions { + fill?: ol.style.Fill; + radius: number; + snapToPixel?: boolean; + stroke?: ol.style.Stroke; + } + } + + namespace tilegrid { + + interface TileGridOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.Tile sources. When no origin or origins are configured, the origin will be set to the bottom-left corner of the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Origin, i.e. the bottom-left corner of the grid. Default is null. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the bottom-left corners of the grid for each zoom level. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different origin. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1. + */ + resolutions?: Array; + + /** + * Tile size. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different tile size. + */ + tileSizes?: Array; + } + + interface WMTSOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.WMTS sources. When no origin or origins are configured, the origin will be calculated from the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Origin, i.e. the top-left corner of the grid. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the top-left corners of the grid for each zoom level. The length of this array needs to match the length of the resolutions array. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1 + */ + resolutions?: Array; + + /** + * matrix IDs. The length of this array needs to match the length of the resolutions array. + */ + matrixIds?: Array; + + /** + * Number of tile rows and columns of the grid for each zoom level. The values here are the TileMatrixWidth and TileMatrixHeight advertised in the GetCapabilities response of the WMTS, and define the grid's extent together with the origin. An extent can be configured in addition, and will further limit the extent for which tile requests are made by sources. + */ + sizes?: Array; + + /** + * Tile size. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. The length of this array needs to match the length of the resolutions array. + */ + tileSizes?: Array; + + /** + * Number of tile columns that cover the grid's extent for each zoom level. Only required when used with a source that has wrapX set to true, and only when the grid's origin differs from the one of the projection's extent. The array length has to match the length of the resolutions array, i.e. each resolution will have a matching entry here. + */ + widths?: Array; + } + + interface XYZOptions { + + /** + * Extent for the tile grid. The origin for an XYZ tile grid is the top-left corner of the extent. The zero level of the grid is defined by the resolution at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used. + */ + extent?: ol.Extent; + + /** + * Maximum zoom. The default is ol.DEFAULT_MAX_ZOOM. This determines the number of levels in the grid set. For example, a maxZoom of 21 means there are 22 levels in the grid set. + */ + maxZoom?: number; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Tile size in pixels. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + } + + interface ZoomifyOptions { + + /** + * Resolutions + */ + resolutions: Array; + } + } + + namespace view { + + interface FitGeometryOptions { + + /** + * Padding (in pixels) to be cleared inside the view. Values in the array are top, right, bottom and left padding. Default is [0, 0, 0, 0]. + */ + padding?: Array; + + /** + * Constrain the resolution. Default is true. + */ + constrainResolution?: boolean; + + /** + * Get the nearest extent. Default is false. + */ + nearest?: boolean; + + /** + * Minimum resolution that we zoom to. Default is 0. + */ + minResolution?: number; + + /** + * Maximum zoom level that we zoom to. If minResolution is given, this property is ignored. + */ + maxZoom?: number; + } + } + + namespace format { + interface WKTOptions { + /** + * Whether to split GeometryCollections into multiple features on reading. Default is false. + */ + splitCollection?: boolean; + } + + interface GeoJSONOptions { + + /** + * Default data projection. + */ + defaultDataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Geometry name to use when creating features + */ + geometryName?: string; + } + + interface ReadOptions { + + /** + * Projection of the data we are reading. If not provided, the projection will be derived from the data (where possible) or the defaultDataProjection of the format is assigned (where set). If the projection can not be derived from the data and if no defaultDataProjection is set for a format, the features will not be reprojected. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries created by the format reader. If not provided, features will be returned in the dataProjection. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface WriteOptions { + + /** + * Projection of the data we are writing. If not provided, the defaultDataProjection of the format is assigned (where set). If no defaultDataProjection is set for a format, the features will be returned in the featureProjection. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries that will be serialized by the format writer. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * When writing geometries, follow the right-hand rule for linear ring orientation. This means that polygons will have counter-clockwise exterior rings and clockwise interior rings. By default, coordinates are serialized as they are provided at construction. If true, the right-hand rule will be applied. If false, the left-hand rule will be applied (clockwise for exterior and counter-clockwise for interior rings). Note that not all formats support this. The GeoJSON format does use this property when writing geometries. + */ + rightHanded?: boolean; + } + } + + namespace control { + interface ControlOptions { + /** + * The element is the control's container element. This only needs to be specified if you're developing a custom control. + */ + element?: Element; + + /** + * Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback. + */ + render?: any; + + /** + * Specify a target if you want the control to be rendered outside of the map's viewport. + */ + target?: Element | string; + } + } +} + +/** + * A high-performance, feature-packed library for all your mapping needs. + */ +declare namespace ol { + + interface TileLoadFunctionType { (image: ol.Image, url: string): void } + + interface ImageLoadFunctionType { (image: ol.Image, url: string): void } + + type AttributionLike = string | Array | ol.Attribution | Array + + /** + * An attribution for a layer source. + */ + class Attribution { + /** + * @constructor + * @param options Attribution options. + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @returns The attribution HTML. + */ + getHTML(): string; + } + + /** + * An expanded version of standard JS Array, adding convenience methods for manipulation. Add and remove changes to the Collection trigger a Collection event. Note that this does not cover changes to the objects within the Collection; they trigger events on the appropriate object, not on the Collection as a whole. + */ + class Collection extends ol.Object { + + /** + * @constructor + * @param values Array. + */ + constructor(values: Array) + + /** + * Remove all elements from the collection. + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array to the end of the collection. + * @param arr Array. + * @returns This collection. + */ + extend(arr: Array): Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param f The function to call for every element. This function takes 3 arguments (the element, the index and the array). + * @param ref The object to use as this in f. + */ + forEach(f: (element: T, index: number, array: Array) => void, ref?: any): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array is mutated, no events will be dispatched by the collection, and the collection's "length" property won't be in sync with the actual length of the array. + * @returns Array. + */ + getArray(): Array; + + /** + * Get the length of this collection. + * @returns The length of the array. + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param index Index. + * @param elem Element. + */ + insertAt(index: number, elem: T): void; + + /** + * Get the element at the provided index. + * @param index Index. + * @returns Element. + */ + item(index: number): T; + + /** + * Remove the last element of the collection and return it. Return undefined if the collection is empty. + * @returns Element + */ + pop(): T; + + /** + * Insert the provided element at the end of the collection. + * @param Element. + * @returns Length. + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param elem Element. + * @returns The removed element or undefined if none found. + */ + remove(elem: T): T; + + /** + * Remove the element at the provided index and return it. Return undefined if the collection does not contain this index. + * @param index Index. + * @returns Value. + */ + removeAt(index: number): T; + + /** + * Set the element at the provided index. + * @param index Index. + * @param elem Element. + */ + setAt(index: number, elem: T): void; + } + + /** + * Events emitted by ol.Collection instances are instances of this type. + */ + class CollectionEvent extends ol.events.Event { + + /** + * The element that is added to or removed from the collection. + */ + element: T; + } + + /** + * The ol.DeviceOrientation class provides access to information from DeviceOrientation events. + */ + class DeviceOrientation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @returns The euler angle in radians of the device from the standard Z axis. + */ + getAlpha(): number; + + /** + * Rotation around the device x-axis (in radians). + * @returns The euler angle in radians of the device from the planar X axis. + */ + getBeta(): number; + + /** + * Rotation around the device y-axis (in radians). + * @returns The euler angle in radians of the device from the planar Y axis. + */ + getGamma(): number; + + /** + * The heading of the device relative to north (in radians). + * @returns The heading of the device relative to north, in radians, normalizing for different browser behavior. + */ + getHeading(): number; + + /** + * Determine if orientation is being tracked. + * @returns Changes in device orientation are being tracked. + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately. + */ + setTracking(tracking: boolean): void; + } + + /** + * Events emitted by ol.interaction.DragBox instances are instances of this type. + */ + class DragBoxEvent extends ol.events.Event { + + /** + * The coordinate of the drag event. + */ + coordinate: ol.Coordinate; + } + + /** + * A vector object for geographic features with a geometry and other attribute properties, similar to the features in vector file formats like GeoJSON. + */ + class Feature extends ol.Object { + + /** + * @constructor + * @param geometry Geometry. + */ + // TODO: replace any with Object + constructor(geometryOrProperties?: ol.geom.Geometry | any); + + /** + * Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone. + * @returns The clone. + */ + clone(): Feature; + + /** + * Get the feature's default geometry. A feature may have any number of named geometries. The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry. + * @returns The default geometry for the feature. + */ + getGeometry(): ol.geom.Geometry; + + /** + * Get the name of the feature's default geometry. By default, the default geometry is named geometry. + * @returns Get the property name associated with the default geometry for this feature. + */ + getGeometryName(): string; + + /** + * @returns Id. + */ + getId(): string | number; + + /** + * Get the feature's style. This return for this method depends on what was provided to the ol.Feature#setStyle method. + * The feature style. + */ + getStyle(): ol.style.Style | Array | ol.FeatureStyleFunction; + + /** + * Get the feature's style function. + * @returns Return a function representing the current style of this feature. + */ + getStyleFunction(): ol.FeatureStyleFunction; + + /** + * Set the default geometry for the feature. This will update the property with the name returned by ol.Feature#getGeometryName. + * @param geometry The new geometry. + */ + setGeometry(geometry: ol.geom.Geometry): void; + + /** + * Set the property name to be used when getting the feature's default geometry. When calling ol.Feature#getGeometry, the value of the property with this name will be returned. + * @param name The property name of the default geometry. + */ + setGeometryName(name: string): void; + + /** + * Set the feature id. The feature id is considered stable and may be used when requesting features or comparing identifiers returned from a remote source. The feature id can be used with the ol.source.Vector#getFeatureById method. + * @param id The feature id. + */ + setId(id: string | number): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: Array): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.FeatureStyleFunction): void; + } + + /** + * A mechanism for changing the style of a small number of features on a temporary basis, for example highlighting. + */ + class FeatureOverlay { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.FeatureOverlayOptions); + + /** + * Add a feature to the overlay. + * @param feature Feature. + */ + addFeature(feature: ol.Feature): void; + + /** + * Get the features on the overlay. + * @returns Features collection. + */ + getFeatures: ol.Collection; + + /** + * Get the map associated with the overlay. + * @returns The map with which this feature overlay is associated. + */ + getMap(): ol.Map; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + * @returns Overlay style. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function + * @returns Style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Remove a feature from the overlay. + * @param feature The feature to be removed. + */ + removeFeature(feature: ol.Feature): void; + + /** + * Set the features for the overlay. + * @param features Features collection. + */ + setFeatures(features: ol.Collection): void; + + /** + * Set the map for the overlay. + * @param map Map. + */ + setMap(map: ol.Map): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.StyleFunction): void; + } + + /** + * Helper class for providing HTML5 Geolocation capabilities. The Geolocation API is used to locate a user's position. + */ + class Geolocation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GeolocationOptions); + + /** + * Get the accuracy of the position in meters. + * @returns The accuracy of the position measurement in meters. + */ + getAccuracy(): number; + + /** + * Get a geometry of the position accuracy. + * @returns A geometry of the position accuracy. + */ + getAccuracyGeometry(): ol.geom.Geometry; + + /** + * Get the altitude associated with the position. + * @returns The altitude of the position in meters above mean sea level. + */ + getAltitude(): number; + + /** + * Get the altitude accuracy of the position. + * @returns The accuracy of the altitude measurement in meters. + */ + getAltitudeAccuracy(): number; + + /** + * Get the heading as radians clockwise from North. + * @returns The heading of the device in radians from north. + */ + getHeading(): number; + + /** + * Get the position of the device. + * @returns The current position of the device reported in the current projection. + */ + getPosition(): ol.Coordinate; + + /** + * Get the projection associated with the position. + * @returns The projection the position is reported in. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the speed in meters per second. + * @returns The instantaneous speed of the device in meters per second. + */ + getSpeed(): number; + + /** + * Determine if the device location is being tracked. + * @returns The device location is being tracked. + */ + getTracking(): boolean; + + /** + * Get the tracking options. + * @returns PositionOptions as defined by the HTML5 Geolocation spec. + */ + getTrackingOptions(): PositionOptions; + + /** + * Set the projection to use for transforming the coordinates. + * @param projection The projection the position is reported in. + */ + setProjection(projection: ol.proj.Projection): void; + + /** + * Enable or disable tracking. + * @param tracking Enable tracking + */ + setTracking(tracking: boolean): void; + + /** + * Set the tracking options. + * @param PositionOptions as defined by the HTML5 Geolocation spec. + */ + setTrackingOptions(options: PositionOptions): void; + } + + /** + * Render a grid for a coordinate system on a map. + */ + class Graticule { + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GraticuleOptions); + + /** + * Get the map associated with this graticule. + * @returns The map. + */ + getMap(): Map; + + /** + * Get the list of meridians. Meridians are lines of equal longitude. + * @returns The meridians. + */ + getMeridians(): Array; + + /** + * Get the list of parallels. Pallels are lines of equal latitude. + * @returns The parallels. + */ + getParallels(): Array; + + /** + * Set the map for this graticule.The graticule will be rendered on the provided map. + * @param map Map + */ + setMap(map: Map): void; + } + + /** + * + */ + class Image extends ol.ImageBase { + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + } + + /** + * + */ + class ImageBase { + } + + /** + * + */ + class ImageTile extends ol.Tile { + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + + } + + /** + * Implementation of inertial deceleration for map movement. + */ + class Kinetic { + + /** + * @constructor + * @param decay Rate of decay (must be negative). + * @param Minimum velocity (pixels/millisecond). + * @param Delay to consider to calculate the kinetic initial values (milliseconds). + */ + constructor(decay: number, minVelocity: number, delay: number); + } + + /** + * The map is the core component of OpenLayers. For a map to render, a view, one or more layers, and a target container are needed. + */ + class Map extends ol.Object { + + /** + * @constructor + * @params options Options. + */ + constructor(options: olx.MapOptions); + + /** + * Add the given control to the map. + * @param control Control. + */ + addControl(control: ol.control.Control): void; + + /** + * Add the given interaction to the map. + * @param interaction Interaction to add. + */ + addInteraction(interaction: ol.interaction.Interaction): void; + + /** + * Adds the given layer to the top of this map. If you want to add a layer elsewhere in the stack, use getLayers() and the methods available on ol.Collection. + * @param Layer. + */ + addLayer(layer: ol.layer.Base): void; + + /** + * Add the given overlay to the map. + * @param overlay Overlay. + */ + addOverlay(overlay: ol.Overlay): void; + + /** + * Add functions to be called before rendering. This can be used for attaching animations before updating the map's view. The ol.animation namespace provides several static methods for creating prerender functions. + * @param var_args Any number of pre-render functions. + */ + beforeRender(var_args: ol.PreRenderFunction): void; + + /** + * Detect features that intersect a pixel on the viewport, and execute a callback with each intersecting feature. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Feature callback. The callback will be called with two arguments. The first argument is one feature at the pixel, the second is the layer of the feature. If the detected feature is not on a layer, but on a ol.FeatureOverlay, then the second argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Layer callback. Will receive one argument, the layer that contains the color pixel. If the detected color value is not from a layer, but from a ol.FeatureOverlay, then the argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachLayerAtPixel(pixel: ol.Pixel, callback: (layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Get the map controls. Modifying this collection changes the controls associated with the map. + * @returns Controls. + */ + getControls(): ol.Collection; + + /** + * Get the coordinate for a given pixel. This returns a coordinate in the map view projection. + * @param pixel Pixel position in the map viewport. + * @returns The coordinate for the pixel position. + */ + getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate; + + /** + * Returns the geographical coordinate for a browser event. + * @param event Event. + * @returns Coordinate. + */ + getEventCoordinate(event: Event): ol.Coordinate; + + /** + * Returns the map pixel position for a browser event relative to the viewport. + * @param event Event. + * @returns Pixel. + */ + getEventPixel(event: Event): ol.Pixel; + + /** + * Get the map interactions. Modifying this collection changes the interactions associated with the map. + * @returns Interactions + */ + getInteractions(): ol.Collection; + + /** + * Get the layergroup associated with this map. + * @returns A layer group containing the layers in this map. + */ + getLayerGroup(): ol.layer.Group; + + /** + * Get the collection of layers associated with this map. + * @returns Layers. + */ + getLayers(): ol.Collection; + + /** + * Get the map overlays. Modifying this collection changes the overlays associated with the map. + * @returns Overlays. + */ + getOverlays(): ol.Collection; + + /** + * Get the pixel for a coordinate. This takes a coordinate in the map view projection and returns the corresponding pixel. + * @param coordinate A map coordinate. + * @returns A pixel position in the map viewport. + */ + getPixelFromCoordinate(coordinate: ol.Coordinate): ol.Pixel; + + /** + * Get the size of this map. + * @returns The size in pixels of the map in the DOM. + */ + getSize(): ol.Size; + + /** + * Get the target in which this map is rendered. Note that this returns what is entered as an option or in setTarget: if that was an element, it returns an element; if a string, it returns that. + * @returns The Element or id of the Element that the map is rendered in. + */ + getTarget(): Element | string; + + /** + * Get the DOM element into which this map is rendered. In contrast to getTarget this method always return an Element, or null if the map has no target. + * @returns The element that the map is rendered in. + */ + getTargetElement(): Element; + + /** + * Get the view associated with this map. A view manages properties such as center and resolution. + * @returns The view that controls this map. + */ + getView(): View; + + /** + * Get the element that serves as the map viewport. + * @returns Viewport. + */ + getViewport(): Element; + + /** + * Detect if features intersect a pixel on the viewport. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref Value to use as this when executing layerFilter. + * @returns Is there a feature at the given pixel? + */ + hasFeatureAtPixel(pixel: ol.Pixel, layerFilter?: (layer: ol.layer.Layer) => boolean, ref?: any): boolean; + + /** + * Remove the given control from the map. + * @param Control. + * @returns The removed control (or undefined if the control was not found). + */ + removeControl(control: ol.control.Control): ol.control.Control; + + /** + * Remove the given interaction from the map. + * @param interaction Interaction to remove. + * @returns The removed interaction (or undefined if the interaction was not found). + */ + removeInteraction(interaction: ol.interaction.Interaction): ol.interaction.Interaction; + + /** + * Removes the given layer from the map. + * @param Layer. + * @returns The removed layer (or undefined if the layer was not found). + */ + removeLayer(layer: ol.layer.Base): ol.layer.Base; + + /** + * Remove the given overlay from the map. + * @param Overlay. + * @returns The removed overlay (or undefined if the overlay was not found). + */ + removeOverlay(overlay: ol.Overlay): ol.Overlay; + + /** + * Request a map rendering (at the next animation frame). + */ + render(): void; + + /** + * Requests an immediate render in a synchronous manner. + */ + renderSync(): void; + + /** + * Sets the layergroup of this map. + * @param layerGroup A layer group containing the layers in this map. + */ + setLayerGroup(layerGroup: ol.layer.Group): void; + + /** + * Set the size of this map. + * @param size The size in pixels of the map in the DOM. + */ + setSize(size: ol.Size): void; + + /** + * Set the target element to render this map into. + * @param target The Element that the map is rendered in. + */ + setTarget(target: Element): void; + + /** + * Set the target element to render this map into. + * @param target The id of the element that the map is rendered in. + */ + setTarget(target: string): void; + + /** + * Set the view for this map. + * @param view The view that controls this map. + */ + setView(view: View): void; + + /** + * Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport. + * */ + updateSize(): void; + } + + /** + * Events emitted as map browser events are instances of this type. See ol.Map for which events trigger a map browser event. + */ + class MapBrowserEvent extends MapEvent { + + /** + * The coordinate of the original browser event + */ + coordinate: Coordinate; + + /** + * Indicates if the map is currently being dragged. Only set for POINTERDRAG and POINTERMOVE events. Default is false. + */ + dragging: boolean; + + /** + * The frame state at the time of the event + */ + frameState: olx.FrameState; + + /** + * The map where the event occured + */ + map: Map; + + /** + * The original browser event + */ + originalEvent: Event; + + /** + * The pixel of the original browser event. + */ + pixel: Pixel; + + + // Methods + + /** + * Prevents the default browser action. + */ + preventDefault(): void; + + /** + * Prevents further propagation of the current event. + */ + stopPropagation(): void; + } + + /** + * Events emitted as map events are instances of this type. See ol.Map for which events trigger a map event. + */ + class MapEvent extends ol.events.Event { + + /** + * The frame state at the time of the event. + */ + frameState: olx.FrameState; + + /** + * The map where the event occurred. + */ + map: Map; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Most non-trivial classes inherit from this. + */ + class Object extends Observable { + + /** + * @constructor + * @param values An object with key-value pairs. + */ + constructor(values?: Object); + + /** + * Gets a value. + * @param key Key name. + * @returns Value. + */ + get(key: string): any; + + /** + * Get a list of object property names. + * @returns List of property names. + */ + getKeys(): Array; + + /** + * Get an object of all property names and values. + * @returns Object. + */ + getProperties(): Object; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Sets a value. + * @param key Key name. + * @param value Value. + */ + set(key: string, value: any): void; + + /** + * Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties). + * @param Values. + */ + setProperties(values: Object): void; + + /** + * Unsets a property. + */ + unset(key: string): void; + } + + /** + * Events emitted by ol.Object instances are instances of this type. + */ + class ObjectEvent extends ol.events.Event { + + /** + * The name of the property whose value is changing. + */ + key: string; + + /** + * The old value. To get the new value use e.target.get(e.key) where e is the event object. + */ + oldValue: any; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. An event target providing convenient methods for listener registration and unregistration. A generic change event is always available through ol.Observable#changed. + */ + class Observable { + + /** + * Removes an event listener using the key returned by on() or once(). + */ + unByKey(key: any): void; + + /** + * Increases the revision counter and dispatches a 'change' event. + */ + changed(): void; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Listen for a certain type of event. + * @param type The event type. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen once for a certain type of event. + * @param type The event type. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: string, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Listen once for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Unlisten for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param ref The object to use as this in listener. + * @returns Unique key for the listener. + */ + un(type: Array, listener: (event: ol.events.Event) => void, ref?: any): any; + + /** + * Removes an event listener using the key returned by on() or once(). Note that using the ol.Observable.unByKey static function is to be preferred. + * @param key The key returned by on() or once() + */ + unByKey(key: any): void; + } + + /** + * An element to be displayed over the map and attached to a single map location. + */ + class Overlay extends ol.Object { + + /** + * @constructor + * @param options Overlay options. + */ + constructor(options: olx.OverlayOptions); + + /** + * Get the DOM element of this overlay. + * @returns The Element containing the overlay. + */ + getElement(): Element; + + /** + * Get the map associated with this overlay. + * @returns The map that the overlay is part of. + */ + getMap(): ol.Map; + + /** + * Get the offset of this overlay. + * @returns The offset. + */ + getOffset(): Array; + + /** + * Get the current position of this overlay. + * @returns The spatial point that the overlay is anchored at. + */ + getPosition(): ol.Coordinate; + + /** + * Get the current positioning of this overlay. + * @returns How the overlay is positioned relative to its point on the map. + */ + getPositioning(): ol.OverlayPositioning; + + /** + * Set the DOM element to be associated with this overlay. + * @param element The element containing the overlay. + */ + setElement(element: Element): void; + + /** + * Set the map to be associated with this overlay. + * @param map The map that the overlay is part of. + */ + setMap(map: Map): void; + + /** + * Set the offset for this overlay. + * @param offset Offset. + */ + setOffset(offset: Array): void; + + /** + * Set the position for this overlay. If the position is undefined the overlay is hidden. + * @param position The spatial point that the overlay is anchored at. + */ + setPosition(position: ol.Coordinate): void; + + /** + * Set the positioning for this overlay. + * @param How the overlay is positioned relative to its point on the map. + */ + setPositioning(positioning: ol.OverlayPositioning): void; + } + + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent extends ol.events.Event { + + /** + * Deselected features array. + */ + deselected: Array; + + /** + * Associated ol.MapBrowserEvent; + */ + mapBrowserEvent: ol.MapBrowserEvent; + + /** + * Selected features array. + */ + selected: Array + } + + /** + * Class to create objects that can be used with ol.geom.Polygon.circular. + */ + class Sphere { + + /** + * @constructor + * @param radius Radius. + */ + constructor(radius: number); + + /** + * Returns the geodesic area for a list of coordinates. + * @param coordinates List of coordinates of a linear ring. If the ring is oriented clockwise, the area will be positive, otherwise it will be negative. + * @returns Area. + */ + geodesicArea(coordinates: Array): number; + + /** + * Returns the distance from c1 to c2 using the haversine formula. + * @param c1 Coordinate 1. + * @param c2 Coordinate 2. + * @returns Haversine distance. + */ + haversineDistance(c1: ol.Coordinate, c2: ol.Coordinate): number; + } + + /** + * Base class for tiles. + */ + class Tile { + + /** + * Get the tile coordinate for this tile. + * @returns TileCoord. + */ + getTileCoord(): ol.TileCoord; + } + + /** + * An ol.View object represents a simple 2D view of the map. + */ + class View extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.ViewOptions); + + /** + * Calculate the extent for the current view state and the passed size. The size is the pixel dimensions of the box into which the calculated extent should fit. In most cases you want to get the extent of the entire map, that is map.getSize(). + * @param size Box pixel size + * @returns Extent. + */ + calculateExtent(size: ol.Size): ol.Extent; + + /** + * Center on coordinate and view position. + * @param coordinate Coordinate. + * @param size Box pixel size + * @param position Position on the view to center on + */ + centerOn(coordinate: ol.Coordinate, size: ol.Size, position: ol.Pixel): void; + + /** + * Get the constrained center of this view. + * @param center Center. + * @returns Constrained center. + */ + constrainCenter(center: ol.Coordinate): ol.Coordinate; + + /** + * Get the constrained resolution of this view. + * @param resolution: Resolution. + * @param delta Delta. Default is 0. + * @param direction Direction. Default is 0. + * @returns Constrained resolution + */ + constrainResolution(resolution: number, delta?: number, direction?: number): number; + + /** + * Fit the map view to the passed extent and size. The size is pixel dimensions of the box to fit the extent into. In most cases you will want to use the map size, that is map.getSize(). + * @param extent Extent. + * @param size Box pixel size. + * @param options Options + */ + fit(geometry: ol.geom.SimpleGeometry | ol.Extent, size: ol.Size, opt_options?: olx.view.FitGeometryOptions): void; + + /** + * Get the view center. + * @returns The center of the view. + */ + getCenter(): ol.Coordinate; + + /** + * Get the view projection + * @returns The projection of the view. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the view resolution + * @returns The resolution of the view. + */ + getResolution(): number; + + /** + * Get the view rotation + * @returns The rotation of the view in radians + */ + getRotation(): number; + + /** + * Get the current zoom level. Return undefined if the current resolution is undefined or not a "constrained resolution". + * @returns Zoom. + */ + getZoom(): number; + + /** + * Rotate the view around a given coordinate. + * @param rotation New rotation value for the view. + * @param anchor The rotation center. + */ + rotate(rotation: number, anchor: ol.Coordinate): void; + + /** + * Set the center of the current view. + * @param center The center of the view. + */ + setCenter(center: ol.Coordinate): void; + + /** + * Set the resolution for this view. + * @param resolution The resolution of the view. + */ + setResolution(resolution: number): void; + + /** + * Set the rotation for this view. + * @param rotation The rotation of the view in radians. + */ + setRotation(rotation: number): void; + + /** + * Zoom to a specific zoom level. + * @param zoom Zoom level. + */ + setZoom(zoom: number): void; + } + + // NAMESPACES + + /** + * The animation static methods are designed to be used with the ol.Map#beforeRender method. + */ + namespace animation { + + /** + * Generate an animated transition that will "bounce" the resolution as it approaches the final value. + * @param options Bounce options. + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param options Pan options. + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param options Rotate options. + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param options Zoom options. + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + */ + namespace color { + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: ol.Color): ol.Color; + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: string): ol.Color; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: ol.Color): string; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: string): string; + } + + namespace control { + + /** + * Set of controls included in maps by default. Unless configured otherwise, this returns a collection containing an instance of each of the following controls: ol.control.Zoom, ol.control.Rotate, ol.control.Attribution + * @param options Defaults options + * @returns Control.s + */ + function defaults(options?: olx.control.DefaultsOptions): ol.Collection; + + namespace ScaleLine { + + /** + * Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'. + */ + type Units = 'degrees' | 'imperial' | 'nautical' | 'metric' | 'us'; + } + + class Control extends ol.Object{ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + */ + getMap():ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to the map here. + */ + setMap(map: ol.Map):void; + + /** + * This function is used to set a target element for the control. + * It has no effect if it is called after the control has been added to the map (i.e. after setMap is called on the control). + * If no target is set in the options passed to the control constructor and if setTarget is not called then the control is + * added to the map's overlay container. + */ + setTarget(target: Element | string):void; + + + } + + class Attribution extends Control { + } + + class FullScreen extends Control { + } + + class MousePosition extends Control { + } + + class OverviewMap extends Control { + constructor(options?: olx.OverviewMapOptions); + + /** + * Update the overview map element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Determine if the overview map is collapsed. + */ + getCollapsed(): boolean; + + /** + * Return true if the overview map is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Return the overview map. + */ + getOverviewMap(): ol.Map; + + /** + * Collapse or expand the overview map according to the passed parameter. Will not do anything if the overview map isn't collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the overview map should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; + } + + class Rotate extends Control { + constructor(opt_options?: olx.RotateOptions); + } + + class ScaleLine extends Control { + + /** + * Return the units to use in the scale line. + */ + getUnits(): ScaleLine.Units; + + /** + * Set the units to use in the scale line. + */ + setUnits(units: ScaleLine.Units): void; + + } + + class Zoom extends Control{ + } + + class ZoomSlider extends Control{ + } + + class ZoomToExtent extends Control{ + constructor(options?: olx.ZoomToExtentOptions); + } + } + + namespace coordinate { + + /** + * Add delta to coordinate. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param delta Delta + * @returns The input coordinate adjusted by the given delta. + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a ol.CoordinateFormatType function that can be used to format a {ol.Coordinate} to a string. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Coordinate format + */ + function createStringXY(fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given ol.Coordinate to a string using the given string template. The strings {x} and {y} in the template will be replaced with the first and second coordinate values respectively. + * @param coordinate Coordinate + * @param template A template string with {x} and {y} placeholders that will be replaced by first and second coordinate values. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Formatted coordinate + */ + function format(coordinate: ol.Coordinate, template: string, fractionDigits?: number): string; + + /** + * Rotate coordinate by angle. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param angle Angle in radian + * @returns Coordinatee + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and seconds. + * @param coordinate COordinate + * @returns Hemisphere, degrees, minutes and seconds. + */ + function toStringHDMS(coordinate?: ol.Coordinate): string; + + /** + * Format a coordinate as a comma delimited string. + * @param coordinate Coordinate + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns XY + */ + function toStringXY(coordinate?: ol.Coordinate, fractionDigits?: number): string; + } + + /** + * Easing functions for ol.animation. + */ + namespace easing { + + /** + * Start slow and speed up. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the same general behavior as ol.easing.inAndOut, but the final slowdown is delayed. + * @param number Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function upAndDown(t: number): number; + } + + namespace events { + namespace condition { + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function altShiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function mouseOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function targetNotEditable(mapBrowserEvent: ol.MapBrowserEvent): boolean; + } + interface ConditionType { (mapBrowseEvent: ol.MapBrowserEvent): boolean; } + class Event { + target: any; + type: string; + preventDefault(): void; + stopPropagation(): void; + } + } + + namespace extent { + + /** + * Apply a transform function to the extent. + * @param extent Extent + * @param transformFn Transform function. Called with [minX, minY, maxX, maxY] extent coordinates. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function applyTransform(extent: ol.Extent, transformFn: ol.TransformFunction, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Build an extent that includes all given coordinates. + * @param coordinates Coordinates + * @returns Bounding extent + */ + function boundingExtent(coordinates: Array): ol.Extent; + + /** + * Return extent increased by the provided value. + * @param extent Extent + * @param value The amount by which the extent should be buffered. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function buffer(extent: ol.Extent, value: number, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param coordinate Coordinate + * @returns The coordinate is contained in the extent + */ + function containsCoordinate(extent: ol.Extent, coordinate: ol.Coordinate): boolean; + + /** + * Check if one extent contains another. An extent is deemed contained if it lies completely within the other extent, including if they share one or more edges. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The second extent is contained by or on the edge of the first + */ + function containsExtent(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param x X coordinate + * @param y Y coordinate + * @returns The x, y values are contained in the extent. + */ + function containsXY(extent: ol.Extent, x: number, y: number): boolean; + + /** + * Create an empty extent. + * @returns Empty extent + */ + function createEmpty(): ol.Extent; + + /** + * Determine if two extents are equivalent. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents are equivalent + */ + function equals(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Modify an extent to include another extent. + * @param extent1 The extent to be modified. + * @param extent2 The extent that will be included in the first. + * @returns A reference to the first (extended) extent. + */ + function extend(extent1: ol.Extent, extent2: ol.Extent): ol.Extent; + + /** + * Get the bottom left coordinate of an extent. + * @param extent Extent + * @returns Bottom left coordinate + */ + function getBottomLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the bottom right coordinate of an extent. + * @param extent Extent + * @returns Bottom right coordinate + */ + function getBottomRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the center coordinate of an extent. + * @param extent Extent + * @returns Center + */ + function getCenter(extent: ol.Extent): ol.Coordinate; + + /** + * Get the height of an extent. + * @param extent Extent + * @returns Height + */ + function getHeight(extent: ol.Extent): number; + + /** + * Get the intersection of two extents. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @param extent Optional extent to populate with intersection. + * @returns Intersecting extent + */ + function getIntersection(extent1: ol.Extent, extent2: ol.Extent, extent?: ol.Extent): ol.Extent; + + /** + * Get the size (width, height) of an extent. + * @param extent Extent + * @returns The extent size + */ + function getSize(extent: ol.Extent): ol.Size; + + /** + * Get the top left coordinate of an extent. + * @param extent Extent + * @returns Top left coordinate + */ + function getTopLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the top right coordinate of an extent. + * @param extent Extent + * @returns Top right coordinate + */ + function getTopRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the width of an extent. + * @param extent Extent + * @returns Width + */ + function getWidth(extent: ol.Extent): number; + + /** + * Determine if one extent intersects another. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents intersects + */ + function intersects(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Determine if an extent is empty. + * @param extent Extent + * @returns Is empty + */ + function isEmpty(extent: ol.Extent): boolean; + } + + /** + * Loading mechanisms for vector data. + */ + namespace featureloader { + + /** + * Create an XHR feature loader for a url and format. The feature loader loads features (with XHR), parses the features, and adds them to the vector source. + * @param url Feature URL Service + * @param format Feature format + * @returns The feature loader + */ + function xhr(url: string, format: ol.format.Feature): ol.FeatureLoader; + } + + namespace format { + + // Type definitions + interface IGCZ extends String { } + + // Classes + class EsriJSON { + } + + class Feature { + } + + /** + * Feature format for reading and writing data in the GeoJSON format. + */ + class GeoJSON extends ol.format.JSONFeature { + + /** + * @constructor + * @param Options + */ + constructor(options?: olx.format.GeoJSONOptions); + + /** + * Read a feature from a GeoJSON Feature source. Only works for Feature, use readFeatures to read FeatureCollection source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a GeoJSON source. Works with both Feature and FeatureCollection sources. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Read the projection from a GeoJSON source. + * @param Source + * @returns Projection + */ + readProjection(source: Document | Node | JSON | string): ol.proj.Projection; + + /** + * Encode a feature as a GeoJSON Feature string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode a feature as a GeoJSON Feature object. + * @param feature Feature + * @param options Write options + * @returns GeoJSON object + */ + writeFeatureObject(feature: ol.Feature, options?: olx.format.WriteOptions): JSON; + + /** + * Encode an array of features as GeoJSON. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a GeoJSON object. + * @param features Features + * @param options Write options + * @returns GeoJSON object + */ + writeFeaturesObject(features: Array, options?: olx.format.WriteOptions): JSON; + + /** + * Encode a geometry as a GeoJSON string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + + /** + * Encode a geometry as a GeoJSON object. + * @param geometry Geometry + * @options Write options + * @returns GeoJSON object + */ + writeGeometryObject(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): JSON; + } + + class GML { + } + + class GML2 { + } + + class GML3 { + } + + class GMLBase { + } + + class GPX { + } + + class IGC { + } + + class JSONFeature { + } + + class KML { + } + + class OSMXML { + } + + class Polyline { + } + + class TextFeature { + } + + class TopoJSON { + } + + class WFS { + readFeatures(source: Document | Node | Object | string, option?: olx.format.ReadOptions): Array; + } + + class WKT { + constructor(opt_options?: olx.format.WKTOptions); + + /** + * Read a feature from a WKT source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, opt_options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a WKT source. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Encode a feature as a WKT string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a WKT string. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Write a single geometry as a WKT string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + } + + class WMSCapabilities { + } + + class WMSGetFeatureInfo { + } + + class WMTSCapabilities { + } + + class XML { + } + + class XMLFeature { + } + } + + namespace geom { + + // Type definitions + interface GeometryLayout extends String { } + interface GeometryType extends String { } + + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class Circle extends ol.geom.SimpleGeometry { + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Transform each coordinate of the circle from one coordinate reference system + * to another. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * + * Internally a circle is currently represented by two points: the center of + * the circle `[cx, cy]`, and the point to the right of the circle + * `[cx + r, cy]`. This `transform` function just transforms these two points. + * So the resulting geometry is also a circle, and that circle does not + * correspond to the shape that would be obtained by transforming every point + * of the original circle. + * @param source The current projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @param destination The desired projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @returns This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Circle; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Base class for vector geometries. + */ + class Geometry extends ol.Object { + + /** + * Return the closest point of the geometry to the passed point as coordinate. + * @param point Point + * @param closestPoint Closest Point + * @returns Closest Point + */ + getClosestPoint(point: ol.Coordinate, closestPoint?: ol.Coordinate): ol.Coordinate; + + /** + * Get the extent of the geometry. + * @param Extent + * @returns Extent + */ + getExtent(extent?: ol.Extent): ol.Extent; + + /** + * Transform each coordinate of the geometry from one coordinate reference system to another. + * The geometry is modified in place. For example, a line will be transformed to a line and a + * circle to a circle. If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * @param source The current projection. Can be a string identifier or a ol.proj.Projection object. + * @param destination The desired projection. Can be a string identifier or a ol.proj.Projection object. + * @return This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike | ol.proj.Projection, destination: ol.proj.ProjectionLike | ol.proj.Projection): ol.geom.Geometry; + } + + /** + * An array of ol.geom.Geometry objects. + */ + class GeometryCollection extends ol.geom.Geometry { + + /** + * constructor + * @param geometries Geometries. + */ + constructor(geometries?: Array); + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.GeometryCollection; + + /** + * Return the geometries that make up this geometry collection. + * @returns Geometries. + */ + getGeometries(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the geometries that make up this geometry collection. + * @param geometries Geometries. + */ + setGeometries(geometries: Array): void; + + } + + /** + * Linear ring geometry. Only used as part of polygon; cannot be rendered + * on its own. + */ + class LinearRing extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LinearRing; + + /** + * Return the area of the linear ring on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Return the coordinates of the linear ring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * @Set the coordinates of the linear ring + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: any): void; + + } + + /** + * Linestring geometry. + */ + class LineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param coordinate Coordinate. + */ + appendCoordinate(coordinate: ol.Coordinate): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the linestring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the length of the linestring on projected plane. + * @returns Length (on projected plane). + */ + getLength(): number; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the linestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-linestring geometry. + */ + class MultiLineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed linestring to the multilinestring. + * @param lineString LineString. + */ + appendLineString(lineString: ol.geom.LineString): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiLineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @param interpolate Interpolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean, interpolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the multilinestring. + * @returns Coordinates. + */ + getCoordinates(): Array>; + + /** + * Return the linestring at the specified index. + * @param index Index. + * @returns LineString. + */ + getLineString(index: number): ol.geom.LineString; + + /** + * Return the linestrings of this multilinestring. + * @returns LineStrings. + */ + getLineStrings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multilinestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-point geometry. + */ + class MultiPoint extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed point to this multipoint. + * @param {ol.geom.Point} point Point. + */ + appendPoint(point: ol.geom.Point): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPoint; + + /** + * Return the coordinates of the multipoint. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the point at the specified index. + * @param index Index. + * @returns Point. + */ + getPoint(index: number): ol.geom.Point; + + /** + * Return the points of this multipoint. + * @returns Points. + */ + getPoints(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipoint. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-polygon geometry. + */ + class MultiPolygon extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed polygon to this multipolygon. + * @param polygon Polygon. + */ + appendPolygon(polygon: ol.geom.Polygon): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPolygon; + + /** + * Return the area of the multipolygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>>; + + /** + * Return the interior points as {@link ol.geom.MultiPoint multipoint}. + * @returns Interior points. + */ + getInteriorPoints(): ol.geom.MultiPoint; + + /** + * Return the polygon at the specified index. + * @param index Index. + * @returns Polygon. + */ + getPolygon(index: number): ol.geom.Polygon; + + /** + * Return the polygons of this multipolygon. + * @returns Polygons. + */ + getPolygons(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipolygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Point geometry. + */ + class Point extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Point; + + /** + * Return the coordinate of the point. + * @returns Coordinates. + */ + getCoordinates(): ol.Coordinate; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinate of the point. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Polygon geometry. + */ + class Polygon extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Create an approximation of a circle on the surface of a sphere. + * @param sphere The sphere. + * @param center Center (`[lon, lat]` in degrees). + * @param radius The great-circle distance from the center to the polygon vertices. + * @param n Optional number of vertices for the resulting polygon. Default is `32`. + * @returns The "circular" polygon. + */ + static circular(sphere: ol.Sphere, center: ol.Coordinate, radius: number, n?: number): ol.geom.Polygon; + + /** + * Append the passed linear ring to this polygon. + * @param linearRing Linear ring. + */ + appendLinearRing(linearRing: ol.geom.LinearRing): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Polygon; + + /** + * Return the area of the polygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>; + + /** + * Return an interior point of the polygon. + * @returns Interior point. + */ + getInteriorPoint(): ol.geom.Point; + + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param index Index. + * @returns Linear ring. + */ + getLinearRing(index: number): ol.geom.LinearRing; + + /** + * Return the linear rings of the polygon. + * @returns Linear rings. + */ + getLinearRings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the polygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class SimpleGeometry extends ol.geom.Geometry { + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Return the first coordinate of the geometry. + * @returns First coordinate. + */ + getFirstCoordinate(): ol.Coordinate; + + /** + * Return the last coordinate of the geometry. + * @returns Last point. + */ + getLastCoordinate(): ol.Coordinate; + + /** + * Return the {@link ol.geom.GeometryLayout layout} of the geometry. + * @returns Layout. + */ + getLayout(): ol.geom.GeometryLayout; + + /** + * Translate the geometry. This modifies the geometry coordinates in place. + * If instead you want a new geometry, first clone() this geometry. + * @param deltaX Delta X + * @param deltaY Delta Y + */ + translate(deltaX: number, deltaY: number): void; + } + } + + namespace has { + } + + namespace interaction { + /** + * Allows the user to zoom by double-clicking on the map. + */ + class DoubleClickZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DoubleClickZoomOptions); + } + /** + * Handles input of vector data by drag and drop. + */ + class DragAndDrop extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.DragAndDropOptions); + } + /** + * Events emitted by ol.interaction.DragAndDrop instances are instances of this type. + */ + class DragAndDropEvent extends ol.events.Event { + } + /** + * Allows the user to draw a vector box by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the shift or other key is held down. + * This is used, for example, for zooming to a specific area of the map + * (see ol.interaction.DragZoom and ol.interaction.DragRotateAndZoom). + * + * This interaction is only supported for mouse devices. + */ + class DragBox extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragBoxOptions); + /** + * Returns geometry of last drawn box. + */ + getGeometry(): ol.geom.Polygon; + } + /** + * Allows the user to pan the map by dragging the map. + */ + class DragPan extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragPanOptions); + } + /** + * Allows the user to rotate the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when the alt and shift keys are held down. + * + * This interaction is only supported for mouse devices. + */ + class DragRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateOptions); + } + /** + * Allows the user to zoom and rotate the map by clicking and dragging on the map. + * By default, this interaction is limited to when the shift key is held down. + * + * This interaction is only supported for mouse devices. + * + * And this interaction is not included in the default interactions. + */ + class DragRotateAndZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DragRotateAndZoomOptions); + } + /** + * Allows the user to zoom the map by clicking and dragging on the map, + * normally combined with an ol.events.condition that limits it to when a key, shift by default, is held down. + * + * To change the style of the box, use CSS and the .ol-dragzoom selector, or your custom one configured with className. + */ + class DragZoom extends ol.interaction.DragBox { + constructor(opt_options?: olx.interaction.DragZoomOptions); + } + /** + * Interaction for drawing feature geometries. + */ + class Draw extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DrawOptions); + } + /** + * Events emitted by ol.interaction.Draw instances are instances of this type. + */ + class DrawEvent extends ol.events.Event { + /** + * The feature being drawn. + */ + feature: ol.Feature; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; + } + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. + * User actions that change the state of the map. Some are similar to controls, but are not associated with a DOM element. + * For example, ol.interaction.KeyboardZoom is functionally the same as ol.control.Zoom, but triggered by a keyboard event + * not a button element event. Although interactions do not have a DOM element, + * some of them do render vectors and so are visible on the screen. + */ + class Interaction extends ol.Object { + constructor (options: olx.interaction.InteractionOptions) + /** + * Return whether the interaction is currently active. + */ + getActive (): boolean; + /** + * Get the map associated with this interaction. + */ + getMap (): ol.Map; + /** + * Activate or deactivate the interaction. + */ + setActive (active: boolean): void; + } + /** + * Allows the user to pan the map using keyboard arrows. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. + * By default, this is the map div, though you can change this with the keyboardEventTarget in ol.Map. + * document never loses focus but, for any other element, focus will have to be on, and returned to, + * this element if the keys are to function. See also ol.interaction.KeyboardZoom. + */ + class KeyboardPan extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardPanOptions); + } + /** + * Allows the user to zoom the map using keyboard + and -. Note that, although this interaction is by default included in maps, + * the keys can only be used when browser focus is on the element to which the keyboard events are attached. By default, + * this is the map div, though you can change this with the keyboardEventTarget in ol.Map. document never loses focus but, + * for any other element, focus will have to be on, and returned to, this element if the keys are to function. + * See also ol.interaction.KeyboardPan. + */ + class KeyboardZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.KeyboardZoomOptions); + } + /** + * Interaction for modifying feature geometries. + */ + class Modify extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.ModifyOptions); + } + /** + * Allows the user to zoom the map by scrolling the mouse wheel. + */ + class MouseWheelZoom extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.MouseWheelZoomOptions); + } + /** + * Allows the user to rotate the map by twisting with two fingers on a touch screen. + */ + class PinchRotate extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchRotateOptions); + } + /** + * Allows the user to zoom the map by pinching with two fingers on a touch screen. + */ + class PinchZoom extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.PinchZoomOptions); + } + /** + * Base class that calls user-defined functions on down, move and up events. This class also manages "drag sequences". + * + * When the handleDownEvent user function returns true a drag sequence is started. During a drag sequence the handleDragEvent + * user function is called on move events. The drag sequence ends when the handleUpEvent user function is called and returns false. + */ + class Pointer extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.PointerOptions); + } + /** + * Interaction for selecting vector features. By default, selected features are styled differently, so this interaction can be used + * for visual highlighting, as well as selecting features for other actions, such as modification or output. There are three ways of + * controlling which features are selected: using the browser event as defined by the condition and optionally the toggle, + * add/remove, and multi options; a layers filter; and a further feature filter using the filter option. + * + * Selected features are added to an internal unmanaged layer. + */ + class Select extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.SelectOptions); + /** + * Returns the associated vectorlayer of the (last) selected feature. + * Note that this will not work with any programmatic method like pushing features to collection. + */ + getLayer(): ol.layer.Layer; + /** + * Get the selected features. + */ + getFeatures(): ol.Collection; + } + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent extends ol.events.Event { + /** + * Deselectd features array. + */ + deselected: Array; + /** + * Associated ol.MapBrowserEvent. + */ + mapBrowserEvent: ol.MapBrowserEvent; + /** + * Selected features array. + */ + selected: Array; + /** + * The event target. + */ + target: ol.Object; + /** + * The event type. + */ + type: string; + /** + * Stop event propagation. + */ + preventDefault(): void; + /** + * Stop event propagation. + */ + stopPropagation(): void; + } + /** + * Handles snapping of vector features while modifying or drawing them. The features can come from a ol.source.Vector or + * ol.Collection Any interaction object that allows the user to interact with the features using the mouse can benefit + * from the snapping, as long as it is added before. + * + *The snap interaction modifies map browser event coordinate and pixel properties to force the snap to occur + * to any interaction that them. + */ + class Snap extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.SnapOptions); + } + /** + * Set of interactions included in maps by default. Specific interactions can be excluded by setting the appropriate option + * to false in the constructor options, but the order of the interactions is fixed. If you want to specify a different order for + * interactions, you will need to create your own ol.interaction.Interaction instances and insert them into a ol.Collection in + * the order you want before creating your ol.Map instance. + */ + function defaults(opts: olx.interaction.DefaultsOptions): ol.Collection; + /** + * Function that takes coordinates and an optional existing geometry as arguments, and returns a geometry. + * The optional existing geometry is the geometry that is returned when the function is called without a second argument. + */ + interface DrawGeometryFunctionType { (coordinates: ol.Coordinate, geom?: ol.geom.Geometry): ol.geom.Geometry; } + /** + * A function that takes an ol.Feature or ol.render.Feature and an ol.layer.Layer and returns true if the feature + * may be selected or false otherwise. + */ + interface SelectFilterFunction { (feature: ol.Feature | ol.render.Feature, layer: ol.layer.Layer): boolean; } + /** + * A function that takes a ol.MapBrowserEvent and two ol.Pixels and returns a {boolean}. + * If the condition is met, true should be returned. + */ + interface DragBoxEndConditionType { + (evt: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel): boolean + } + } + + namespace layer { + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Note that with ol.layer.Base and all its subclasses, any property set in the options is set as a ol.Object property on the layer object, so is observable, and has get/set accessors. + */ + class Base extends ol.Object { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.BaseOptions); + + /** + * Return the brightness of the layer. + * @returns The brightness of the layer. + */ + getBrightness(): number; + + /** + * Return the contrast of the layer. + * @returns The contrast of the layer. + */ + getContrast(): number; + + /** + * Return the extent of the layer or undefined if it will be visible regardless of extent. + * @returns The layer extent. + */ + getExtent(): ol.Extent; + + /** + * Return the hue of the layer. + * @returns The hue of the layer + */ + getHue(): number; + + /** + * Return the maximum resolution of the layer. + * @returns The maximum resolution of the layer + */ + getMaxResolution(): number; + + /** + * Return the minimum resolution of the layer. + * @returns The minimum resolution of the layer. + */ + getMinResolution(): number; + + /** + * Return the opacity of the layer (between 0 and 1). + * @returns The opacity of the layer. + */ + getOpacity(): number; + + /** + * Return the saturation of the layer. + * @returns The saturation of the layer. + */ + getSaturation(): number; + + /** + * Return the visibility of the layer (true or false). + * The visibility of the layer + */ + getVisible(): boolean; + + /** + * Adjust the layer brightness. A value of -1 will render the layer completely black. A value of 0 will leave the brightness unchanged. A value of 1 will render the layer completely white. Other values are linear multipliers on the effect (values are clamped between -1 and 1). + * @param brightness The brightness of the layer + */ + setBrightness(brigthness: number): void; + + /** + * Adjust the layer contrast. A value of 0 will render the layer completely grey. A value of 1 will leave the contrast unchanged. Other values are linear multipliers on the effect (and values over 1 are permitted). + * @param contrast The contrast of the layer + */ + setContrast(contrast: number): void; + + /** + * Set the extent at which the layer is visible. If undefined, the layer will be visible at all extents. + * @param extent The extent of the layer + */ + setExtent(extent?: ol.Extent): void; + + /** + * Apply a hue-rotation to the layer. A value of 0 will leave the hue unchanged. Other values are radians around the color circle. + * @param hue The hue of the layer + */ + setHue(hue: number): void; + + /** + * Set the maximum resolution at which the layer is visible. + * @param maxResolution The maximum resolution of the layer. + */ + setMaxResolution(maxResolution: number): void; + + /** + * Set the minimum resolution at which the layer is visible. + * @param minResolution The minimum resolution of the layer. + */ + setMinResolution(minResolution: number): void; + + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param opactity The opacity of the layer. + */ + setOpacity(opacity: number): void; + + /** + * Adjust layer saturation. A value of 0 will render the layer completely unsaturated. A value of 1 will leave the saturation unchanged. Other values are linear multipliers of the effect (and values over 1 are permitted). + * @param saturation The saturation of the layer. + */ + setSaturation(saturation: number): void; + + /** + * Set the visibility of the layer (true or false). + * @param visible The visibility of the layer. + */ + setVisible(visible: boolean): void; + } + + /** + * A ol.Collection of layers that are handled together. + */ + class Group extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.GroupOptions); + + /** + * Returns the collection of layers in this group. + * @returns Collection of layers that are part of this group. + */ + getLayers(): ol.Collection; + + /** + * Set the collection of layers in this group. + * @param layers Collection of layers that are part of this group. + */ + setLayers(layers: ol.Collection): void; + } + + /** + * Layer for rendering vector data as a heatmap. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Heatmap extends ol.layer.Vector { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.HeatmapOptions); + + /** + * Return the blur size in pixels. + * @returns Blur size in pixels + */ + getBlur(): number; + + /** + * Return the gradient colors as array of strings. + * @returns Colors + */ + getGradient(): Array; + + /** + * Return the size of the radius in pixels. + * @returns Radius size in pixel + */ + getRadius(): number; + + /** + * Set the blur size in pixels. + * @param blur Blur size in pixels + */ + setBlur(blur: number): void; + + /** + * Set the gradient colors as array of strings. + * @param colors Gradient + */ + setGradient(colors: Array): void; + + /** + * Set the size of the radius in pixels. + * @param radius Radius size in pixels + */ + setRadius(radius: number): void; + } + + /** + * Server-rendered images that are available for arbitrary extents and resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Image extends ol.layer.Layer { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.ImageOptions); + + /** + * Return the associated source of the image layer. + * @returns Source. + */ + getSource(): ol.source.Image; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. A visual representation of raster or vector map data. Layers group together those properties that pertain to how the data is to be displayed, irrespective of the source of that data. + */ + class Layer extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.LayerOptions); + + /** + * Get the layer source. + * @returns The layer source (or null if not yet set) + */ + getSource(): ol.source.Source; + + /** + * Set the layer source. + * @param source The layer source. + */ + setSource(source: ol.source.Source): void; + } + + /** + * For layer sources that provide pre-rendered, tiled images in grids that are organized by zoom levels for specific resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Tile extends ol.layer.Layer { + + /** + * @constructor + * @param options Tile layer options. + */ + constructor(options?: olx.layer.TileOptions); + + /** + * Return the level as number to which we will preload tiles up to. + * @retruns The level to preload tiled up to. + */ + getPreload(): number; + + /** + * Return the associated tilesource of the layer. + * @returns Source + */ + getSource(): ol.source.Tile; + + /** + * Whether we use interim tiles on error. + * @returns Use interim tiles on error. + */ + getUseInterimTilesOnError(): boolean; + + /** + * Set the level as number to which we will preload tiles up to. + * @param preload The level to preload tiled up to + */ + setPreload(preload: number): void; + + /** + * Set whether we use interim tiles on error. + * @param useInterimTilesOnError Use interim tiles on error. + */ + setUseInterimTilesOnError(useInterimTilesOnError: boolean): void; + } + + /** + * Vector data that is rendered client-side. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Vector extends ol.layer.Layer { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.VectorOptions); + + /** + * Return the associated vectorsource of the layer. + * @returns Source. + */ + getSource(): ol.source.Vector; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function. + * @returns Layer style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + */ + setStyle(): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param layer Layer style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param layer Layer style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param Layer style + */ + setStyle(style: ol.style.StyleFunction): void; + + /** + * Sets the layer to be rendered on top of other layers on a map. The map will not manage this layer + * in its layers collection, and the callback in ol.Map#forEachLayerAtPixel will receive null as + * layer. This is useful for temporary layers. To remove an unmanaged layer from the map, use #setMap(null). + * To add the layer to a map and have it managed by the map, use ol.Map#addLayer instead. + * @argument map. + */ + setMap(map: ol.Map): void; + + /** + * Set Z-index of the layer, which is used to order layers before rendering. The default Z-index is 0. + */ + setZIndex(zIndex: number): void; + } + } + + namespace loadingstrategy { + + /** + * Strategy function for loading all features with a single request. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function all(extent: ol.Extent, resolution: number): Array; + + /** + * Strategy function for loading features based on the view's extent and resolution. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function bbox(extent: ol.Extent, resolution: number): Array; + + /** + * Creates a strategy function for loading features based on a tile grid. + * @param tilegrid Tile grid + * @returns Loading strategy + */ + function tile(tileGrid: ol.tilegrid.TileGrid): ol.LoadingStrategy; + } + + namespace proj { + + // Type definitions + interface ProjectionLike extends String { } + interface Units extends String { } + + // Methods + + /** + * Meters per unit lookup table. + */ + //TODO: validate! + var METERS_PER_UNIT: Object; + + /** + * Registers coordinate transform functions to convert coordinates between the source projection and the destination projection. The forward and inverse functions convert coordinate pairs; this function converts these into the functions used internally which also handle extents and coordinate arrays. + * @param source Source projection + * @param destination Destination projection + * @param forward The forward transform function (that is, from the source projection to the destination projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + * @param inverse The inverse transform function (that is, from the destination projection to the source projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + */ + function addCoordinateTransforms(source: ProjectionLike, destination: ProjectionLike, forward: (coordinate: Coordinate) => Coordinate, inverse: (coordinate: Coordinate) => Coordinate): void; + + /** + * Registers transformation functions that don't alter coordinates. Those allow to transform between projections with equal meaning. + * @param projections Projections. + */ + function addEquivalentProjections(projections: Array): void; + + /** + * Add a Projection object to the list of supported projections that can be looked up by their code. + * @param projection Projection instance. + */ + function addProjection(projection: Projection): void; + + /** + * Transforms a coordinate from longitude/latitude to a different projection. + * @param coordinate Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + * @param projection Target projection. The default is Web Mercator, i.e. 'EPSG:3857'. + */ + function fromLonLat(coordinate: Coordinate, opt_projection: ProjectionLike): Coordinate; + + /** + * Fetches a Projection object for the code specified. + * @param projectionLike Either a code string which is a combination of authority and identifier such as "EPSG:4326", or an existing projection object, or undefined. + * @returns Projection object, or null if not in list. + */ + function get(projectionLike: ProjectionLike): Projection; + + /** + * Given the projection-like objects, searches for a transformation function to convert a coordinates array from the source projection to the destination projection. + * @param source Source. + * @param destination Destination. + * @returns Transform function. + */ + function getTransform(source: ProjectionLike, destination: ProjectionLike): ol.TransformFunction; + + /** + * Transforms a coordinate to longitude/latitude. + * @param coordinate Projected coordinate. + * @param projection Projection of the coordinate. The default is Web Mercator, i.e. 'EPSG:3857'. + * @returns Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + */ + function toLonLat(coordinate: Coordinate, projection: ProjectionLike): Coordinate; + + /** + * Transforms a coordinate from source projection to destination projection. This returns a new coordinate (and does not modify the original). + * @param coordinate Coordinate. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns Coordinate. + */ + function transform(coordinate: Coordinate, source: ProjectionLike, destination: ProjectionLike): Coordinate; + + /** + * Transforms an extent from source projection to destination projection. This returns a new extent (and does not modify the original). + * @param extent The extent to transform. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns The transformed extent. + */ + function transformExtent(extent: Extent, source: ProjectionLike, destination: ProjectionLike): Extent; + + class Projection { + constructor(options: olx.Projection); + + getExtent(): Extent; + + /** + * Set the validity extent for this projection. + * @param extent The new extent of the projection. + */ + setExtent(extent: Extent): void; + } + } + + namespace render { + + class Event extends ol.events.Event { + } + + class VectorContext { + } + class Feature { + get(key: string): any; + getExtent(): ol.Extent; + getGeometry(): ol.geom.Geometry; + getProperties: Object[]; + getType(): ol.geom.GeometryType; + } + namespace canvas { + class Immediate { + } + } + } + + namespace source { + + class BingMaps extends TileImage { + } + + class CartoDB extends XYZ { + } + + class Cluster extends Vector { + constructor(options: olx.source.ClusterOptions); + } + + class Image extends Source { + } + + class ImageArcGISRest extends Image { + } + + class ImageCanvas extends Image { + } + + class ImageEvent extends ol.events.Event { + } + + class ImageMapGuide extends Image { + } + + class ImageStatic extends ol.source.Image { + constructor(options?: olx.StaticImageOptions); + } + + class ImageVector extends ImageCanvas { + } + + class ImageWMS extends Image { + constructor(options: olx.ImageWMSOptions); + } + + class MapQuest extends XYZ { + constructor(options: any); + } + + class OSM extends XYZ { + constructor(opt_options?: olx.OSMOptions); + } + + class Source extends ol.Object { + + constructor(options: any); + + /** + * Get the projection of the source. + * @return Projection. + */ + getProjection(): ol.proj.Projection; + + /** + * Refreshes the source and finally dispatches a 'change' event. + */ + refresh(): void; + } + + class Stamen extends XYZ { + } + + class Tile extends Source { + } + + class TileArcGISRest extends TileImage { + } + + class TileDebug extends Tile { + } + + class TileEvent extends ol.events.Event { + } + + class TileImage extends UrlTile { + } + + class TileJSON extends TileImage { + } + + class TileUTFGrid extends Tile { + } + + class TileWMS extends TileImage { + constructor(options: olx.TileWMSOptions); + + /** + * Update the user-provided (WMS request) parameters. + */ + updateParams(params: any): void; + + /** + * Get the user-provided (WMS request) params, i.e. those passed to the constructor through the "params" option, and possibly updated using the updateParams method. + */ + getParams(): any; + + /** + * Return the GetFeatureInfo URL for the passed coordinate, resolution, and + * projection. Return `undefined` if the GetFeatureInfo URL cannot be + * constructed. + * @param coordinate Coordinate. + * @param resolution Resolution. + * @param rojection Projection. + * @param params GetFeatureInfo params. `INFO_FORMAT` at least should + * be provided. If `QUERY_LAYERS` is not provided then the layers specified + * in the `LAYERS` parameter will be used. `VERSION` should not be + * specified here. + * @return GetFeatureInfo URL. + */ + getGetFeatureInfoUrl(coordinate: ol.Coordinate, resolution: number, projection: ol.proj.ProjectionLike, params: {}): string; + } + + class UrlTile extends Tile { + } + + class Vector extends Source { + constructor(opts?: olx.source.VectorOptions) + /** + * Add a single feature to the source. If you want to add a batch of features at once, + * call source.addFeatures() instead. + */ + addFeature(feature: ol.Feature): void; + + /** + * Add a batch of features to the source. + */ + addFeatures(features: ol.Feature[]): void; + + /** + * Remove all features from the source. + * @param Skip dispatching of removefeature events. + */ + clear(fast?: boolean): void; + /** + * Get the extent of the features currently in the source. + */ + getExtent(): ol.Extent; + + /** + * Get all features in the provided extent. Note that this returns all features whose bounding boxes + * intersect the given extent (so it may include features whose geometries do not intersect the extent). + * This method is not available when the source is configured with useSpatialIndex set to false. + */ + getFeaturesInExtent(extent: ol.Extent): ol.Feature[]; + + /** + * Get all features on the source + */ + getFeatures(): ol.Feature[]; + + /** + * Get all features whose geometry intersects the provided coordinate. + */ + getFeaturesAtCoordinate(coordinate: ol.Coordinate): ol.Feature[]; + } + + class VectorEvent extends ol.events.Event { + } + + class VectorTile extends UrlTile { + } + + class WMTS extends TileImage { + constructor(options: olx.source.WMTSOptions); + } + + class XYZ extends TileImage { + } + + class Zoomify extends TileImage { + } + + // Namespaces + namespace wms { + interface ServerType extends String { } + } + + // Type definitions + interface State extends String { } + interface WMTSRequestEncoding extends String { } + } + + namespace style { + + class AtlasManager { + } + + class Circle extends Image { + constructor(opt_options?: olx.style.CircleOptions); + } + + /** + * Set fill style for vector features. + */ + class Fill { + + constructor(opt_options?: olx.style.FillOptions); + + getColor(): ol.Color | string; + + /** + * Set the color. + */ + setColor(color: ol.Color | string): void; + + getChecksum(): string; + } + + class Icon extends Image { + constructor(option: olx.style.IconOptions) + } + + class Image { + getOpacity(): number; + getRotateWithView(): boolean; + getRotation(): number; + getScale(): number; + getSnapToPiexl(): boolean; + + setOpacity(opacity: number): void; + setRotation(rotation: number): void; + setScale(scale: number): void; + } + + interface GeometryFunction { + (feature: Feature): ol.geom.Geometry + } + + class RegularShape { + } + + class Stroke { + constructor(opts?: olx.style.StrokeOptions); + getColor(): ol.Color | string; + getLineCap(): string; + getLineDash(): number[]; + getLineJoin(): string; + getMitterLimit(): number; + getWidth(): number; + setColor(color: ol.Color | string): void; + setLineCap(lineCap: string): void; + setLineDash(lineDash: number[]): void; + setLineJoin(lineJoin: string): void; + setMiterLimit(miterLimit: number): void; + setWidth(width: number): void; + } + + /** + * Container for vector feature rendering styles. Any changes made to the style + * or its children through `set*()` methods will not take effect until the + * feature, layer or FeatureOverlay that uses the style is re-rendered. + */ + class Style { + constructor(opts: olx.style.StyleOptions); + + getFill(): ol.style.Fill; + /*** + * Get the geometry to be rendered. + * @return Feature property or geometry or function that returns the geometry that will + * be rendered with this style. + */ + getGeometry(): string | ol.geom.Geometry | ol.style.GeometryFunction; + getGeometryFunction(): ol.style.GeometryFunction; + getImage(): ol.style.Image; + getStroke(): ol.style.Stroke; + getText(): ol.style.Text; + getZIndex(): number; + + setGeometry(geometry: string | ol.geom.Geometry | ol.style.GeometryFunction): void; + setZIndex(zIndex: number): void; + } + + /** + * Set text style for vector features. + */ + class Text { + constructor(opt?: olx.style.TextOptions); + + getFont(): string; + getOffsetX(): number; + getOffsetY(): number; + getFill(): Fill; + getRotation(): number; + getScale(): number; + getStroke(): Stroke; + getText(): string; + getTextAlign(): string; + getTextBaseline(): string; + + /** + * Set the font. + */ + setFont(font: string): void; + + /** + * Set the x offset. + */ + setOffsetX(offsetX: number): void; + + /** + * Set the y offset. + */ + setOffsetY(offsetY: number): void; + + /** + * Set the fill. + */ + setFill(fill: Fill): void; + + /** + * Set the rotation. + */ + setRotation(rotation: number): void; + + /** + * Set the scale. + */ + setScale(scale: number): void; + + /** + * Set the stroke. + * + */ + setStroke(stroke: Stroke): void; + + /** + * Set the text. + */ + setText(text: string): void; + + /** + * Set the text alignment. + */ + setTextAlign(textAlign: string): void; + + /** + * Set the text baseline. + */ + setTextBaseline(textBaseline: string): void; + } + + /** + * A function that takes an ol.Feature and a {number} representing the view's resolution. The function should return an array of ol.style.Style. This way e.g. a vector layer can be styled. + */ + interface StyleFunction { (feature: ol.Feature, resolution: number): ol.style.Style } + } + + namespace tilegrid { + + /** + * Base class for setting the grid pattern for sources accessing tiled-image servers. + */ + class TileGrid { + + /** + * @constructor + * @param options Tile grid options + */ + constructor(options: olx.tilegrid.TileGridOptions); + + /** + * Creates a TileCoord transform function for use with this tile grid. Transforms the internal tile coordinates with bottom-left origin to the tile coordinates used by the ol.TileUrlFunction. The returned function expects an ol.TileCoord as first and an ol.proj.Projection as second argument and returns a transformed ol.TileCoord. + */ + createTileCoordTransform(): { (tilecoord: ol.TileCoord, projection: ol.proj.Projection): ol.TileCoord }; + + /** + * Get the maximum zoom level for the grid. + * @returns Max zoom + */ + getMaxZoom(): number; + + /** + * Get the minimum zoom level for the grid. + * @returns Min zoom + */ + getMinZoom(): number; + + /** + * Get the origin for the grid at the given zoom level. + * @param z Z + * @returns Origin + */ + getOrigin(z: number): ol.Coordinate; + + /** + * Get the list of resolutions for the tile grid. + * @param z Z + * @returns Resolution + */ + getResolution(z: number): number; + + /** + * Get the list of resolutions for the tile grid. + * @returns Resolutions + */ + getResolutions(): Array; + + /** + * Get the tile coordinate for the given map coordinate and resolution. This method considers that coordinates that intersect tile boundaries should be assigned the higher tile coordinate. + * @param coordinate Coordinate + * @param resolution Resolution + * @param tileCoord Destination ol.TileCoord object. + * @returns Tile coordinate + */ + getTileCoordForCoordAndResolution(coordinate: ol.Coordinate, resolution: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get a tile coordinate given a map coordinate and zoom level. + * @param coordinate Coordinate + * @param z Zoom level + * @param tileCoord Destination ol.TileCoord object + * @returns Tile coordinate + */ + getTileCoordForCoordAndZ(coordinate: ol.Coordinate, z: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get the tile size for a zoom level. The type of the return value matches the tileSize or tileSizes that the tile grid was configured with. To always get an ol.Size, run the result through ol.size.toSize(). + * @param z Z + * @returns Tile size + */ + getTileSize(z: number): number | ol.Size; + } + + /** + * Set the grid pattern for sources accessing WMTS tiled-image servers. + */ + class WMTS extends TileGrid { + + /** + * @constructor + * @param options WMTS options + */ + constructor(options: olx.tilegrid.WMTSOptions); + + /** + * Create a tile grid from a WMTS capabilities matrix set. + * @param matrixSet An object representing a matrixSet in the capabilities document. + * @param extent An optional extent to restrict the tile ranges the server provides. + * @returns WMTS tilegrid instance + */ + createFromCapabilitiesMatrixSet(matrixSet: any, extent: ol.Extent): ol.tilegrid.WMTS; + + /** + * Get the list of matrix identifiers. + * @returns MatrixIds + */ + getMatrixIds(): Array; + } + + /** + * Set the grid pattern for sources accessing Zoomify tiled-image servers. + */ + class Zoomify extends TileGrid { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.tilegrid.ZoomifyOptions); + } + + /** + * Creates a tile grid with a standard XYZ tiling scheme. + * @param options Tile grid options. + * @returns The grid instance + */ + function createXYZ(options?: olx.tilegrid.XYZOptions): ol.tilegrid.TileGrid; + } + + namespace webgl { + + class Context { + + /** + * @constructor + * @param canvas HTML Canvas Element + * @param gl WebGL Rendering context + */ + constructor(canvas: HTMLCanvasElement, gl: WebGLRenderingContext); + + /** + Get the WebGL rendering context + @returns The rendering context. + */ + getGL(): WebGLRenderingContext; + + /** + * Get the frame buffer for hit detection. + * @returns The hit detection frame buffer. + */ + getHitDetectionFramebuffer(): WebGLFramebuffer; + + /** + * Use a program. If the program is already in use, this will return false. + * @param program Program. + * @returns Changed. + */ + useProgram(program: WebGLProgram): boolean; + } + } + + // Type definitions + + /** + * A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas. + */ + function CanvasFunctionType(extent: Extent, resolution: number, pixelRatio: number, size: Size, projection: proj.Projection): HTMLCanvasElement; + + /** + * A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive. + */ + interface Color extends Array { } + + /** + * An array of numbers representing an xy coordinate. Example: [16, 48]. + */ + interface Coordinate extends Array { } + + /** + * An array of numbers representing an extent: [minx, miny, maxx, maxy]. + */ + interface Extent extends Array { } + + /** + * Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right' + */ + interface OverlayPositioning extends String { } + + /** + * An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel. + */ + interface Pixel extends Array { } + + /** + * Available renderers: 'canvas', 'dom' or 'webgl'. + */ + interface RendererType extends String { } + + /** + * An array of numbers representing a size: [width, height]. + */ + interface Size extends Array { } + + /** + * An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level. + */ + interface TileCoord extends Array { } + + // Functions + + /** + * A function that takes a ol.Coordinate and transforms it into a {string}. + */ + interface CoordinateFormatType { (coordinate?: Coordinate): string; } + + /** + * Implementation based on the code of OpenLayers, no documentation available (yet). If it is incorrect, please create an issue and I will change it. + */ + interface FeatureLoader { (extent: ol.Extent, number: number, projection: ol.proj.Projection): string } + + /** + * A function that returns a style given a resolution. The this keyword inside the function references the ol.Feature to be styled. + */ + interface FeatureStyleFunction { (resolution: number): ol.style.Style } + + /** + * Loading strategy + */ + interface LoadingStrategy { (extent: ol.Extent, resolution: number): Array } + + /** + * Function to perform manipulations before rendering. This function is called with the ol.Map as first and an optional olx.FrameState as second argument. Return true to keep this function for the next frame, false to remove it. + */ + interface PreRenderFunction { (map: ol.Map, frameState?: olx.FrameState): boolean } + + /** + * A transform function accepts an array of input coordinate values, an optional output array, and an optional dimension (default should be 2). The function transforms the input coordinate values, populates the output array, and returns the output array. + */ + interface TransformFunction { (input: Array, output?: Array, dimension?: number): Array } +} + +declare module "openlayers" { + export = ol; +} diff --git a/openlayers/openlayers-tests.ts b/openlayers/openlayers-tests.ts index 4937d52516..5c1f6d46c8 100644 --- a/openlayers/openlayers-tests.ts +++ b/openlayers/openlayers-tests.ts @@ -1,11 +1,17 @@ -/// +/// // Basic type variables for test functions +var anyValue: any; var voidValue: void; var numberValue: number; var booleanValue: boolean; var stringValue: string; +var stringArray: Array; var jsonValue: JSON; +var voidOrBooleanValue: void | boolean; +var domEventTarget: EventTarget; +var fn: Function; +var object: Object; // Callback predefinitions for OpenLayers var preRenderFunction: ol.PreRenderFunction; @@ -14,44 +20,55 @@ var coordinateFormatType: ol.CoordinateFormatType; var featureStyleFunction: ol.FeatureStyleFunction; var featureLoader: ol.FeatureLoader; var easingFunction: (t: number) => number; +var drawGeometryFunction: ol.DrawGeometryFunctionType; // Type variables for OpenLayers +var attribution: ol.Attribution; +var boundingCoordinates: Array; var circle: ol.geom.Circle; var color: ol.Color; var coordinate: ol.Coordinate; var coordinatesArray: Array; var coordinatesArrayDim2: Array>; var extent: ol.Extent; -var boundingCoordinates: Array; -var size: ol.Size; -var style: ol.style.Style; -var styleArray: Array; -var feature: ol.Feature; -var featureArray: Array; -var graticule: ol.Graticule -var geometry: ol.geom.Geometry; -var geometriesArray: Array; +var olEvent: ol.events.Event; +var eventKey: ol.EventsKey; +var eventKeyArray: Array; +var eventKeyMixed: ol.EventsKey | Array; +var eventTarget: ol.events.EventTarget; var feature: ol.Feature; var featureArray: Array; +var featureCollection: ol.Collection; var featureFormat: ol.format.Feature; +var featureUrlFunction: ol.FeatureUrlFunction; +var graticule: ol.Graticule; +var geometriesArray: Array; var geometry: ol.geom.Geometry; var geometryCollection: ol.geom.GeometryCollection; var geometryLayout: ol.geom.GeometryLayout; var geometryType: ol.geom.GeometryType; var linearRing: ol.geom.LinearRing; var lineString: ol.geom.LineString; -var loadingstrategy: ol.LoadingStrategy; +var loadingStrategy: ol.LoadingStrategy; +var logoOptions: olx.LogoOptions; +var mapBrowserEvent: ol.MapBrowserEvent; var multiLineString: ol.geom.MultiLineString; var multiPoint: ol.geom.MultiPoint; var multiPolygon: ol.geom.MultiPolygon; var point: ol.geom.Point; var polygon: ol.geom.Polygon; -var simpleGeometry: ol.geom.SimpleGeometry; -var tilegrid: ol.tilegrid.TileGrid; -var vector: ol.source.Vector; var projection: ol.proj.Projection; -var projectionLike: ol.proj.ProjectionLike; +var projectionLike: ol.ProjectionLike; +var simpleGeometry: ol.geom.SimpleGeometry; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var styleFunction: ol.StyleFunction; +var tilegrid: ol.tilegrid.TileGrid; var transformFn: ol.TransformFunction; +var vectorSource: ol.source.Vector; +var units: ol.proj.Units; +var styleRegularShape: ol.style.RegularShape; // // ol.Attribution @@ -116,16 +133,16 @@ featureLoader = ol.featureloader.xhr(stringValue, featureFormat); // // ol.loadingstrategy // -loadingstrategy = ol.loadingstrategy.all; -loadingstrategy = ol.loadingstrategy.bbox; -loadingstrategy = ol.loadingstrategy.tile(tilegrid); +loadingStrategy = ol.loadingstrategy.all; +loadingStrategy = ol.loadingstrategy.bbox; +loadingStrategy = ol.loadingstrategy.tile(tilegrid); // // // ol.geom.Circle // booleanValue = circle.intersectsExtent(extent); -circle = circle.transform(projectionLike, projectionLike); +circle = circle.transform(projectionLike, projectionLike); // // @@ -136,7 +153,7 @@ coordinate = geometryResult.getClosestPoint(coordinate); geometryResult.getClosestPoint(coordinate, coordinate); extent = geometryResult.getExtent(); geometryResult.getExtent(extent); -geometryResult.transform(projection, projection); +geometryResult.transform(projectionLike, projectionLike); // // @@ -266,6 +283,10 @@ polygon = new ol.geom.Polygon(coordinatesArrayDim2); polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue, numberValue); +polygon = ol.geom.Polygon.fromExtent(extent); voidValue = polygon.appendLinearRing(linearRing); polygon = polygon.clone(); numberValue = polygon.getArea(); @@ -273,9 +294,12 @@ coordinatesArrayDim2 = polygon.getCoordinates(); coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); point = polygon.getInteriorPoint(); linearRing = polygon.getLinearRing(numberValue); +numberValue = polygon.getLinearRingCount(); linearRingsArray = polygon.getLinearRings(); geometryType = polygon.getType(); booleanValue = polygon.intersectsExtent(extent); +voidValue = polygon.setCoordinates([[coordinate]]); +voidValue = polygon.setCoordinates([[coordinate]], geometryLayout); // // @@ -290,9 +314,42 @@ voidValue = simpleGeometry.translate(numberValue, numberValue); // // ol.source // -vector = new ol.source.Vector({ - features: [feature] +var featureCallback: (f: ol.Feature) => any; +vectorSource = new ol.source.Vector({ + attributions: [attribution], + features: featureCollection, + format: featureFormat, + loader: featureLoader, + logo: logoOptions, + strategy: loadingStrategy, + url: stringValue, + useSpatialIndex: booleanValue, + wrapX: booleanValue }); +vectorSource = new ol.source.Vector({ + features: featureArray +}); +vectorSource = new ol.source.Vector({ + url: featureUrlFunction, + loader: featureLoader +}); +voidValue = vectorSource.addFeature(feature); +voidValue = vectorSource.addFeatures(featureArray); +voidValue = vectorSource.clear(); +voidValue = vectorSource.clear(booleanValue); +anyValue = vectorSource.forEachFeature(featureCallback); +anyValue = vectorSource.forEachFeature(featureCallback, object); +anyValue = vectorSource.forEachFeatureInExtent(extent, featureCallback, object); +anyValue = vectorSource.forEachFeatureIntersectingExtent(extent, featureCallback, object); +feature = vectorSource.getClosestFeatureToCoordinate(coordinate); +extent = vectorSource.getExtent(); +feature = vectorSource.getFeatureById(stringValue); +feature = vectorSource.getFeatureById(numberValue); +featureArray = vectorSource.getFeatures(); +featureArray = vectorSource.getFeaturesAtCoordinate(coordinate); +featureCollection = vectorSource.getFeaturesCollection(); +featureArray = vectorSource.getFeaturesInExtent(extent); +voidValue = vectorSource.removeFeature(feature); // // ol.Feature @@ -300,7 +357,11 @@ vector = new ol.source.Vector({ feature = new ol.Feature(); feature = new ol.Feature(geometry); feature = new ol.Feature({ - geometry: geometry + geometry: geometry, + a: numberValue, + b: stringValue, + c: null, + d: object }); feature = feature.clone(); geometry = feature.getGeometry(); @@ -315,6 +376,7 @@ voidValue = feature.setId(numberValue); voidValue = feature.setStyle(style); voidValue = feature.setStyle(styleArray); voidValue = feature.setStyle(featureStyleFunction); +voidValue = feature.setProperties(object); // // ol.View @@ -329,19 +391,71 @@ var view: ol.View = new ol.View({ // ol.layer.Tile // var tileLayer: ol.layer.Tile = new ol.layer.Tile({ - source: new ol.source.MapQuest({ layer: 'osm' }) + source: new ol.source.OSM() }); +// +// ol.Object +// +var olObject: ol.Object = new ol.Object({ + a: numberValue, + b: stringValue, + c: booleanValue, + d: voidValue, + e: object, + f: fn +}); +anyValue = olObject.get(stringValue); +stringArray = olObject.getKeys(); +object = olObject.getProperties(); +voidValue = olObject.set(stringValue, anyValue); +voidValue = olObject.set(stringValue, anyValue, booleanValue); +voidValue = olObject.setProperties(object, booleanValue); +voidValue = olObject.unset(stringValue, booleanValue); + +// +// ol.Observable +// +ol.Observable.unByKey(eventKey); +var observable: ol.Observable = new ol.Observable(); +voidValue = observable.changed(); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: domEventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: eventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, a: numberValue, b: stringValue, c: booleanValue, d: null, e: {}}); +voidOrBooleanValue = observable.dispatchEvent(olEvent); +voidOrBooleanValue = observable.dispatchEvent(stringValue); +numberValue = observable.getRevision(); +eventKeyMixed = observable.on(stringValue, fn); +eventKeyMixed = observable.on([stringValue, stringValue], fn, {}); +eventKeyMixed = observable.once(stringValue, fn); +eventKeyMixed = observable.once([stringValue, stringValue], fn, {}); +voidValue = observable.un(stringValue, fn); +voidValue = observable.un([stringValue, stringValue], fn, {}); +voidValue = observable.unByKey(eventKey); +voidValue = observable.unByKey(eventKeyArray); + // // ol.proj // +var getPointResolutionFn: (n: number, c: ol.Coordinate) => number; projection = new ol.proj.Projection({ - code:stringValue, + code:stringValue, }); -projection.setExtent(projection.getExtent()); +stringValue = projection.getCode(); +extent = projection.getExtent(); +numberValue = projection.getMetersPerUnit(); +numberValue = projection.getPointResolution(numberValue, coordinate); +units = projection.getUnits(); +extent = projection.getWorldExtent(); +booleanValue = projection.isGlobal(); +voidValue = projection.setExtent(extent); +voidValue = projection.setGetPointResolution(getPointResolutionFn); +voidValue = projection.setGlobal(booleanValue); +voidValue = projection.setWorldExtent(extent); // -// ol.Map +// ol.Map // var map: ol.Map = new ol.Map({ @@ -349,12 +463,14 @@ var map: ol.Map = new ol.Map({ layers: [tileLayer], target: stringValue }); -map.beforeRender(preRenderFunction); +voidValue = map.beforeRender(preRenderFunction); // // ol.source.ImageWMS // var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + params: {}, + projection: projection, serverType: stringValue, url:stringValue }); @@ -363,7 +479,6 @@ var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ // ol.source.Source // const source = imageWMS as ol.source.Source; -voidValue = source.refresh(); projection = source.getProjection(); // @@ -371,22 +486,27 @@ projection = source.getProjection(); // var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ params: {}, + projection: projection, serverType: stringValue, url:stringValue }); -tileWMS.updateParams(tileWMS.getParams()); +voidValue = tileWMS.updateParams(tileWMS.getParams()); stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); // // ol.source.WMTS // var wmts: ol.source.WMTS = new ol.source.WMTS({ - tileGrid: new ol.tilegrid.WMTS({}), - layer: "", - style: "", - matrixSet: "", - wrapX: true + layer: "", + projection: projection, + matrixSet: "", + style: "", + tileGrid: new ol.tilegrid.WMTS({ + matrixIds: [], + resolutions: [], + }), + wrapX: true, }); // @@ -420,7 +540,7 @@ zoomOptions.start = numberValue; zoomOptions.resolution = numberValue; zoomOptions.easing = easingFunction; preRenderFunction = ol.animation.zoom(zoomOptions); -map.beforeRender(preRenderFunction); +voidValue = map.beforeRender(preRenderFunction); // // ol.coordinate @@ -433,6 +553,7 @@ stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); coordinate = ol.coordinate.rotate(coordinate, numberValue); stringValue = ol.coordinate.toStringHDMS(); stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringHDMS(coordinate, numberValue); stringValue = ol.coordinate.toStringXY(); stringValue = ol.coordinate.toStringXY(coordinate); stringValue = ol.coordinate.toStringXY(coordinate, numberValue); @@ -452,9 +573,7 @@ easingFunction = ol.easing.upAndDown; var geolocation: ol.Geolocation = new ol.Geolocation({ projection: projection }); -geolocation.on('change', function (evt) { - window.console.log(geolocation.getPosition()); -}); +coordinate = geolocation.getPosition(); // // ol.Graticule @@ -467,7 +586,7 @@ graticule = new ol.Graticule({ var graticuleMap: ol.Map = graticule.getMap(); var graticuleMeridians: Array = graticule.getMeridians(); var graticuleParallels: Array = graticule.getParallels(); -graticule.setMap(graticuleMap); +voidValue = graticule.setMap(graticuleMap); // // ol.DeviceOrientation @@ -476,9 +595,7 @@ graticule.setMap(graticuleMap); var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ tracking: true, }); -deviceOrientation.on('change', function (evt) { - window.console.log(deviceOrientation.getHeading()); -}); +numberValue = deviceOrientation.getHeading(); // // ol.Overlay @@ -487,17 +604,17 @@ deviceOrientation.on('change', function (evt) { var popup: ol.Overlay = new ol.Overlay({ element: document.getElementById('popup') }); -map.addOverlay(popup); +voidValue = map.addOverlay(popup); var popupElement: Element = popup.getElement(); var popupMap: ol.Map = popup.getMap(); var popupOffset: Array = popup.getOffset(); coordinate = popup.getPosition(); var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); -popup.setElement(popupElement); -popup.setMap(popupMap); -popup.setOffset(popupOffset); -popup.setPosition(coordinate); -popup.setPositioning(popupPositioning); +voidValue = popup.setElement(popupElement); +voidValue = popup.setMap(popupMap); +voidValue = popup.setOffset(popupOffset); +voidValue = popup.setPosition(coordinate); +voidValue = popup.setPositioning(popupPositioning); // @@ -555,9 +672,76 @@ var modify: ol.interaction.Modify = new ol.interaction.Modify({ }); var draw: ol.interaction.Draw = new ol.interaction.Draw({ - type: "Point" -}) + type: "Point", + clickTolerance: numberValue, + features: new ol.Collection([]), + source: vectorSource, + snapTolerance: numberValue, + maxPoints: numberValue, + minPoints: numberValue, + style: style, + geometryFunction: drawGeometryFunction, + geometryName: stringValue, + condition: ol.events.condition.never, + freehandCondition: ol.events.condition.never, + wrapX: booleanValue +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleArray +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunction +}); +var styleFunctionAsStyle = function(feature: ol.Feature, resolution: number): ol.style.Style { return style; } +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunctionAsStyle +}); +var styleFunctionAsArray = function(feature: ol.Feature, resolution: number): ol.style.Style[] { return styleArray; } +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunctionAsArray +}); + +var dragbox: ol.interaction.DragBox = new ol.interaction.DragBox({ + className: stringValue, + condition: ol.events.condition.always, + boxEndCondition: function (mapBrowserEvent: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel) { + var width: number = endPixel[0] - startPixel[0]; + var height: number = endPixel[1] - startPixel[1]; + return booleanValue; + } +}); +polygon = dragbox.getGeometry(); + +var interaction: ol.interaction.Interaction = new ol.interaction.Interaction({ + handleEvent: function (e: ol.MapBrowserEvent) { + return booleanValue; + } +}); +booleanValue = interaction.getActive(); +map = interaction.getMap(); +voidValue = interaction.setActive(true); + + const select: ol.interaction.Select = new ol.interaction.Select({ layers: (layer: ol.layer.Layer) => true, }); + +// +// ol.style.RegularShape +// + +styleRegularShape = new ol.style.RegularShape({ + fill: new ol.style.Fill({color: 'red'}), + points: 4, +}); + +// +// ol.proj +// + +let value = ol.proj.METERS_PER_UNIT['degrees']; diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 36026fa70d..ed3c8e9e21 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -1,1265 +1,13443 @@ // Type definitions for OpenLayers v3.18.2 // Project: http://openlayers.org/ -// Definitions by: Wouter Goedhart +// Definitions by: Olivier Sechet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) -declare namespace olx { - interface StaticImageOptions { +declare type GlobalObject = Object; - /** Attributions */ - attributions?: Array - - /*** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ - crossOrigin?: string - - /*** Extent of the image in map coordinates. This is the [left, bottom, right, top] map coordinates of your image.*/ - imageExtent: ol.Extent; - - /*** Size of the image in pixels.*/ - imageSize?: ol.Size; - - /*** experimental Optional function to load an image given a URL.*/ - imageLoadFunction?: ol.TileLoadFunctionType; - - /*** Optional logo.*/ - logo?: olx.LogoOptions; - - /*** experimental Projection.*/ - projection: ol.proj.Projection; - - /*** Image URL.*/ - url: string; - } - - interface ZoomToExtentOptions { - /*** Class name. Default is ol-zoom-extent.*/ - className?: string; - - /*** Target.*/ - target?: Element; - - /*** Text label to use for the button. Default is E. Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Node; - - /*** Text label to use for the button tip. Default is Zoom to extent.*/ - tipLabel?: string; - - /*** The extent to zoom to. If undefined the validity extent of the view projection is used.*/ - extent: ol.Extent; - } - - interface OverviewMapOptions { - /*** Whether the control should start collapsed or not (expanded). Default to true.*/ - collapsed?: boolean; - /*** Text label to use for the expanded overviewmap button. Default is «. Instead of text, also a Node (e.g. a span element) can be used.*/ - collapseLabel? :string | Node; - /*** Whether the control can be collapsed or not. Default to true.*/ - collapsible?: boolean; - /*** Text label to use for the collapsed overviewmap button. Default is ». Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Node; - /*** Layers for the overview map. If not set, then all main map layers are used instead.*/ - layers?: ol.layer.Layer[] | ol.Collection; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; - /*** Specify a target if you want the control to be rendered outside of the map's viewport.*/ - target?: Element; - /*** Text label to use for the button tip. Default is Overview map*/ - tipLabel?: string; - /*** Custom view for the overview map. If not provided, a default view with an EPSG:3857 projection will be used.*/ - view?: ol.View; - } - - interface RotateOptions { - /*** CSS class name. Default is ol-rotate.*/ - className?: string; - /*** Text label to use for the rotate button. Default is ⇧. Instead of text, also a Node (e.g. a span element) can be used.*/ - label?: string | Element; - /*** Text label to use for the rotate tip. Default is Reset rotation.*/ - tipLabel?: string; - /*** Animation duration in milliseconds. Default is 250.*/ - duration?: number; - /*** Hide the control when rotation is 0. Default is true.*/ - autoHide?: boolean; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; - /*** Function called when the control is clicked. This will override the default resetNorth.*/ - resetNorth?: Function; - /*** Target.*/ - target?: Element; - } - - interface AttributionControlOptions { - /*** CSS class name. Default is ol-attribution.*/ - className?: string; - /*** Target.*/ - target?: Element; +/** + * @namespace ol + */ +declare module ol { + /** + * The animation static methods are designed to be used with the + * {@link ol.Map#beforeRender} method. For example: + * + * var map = new ol.Map({ ... }); + * var zoom = ol.animation.zoom({ + * resolution: map.getView().getResolution() + * }); + * map.beforeRender(zoom); + * map.getView().setResolution(map.getView().getResolution() * 2); + * + * @namespace ol.animation + */ + module animation { /** - * Specify if attributions can be collapsed. If you use an OSM source, - * should be set to false — see OSM Copyright — Default is true. + * Generate an animated transition that will "bounce" the resolution as it + * approaches the final value. + * @param {olx.animation.BounceOptions} options Bounce options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - collapsible?: boolean; - /*** Specify if attributions should be collapsed at startup. Default is true.*/ - collapsed?: boolean; - /*** Text label to use for the button tip. Default is "Attributions".*/ - tipLabel?: Array | ol.Collection; + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + /** - * Text label to use for the collapsed attributions button. Default is i. - * Instead of text, also a Node (e.g. a span element) can be used. + * Generate an animated transition while updating the view center. + * @param {olx.animation.PanOptions} options Pan options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - label?: string | Node; + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + /** - * Text label to use for the expanded attributions button. Default is ». - * Instead of text, also a Node (e.g. a span element) can be used. + * Generate an animated transition while updating the view rotation. + * @param {olx.animation.RotateOptions} options Rotate options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api */ - collapseLabel?: string | Node; - /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ - render?: Function; + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param {olx.animation.ZoomOptions} options Zoom options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } - interface AttributionOptions { - - /** HTML markup for this attribution. */ - html: string; - } - - interface DeviceOrientationOptions { - + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + class AssertionError extends Error { /** - * Start tracking. Default is false. + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. */ - tracking?: boolean; - } - - interface FrameState { + constructor(code: number); /** + * Error code. The meaning of the code can be found on + * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with + * the version found in the OpenLayers script's header comment if a version + * other than the latest is used). + * @type {number} + * @api + */ + code: number; + + } + + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + class Attribution { + /** + * @classdesc + * An attribution for a layer source. * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable */ - pixelRatio: number; + constructor(options: olx.AttributionOptions); /** - * + * Get the attribution markup. + * @return {string} The attribution HTML. + * @api stable */ - time: number; + getHTML(): string; - /** - * - */ - viewState: olx.ViewState; } - interface FeatureOverlayOptions { - + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + class Collection extends ol.Object { /** - * Features + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable */ - features?: Array | ol.Collection | ol.style.StyleFunction; + constructor(opt_array?: T[]); /** - * Map + * Remove all elements from the collection. + * @api stable + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array.} arr Array. + * @return {ol.Collection.} This collection. + * @api stable + */ + extend(arr: T[]): ol.Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param {function(this: S, T, number, Array.): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @param {S=} opt_this The object to use as `this` in `f`. + * @template S + * @api stable + */ + forEach(f: ((self: S, item: T, index: number, array: T[]) => any), opt_this?: S): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array.} Array. + * @api stable + */ + getArray(): T[]; + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api stable + */ + item(index: number): T; + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api stable + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + insertAt(index: number, elem: T): void; + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api stable + */ + pop(): (T); + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} Length. + * @api stable + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api stable + */ + remove(elem: T): (T); + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api stable + */ + removeAt(index: number): (T); + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + setAt(index: number, elem: T): void; + + } + + module Collection { + + type EventType = string; + + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + constructor(type: ol.Collection.EventType, opt_element?: any); + + /** + * The element that is added to or removed from the collection. + * @type {*} + * @api stable + */ + element: any; + + } + } + + /** + * Colors can be defined as a {@link ol.Color} array, or as strings in + * `rgb(r,g,b)` or `rgba(r,g,b,a)` format, or in hex `#rrggbb` or `#rgb` format. + * Color names, like 'red', 'blue' or 'green', may also be used with the + * Canvas renderer. + * + * @namespace ol.color + */ + module color { + /** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {ol.Color|string} color Color. + * @return {ol.Color} Color. + * @api + */ + function asArray(color: (ol.Color | string)): ol.Color; + + /** + * Return the color as an rgba string. + * @param {ol.Color|string} color Color. + * @return {string} Rgba string. + * @api + */ + function asString(color: (ol.Color | string)): string; + + } + + /** + * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by + * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). + * @namespace ol.colorlike + */ + module colorlike { + /** + * @param {ol.Color|ol.ColorLike} color Color. + * @return {ol.ColorLike} The color as an ol.ColorLike + * @api + */ + function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; + + } + + /** + * @namespace ol.control + */ + module control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + class Attribution extends ol.control.Control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + constructor(opt_options?: olx.control.AttributionOptions); + + /** + * Update the attribution element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Attribution} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + } + + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + class Control extends ol.Object { + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + * @return {ol.Map} Map. + * @api stable + */ + getMap(): ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {ol.Map} map Map. + * @api stable + */ + setMap(map: ol.Map): void; + + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {Element|string} target Target. + * @api + */ + setTarget(target: (Element | string)): void; + + } + + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + class FullScreen extends ol.control.Control { + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.FullScreenOptions); + + } + + /** + * Set of controls included in maps by default. Unless configured otherwise, + * this returns a collection containing an instance of each of the following + * controls: + * * {@link ol.control.Zoom} + * * {@link ol.control.Rotate} + * * {@link ol.control.Attribution} + * + * @param {olx.control.DefaultsOptions=} opt_options Defaults options. + * @return {ol.Collection.} Controls. + * @api stable + */ + function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + class MousePosition extends ol.control.Control { + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + constructor(opt_options?: olx.control.MousePositionOptions); + + /** + * Update the mouseposition element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.MousePosition} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return the coordinate format type used to render the current position or + * undefined. + * @return {ol.CoordinateFormatType|undefined} The format to render the current + * position in. + * @observable + * @api stable + */ + getCoordinateFormat(): (ol.CoordinateFormatType); + + /** + * Return the projection that is used to report the mouse position. + * @return {ol.proj.Projection|undefined} The projection to report mouse + * position in. + * @observable + * @api stable + */ + getProjection(): (ol.proj.Projection); + + /** + * Set the coordinate format type used to render the current position. + * @param {ol.CoordinateFormatType} format The format to render the current + * position in. + * @observable + * @api stable + */ + setCoordinateFormat(format: ol.CoordinateFormatType): void; + + /** + * Set the projection that is used to report the mouse position. + * @param {ol.proj.Projection} projection The projection to report mouse + * position in. + * @observable + * @api stable + */ + setProjection(projection: ol.proj.Projection): void; + + } + + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + class OverviewMap extends ol.control.Control { + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + constructor(opt_options?: olx.control.OverviewMapOptions); + + /** + * Update the overview map element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.OverviewMap} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the overview map is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the overview map should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the overview map according to the passed parameter. Will + * not do anything if the overview map isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Determine if the overview map is collapsed. + * @return {boolean} The overview map is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + /** + * Return the overview map. + * @return {ol.Map} Overview map. + * @api + */ + getOverviewMap(): ol.Map; + + } + + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + class Rotate extends ol.control.Control { + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + constructor(opt_options?: olx.control.RotateOptions); + + /** + * Update the rotate control element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Rotate} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + class ScaleLine extends ol.control.Control { + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + constructor(opt_options?: olx.control.ScaleLineOptions); + + /** + * Return the units to use in the scale line. + * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * line. + * @observable + * @api stable + */ + getUnits(): (ol.control.ScaleLine.Units); + + /** + * Update the scale line element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ScaleLine} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Set the units to use in the scale line. + * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @observable + * @api stable + */ + setUnits(units: ol.control.ScaleLine.Units): void; + } + + module ScaleLine { + /** + * @enum {string} + * @api + */ + type Property = string; + + /** + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + * @enum {string} + */ + type Units = string; + } + + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + class Zoom extends ol.control.Control { + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomOptions); + + } + + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + class ZoomSlider extends ol.control.Control { + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomSliderOptions); + + /** + * Update the zoomslider element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ZoomSlider} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + class ZoomToExtent extends ol.control.Control { + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomToExtentOptions); + + } + + } + + /** + * @namespace ol.coordinate + */ + module coordinate { + /** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * ol.coordinate.add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {ol.Coordinate} delta Delta. + * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @api stable + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a {@link ol.CoordinateFormatType} function that can be used to format + * a {ol.Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(); + * var out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(2); + * var out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {ol.CoordinateFormatType} Coordinate format. + * @api stable + */ + function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given {@link ol.Coordinate} to a string using the given string + * template. The strings `{x}` and `{y}` in the template will be replaced with + * the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api stable + */ + function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; + + /** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * var rotateRadians = Math.PI / 2; // 90 degrees + * ol.coordinate.rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {ol.Coordinate} Coordinate. + * @api stable + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api stable + */ + function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + /** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api stable + */ + function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + } + + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + class DeviceOrientation extends ol.Object { + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + constructor(opt_options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ + getAlpha(): (number); + + /** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ + getBeta(): (number); + + /** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ + getGamma(): (number); + + /** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ + getHeading(): (number); + + /** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ + setTracking(tracking: boolean): void; + + } + + /** + * Objects that need to clean up after themselves. + * @constructor + */ + class Disposable { + /** + * Objects that need to clean up after themselves. + * @constructor + */ + constructor(); + + } + + /** + * Easing functions for {@link ol.animation}. + * @namespace ol.easing + */ + module easing { + /** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown + * is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function upAndDown(t: number): number; + + } + + /** + * Applications do not normally create event instances. They register (and + * unregister) event listener functions, which, when called by the library as + * the result of an event being dispatched, are passed event instances as their + * first argument. Listeners can be registered and unregistered on all objects + * descending from {@link ol.Observable}. All event instances have a `target` + * property, which corresponds to the object on which the event was dispatched. + * By default, `this` within the listener also refers to the target, though + * this can be configured in the listener registration function. + * Some classes have their own event type, which return additional + * properties; see the specific event class page for details. + * + * @namespace ol.events + */ + module events { + /** + * @namespace ol.events.condition + */ + module condition { + /** + * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when + * additionally the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt key is pressed. + * @api stable + */ + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise + * (e.g. when additionally the platform-modifier-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt and shift keys are pressed. + * @api stable + */ + function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always true. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True. + * @function + * @api stable + */ + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a `click` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `click` event. + * @api stable + */ + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always false. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} False. + * @function + * @api stable + */ + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the browser event is a `pointermove` event, `false` + * otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the browser event is a `pointermove` event. + * @api + */ + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `singleclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `singleclick` event. + * @api stable + */ + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `dblclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `dblclick` event. + * @api stable + */ + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is + * pressed. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True only if there no modifier keys are pressed. + * @api stable + */ + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the platform-modifier-key (the meta-key on Mac, + * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally + * the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the platform modifier key is pressed. + * @api stable + */ + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when + * additionally the alt-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the shift key is pressed. + * @api stable + */ + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the target element is not editable, i.e. not a ``-, + * `