diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6140babecd..4317128869 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -695,7 +695,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](heap/heap.d.ts) [heap](https://github.com/qiao/heap.js) by [Ryan McNamara](https://github.com/ryan10132) * [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable) * [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ) -* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher) +* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher), [Evan Hahn](https://github.com/EvanHahn) * [:link:](highcharts/highcharts.d.ts) [Highcharts](http://www.highcharts.com) by [Damiano Gambarotto](http://github.com/damianog), [Dan Lewi Harkestad](http://github.com/baltie) * [:link:](highcharts-ng/highcharts-ng.d.ts) [highcharts-ng](https://github.com/pablojim/highcharts-ng) by [Scott Hatcher](https://github.com/scatcher) * [:link:](highland/highland.d.ts) [Highland](http://highlandjs.org) by [Bart van der Schoor](https://github.com/Bartvds) diff --git a/CybozuLabs-md5/CybozuLabs-md5-tests.ts b/CybozuLabs-md5/CybozuLabs-md5-tests.ts new file mode 100644 index 0000000000..16dd05b059 --- /dev/null +++ b/CybozuLabs-md5/CybozuLabs-md5-tests.ts @@ -0,0 +1,9 @@ +/// + +var hash: string; +hash = CybozuLabs.MD5.calc("abc"); +hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII); +hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16); + +var version: string; +version = CybozuLabs.MD5.VERSION; \ No newline at end of file diff --git a/CybozuLabs-md5/CybozuLabs-md5.d.ts b/CybozuLabs-md5/CybozuLabs-md5.d.ts new file mode 100644 index 0000000000..6e1f31739d --- /dev/null +++ b/CybozuLabs-md5/CybozuLabs-md5.d.ts @@ -0,0 +1,11 @@ +// Type definitions for CybozuLabs.MD5 +// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html +// Definitions by: MIZUNE Pine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace CybozuLabs.MD5 { + var VERSION: string; + var BY_ASCII: number; + var BY_UTF16: number; + function calc(str: string, option?: number): string; +} diff --git a/README.md b/README.md index 5c218aaa19..279be10799 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Please see the [contribution guide](http://definitelytyped.org/guides/contributi ## Requested definitions -Here is are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). +Here are the [currently requested definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest). ## License diff --git a/adal-angular/adal-tests.ts b/adal-angular/adal-tests.ts index 598134d0a0..3b9e46c961 100644 --- a/adal-angular/adal-tests.ts +++ b/adal-angular/adal-tests.ts @@ -12,4 +12,12 @@ var config : adal.Config = { var auth = new AuthenticationContext(config); +Logging.log = (message: string) => { + console.log(message); +} + +Logging.level = 4; + +auth.info("Logging message"); + var userName: string = auth.getCachedUser().userName; \ No newline at end of file diff --git a/adal-angular/adal.d.ts b/adal-angular/adal.d.ts index c5a64efd0b..76b86e7150 100644 --- a/adal-angular/adal.d.ts +++ b/adal-angular/adal.d.ts @@ -4,9 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var AuthenticationContext: adal.AuthenticationContextStatic; +declare var Logging: adal.Logging; declare module 'adal' { - export = AuthenticationContext; + export = { AuthenticationContext, Logging }; } declare namespace adal { @@ -36,6 +37,18 @@ declare namespace adal { stateResponse: string, requestType: string } + + interface Logging { + log: (message: string) => void; + level: LoggingLevel; + } + + enum LoggingLevel { + ERROR = 0, + WARNING = 1, + INFO = 2, + VERBOSE = 3 + } interface AuthenticationContextStatic { new (config: Config): AuthenticationContext; diff --git a/angular-local-storage/angular-local-storage.d.ts b/angular-local-storage/angular-local-storage.d.ts index b2bcf377d2..7efc681491 100644 --- a/angular-local-storage/angular-local-storage.d.ts +++ b/angular-local-storage/angular-local-storage.d.ts @@ -56,6 +56,15 @@ declare namespace angular.local.storage { * @param val */ set(key:string, val:string):boolean; + /** + * Directly adds a value to cookies with an expiration. + * Note: Typically used as a fallback if local storage is not supported. + * Returns: Boolean + * @param key + * @param val + * @param daysToExpiry + */ + set(key:string, val:string, daysToExpiry:number):boolean; /** * Directly get a value from a cookie. * Returns: value from local storage diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 3c70dd27e8..cecaf07e67 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -55,6 +55,18 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material. $scope['confirmDialog'] = () => { $mdDialog.show($mdDialog.confirm().htmlContent('Confirm!')); }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().textContent('Prompt!')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().htmlContent('Prompt!')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().cancel('Prompt "Cancel" button text')); + }; + $scope['promptDialog'] = () => { + $mdDialog.show($mdDialog.prompt().placeholder('Prompt input placeholder text')); + }; $scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide'); $scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel'); }); diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 5120f76370..50389b9c72 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -4,6 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// + +declare module 'angular-material' { +    var _: string; +   export = _; +} + declare namespace angular.material { interface IBottomSheetOptions { @@ -59,6 +65,11 @@ declare namespace angular.material { interface IConfirmDialog extends IPresetDialog { cancel(cancel: string): IConfirmDialog; } + + interface IPromptDialog extends IPresetDialog { + cancel(cancel: string): IPromptDialog; + placeholder(placeholder: string): IPromptDialog; + } interface IDialogOptions { templateUrl?: string; @@ -91,6 +102,7 @@ declare namespace angular.material { show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise; confirm(): IConfirmDialog; alert(): IAlertDialog; + prompt(): IPromptDialog; hide(response?: any): angular.IPromise; cancel(response?: any): void; } diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 045f2f5994..51946281ce 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -72,7 +72,7 @@ declare namespace angular.translate { } interface ITranslateProvider extends angular.IServiceProvider { - translations(): ITranslationTable; + translations(key?: string): ITranslationTable; translations(key: string, translationTable: ITranslationTable): ITranslateProvider; cloakClassName(): string; cloakClassName(name: string): ITranslateProvider; diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 0a7b54775e..38a1c321bd 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -387,6 +387,12 @@ declare namespace angular.ui.bootstrap { * @default 'model-open' */ openedClass?: string; + + /** + * CSS class(es) to be added to the top modal window. + */ + + windowTopClass?: string; } interface IModalStackService { diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 0512528097..88f00c9b5d 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -35,7 +35,7 @@ declare namespace angular.ui { /** * String HTML content, or function that returns an HTML string */ - template?: string | {(): string}; + template?: string | {(params: IStateParamsService): string}; /** * String URL path to template file OR Function, returns URL path string */ @@ -229,9 +229,9 @@ declare namespace angular.ui { */ notify?: boolean; /** - * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. + * {boolean=false|string|IState}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params. */ - reload?: boolean; + reload?: boolean | string | IState; } interface IHrefOptions { diff --git a/angularjs/angular-animate.d.ts b/angularjs/angular-animate.d.ts index 2f3cbc0f18..f68cd60d14 100644 --- a/angularjs/angular-animate.d.ts +++ b/angularjs/angular-animate.d.ts @@ -19,14 +19,14 @@ declare namespace angular.animate { } interface IAnimateCallbackObject { - eventFn?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any; - setClass?: (element: IAugmentedJQuery, addedClasses: string, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; - addClass?: (element: IAugmentedJQuery, addedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; - removeClass?: (element: IAugmentedJQuery, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; - enter?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any; - leave?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any; - move?: (element: IAugmentedJQuery, doneFunction: Function, options: IAnimationOptions) => any; - animate?: (element: IAugmentedJQuery, fromStyles: string, toStyles: string, doneFunction: Function, options: IAnimationOptions) => any; + eventFn?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any; + setClass?: (element: JQuery, addedClasses: string, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; + addClass?: (element: JQuery, addedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; + removeClass?: (element: JQuery, removedClasses: string, doneFunction: Function, options: IAnimationOptions) => any; + enter?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any; + leave?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any; + move?: (element: JQuery, doneFunction: Function, options: IAnimationOptions) => any; + animate?: (element: JQuery, fromStyles: string, toStyles: string, doneFunction: Function, options: IAnimationOptions) => any; } interface IAnimationPromise extends IPromise {} diff --git a/angularjs/angular-component-router.d.ts b/angularjs/angular-component-router.d.ts index 2c56ef3a21..3b037b58b1 100644 --- a/angularjs/angular-component-router.d.ts +++ b/angularjs/angular-component-router.d.ts @@ -428,4 +428,55 @@ declare namespace angular { interface OnReuse { $routerOnReuse(next?: angular.ComponentInstruction, prev?: angular.ComponentInstruction): any; } + + /** + * Runtime representation a type that a Component or other object is instances of. + * + * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by + * the `MyCustomComponent` constructor function. + */ + interface Type extends Function { + } + + /** + * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. + * + * Supported keys: + * - `path` or `aux` (requires exactly one of these) + * - `component`, `loader`, `redirectTo` (requires exactly one of these) + * - `name` or `as` (optional) (requires exactly one of these) + * - `data` (optional) + * + * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. + */ + interface RouteDefinition { + path?: string; + aux?: string; + component?: Type | ComponentDefinition | string; + loader?: Function; + redirectTo?: any[]; + as?: string; + name?: string; + data?: any; + useAsDefault?: boolean; + } + + /** + * Represents either a component type (`type` is `component`) or a loader function + * (`type` is `loader`). + * + * See also {@link RouteDefinition}. + */ + interface ComponentDefinition { + type: string; + loader?: Function; + component?: Type; + } + + // Supplement IComponentOptions from angular.d.ts with router-specific + // fields. + interface IComponentOptions { + $canActivate?: () => boolean; + $routeConfig?: RouteDefinition[]; + } } diff --git a/angularjs/angular-mocks-tests.ts b/angularjs/angular-mocks-tests.ts index 8790e68cf3..ed72401d0c 100644 --- a/angularjs/angular-mocks-tests.ts +++ b/angularjs/angular-mocks-tests.ts @@ -137,15 +137,19 @@ requestHandler = httpBackendService.expect('GET', /test.local/); requestHandler = httpBackendService.expect('GET', /test.local/, 'response data'); requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.expect('GET', /test.local/, /response data/); requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }); requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); @@ -163,17 +167,21 @@ requestHandler = httpBackendService.expect('GET', (url: string) => { return true requestHandler = httpBackendService.expectDELETE('http://test.local'); requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectGET('http://test.local'); requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectHEAD('http://test.local'); requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectJSONP('http://test.local'); requestHandler = httpBackendService.expectJSONP(/test.local/); +requestHandler = httpBackendService.expectJSONP(/test.local\/(\d+)/, ['id']); requestHandler = httpBackendService.expectJSONP((url: string) => { return true; }); requestHandler = httpBackendService.expectPATCH('http://test.local'); @@ -188,12 +196,15 @@ requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'val requestHandler = httpBackendService.expectPATCH(/test.local/); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/); requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' }); requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }); requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -216,12 +227,15 @@ requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'valu requestHandler = httpBackendService.expectPOST(/test.local/); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data'); requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/); requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPOST((url: string) => { return true; }); requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -244,12 +258,16 @@ requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value requestHandler = httpBackendService.expectPUT(/test.local/); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data'); requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/); requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.expectPUT((url: string) => { return true; }); requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -276,16 +294,24 @@ requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'val requestHandler = httpBackendService.when('GET', /test.local/); requestHandler = httpBackendService.when('GET', /test.local/, 'response data'); requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, 'response data', function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, /response data/); requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, /response data/, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local\/(\d+)/, { key: 'value' }, function (headers: Object): boolean { return true; }, ['id']); requestHandler = httpBackendService.when('GET', (url: string) => { return true; }); requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); @@ -303,17 +329,21 @@ requestHandler = httpBackendService.when('GET', (url: string) => { return true; requestHandler = httpBackendService.whenDELETE('http://test.local'); requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenDELETE(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenGET('http://test.local'); requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenGET(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenHEAD('http://test.local'); requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD(/test.local\/(\d+)/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' }); requestHandler = httpBackendService.whenJSONP('http://test.local'); requestHandler = httpBackendService.whenJSONP(/test.local/); +requestHandler = httpBackendService.whenJSONP(/test.local\/(\d+)/, ['id']); requestHandler = httpBackendService.whenJSONP((url: string) => { return true; }); requestHandler = httpBackendService.whenPATCH('http://test.local'); @@ -328,12 +358,16 @@ requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value requestHandler = httpBackendService.whenPATCH(/test.local/); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data'); requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/); requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }); requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -356,12 +390,16 @@ requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' requestHandler = httpBackendService.whenPOST(/test.local/); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data'); requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/); requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPOST((url: string) => { return true; }); requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -384,12 +422,16 @@ requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' requestHandler = httpBackendService.whenPUT(/test.local/); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data'); requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, 'response data', { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/); requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, /response data/, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }); requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, function (data: string): boolean { return true; }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local\/(\d+)/, { key: 'value' }, { header: 'value' }, ['id']); requestHandler = httpBackendService.whenPUT((url: string) => { return true; }); requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data'); requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' }); @@ -410,6 +452,13 @@ requestHandler.passThrough().passThrough(); requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({}); requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); +requestHandler.respond((method, url, data, headers, params) => { + if(params.id === 1) { + return [200, { key: 'value'}, { header: 'value'}, 'responseText']; + } else { + return [404, { key: 'value' }, { header: 'value' }, 'responseText']; + } +}); requestHandler.respond('data'); requestHandler.respond('data').respond({}); requestHandler.respond(expectedData); diff --git a/angularjs/angular-mocks.d.ts b/angularjs/angular-mocks.d.ts index 9031cc56d1..d1b204862f 100644 --- a/angularjs/angular-mocks.d.ts +++ b/angularjs/angular-mocks.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) +// Type definitions for Angular JS 1.5 (ngMock, ngMockE2E module) // Project: http://angularjs.org // Definitions by: Diego Vilar , Tony Curtis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -157,8 +157,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler; + expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]) :mock.IRequestHandler; /** * Creates a new request expectation for DELETE requests. @@ -166,8 +167,9 @@ declare namespace angular { * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. * @param headers HTTP headers object to be compared with the HTTP headers in the request. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; /** * Creates a new request expectation for GET requests. @@ -175,8 +177,9 @@ declare namespace angular { * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object to be compared with the HTTP headers in the request. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; /** * Creates a new request expectation for HEAD requests. @@ -184,16 +187,19 @@ declare namespace angular { * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object to be compared with the HTTP headers in the request. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; + /** * Creates a new request expectation for JSONP requests. * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. - */ - expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; + * @param keys Array of keys to assign to regex matches in the request url. + */ + expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new request expectation for PATCH requests. @@ -202,8 +208,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; /** * Creates a new request expectation for POST requests. @@ -212,8 +219,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; /** * Creates a new request expectation for PUT requests. @@ -222,8 +230,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition. @@ -232,40 +241,46 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for DELETE requests. * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for GET requests. * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in request url described above + * @param keys Array of keys to assign to regex matches in the request url. */ - whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for HEAD requests. * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for JSONP requests. * Returns an object with respond method that controls how a matched request is handled. * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; + whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for PATCH requests. @@ -273,8 +288,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for POST requests. @@ -282,8 +298,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; /** * Creates a new backend definition for PUT requests. @@ -291,8 +308,9 @@ declare namespace angular { * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + * @param keys Array of keys to assign to regex matches in the request url. */ - whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler; } export module mock { @@ -302,9 +320,9 @@ declare namespace angular { /** * Controls the response for a matched request using a function to construct the response. * Returns the RequestHandler object for possible overrides. - * @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text. + * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text. */ - respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler; + respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler; /** * Controls the response for a matched request using supplied static data to construct the response. diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 0fb9351342..441a7e1d3d 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -95,7 +95,7 @@ declare namespace angular.resource { (params: Object, data: Object, success?: Function, error?: Function): IResourceArray; } - // Baseclass for everyresource with default actions. + // Baseclass for every resource with default actions. // If you define your new actions for the resource, you will need // to extend this interface and typecast the ResourceClass to it. // @@ -113,7 +113,7 @@ declare namespace angular.resource { // Also, static calls always return the IResource (or IResourceArray) retrieved // https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549 interface IResourceClass { - new(dataOrParams? : any) : T; + new(dataOrParams? : any) : T & IResource; get: IResourceMethod; query: IResourceArrayMethod; diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 0539ae62ac..7eaf0be763 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -476,6 +476,8 @@ function test_angular_forEach() { var element = angular.element("div.myApp"); var scope: ng.IScope = element.scope(); var isolateScope: ng.IScope = element.isolateScope(); +isolateScope = element.find('div.foo').isolateScope(); +isolateScope = element.children().isolateScope(); // $timeout signature tests @@ -867,7 +869,7 @@ angular.module('docsTabsExample', []) angular.module('componentExample', []) .component('counter', { - require: ['^ctrl'], + require: {'ctrl': '^ctrl'}, bindings: { count: '=' }, diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3d2b248637..1ae64c8e45 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -81,7 +81,7 @@ declare namespace angular { * * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." */ - element: IAugmentedJQueryStatic; + element: JQueryStatic; equals(value1: any, value2: any): boolean; extend(destination: any, ...sources: any[]): any; @@ -156,7 +156,7 @@ declare namespace angular { noop(...args: any[]): void; reloadWithDebugInfo(): void; - toJson(obj: any, pretty?: boolean): string; + toJson(obj: any, pretty?: boolean | number): string; uppercase(str: string): string; version: { full: string; @@ -389,9 +389,9 @@ declare namespace angular { $submitted: boolean; $error: any; $pending: any; - $addControl(control: INgModelController): void; - $removeControl(control: INgModelController): void; - $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void; + $addControl(control: INgModelController | IFormController): void; + $removeControl(control: INgModelController | IFormController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void; $setDirty(): void; $setPristine(): void; $commitViewValue(): void; @@ -883,6 +883,24 @@ declare namespace angular { unwrapPromises(): boolean; unwrapPromises(value: boolean): IParseProvider; + + /** + * Configure $parse service to add literal values that will be present as literal at expressions. + * + * @param literalName Token for the literal value. The literal name value must be a valid literal name. + * @param literalValue Value for this literal. All literal values must be primitives or `undefined`. + **/ + addLiteral(literalName: string, literalValue: any): void; + + /** + * Allows defining the set of characters that are allowed in Angular expressions. The function identifierStart will get called to know if a given character is a valid character to be the first character for an identifier. The function identifierContinue will get called to know if a given character is a valid character to be a follow-up identifier character. The functions identifierStart and identifierContinue will receive as arguments the single character to be identifier and the character code point. These arguments will be string and numeric. Keep in mind that the string parameter can be two characters long depending on the character representation. It is expected for the function to return true or false, whether that character is allowed or not. + * Since this function will be called extensivelly, keep the implementation of these functions fast, as the performance of these functions have a direct impact on the expressions parsing speed. + * + * @param identifierStart The function that will decide whether the given character is a valid identifier start character. + * @param identifierContinue The function that will decide whether the given character is a valid identifier continue character. + **/ + setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean, + identifierContinue?: (character: string, codePoint: number) => boolean): void; } interface ICompiledExpression { @@ -968,7 +986,7 @@ declare namespace angular { // DocumentService // see http://docs.angularjs.org/api/ng.$document /////////////////////////////////////////////////////////////////////////// - interface IDocumentService extends IAugmentedJQuery {} + interface IDocumentService extends JQuery {} /////////////////////////////////////////////////////////////////////////// // ExceptionHandlerService @@ -1231,15 +1249,15 @@ declare namespace angular { // This corresponds to the "publicLinkFn" returned by $compile. interface ITemplateLinkingFunction { - (scope: IScope, cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery; } // This corresponds to $transclude (and also the transclude function passed to link). interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction): IAugmentedJQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. - (cloneAttachFn?: ICloneAttachFunction): IAugmentedJQuery; + (cloneAttachFn?: ICloneAttachFunction): JQuery; } /////////////////////////////////////////////////////////////////////////// @@ -1656,50 +1674,6 @@ declare namespace angular { // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html // and http://toddmotto.com/exploring-the-angular-1-5-component-method/ /////////////////////////////////////////////////////////////////////////// - /** - * Runtime representation a type that a Component or other object is instances of. - * - * An example of a `Type` is `MyCustomComponent` class, which in JavaScript is be represented by - * the `MyCustomComponent` constructor function. - */ - interface Type extends Function { - } - - /** - * `RouteDefinition` defines a route within a {@link RouteConfig} decorator. - * - * Supported keys: - * - `path` or `aux` (requires exactly one of these) - * - `component`, `loader`, `redirectTo` (requires exactly one of these) - * - `name` or `as` (optional) (requires exactly one of these) - * - `data` (optional) - * - * See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}. - */ - interface RouteDefinition { - path?: string; - aux?: string; - component?: Type | ComponentDefinition | string; - loader?: Function; - redirectTo?: any[]; - as?: string; - name?: string; - data?: any; - useAsDefault?: boolean; - } - - /** - * Represents either a component type (`type` is `component`) or a loader function - * (`type` is `loader`). - * - * See also {@link RouteDefinition}. - */ - interface ComponentDefinition { - type: string; - loader?: Function; - component?: Type; - } - /** * Component definition object (a simplified directive definition object) */ @@ -1709,7 +1683,7 @@ declare namespace angular { * controller if passed as a string. Empty function by default. * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) */ - controller?: string | Function | (string | Function)[]; + controller?: string | Function | (string | Function)[] | IComponentController; /** * An identifier name for a reference to the controller. If present, the controller will be published to scope under * the controllerAs name. If not present, this will default to be the same as the component name. @@ -1742,11 +1716,52 @@ declare namespace angular { * Whether transclusion is enabled. Enabled by default. */ transclude?: boolean | string | {[slot: string]: string}; - require?: string | string[] | {[controller: string]: string}; + require?: {[controller: string]: string}; } interface IComponentTemplateFn { - ( $element?: IAugmentedJQuery, $attrs?: IAttributes ): string; + ( $element?: JQuery, $attrs?: IAttributes ): string; + } + + /** + * Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that + * will be called at certain points in the life of the component. + * @url https://docs.angularjs.org/guide/component + */ + interface IComponentController { + /** + * Called on each controller after all the controllers on an element have been constructed and had their bindings + * initialized (and before the pre & post linking functions for the directives on this element). This is a good + * place to put initialization code for your controller. + */ + $onInit?(): void; + /** + * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form + * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as + * cloning the bound value to prevent accidental mutation of the outer value. + */ + $onChanges?(changesObj: {[property:string]: IChangesObject}): void; + /** + * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, + * watches and event handlers. + */ + $onDestroy?(): void; + /** + * Called after this controller's element and its children have been linked. Similar to the post-link function this + * hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain + * templateUrl directives will not have been compiled and linked since they are waiting for their template to load + * asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered + * analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather + * different in Angular 1 there is no direct mapping and care should be taken when upgrading. + */ + $postInit?(): void; + } + + interface IChangesObject { + currentValue: any; + previousValue: any; + isFirstChange(): boolean; } /////////////////////////////////////////////////////////////////////////// @@ -1762,7 +1777,7 @@ declare namespace angular { interface IDirectiveLinkFn { ( scope: IScope, - instanceElement: IAugmentedJQuery, + instanceElement: JQuery, instanceAttributes: IAttributes, controller: {}, transclude: ITranscludeFunction @@ -1776,7 +1791,7 @@ declare namespace angular { interface IDirectiveCompileFn { ( - templateElement: IAugmentedJQuery, + templateElement: JQuery, templateAttributes: IAttributes, /** * @deprecated @@ -1818,44 +1833,14 @@ declare namespace angular { } /** - * angular.element - * when calling angular.element, angular returns a jQuery object, - * augmented with additional methods like e.g. scope. - * see: http://docs.angularjs.org/api/angular.element + * These interfaces are kept for compatibility with older versions of these type definitions. + * Actually, Angular doesn't create a special subclass of jQuery objects. It extends jQuery.prototype + * like jQuery plugins do, that's why all jQuery objects have these Angular-specific methods, not + * only those returned from angular.element. + * See: http://docs.angularjs.org/api/angular.element */ - interface IAugmentedJQueryStatic extends JQueryStatic { - (selector: string, context?: any): IAugmentedJQuery; - (element: Element): IAugmentedJQuery; - (object: {}): IAugmentedJQuery; - (elementArray: Element[]): IAugmentedJQuery; - (object: JQuery): IAugmentedJQuery; - (func: Function): IAugmentedJQuery; - (array: any[]): IAugmentedJQuery; - (): IAugmentedJQuery; - } - - interface IAugmentedJQuery extends JQuery { - // TODO: events, how to define? - //$destroy - - find(selector: string): IAugmentedJQuery; - find(element: any): IAugmentedJQuery; - find(obj: JQuery): IAugmentedJQuery; - controller(): any; - controller(name: string): any; - injector(): any; - scope(): IScope; - - /** - * Overload for custom scope interfaces - */ - scope(): T; - isolateScope(): IScope; - - inheritedData(key: string, value: any): JQuery; - inheritedData(obj: { [key: string]: any; }): JQuery; - inheritedData(key?: string): any; - } + interface IAugmentedJQueryStatic extends JQueryStatic {} + interface IAugmentedJQuery extends JQuery {} /////////////////////////////////////////////////////////////////////////// // AUTO module (angular.js) @@ -1870,6 +1855,33 @@ declare namespace angular { annotate(fn: Function, strictDi?: boolean): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; get(name: string, caller?: string): T; + get(name: '$anchorScroll'): IAnchorScrollService + get(name: '$cacheFactory'): ICacheFactoryService + get(name: '$compile'): ICompileService + get(name: '$controller'): IControllerService + get(name: '$document'): IDocumentService + get(name: '$exceptionHandler'): IExceptionHandlerService + get(name: '$filter'): IFilterService + get(name: '$http'): IHttpService + get(name: '$httpBackend'): IHttpBackendService + get(name: '$httpParamSerializer'): IHttpParamSerializer + get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer + get(name: '$interpolate'): IInterpolateService + get(name: '$interval'): IIntervalService + get(name: '$locale'): ILocaleService + get(name: '$location'): ILocationService + get(name: '$log'): ILogService + get(name: '$parse'): IParseService + get(name: '$q'): IQService + get(name: '$rootElement'): IRootElementService + get(name: '$rootScope'): IRootScopeService + get(name: '$sce'): ISCEService + get(name: '$sceDelegate'): ISCEDelegateService + get(name: '$templateCache'): ITemplateCacheService + get(name: '$templateRequest'): ITemplateRequestService + get(name: '$timeout'): ITimeoutService + get(name: '$window'): IWindowService + get(name: '$xhrFactory'): IXhrFactory has(name: string): boolean; instantiate(typeConstructor: Function, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; @@ -1930,3 +1942,20 @@ declare namespace angular { (obj: Object): string; } } + +interface JQuery { + // TODO: events, how to define? + //$destroy + + find(element: any): JQuery; + find(obj: JQuery): JQuery; + controller(name?: string): any; + injector(): ng.auto.IInjectorService; + /** It's declared generic for custom scope interfaces */ + scope(): T; + isolateScope(): T; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; +} diff --git a/angularjs/legacy/angular-mocks-1.3-tests.ts b/angularjs/legacy/angular-mocks-1.3-tests.ts new file mode 100644 index 0000000000..3a3db64470 --- /dev/null +++ b/angularjs/legacy/angular-mocks-1.3-tests.ts @@ -0,0 +1,403 @@ +/// + +/////////////////////////////////////// +// IAngularStatic +/////////////////////////////////////// +var angular: ng.IAngularStatic; +var mock: ng.IMockStatic; + +mock = angular.mock; + + +/////////////////////////////////////// +// IMockStatic +/////////////////////////////////////// +var date: Date; + +mock.dump({ key: 'value' }); + +mock.inject( + function () { return 1; }, + function () { return 2; } + ); + +mock.inject( + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }]); + +// This overload is not documented on the website, but flows from +// how the injector works. +mock.inject( + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 1; }], + ['$rootScope', function ($rootScope: ng.IRootScopeService) { return 2; }]); + +mock.module('module1', 'module2'); +mock.module( + function () { return 1; }, + function () { return 2; } + ); +mock.module({ module1: function () { return 1; } }); + +date = mock.TzDate(-7, '2013-1-1T15:00:00Z'); +date = mock.TzDate(-8, 12345678); + + +/////////////////////////////////////// +// IExceptionHandlerProvider +/////////////////////////////////////// +var exceptionHandlerProvider: ng.IExceptionHandlerProvider; + +exceptionHandlerProvider.mode('log'); + + +/////////////////////////////////////// +// ITimeoutService +/////////////////////////////////////// +var timeoutService: ng.ITimeoutService; + +timeoutService.flush(); +timeoutService.flush(1234); +timeoutService.flushNext(); +timeoutService.flushNext(1234); +timeoutService.verifyNoPendingTasks(); + +//////////////////////////////////////// +// IIntervalService +//////////////////////////////////////// +var intervalService: ng.IIntervalService; +var intervalServiceTimeActuallyAdvanced: number; + +intervalServiceTimeActuallyAdvanced = intervalService.flush(); +intervalServiceTimeActuallyAdvanced = intervalService.flush(1234); + +/////////////////////////////////////// +// ILogService, ILogCall +/////////////////////////////////////// +var logService: ng.ILogService; +var logCall: ng.ILogCall; +var logs: string[]; + +logService.assertEmpty(); +logService.reset(); + +logCall = logService.debug; +logCall = logService.error; +logCall = logService.info; +logCall = logService.log; +logCall = logService.warn; + +logs = logCall.logs; + + +/////////////////////////////////////// +// IHttpBackendService +/////////////////////////////////////// +var httpBackendService: ng.IHttpBackendService; +var requestHandler: ng.mock.IRequestHandler; + +httpBackendService.flush(); +httpBackendService.flush(1234); +httpBackendService.resetExpectations(); +httpBackendService.verifyNoOutstandingExpectation(); +httpBackendService.verifyNoOutstandingRequest(); + +requestHandler = httpBackendService.expect('GET', 'http://test.local'); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data'); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data'); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expect('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); + +requestHandler = httpBackendService.expectDELETE('http://test.local'); +requestHandler = httpBackendService.expectDELETE('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectGET('http://test.local'); +requestHandler = httpBackendService.expectGET('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD('http://test.local'); +requestHandler = httpBackendService.expectHEAD('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.expectHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.expectHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectJSONP('http://test.local'); +requestHandler = httpBackendService.expectJSONP(/test.local/); +requestHandler = httpBackendService.expectJSONP((url: string) => { return true; }); + +requestHandler = httpBackendService.expectPATCH('http://test.local'); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/); +requestHandler = httpBackendService.expectPATCH('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/); +requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/); +requestHandler = httpBackendService.expectPATCH(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.expectPOST('http://test.local'); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/); +requestHandler = httpBackendService.expectPOST('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/); +requestHandler = httpBackendService.expectPOST(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, /response data/); +requestHandler = httpBackendService.expectPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.expectPUT('http://test.local'); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data'); +requestHandler = httpBackendService.expectPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/); +requestHandler = httpBackendService.expectPUT('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.expectPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/); +requestHandler = httpBackendService.expectPUT(/test.local/, 'response data'); +requestHandler = httpBackendService.expectPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, /response data/); +requestHandler = httpBackendService.expectPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.expectPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.expectPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.when('GET', 'http://test.local'); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data'); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', 'http://test.local', { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data'); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', /test.local/, { key: 'value' }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, 'response data', function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, /response data/, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, function (data: string): boolean { return true; }, function (headers: Object): boolean { return true; }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.when('GET', (url: string) => { return true; }, { key: 'value' }, function (headers: Object): boolean { return true; }); + +requestHandler = httpBackendService.whenDELETE('http://test.local'); +requestHandler = httpBackendService.whenDELETE('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenDELETE(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenDELETE((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenGET('http://test.local'); +requestHandler = httpBackendService.whenGET('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenGET(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenGET((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD('http://test.local'); +requestHandler = httpBackendService.whenHEAD('http://test.local', { header: 'value' }); +requestHandler = httpBackendService.whenHEAD(/test.local/, { header: 'value' }); +requestHandler = httpBackendService.whenHEAD((url: string) => { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenJSONP('http://test.local'); +requestHandler = httpBackendService.whenJSONP(/test.local/); +requestHandler = httpBackendService.whenJSONP((url: string) => { return true; }); + +requestHandler = httpBackendService.whenPATCH('http://test.local'); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPATCH('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/); +requestHandler = httpBackendService.whenPATCH('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPATCH('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/); +requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPATCH(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/); +requestHandler = httpBackendService.whenPATCH(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPATCH(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPATCH((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.whenPOST('http://test.local'); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPOST('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/); +requestHandler = httpBackendService.whenPOST('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPOST('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/); +requestHandler = httpBackendService.whenPOST(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPOST(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, /response data/); +requestHandler = httpBackendService.whenPOST(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPOST(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPOST((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + +requestHandler = httpBackendService.whenPUT('http://test.local'); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data'); +requestHandler = httpBackendService.whenPUT('http://test.local', 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/); +requestHandler = httpBackendService.whenPUT('http://test.local', /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT('http://test.local', function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }); +requestHandler = httpBackendService.whenPUT('http://test.local', { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/); +requestHandler = httpBackendService.whenPUT(/test.local/, 'response data'); +requestHandler = httpBackendService.whenPUT(/test.local/, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, /response data/); +requestHandler = httpBackendService.whenPUT(/test.local/, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT(/test.local/, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }); +requestHandler = httpBackendService.whenPUT(/test.local/, { key: 'value' }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data'); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, 'response data', { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, /response data/, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, function (data: string): boolean { return true; }, { header: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }); +requestHandler = httpBackendService.whenPUT((url: string) => { return true; }, { key: 'value' }, { header: 'value' }); + + +/////////////////////////////////////// +// IRequestHandler +/////////////////////////////////////// +var expectedData = { key: 'value'}; +requestHandler.passThrough(); +requestHandler.passThrough().passThrough(); +requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']); +requestHandler.respond((method, url, data, headers) => [404, 'data', { header: 'value' }, 'responseText']).respond({}); +requestHandler.respond((method, url, data, headers) => { return [404, { key: 'value' }, { header: 'value' }, 'responseText']; }); +requestHandler.respond('data'); +requestHandler.respond('data').respond({}); +requestHandler.respond(expectedData); +requestHandler.respond({ key: 'value' }); +requestHandler.respond({ key: 'value' }, { header: 'value' }); +requestHandler.respond({ key: 'value' }, { header: 'value' }, 'responseText'); +requestHandler.respond(404, 'data'); +requestHandler.respond(404, 'data').respond({}); +requestHandler.respond(404, { key: 'value' }); +requestHandler.respond(404, { key: 'value' }, { header: 'value' }); +requestHandler.respond(404, { key: 'value' }, { header: 'value' }, 'responseText'); diff --git a/angularjs/legacy/angular-mocks-1.3.d.ts b/angularjs/legacy/angular-mocks-1.3.d.ts new file mode 100644 index 0000000000..1850ac266c --- /dev/null +++ b/angularjs/legacy/angular-mocks-1.3.d.ts @@ -0,0 +1,318 @@ +// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module) +// Project: http://angularjs.org +// Definitions by: Diego Vilar , Tony Curtis +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "angular-mocks/ngMock" { + var _: string; + export = _; +} + +declare module "angular-mocks/ngMockE2E" { + var _: string; + export = _; +} + +declare module "angular-mocks/ngAnimateMock" { + var _: string; + export = _; +} + +/////////////////////////////////////////////////////////////////////////////// +// ngMock module (angular-mocks.js) +/////////////////////////////////////////////////////////////////////////////// +declare module angular { + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // We reopen it to add the MockStatic definition + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + mock: IMockStatic; + } + + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject + interface IInjectStatic { + (...fns: Function[]): any; + (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works + strictDi(val?: boolean): void; + } + + interface IMockStatic { + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump + dump(obj: any): string; + + inject: IInjectStatic + + // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module + module(...modules: any[]): any; + + // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate + TzDate(offset: number, timestamp: number): Date; + TzDate(offset: number, timestamp: string): Date; + } + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler + // see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerProvider extends IServiceProvider { + mode(mode: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see https://docs.angularjs.org/api/ngMock/service/$timeout + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + flush(delay?: number): void; + flushNext(expectedDelay?: number): void; + verifyNoPendingTasks(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see https://docs.angularjs.org/api/ngMock/service/$interval + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + flush(millis?: number): number; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see https://docs.angularjs.org/api/ngMock/service/$log + // Augments the original service + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + assertEmpty(): void; + reset(): void; + } + + interface ILogCall { + logs: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see https://docs.angularjs.org/api/ngMock/service/$httpBackend + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + /** + * Flushes all pending requests using the trained responses. + * @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed. + */ + flush(count?: number): void; + + /** + * Resets all request expectations, but preserves all backend definitions. + */ + resetExpectations(): void; + + /** + * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception. + */ + verifyNoOutstandingExpectation(): void; + + /** + * Verifies that there are no outstanding requests that need to be flushed. + */ + verifyNoOutstandingRequest(): void; + + /** + * Creates a new request expectation. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler; + + /** + * Creates a new request expectation for DELETE requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for GET requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for HEAD requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object to be compared with the HTTP headers in the request. + */ + expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for JSONP requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + */ + expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; + + /** + * Creates a new request expectation for PATCH requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for POST requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new request expectation for PUT requests. + * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler; + + /** + * Creates a new backend definition. + * Returns an object with respond method that controls how a matched request is handled. + * @param method HTTP method. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for DELETE requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for GET requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for HEAD requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for JSONP requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for PATCH requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for POST requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + + /** + * Creates a new backend definition for PUT requests. + * Returns an object with respond method that controls how a matched request is handled. + * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation. + * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation. + * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation. + */ + whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler; + } + + export module mock { + // returned interface by the the mocked HttpBackendService expect/when methods + interface IRequestHandler { + + /** + * Controls the response for a matched request using a function to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text. + */ + respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler; + + /** + * Controls the response for a matched request using supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param status HTTP status code to add to the response. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + + /** + * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response. + * Returns the RequestHandler object for possible overrides. + * @param data Data to add to the response. + * @param headers Headers object to add to the response. + * @param responseText Response text to add to the response. + */ + respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler; + + // Available when ngMockE2E is loaded + /** + * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.) + */ + passThrough(): IRequestHandler; + } + + } + +} + +/////////////////////////////////////////////////////////////////////////////// +// functions attached to global object (window) +/////////////////////////////////////////////////////////////////////////////// +//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs. +//declare var module: (...modules: any[]) => any; +declare var inject: angular.IInjectStatic; \ No newline at end of file diff --git a/applicationinsights-js/applicationinsights-js-tests.ts b/applicationinsights-js/applicationinsights-js-tests.ts new file mode 100644 index 0000000000..b90ec6c6fe --- /dev/null +++ b/applicationinsights-js/applicationinsights-js-tests.ts @@ -0,0 +1,115 @@ +/// +// More samples on: https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md + +var config: Microsoft.ApplicationInsights.IConfig = { + instrumentationKey: "", + endpointUrl: "endpointUrl", + emitLineDelimitedJson: false, + accountId: "accountId", + sessionRenewalMs: 30, + sessionExpirationMs: 24 * 60 * 60 * 1000, + maxBatchSizeInBytes: 100 * 1024, + maxBatchInterval: 15, + enableDebug: false, + disableTelemetry: false, + verboseLogging: false, + diagnosticLogInterval: 10, + samplingPercentage: 100, + autoTrackPageVisitTime: true, + disableExceptionTracking: false, + disableAjaxTracking: false, + overridePageViewDuration: false, + maxAjaxCallsPerView: -1, + disableDataLossAnalysis: true, + disableCorrelationHeaders: true, + disableFlushOnBeforeUnload: false, + enableSessionStorageBuffer: false, + cookieDomain: "" +}; + +var appInsights: Microsoft.ApplicationInsights.IAppInsights = { + config: config, + context: null, + queue: null, + + startTrackPage(name?: string) { return null; }, + stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, + trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; }, + startTrackEvent(name: string) { return null }, + stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null }, + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string) { return null }, + trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null }, + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null }, + trackTrace(message: string, properties?: { [name: string]: string; }) { return null }, + flush() { return null }, + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null }, + clearAuthenticatedUserContext() { return null }, + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null } +}; + +// trackPageView +appInsights.trackPageView("page1"); +appInsights.trackPageView("page2", "http://example.com", null, null, 1000); + +// startTrackPage +appInsights.startTrackPage("page"); + +// stopTrackPage +appInsights.stopTrackPage("page"); +appInsights.stopTrackPage("page", "http://example.com", null, null); + +// trackEvent +appInsights.trackEvent("page1"); +appInsights.trackEvent("page1", null, null); + +// trackMetric +appInsights.trackMetric("page1", 999); +appInsights.trackMetric("page1", 999, 1, 1, 2, null); + +// trackException +appInsights.trackException(new Error("sample error")); +appInsights.trackException(new Error("sample error"), "handledAt", null, null); + +// trackTrace +appInsights.trackTrace("message"); +appInsights.trackTrace("message", null); + +// flush +appInsights.flush(); + +// setAuthenticatedUserContext +appInsights.setAuthenticatedUserContext("userId"); +appInsights.setAuthenticatedUserContext("userId", "accountId"); + +// set config dynamically +appInsights.config.instrumentationKey = ""; + + +// TelementryContext +var context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context; + +context.application.ver = "v0.0.0"; +context.application.build = "1.1.1"; + +context.device.type = "sampleDevice"; +context.device.locale = "en-US"; + +context.user.id = "userId"; +context.user.authenticatedId = "authId"; + +context.session.id = "sessionId"; +context.session.isFirst = true; + +context.location.ip = "127.0.0.1"; + +context.operation.id = "1"; +context.operation.syntheticSource = "testAgent"; + +// track +var data = new Microsoft.Telemetry.Base(); +var envelope = new Microsoft.Telemetry.Envelope(); + +context.track(envelope); + +context.addTelemetryInitializer((envelope) => false); \ No newline at end of file diff --git a/applicationinsights-js/applicationinsights-js.d.ts b/applicationinsights-js/applicationinsights-js.d.ts new file mode 100644 index 0000000000..5bb2a535f9 --- /dev/null +++ b/applicationinsights-js/applicationinsights-js.d.ts @@ -0,0 +1,408 @@ +// Type definitions for ApplicationInsights-JS v0.22.14 +// Project: https://github.com/Microsoft/ApplicationInsights-JS +// Definitions by: Kamil Szostak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module AI { + enum SeverityLevel { + Verbose = 0, + Information = 1, + Warning = 2, + Error = 3, + Critical = 4, + } +} + +declare module Microsoft.ApplicationInsights.Context { + interface IApplication { + /** + * The application version. + */ + ver: string; + /** + * The application build version. + */ + build: string; + } + + interface IDevice { + /** + * The type for the current device. + */ + type: string; + /** + * A device unique ID. + */ + id: string; + /** + * The device OEM for the current device. + */ + oemName: string; + /** + * The device model for the current device. + */ + model: string; + /** + * The IANA interface type for the internet connected network adapter. + */ + network: number; + /** + * The application screen resolution. + */ + resolution: string; + /** + * The current display language of the operating system. + */ + locale: string; + /** + * The IP address. + */ + ip: string; + /** + * The device language. + */ + language: string; + /** + * The OS name. + */ + os: string; + /** + * The OS version. + */ + osversion: string; + } + + interface ILocation { + /** + * Client IP address for reverse lookup + */ + ip: string; + } + + interface IInternal { + /** + * The SDK version used to create this telemetry item. + */ + sdkVersion: string; + /** + * The SDK agent version. + */ + agentVersion: string; + } + + interface ISample { + /** + * Sample rate + */ + sampleRate: number; + } + + interface ISession { + /** + * The session ID. + */ + id: string; + /** + * The true if this is the first session + */ + isFirst: boolean; + /** + * The date at which this guid was genereated. + * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time. + */ + acquisitionDate: number; + /** + * The date at which this session ID was last reported. + * This value should be updated whenever telemetry is sent using this ID. + * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. + */ + renewalDate: number; + } + + interface IOperation { + /** + * Operation id + */ + id: string; + /** + * Operation name + */ + name: string; + /** + * Parent operation id + */ + parentId: string; + /** + * Root operation id + */ + rootId: string; + /** + * Synthetic source of the operation + */ + syntheticSource: string; + } + + interface IUser { + /** + * The telemetry configuration. + */ + config: any; + /** + * The user ID. + */ + id: string; + /** + * Authenticated user id + */ + authenticatedId: string; + /** + * The account ID. + */ + accountId: string; + /** + * The account acquisition date. + */ + accountAcquisitionDate: string; + /** + * The user agent string. + */ + agent: string; + /** + * The store region. + */ + storeRegion: string; + } +} + +declare module Microsoft.Telemetry { + class Base { + baseType: string; + constructor(); + } + + class Envelope { + ver: number; + name: string; + time: string; + sampleRate: number; + seq: string; + iKey: string; + flags: number; + deviceId: string; + os: string; + osVer: string; + appId: string; + appVer: string; + userId: string; + tags: any; + data: Base; + constructor(); + } +} + +declare module Microsoft.ApplicationInsights { + interface IConfig { + instrumentationKey?: string; + endpointUrl?: string; + emitLineDelimitedJson?: boolean; + accountId?: string; + sessionRenewalMs?: number; + sessionExpirationMs?: number; + maxBatchSizeInBytes?: number; + maxBatchInterval?: number; + enableDebug?: boolean; + disableExceptionTracking?: boolean; + disableTelemetry?: boolean; + verboseLogging?: boolean; + diagnosticLogInterval?: number; + samplingPercentage?: number; + autoTrackPageVisitTime?: boolean; + disableAjaxTracking?: boolean; + overridePageViewDuration?: boolean; + maxAjaxCallsPerView?: number; + disableDataLossAnalysis?: boolean; + disableCorrelationHeaders?: boolean; + disableFlushOnBeforeUnload?: boolean; + enableSessionStorageBuffer?: boolean; + cookieDomain?: string; + url?: string; + } + + interface ITelemetryContext { + /** + * The object describing a component tracked by this object. + */ + application: Context.IApplication; + /** + * The object describing a device tracked by this object. + */ + device: Context.IDevice; + /** + * The object describing internal settings. + */ + internal: Context.IInternal; + /** + * The object describing a location tracked by this object. + */ + location: Context.ILocation; + /** + * The object describing a operation tracked by this object. + */ + operation: Context.IOperation; + /** + * The object describing sampling settings. + */ + sample: Context.ISample; + /** + * The object describing a user tracked by this object. + */ + user: Context.IUser; + /** + * The object describing a session tracked by this object. + */ + session: Context.ISession; + /** + * Adds telemetry initializer to the collection. Telemetry initializers will be called one by one + * before telemetry item is pushed for sending and in the order they were added. + */ + addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.Telemetry.Envelope) => boolean): any; + /** + * Tracks telemetry object. + */ + track(envelope: Microsoft.Telemetry.Envelope): any; + } + + interface IAppInsights { + config: IConfig; + context: ITelemetryContext; + queue: (() => void)[]; + /** + * Starts timing how long the user views a page or other item. Call this when the page opens. + * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. + */ + startTrackPage(name?: string): any; + /** + * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. + * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. + * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + stopTrackPage(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; + /** + * Logs that a page or other item was viewed. + * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. + * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. + * @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally. + */ + trackPageView(name?: string, url?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, duration?: number): any; + /** + * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. + * @param name A string that identifies this event uniquely within the document. + */ + startTrackEvent(name: string): any; + /** + * Log an extended event that you started timing with {@link startTrackEvent}. + * @param name The string you used to identify this event in startTrackEvent. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + stopTrackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; + /** + * Log a user action or other occurrence. + * @param name A string to identify this event in the portal. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + */ + trackEvent(name: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }): any; + /** + * Log an AJAX request + * @param id Event id + * @param absoluteUrl Full url + * @param pathName Leave this parameter blank + * @param totalTime Total time it took for AJAX request to complete + * @param success Whether AJAX request succeeded or failed + * @param resultCode Result code returned from AJAX call + * @param method HTTP verb that was used (GET, POST) + */ + trackAjax(id: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, method?: string): any; + /** + * Log an exception you have caught. + * @param exception An Error from a catch clause, or the string error message. + * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. + * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. + * @param severityLevel AI.SeverityLevel - severity level + */ + trackException(exception: Error, handledAt?: string, properties?: { + [name: string]: string; + }, measurements?: { + [name: string]: number; + }, severityLevel?: AI.SeverityLevel): any; + /** + * Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators. + * To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the + * telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals. + * @param name A string that identifies the metric. + * @param average Number representing either a single measurement, or the average of several measurements. + * @param sampleCount The number of measurements represented by the average. Defaults to 1. + * @param min The smallest measurement in the sample. Defaults to the average. + * @param max The largest measurement in the sample. Defaults to the average. + */ + trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { + [name: string]: string; + }): any; + /** + * Log a diagnostic message. + * @param message A message string + * @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty. + */ + trackTrace(message: string, properties?: { + [name: string]: string; + }): any; + /** + * Immediately send all queued telemetry. + */ + flush(): any; + /** + * Sets the autheticated user id and the account id in this session. + * User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars. + * + * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. + * @param accountId {string} - An optional string to represent the account associated with the authenticated user. + */ + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; + /** + * Clears the authenticated user id and the account id from the user context. + */ + clearAuthenticatedUserContext(): any; + downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void; + /** + * The custom error handler for Application Insights + * @param {string} message - The error message + * @param {string} url - The url where the error was raised + * @param {number} lineNumber - The line number where the error was raised + * @param {number} columnNumber - The column number for the line where the error was raised + * @param {Error} error - The Error object + */ + _onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error): any; + } +} diff --git a/argv/argv-tests.ts b/argv/argv-tests.ts new file mode 100644 index 0000000000..6d73c53ec7 --- /dev/null +++ b/argv/argv-tests.ts @@ -0,0 +1,15 @@ +/// +import argv = require('argv'); +argv.version( 'v1.0' ); +argv.info( 'Special script info' ); +argv.clear() +.option({ + name: 'option', + short: 'o', + type: 'string', + description: 'Defines an option for your script', + example: "'script --opiton=value' or 'script -o value'" +}) +.run([ '--option=123', '-o', '123' ]); +argv.run(); +argv.help(); diff --git a/argv/argv.d.ts b/argv/argv.d.ts new file mode 100644 index 0000000000..182ffde861 --- /dev/null +++ b/argv/argv.d.ts @@ -0,0 +1,59 @@ +// Type definitions for argv +// Project: https://www.npmjs.com/package/argv +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "argv" { + // argv module + type args = { + targets:string[], + options:{[key:string]:any} + }; + + type helpOption = { + name: string, + type: string, + short?: string, + description?: string, + example?: string + }; + + type module = { + mod: string, + description: string, + options: {[key:string]:helpOption} + }; + + type typeFunction = (value:any, ...arglist:any[]) => any; + + type argv = { + + // Runs the arguments parser + run: ( argv?:string[] ) => args, + + // Adding options to definitions list + option: ( mod:helpOption|helpOption[] ) => argv, + + // Creating module + mod: ( object:module|module[] ) => argv, + + // Creates custom type function + type: ( name:string|{[key:string]:typeFunction}, callback?:typeFunction ) => any, + + // Setting version number, and auto setting version option + version: ( v:string ) => argv, + + // Description setup + info: ( mod:string, description?:module ) => argv, + + // Cleans out current options + clear: () => argv, + + // Prints out the help doc + help: ( mod?:string ) => argv + + }; + + var argv:argv; + + export = argv; +} diff --git a/async/async-tests.ts b/async/async-tests.ts index 037481b6fa..e7af9120a1 100644 --- a/async/async-tests.ts +++ b/async/async-tests.ts @@ -378,6 +378,7 @@ async.auto({ async.retry(3, function (callback, results) { }, function (err, result) { }); async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { }); +async.retry({ times: 3, interval: (retryCount) => { return 200 * retryCount; } }, function (callback, results) { }, function (err, result) { }); async.parallel([ diff --git a/async/async.d.ts b/async/async.d.ts index c3d218fabc..6288a269a1 100644 --- a/async/async.d.ts +++ b/async/async.d.ts @@ -12,7 +12,7 @@ interface AsyncResultObjectCallback { (err: Error, results: Dictionary): v interface AsyncFunction { (callback: (err?: Error, result?: T) => void): void; } interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -interface AsyncForEachOfIterator { (item: T, key: number, callback: ErrorCallback): void; } +interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } interface AsyncMemoIterator { (memo: R, item: T, callback: AsyncResultCallback): void; } interface AsyncBooleanIterator { (item: T, callback: (err: string, truthValue: boolean) => void): void; } @@ -136,7 +136,7 @@ interface Async { cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; auto(tasks: any, callback?: (error: Error, results: any) => void): void; retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: (error: Error, results: any) => void): void; - retry(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; + retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: (error: Error, results: any) => void): void; iterator(tasks: Function[]): Function; apply(fn: Function, ...arguments: any[]): AsyncFunction; nextTick(callback: Function): void; diff --git a/atmosphere/atmosphere.d.ts b/atmosphere/atmosphere.d.ts index bf26ba0db4..239986b3a1 100644 --- a/atmosphere/atmosphere.d.ts +++ b/atmosphere/atmosphere.d.ts @@ -102,5 +102,6 @@ declare namespace Atmosphere { } declare var atmosphere:Atmosphere.Atmosphere; - - +declare module 'atmosphere' { + export = atmosphere; +} diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 9ca4c562cc..97837b52d0 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -181,7 +181,7 @@ declare namespace autobahn { open(): void; - close(reason: string, message: string): void; + close(reason?: string, message?: string): void; onopen: (session: Session, details: any) => void; onclose: (reason: string, details: any) => boolean; diff --git a/aws-sdk/aws-sdk-tests.ts b/aws-sdk/aws-sdk-tests.ts index 7411beb930..b771b86172 100644 --- a/aws-sdk/aws-sdk-tests.ts +++ b/aws-sdk/aws-sdk-tests.ts @@ -11,6 +11,32 @@ creds = new AWS.Credentials(str, str, str); str = creds.accessKeyId; +/* + * ECS + */ +var ecs:AWS.ECS + +ecs = new AWS.ECS(); +ecs = new AWS.ECS({apiVersion: '2012-11-05'}); + +ecs.describeClusters({ + clusters: ['STRING_VALUE', 'STRING_VALUE'] + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + +ecs.describeTasks({ + cluster: 'STRING_VALUE', + tasks: ['STRING_VALUE', 'STRING_VALUE'] + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + }); + + /* * SQS */ @@ -253,4 +279,107 @@ sqs.setQueueAttributes({ else console.log(data); // successful response }); - \ No newline at end of file + +var dynamoDBDocClient:AWS.DynamoDB.DocumentClient; +dynamoDBDocClient = new AWS.DynamoDB.DocumentClient(); +dynamoDBDocClient = new AWS.DynamoDB.DocumentClient({}); +dynamoDBDocClient.createSet([1, 2, 3], { validate: true }); +dynamoDBDocClient.get( + { + TableName: 'TABLE_NAME', + Key: { userId: 'abc123', email: 'abc123@abc123.com' } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); +dynamoDBDocClient.put( + { + TableName: 'TABLE_NAME', + Item: { + userId: 'abc123', + email: 'abc123@abc123.com', + firstName: 'Matt', + lastName: 'Forrester the ' + new Date().getTime() + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); +dynamoDBDocClient.delete( + { + TableName: 'TABLE_NAME', + Key: { + userId: 'abc123', + email: 'abc123@abc123.com' + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); +dynamoDBDocClient.update( + { + TableName: 'TABLE_NAME', + Key: { + userId: 'abc123', + email: 'abc123@abc123.com' + }, + AttributeUpdates: { + thingsWithWheels: { + Action: 'PUT', + Value: dynamoDBDocClient.createSet( + [ + 'SkateBoard', + 'Skates', + 'Mountain Bike', + 'Evolve Electric Skateboard' + ], + { validate: true } + ) + }, + age: { + Action: 'PUT', + Value: 35 + } + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); +dynamoDBDocClient.scan( + { + TableName: 'TABLE_NAME', + KeyConditions: { + age: { + ComparisonOperator: 'EQ', + AttributeValueList: [35] + } + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); +dynamoDBDocClient.query( + { + TableName: 'TABLE_NAME', + KeyConditions: { + userId: { + ComparisonOperator: 'EQ', + AttributeValueList: ['abc123'] + } + } + }, + function(err, data) { + if (err) console.log(err, err.stack); // an error occurred + else console.log(data); // successful response + } +); diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 64805da137..a13e03fe7a 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -154,11 +154,33 @@ declare module "aws-sdk" { export class ECS { constructor(options?: any); - + /** + * Runs and maintains a desired number of tasks from a specified task definition. If the number of tasks running in a service drops below desiredCount, Amazon ECS spawns another instantiation of the task in the specified cluster. To update an existing service, see UpdateService. + */ createService(params: ecs.CreateServicesParams, callback: (err: any, data: any) => void): void; + /** + * Describes one or more of your clusters. + */ + describeClusters(params: ecs.DescribeClustersParams, callback: (err: any, data: any) => void): void; + /** + * Describes the specified services running in your cluster. + */ describeServices(params: ecs.DescribeServicesParams, callback: (err: any, data: any) => void): void; + /** + * Describes a specified task or tasks. + */ + describeTasks(params: ecs.DescribeTasksParams, callback: (err: any, data: any) => void): void; + /** + * Describes a task definition. You can specify a family and revision to find information about a specific task definition, or you can simply specify the family to find the latest ACTIVE revision in that family. + */ describeTaskDefinition(params: ecs.DescribeTaskDefinitionParams, callback: (err: any, data: any) => void): void; + /** + * Registers a new task definition from the supplied family and containerDefinitions. Optionally, you can add data volumes to your containers with the volumes parameter. For more information about task definition parameters and defaults, see Amazon ECS Task Definitions in the Amazon EC2 Container Service Developer Guide. + */ registerTaskDefinition(params: ecs.RegisterTaskDefinitionParams, callback: (err: any, data: any) => void): void; + /** + * Modifies the desired count, deployment configuration, or task definition used in a service. + */ updateService(params: ecs.UpdateServiceParams, callback: (err: any, data: any) => void): void; } @@ -166,12 +188,106 @@ declare module "aws-sdk" { constructor(options?: any); } + // ========================================================== + export module DynamoDB { + + interface _DDBDC_Generic { + TableName: string; + ExpressionAttributeNames?: string[]; + ReturnConsumedCapacity?: "INDEXES" | "TOTAL" | "NONE"; + } + + type _DDBDC_ComparisonOperator = "EQ" | "NE" | "IN" | "LE" | "LT" | "GE" | "GT" | "BETWEEN" | "NOT_NULL" | "NULL" | "CONTAINS" | "NOT_CONTAINS" | "BEGINS_WITH" + type _DDBDC_Keys = { [someKey: string]: any }; + type _DDBDC_KeyComparison = { + [someKey: string]: { + AttributeValueList: any[]; + ComparisonOperator: _DDBDC_ComparisonOperator; + } + }; + + interface _DDBDC_Reader extends _DDBDC_Generic { + ConsistentRead?: boolean; + ProjectionExpression?: string; + AttributesToGet?: string[]; + } + + interface _DDBDC_Writer extends _DDBDC_Generic { + ExpressionAttributeValues?: _DDBDC_Keys; + ReturnItemCollectionMetrics?: "SIZE" | "NONE"; + ReturnValues?: "NONE" | "ALL_OLD" | "UPDATED_OLD" | "ALL_NEW" | "UPDATED_NEW"; + ConditionExpression?: string; + ConditionalOperator?: "AND" | "OR"; + Expected?: { + [someKey: string]: { + AttributeValueList: any[]; + ComparisonOperator: _DDBDC_ComparisonOperator; + Exists: boolean; + Value: any; + } + } + } + + interface UpdateParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + AttributeUpdates: { + [someKey: string]: { + Action: "PUT" | "ADD" | "DELETE"; + Value: any + } + } + } + + interface QueryParam extends _DDBDC_Reader { + ConditionalOperator?: "AND" | "OR"; + ExclusiveStartKey?: _DDBDC_Keys; + ExpressionAttributeValues?: _DDBDC_Keys; + FilterExpression?: string; + IndexName?: string; + KeyConditionExpression?: string; + KeyConditions?: _DDBDC_KeyComparison; + Limit?: number; + QueryFilter?: _DDBDC_KeyComparison; + ScanIndexForward?: boolean; + Select?: "ALL_ATTRIBUTES" | "ALL_PROJECTED_ATTRIBUTES" | "SPECIFIC_ATTRIBUTES" | "COUNT"; + } + + interface ScanParam extends QueryParam { + Segment?: number; + ScanFilter?: _DDBDC_KeyComparison; + TotalSegments?: number; + } + + interface GetParam extends _DDBDC_Reader { + Key: _DDBDC_Keys; + } + + interface PutParam extends _DDBDC_Writer { + Item: _DDBDC_Keys; + } + + interface DeleteParam extends _DDBDC_Writer { + Key: _DDBDC_Keys; + } + export class DocumentClient { constructor(options?: any); + get(params: GetParam, next: (err: any, data: any) => void): void; + put(params: PutParam, next: (err: any, data: any) => void): void; + delete(params: DeleteParam, next: (err: any, data: any) => void): void; + query(params: QueryParam, next: (err: any, data: any) => void): void; + scan(params: ScanParam, next: (err: any, data: any) => void): void; + update(params: UpdateParam, next: (err: any, data: any) => void): void; + createSet(list: any[], options?: { validate?: boolean }): { values: any[], type: string }; + batchGet(params: any, next: (err: any, data: any) => void): void; + batchWrite(params: any, next: (err: any, data: any) => void): void; } + } +// =========================================================== + export module SQS { export interface SqsOptions { @@ -1125,11 +1241,38 @@ declare module "aws-sdk" { } export interface DescribeServicesParams { + /** + * A list of services to describe. + */ services: string[]; - cluster: string; + /** + * The name of the cluster that hosts the service to describe. If you do not specify a cluster, the default cluster is assumed. + */ + cluster?: string; + } + + export interface DescribeClustersParams { + /** + * A space-separated list of cluster names or full cluster Amazon Resource Name (ARN) entries. If you do not specify a cluster, the default cluster is assumed. + */ + clusters?: string[]; + } + + export interface DescribeTasksParams { + /** + * A space-separated list of task IDs or full Amazon Resource Name (ARN) entries. + */ + tasks: string[]; + /** + * The short name or full Amazon Resource Name (ARN) of the cluster that hosts the task to describe. If you do not specify a cluster, the default cluster is assumed. + */ + cluster?: string; } export interface DescribeTaskDefinitionParams { + /** + * The `family` for the latest `ACTIVE` revision, `family` and `revision` (`family:revision`) for a specific revision in the family, or full Amazon Resource Name (ARN) of the task definition to describe. + */ taskDefinition: string; } diff --git a/backbone.radio/backbone.radio-tests.ts b/backbone.radio/backbone.radio-tests.ts index 295c552af2..764fb65943 100644 --- a/backbone.radio/backbone.radio-tests.ts +++ b/backbone.radio/backbone.radio-tests.ts @@ -101,4 +101,10 @@ function TestGlobalApiAndChannels() { Backbone.Radio.reply('auth', 'authenticate', onStart); Backbone.Radio.request('auth', 'authenticate', 'pelle', 42); -} \ No newline at end of file +} + +import Radio = require('backbone.radio'); +function TestImport() { + var channel: Backbone.Radio.Channel = Radio.channel('channel-name'); + channel.command('show:view'); +} diff --git a/backbone.radio/backbone.radio.d.ts b/backbone.radio/backbone.radio.d.ts index 50895b0275..dd049ec1fe 100644 --- a/backbone.radio/backbone.radio.d.ts +++ b/backbone.radio/backbone.radio.d.ts @@ -90,3 +90,9 @@ declare namespace Backbone { } } } + +declare module 'backbone.radio' { + import Backbone = require('backbone'); + + export = Backbone.Radio; +} diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index 2d40a2a8a4..ef0a10f006 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -316,7 +316,7 @@ declare namespace Backbone { stop(): void; route(route: string, callback: Function): number; checkUrl(e?: any): void; - loadUrl(fragmentOverride: string): boolean; + loadUrl(fragmentOverride?: string): boolean; navigate(fragment: string, options?: any): boolean; static started: boolean; options: any; diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts index 3669a6c4e1..50632712a6 100644 --- a/backbone/backbone-tests.ts +++ b/backbone/backbone-tests.ts @@ -166,6 +166,9 @@ function test_collection() { ////////// Backbone.history.start(); +Backbone.History.started; +Backbone.history.loadUrl(); +Backbone.history.loadUrl('12345'); namespace v1Changes { namespace events { diff --git a/base64-js/base64-js-tests.ts b/base64-js/base64-js-tests.ts new file mode 100644 index 0000000000..6852ddb626 --- /dev/null +++ b/base64-js/base64-js-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as base64js from 'base64-js'; + +const bytes: Uint8Array = base64js.toByteArray('shemp'); +const decoded: string = base64js.fromByteArray(new Uint8Array(0)); diff --git a/base64-js/base64-js.d.ts b/base64-js/base64-js.d.ts new file mode 100644 index 0000000000..cc7d2165c8 --- /dev/null +++ b/base64-js/base64-js.d.ts @@ -0,0 +1,10 @@ +// Type definitions for base64-js v1.1.2 +// Project: https://github.com/beatgammit/base64-js +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base64-js' { + + export function toByteArray(encoded: string): Uint8Array; + export function fromByteArray(bytes: Uint8Array): string; +} diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts new file mode 100644 index 0000000000..54c629d11b --- /dev/null +++ b/bezier-js/bezier-js-tests.ts @@ -0,0 +1,96 @@ +/// + +function test() { + + var bezierjs: typeof BezierJs; + + var bezier = new bezierjs.Bezier([1,2,3,4]); + var cap = new bezierjs.BezierCap([]); + var point: BezierJs.Point = { x: 0, y: 0 }; + var utils = bezier.getUtils(); + var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}}; + var abc: BezierJs.ABC = { A: null, B: null, C: null }; + var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 }; + var bbox: BezierJs.BBox = bezier.bbox(); + var closest: BezierJs.Closest = { mdist: 1, mpos: 0 }; + var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] }; + var minmax: BezierJs.MinMax = { min: 0, max: 0 }; + var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point }; + var pair: BezierJs.Pair = { left: bezier, right: bezier }; + var poly: BezierJs.PolyBezier = bezier.outline(1); + var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 }; + var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox }; + var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] }; + + bezier.arcs(); + bezier.clockwise; + bezier.compute(.5); + bezier.computedirection(); + bezier.curveintersects([bezier], [bezier]); + bezier.derivative(0); + bezier.get(1); + bezier.getLUT()[0].x; + bezier.hull(0); + bezier.extrema(); + bezier.intersects(bezier); + bezier.length(); + bezier.lineIntersects(line); + bezier.normal(0); + bezier.offset(1,2); + bezier.on(point, 0); + bezier.order = 5; + bezier.outlineshapes(1,3); + bezier.overlaps(bezier); + bezier.point(9); + bezier.project(point); + bezier.raise(); + bezier.reduce(); + bezier.scale(4); + bezier.selfintersects(); + bezier.simple(); + bezier.split(0, 1).clockwise; + bezier.split(0.5).left; + bezier.toSVG(); + bezier.update(); + + cap.virtual = true; + + poly.addCurve(bezier); + poly.bbox(); + poly.curve(7); + poly.curves[0]._3d; + poly.length(); + poly.offset(9).points[0].y; + poly.points[0]; + + utils.abcratio(0, 1); + utils.align([point], line); + utils.angle(point, point, point); + utils.approximately(5, 7, .001); + utils.arcfn(1, function(){}); + utils.bboxoverlap(bbox, bbox); + utils.between(0, 0, 1); + utils.closest([point], point); + utils.copy({}); + utils.dist(point, point); + utils.droots([9]); + utils.expandbox(bbox, bbox); + utils.findbbox([bezier]); + utils.getccenter(point, point, point); + utils.getminmax(bezier, 'x', [0]); + utils.length(function(){}); + utils.lerp(1, point, point); + utils.lli(offset, offset); + utils.lli4(point, point, point, point); + utils.lli8(0, 0, 0, 0, 0, 0, 0, 0); + utils.makeline(point, point); + utils.makeshape(bezier, bezier); + utils.map(0, 0, 0, 0, 0); + utils.pairiteration(bezier, bezier); + utils.pointsToString([point]); + utils.projectionratio(0, 0); + utils.roots([point], line); + utils.round(.999, .001); + utils.shapeintersections(shape, bbox, shape, bbox); + +} \ No newline at end of file diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts new file mode 100644 index 0000000000..8256f4ce99 --- /dev/null +++ b/bezier-js/bezier-js.d.ts @@ -0,0 +1,198 @@ +// Type definitions for Bezier.js +// Project: https://github.com/Pomax/bezierjs +// Definitions by: Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module BezierJs { + interface Point { + x: number; + y: number; + z?: number; + } + interface Projection extends Point { + t?: number; + d?: number; + } + interface Inflection { + x: number[]; + y: number[]; + z?: number[]; + values: number[]; + } + interface Offset extends Point { + c: Point; + n: Point; + } + interface Pair { + left: Bezier; + right: Bezier; + } + interface Split extends Pair { + span: Point[]; + _t1?: number; + _t2?: number; + } + interface MinMax { + min: number; + mid?: number; + max: number; + size?: number; + } + interface BBox { + x: MinMax; + y: MinMax; + z?: MinMax; + } + interface Line { + p1: Point; + p2: Point; + } + interface Arc extends Point { + e: number; + r: number; + s: number; + } + interface Shape { + startcap: BezierCap; + forward: Bezier; + back: Bezier; + endcap: BezierCap; + bbox: BBox; + } + interface ABC { + A: Point; + B: Point; + C: Point; + } + interface Closest { + mdist: number; + mpos: number; + } + /** + * Bezier curve constructor. The constructor argument can be one of three things: + * + * 1. array/4 of {x:..., y:..., z:...}, z optional + * 2. numerical array/8 ordered x1,y1,x2,y2,x3,y3,x4,y4 + * 3. numerical array/12 ordered x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4 + * + */ + class Bezier { + clockwise: boolean; + private _linear; + _3d: boolean; + _t1: number; + _t2: number; + _lut: Point[]; + dpoints: Point[][]; + order: number; + points: Point[]; + dims: string[]; + dimlen: number; + constructor(points: Point[]); + constructor(coords: number[]); + constructor(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4?: number, y4?: number); + constructor(p1: Point, p2: Point, p3: Point, p4?: Point); + static fromSVG(svgString: string): Bezier; + static getABC(n: number, S: Point, B: Point, E: Point, t: number): ABC; + static quadraticFromPoints(p1: Point, p2: Point, p3: Point, t: number): Bezier; + static cubicFromPoints(S: Point, B: Point, E: Point, t: number, d1: number): Bezier; + static getUtils(): typeof utils; + getUtils(): typeof utils; + valueOf(): string; + toString(): string; + toSVG(): string; + update(): void; + computedirection(): void; + length(): number; + getLUT(steps?: number): Point[]; + on(point: Point, error: number): number; + project(point: Point): Projection; + get(t: number): Point; + point(idx: number): Point; + compute(t: number): Point; + raise(): Bezier; + derivative(t: number): Point; + inflections(): number[]; + normal(t: number): Point; + private __normal2(t); + private __normal3(t); + private __normal(t); + hull(t: number): Point[]; + split(t1: number): Split; + split(t1: number, t2: number): Bezier; + extrema(): Inflection; + bbox(): BBox; + overlaps(curve: Bezier): boolean; + offset(t: number, d?: number): Offset | Bezier[]; + simple(): boolean; + reduce(): any[]; + scale(d: Function): Bezier; + scale(d: number): Bezier; + outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier; + outlineshapes(d1: number, d2: number): Shape[]; + intersects(curve: Bezier): string[] | number[]; + intersects(curve: Line): string[] | number[]; + lineIntersects(line: Line): number[]; + selfintersects(): string[]; + curveintersects(c1: Bezier[], c2: Bezier[]): string[]; + arcs(errorThreshold?: number): Arc[]; + private _error(pc, np1, s, e); + private _iterate(errorThreshold, circles); + } + class BezierCap extends Bezier { + virtual: boolean; + } +} +declare module BezierJs.utils { + var Tvalues: number[]; + var Cvalues: number[]; + function arcfn(t: number, derivativeFn: Function): number; + function between(v: number, m: number, M: number): boolean; + function approximately(a: number, b: number, precision?: number): boolean; + function length(derivativeFn: Function): number; + function map(v: number, ds: number, de: number, ts: number, te: number): number; + function lerp(r: number, v1: Point, v2: Point): Point; + function pointToString(p: Point): string; + function pointsToString(points: Point[]): string; + function copy(obj: Object): any; + function angle(o: Point, v1: Point, v2: Point): number; + function round(v: number, d: number): number; + function dist(p1: Point, p2: Point): number; + function closest(LUT: Point[], point: Point): Closest; + function abcratio(t: number, n: number): number; + function projectionratio(t: number, n: number): number; + function lli8(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point; + function lli4(p1: Point, p2: Point, p3: Point, p4: Point): Point; + function lli(v1: Offset, v2: Offset): Point; + function makeline(p1: Point, p2: Point): Bezier; + function findbbox(sections: Bezier[]): BBox; + function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][]; + function makeshape(forward: Bezier, back: Bezier): Shape; + function getminmax(curve: Bezier, d: string, list: number[]): MinMax; + function align(points: Point[], line: Line): Point[]; + function roots(points: Point[], line: Line): number[]; + function droots(p: number[]): number[]; + function inflections(points: Point[]): number[]; + function bboxoverlap(b1: BBox, b2: BBox): boolean; + function expandbox(bbox: BBox, _bbox: BBox): void; + function pairiteration(c1: Bezier, c2: Bezier): string[]; + function getccenter(p1: Point, p2: Point, p3: Point): Arc; +} +declare module BezierJs { + /** + * Poly Bezier + * @param {[type]} curves [description] + */ + class PolyBezier { + curves: Bezier[]; + private _3d; + points: Point[]; + constructor(curves: Bezier[]); + valueOf(): string; + toString(): string; + addCurve(curve: Bezier): void; + length(): number; + curve(idx: number): Bezier; + bbox(): BBox; + offset(d: number): PolyBezier; + } +} diff --git a/bingmaps/Microsoft.Maps.d.ts b/bingmaps/Microsoft.Maps.d.ts index c558c7a64b..1e7e464930 100644 --- a/bingmaps/Microsoft.Maps.d.ts +++ b/bingmaps/Microsoft.Maps.d.ts @@ -174,6 +174,7 @@ declare namespace Microsoft.Maps { fixedMapPosition?: boolean; height?: number; inertiaIntensity?: number; + navigationBarMode?: number; showBreadcrumb?: boolean; showCopyright?: boolean; showDashboard?: boolean; @@ -216,6 +217,12 @@ declare namespace Microsoft.Maps { getY(): number; } + export enum NavigationBarMode { + default, + compact, + minified + } + export enum PixelReference { control, page, @@ -301,12 +308,13 @@ declare namespace Microsoft.Maps { getShowPointer(): boolean; getTitle(): string; getTitleAction(): any; - getTitleClickHandler(): () => void; + getTitleClickHandler(): (mouseEvent?: MouseEvent) => void; getVisible(): boolean; getWidth(): number; getZIndex(): number; setHtmlContent(content: string): void; setLocation(location: Location): void; + setMap(map: Map): void; setOptions(options: InfoboxOptions): void; toString(): string; } @@ -329,8 +337,8 @@ declare namespace Microsoft.Maps { showPointer?: boolean; pushpin?: Pushpin; title?: string; - titleAction?: { label?: string; eventHandler: () => void; }; - titleClickHandler?: () => void; + titleAction?: { label?: string; eventHandler: (mouseEvent?: MouseEvent) => void; }; + titleClickHandler?: (mouseEvent?: MouseEvent) => void; typeName?: InfoboxType; visible?: boolean; width?: number; diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 16f639dfaf..f7e691a365 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -33,7 +33,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; /** * parse extended syntax with the qs module. (default: true) */ @@ -65,7 +65,7 @@ declare module "body-parser" { /** * passed to JSON.parse(). */ - receiver?: (key: string, value: any) => any; + reviver?: (key: string, value: any) => any; }): express.RequestHandler; export function raw(options?: { diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 92758e143a..5d6080b99a 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -1,17 +1,52 @@ /// /// +/// +/// import * as Knex from 'knex'; import * as Bookshelf from 'bookshelf'; +import * as assert from 'assert'; +import * as express from 'express'; + + +/** + * The examples/tests below follow Bookshelf documentation chapter after chapter: http://bookshelfjs.org/ + */ + + +/* Installation, see http://bookshelfjs.org/#installation */ var knex = Knex({ - client: 'sqlite3', + client: 'mysql', connection: { - filename: ':memory:', - }, + host : '127.0.0.1', + user : 'your_database_user', + password : 'your_database_password', + database : 'myapp_test', + charset : 'utf8' + } }); -// Examples +var bookshelf = Bookshelf(knex); + +{ + class User extends bookshelf.Model { + get tableName() { return 'users'; } + } + + // In a file named something like bookshelf.js + const dbConfig: Knex.Config = {}; + var knex = Knex(dbConfig); + + // elsewhere, to use the bookshelf client: + var bookshelf = Bookshelf(knex); + + class Post extends bookshelf.Model { + // ... + } +} + +/* Examples, see http://bookshelfjs.org/#examples */ var bookshelf = Bookshelf(knex); @@ -20,14 +55,14 @@ bookshelf.plugin(['virtuals']); class User extends bookshelf.Model { get tableName() { return 'users'; } - messages() : Bookshelf.Collection { - return this.hasMany(Posts); + messages(): Bookshelf.Collection { + return this.hasMany(Post); } } -class Posts extends bookshelf.Model { +class Post extends bookshelf.Model { get tableName() { return 'messages'; } - tags() : Bookshelf.Collection { + tags(): Bookshelf.Collection { return this.belongsToMany(Tag); } } @@ -36,67 +71,1256 @@ class Tag extends bookshelf.Model { get tableName() { return 'tags'; } } -new User({}).where('id', 1).fetch({withRelated: ['posts.tags']}) +new User().where('id', 1).fetch({withRelated: ['posts.tags']}) .then(user => { - console.log(user.related('posts').toJSON()); + const posts = user.related('posts'); + console.log(posts.toJSON()); }).catch(err => { console.error(err); }); +/* Plugins, see http://bookshelfjs.org/#plugins */ -// Associations +/* Support, see http://bookshelfjs.org/#support */ + +/* F.A.Q., see http://bookshelfjs.org/#faq*/ + +/* Associations, see http://bookshelfjs.org/#associations */ + +/* One-to-one, see http://bookshelfjs.org/#one-to-one */ class Book extends bookshelf.Model { get tableName() { return 'books'; } - summary() { + summary(): Summary { return this.hasOne(Summary); } - pages() { - return this.hasMany(Pages); + pages(): Bookshelf.Collection { + return this.hasMany(Page); } - authors() { + authors(): Bookshelf.Collection { return this.belongsToMany(Author); } } class Summary extends bookshelf.Model { get tableName() { return 'summaries'; } - book() : Book { + book(): Book { return this.belongsTo(Book); } } -class Pages extends bookshelf.Model { +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('summaries', table => { + table.increments('id').primary(); + table.string('details'); + table.integer('book_id').unique().references('books.id'); + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('summaries'); +}; + +/* One-to-many, see http://bookshelfjs.org/#one-to-many */ + +class Page extends bookshelf.Model { get tableName() { return 'pages'; } - book() { + book(): Book { return this.belongsTo(Book); } } +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('pages', table => { + table.increments('id').primary(); + table.string('content'); + table.integer('book_id').references('books.id') + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('pages'); +}; + +/* Many-to-many, see http://bookshelfjs.org/#many-to-many */ + class Author extends bookshelf.Model { - get tableName() { return 'author'; } + get tableName() { return 'authors'; } books() { return this.belongsToMany(Book); } } -class Site extends bookshelf.Model { - get tableName() { return 'sites'; } - photo() { - return this.morphOne(Photo, 'imageable'); +exports.up = (knex: Knex) => { + return knex.schema.createTable('books', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('authors', table => { + table.increments('id').primary(); + table.string('name'); + }).createTable('authors_books', table => { + table.integer('author_id').references('authors.id'); + table.integer('book_id').references('books.id'); + }); +}; + +exports.down = (knex: Knex) => { + return knex.schema.dropTable('books') + .dropTable('authors') + .dropTable('authors_books'); +}; + +/* Polymorphic, see http://bookshelfjs.org/#polymorphic */ + +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo(): Photo { + return this.morphOne(Photo, 'imageable'); + } + } + + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos(): Bookshelf.Collection { + return this.morphMany(Photo, 'imageable'); + } + } + + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable(): Photo { + return this.morphTo('imageable', Site, Post); + } } } -class Post extends bookshelf.Model { - get tableName() { return 'posts'; } - photos() { - return this.morphMany(Photo, 'imageable'); +/* Bookshelf, see http://bookshelfjs.org/#section-Bookshelf */ + +/* Construction, see http://bookshelfjs.org/#Bookshelf-subsection-construction */ + +/* new Bookshelf(), see http://bookshelfjs.org/#Bookshelf */ + +/* Members, see http://bookshelfjs.org/#Bookshelf-subsection-members */ + +/* bookshelf.knex, see http://bookshelfjs.org/#Bookshelf-instance-knex */ + +/* Methods, see http://bookshelfjs.org/#Bookshelf-subsection-methods */ + +/* bookshelf.transaction(), see http://bookshelfjs.org/#Bookshelf-instance-transaction */ + +class Library extends bookshelf.Model { + get tableName() { return 'libraries'; } + + relatedBooks(): Bookshelf.Collection { + return > this.related('books'); } } -class Photo extends bookshelf.Model { - get tableName() { return 'photos'; } - imageable() { - return this.morphTo('imageable', Site, Post); +bookshelf.transaction(t => { + return new Library({name: 'Old Books'}) + .save(null, {transacting: t}) + .tap(model => { + return Promise.map([ + {title: 'Canterbury Tales'}, + {title: 'Moby Dick'}, + {title: 'Hamlet'} + ], info => { + // Some validation could take place here. + return new Book(info).save({'shelf_id': model.id}, {transacting: t}); + }); + }); +}).then(library => { + console.log(library.relatedBooks().pluck('title')); +}).catch(err => { + console.error(err); +}); + +/* Type definitions */ + +/* transactionCallback(), see http://bookshelfjs.org/#Bookshelf~transactionCallback */ + +/* Model, see http://bookshelfjs.org/#section-Model */ + +/* Construction, see http://bookshelfjs.org/#Model-subsection-construction */ + +/* new Model(), see http://bookshelfjs.org/#Model */ + +{ + new Book({ + title: "One Thousand and One Nights", + author: "Scheherazade" + }); + + class Book extends bookshelf.Model { + get tableName() { return 'documents'; } + + constructor(json: Object) { + super(json); + + this.on('saving', (model, attrs, options) => { + options.query.where('type', '=', 'book'); + }); + } } } + +/* model.initialize(), see http://bookshelfjs.org/#Model-instance-initialize */ + +/* Static, see http://bookshelfjs.org/#Model-subsection-static */ + +/* Model.collection(), see http://bookshelfjs.org/#Model-static-collection */ + +class Customer extends bookshelf.Model { + get tableName() { return 'customers'; } +} +Customer.collection().fetch().then(collection => { + // ... +}); + +/* Model.count(), see http://bookshelfjs.org/#Model-static-count */ + +/* Model.extend(), see http://bookshelfjs.org/#Model-static-extend */ + +class Account extends bookshelf.Model { + get tableName() { return 'accounts'; } +} +{ + var checkit = require('checkit'); + var bcrypt = Promise.promisifyAll(require('bcrypt')); + + class Customer extends bookshelf.Model { + get tableName() { return 'customers'; } + + initialize() { + this.on('saving', this.validateSave); + } + + validateSave() { + let rules: any; + return checkit(rules).run(this.attributes); + } + + account() { + return this.belongsTo(Account); + } + + static login(email: string, password: string): Promise { + if (!email || !password) throw new Error('Email and password are both required'); + return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(customer => { + return bcrypt.compareAsync(password, customer.get('password')) + .then((res: boolean) => { + if (!res) throw new Error('Invalid password'); + }); + }); + } + } + + const email = 'email'; + const password = 'password'; + Customer.login(email, password) + .then(customer => { + console.log(customer.omit('password')); + }).catch(Customer.NotFoundError, () => { + console.log({error: email + ' not found'}); + }).catch(err => { + console.error(err); + }); +} + +/* Model.fetchAll(), see http://bookshelfjs.org/#Model-static-fetchAll */ + +/* Model.forge(), see http://bookshelfjs.org/#Model-static-forge */ + +/* Members, see http://bookshelfjs.org/#Model-subsection-members */ + +/* model.hasTimestamps, see http://bookshelfjs.org/#Model-instance-hasTimestamps */ + +/* model.idAttribute, see http://bookshelfjs.org/#Model-instance-idAttribute */ + +/* model.tableName, see http://bookshelfjs.org/#Model-instance-tableName */ + +class Television extends bookshelf.Model { + get tableName() { return 'televisions'; } +} + +/* Methods, see http://bookshelfjs.org/#Model-subsection-methods */ + +/* model.belongsTo(), see http://bookshelfjs.org/#Model-instance-belongsTo */ + +{ + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + author(): Author { + return this.belongsTo(Author); + } + } + + // select * from `books` where id = 1 + // select * from `authors` where id = book.author_id + new Book().where({id: 1}).fetch({withRelated: ['author']}).then(book => { + console.log(JSON.stringify(book.related('author'))); + }); +} + +/* model.belongsToMany(), see http://bookshelfjs.org/#Model-instance-belongsToMany */ + +{ + class Account extends bookshelf.Model { + get tableName() { return 'accounts'; } + } + + class User extends bookshelf.Model { + get tableName() { return 'users'; } + allAccounts() { + return this.belongsToMany(Account); + } + adminAccounts() { + return this.belongsToMany(Account).query({where: {access: 'admin'}}); + } + viewAccounts() { + return this.belongsToMany(Account).query({where: {access: 'readonly'}}); + } + } + + class Doctor extends bookshelf.Model { + patients(): Bookshelf.Collection { + return this.belongsToMany(Patient).through(Appointment); + } + } + + class Appointment extends bookshelf.Model { + patient(): Patient { + return this.belongsTo(Patient); + } + doctor(): Doctor { + return this.belongsTo(Doctor); + } + } + + class Patient extends bookshelf.Model { + doctors(): Bookshelf.Collection { + return this.belongsToMany(Doctor).through(Appointment); + } + } +} + +/* model.clear(), see http://bookshelfjs.org/#Model-instance-clear */ + +/* model.clone(), see http://bookshelfjs.org/#Model-instance-clone */ + +/* model.count(), see http://bookshelfjs.org/#Model-instance-count */ + +class Duck extends bookshelf.Model { +} +new Duck().where('color', 'blue').count('name') + .then(count => { + //... + }); + +/* model.destroy(), see http://bookshelfjs.org/#Model-instance-destroy */ +new User({id: 1}) + .destroy() + .then(model => { + // ... + }); + +/* model.escape(), see http://bookshelfjs.org/#Model-instance-escape */ + +/* model.fetch(), see http://bookshelfjs.org/#Model-instance-fetch */ + +// select * from `books` where `ISBN-13` = '9780440180296' +new Book({'ISBN-13': '9780440180296'}) + .fetch() + .then(model => { + // outputs 'Slaughterhouse Five' + console.log(model.get('title')); + }); +{ + class Edition extends bookshelf.Model {} + class Chapter extends bookshelf.Model {} + class Genre extends bookshelf.Model {} + + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + editions() { + return this.hasMany(Edition); + } + chapters() { + return this.hasMany(Chapter); + } + genre() { + return this.belongsTo(Genre); + } + } + + new Book({'ISBN-13': '9780440180296'}).fetch({ + withRelated: [ + 'genre', 'editions', + { chapters: query => query.orderBy('chapter_number') } + ] + }).then(book => { + console.log(book.related('genre').toJSON()); + console.log(book.related('editions').toJSON()); + console.log(book.toJSON()); + }); +} + +/* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */ + +/* model.format(), see http://bookshelfjs.org/#Model-instance-format */ + +/* model.get(), see http://bookshelfjs.org/#Model-instance-get */ +const note = new bookshelf.Model(); +note.get("title"); + +/* model.has(), see http://bookshelfjs.org/#Model-instance-has */ + +/* model.hasChanged(), see http://bookshelfjs.org/#Model-instance-hasChanged */ + +/* model.hasMany(), see http://bookshelfjs.org/#Model-instance-hasMany */ + +{ + class Author extends bookshelf.Model { + get tableName() { return 'authors'; } + + books() { + return this.hasMany(Book); + } + } + + // select * from `authors` where id = 1 + // select * from `books` where author_id = 1 + new Author().where({id: 1}).fetch({withRelated: ['books']}).then(author => { + console.log(JSON.stringify(author.related('books'))); + }); +} + +/* model.hasOne(), see http://bookshelfjs.org/#Model-instance-hasOne */ + +{ + class Record extends bookshelf.Model { + get tableName() { return 'health_records'; } + } + + class Patient extends bookshelf.Model { + get tableName() { return 'patients'; } + record(): Record { + return this.hasOne(Record); + } + } + + // select * from `health_records` where `patient_id` = 1; + const record = new Patient({id: 1}).related('record'); + record.fetch().then(model => { + // ... + }); + + // alternatively, if you don't need the relation loaded on the patient's relations hash: + new Patient({id: 1}).record().fetch().then(model => { + // ... + }); +} + +/* model.isNew(), see http://bookshelfjs.org/#Model-instance-isNew */ + +var modelA = new bookshelf.Model(); +modelA.isNew(); // true + +var modelB = new bookshelf.Model({id: 1}); +modelB.isNew(); // false + +/* model.load(), see http://bookshelfjs.org/#Model-instance-load */ +class Posts extends bookshelf.Collection {} +new Posts().fetch().then(collection => { + collection.at(0) + .load(['author', 'content', 'comments.tags']) + .then(model => { + JSON.stringify(model); + }); +}); +/* +{ + title: 'post title', + author: {...}, + content: {...}, + comments: [ + {tags: [...]}, {tags: [...]} + ] +} +*/ + +/* model.morphMany(), see http://bookshelfjs.org/#Model-instance-morphMany */ + +class Photo extends bookshelf.Model {} +{ + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos() { + return this.morphMany(Photo, 'imageable'); + } + } +} +{ + class Post extends bookshelf.Model { + get tableName() { return 'posts'; } + photos() { + return this.morphMany(Photo, 'imageable', ["ImageableType", "ImageableId"]); + } + } +} + +/* model.morphOne(), see http://bookshelfjs.org/#Model-instance-morphOne */ + +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo() { + return this.morphOne(Photo, 'imageable'); + } + } +} +{ + class Site extends bookshelf.Model { + get tableName() { return 'sites'; } + photo() { + return this.morphOne(Photo, 'imageable', ["ImageableType", "ImageableId"]); + } + } +} + +/* model.morphTo(), see http://bookshelfjs.org/#Model-instance-morphTo */ + +class Site extends bookshelf.Model {} +{ + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable() { + return this.morphTo('imageable', Site, Post); + } + } +} +{ + class Photo extends bookshelf.Model { + get tableName() { return 'photos'; } + imageable() { + return this.morphTo('imageable', ["ImageableType", "ImageableId"], Site, Post); + } + } +} + +/* model.off(), see http://bookshelfjs.org/#Model-instance-off */ + +const customer = new Customer(); +const ship = new bookshelf.Model(); +customer.off('fetched fetching'); +ship.off(); // This will remove all event listeners + +/* model.on(), see http://bookshelfjs.org/#Model-instance-on */ + +customer.on('fetching', (model, columns) => { + // Do something before the data is fetched from the database +}); + +/* model.once(), see http://bookshelfjs.org/#Model-instance-once */ + +/* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */ + +// Example of a "parse" to convert snake_case to camelCase, using `underscore.string` +customer.parse = attrs => { + return _.reduce(<_.Dictionary> attrs, (memo, val, key) => { + (<_.Dictionary> memo)[_.camelCase(key)] = val; + return memo; + }, {}); +}; + +/* model.previous(), see http://bookshelfjs.org/#Model-instance-previous */ + +/* model.previousAttributes(), see http://bookshelfjs.org/#Model-instance-previousAttributes */ + +/* model.query(), see http://bookshelfjs.org/#Model-instance-query */ + +const model = new bookshelf.Model(); +model + .query('where', 'other_id', '=', '5') + .fetch() + .then(model => { + // ... + }); + +model + .query({where: {other_id: '5'}, orWhere: {key: 'value'}}) + .fetch() + .then(model => { + // ... + }); + +model.query(qb => { + qb.where('other_person', 'LIKE', '%Demo').orWhere('other_id', '>', 10); +}).fetch() + .then(model => { + // ... + }); + +let qb = model.query(); +qb.where({id: 1}).select().then(resp => { + // ... +}); + +/* model.refresh(), see http://bookshelfjs.org/#Model-instance-refresh */ + +/* model.related(), see http://bookshelfjs.org/#Model-instance-related */ +class Trip extends bookshelf.Model {} +class Trips extends bookshelf.Collection {} +new Photo({id: 1}).fetch({ + withRelated: ['account'] +}).then(photo => { + if (photo) { + var account = photo.related('account'); + if (account.id) { + return ( account.related('trips')).fetch(); + } + } +}); + +/* model.resetQuery(), see http://bookshelfjs.org/#Model-instance-resetQuery */ + +/* model.save(), see http://bookshelfjs.org/#Model-instance-save */ + +new Post({name: 'New Article'}).save().then(model => { + // ... +}); +// update authors set "bio" = 'Short user bio' where "id" = 1 +new Author({id: 1, first_name: 'User'}) + .save({bio: 'Short user bio'}, {patch: true}) + .then(model => { + // ... + }); + +// Save with no arguments +bookshelf.Model.forge({id: 5, firstName: "John", lastName: "Smith"}).save().then(() => { + //... +}); + +// Or add attributes during save +bookshelf.Model.forge({id: 5}).save({firstName: "John", lastName: "Smith"}).then(() => { + //... +}); + +// Or, if you prefer, for a single attribute +bookshelf.Model.forge({id: 5}).save('name', 'John Smith').then(() => { + //... +}); + +/* model.serialize(), see http://bookshelfjs.org/#Model-instance-serialize */ + +var artist = new bookshelf.Model({ + firstName: "Wassily", + lastName: "Kandinsky" +}); + +artist.set({birthday: "December 16, 1866"}); + +console.log(JSON.stringify(artist)); +// {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"} + +/* model.set(), see http://bookshelfjs.org/#Model-instance-set */ + +customer.set({first_name: "Joe", last_name: "Customer"}); +customer.set("telephone", "555-555-1212"); + +/* model.through(), see http://bookshelfjs.org/#Model-instance-through */ + +{ + class Book extends bookshelf.Model { + get tableName() { return 'books'; } + + // Find all paragraphs associated with this book, by + // passing through the "Chapter" model. + paragraphs(): Paragraphs { + return this.hasMany(Paragraph).through(Chapter); + } + + chapters(): Chapters { + return this.hasMany(Chapter); + } + } + + class Chapter extends bookshelf.Model { + get tableName() { return 'chapters'; } + + paragraphs(): Bookshelf.Collection { + return this.hasMany(Paragraph); + } + } + + class Chapters extends bookshelf.Collection { + } + + class Paragraph extends bookshelf.Model { + get tableName() { return 'paragraphs'; } + + chapter(): Chapter { + return this.belongsTo(Chapter); + } + + // A reverse relation, where we can get the book from the chapter. + book(): Book { + return this.belongsTo(Book).through(Chapter); + } + } + + class Paragraphs extends bookshelf.Collection { + } +} + +/* model.timestamp(), see http://bookshelfjs.org/#Model-instance-timestamp */ + +/* model.toJSON(), see http://bookshelfjs.org/#Model-instance-toJSON */ + +// TODO No example provided on Bookshelf website + +{ + interface UserJson { + name: string; + } + + class User extends bookshelf.Model { + get tableName() { return 'users'; } + + toJSON(): UserJson { + return super.toJSON(); + } + + fetchAll(): Promise { + return super.fetchAll(); + } + } + + class Users extends bookshelf.Collection { + toJSON(): UserJson[] { + return super.toJSON(); + } + } + + new User({id: 1}).fetch().then(user => { + const userJson = user.toJSON(); + console.log('User name:', userJson.name); + }); + + new User({name: 'John'}).fetchAll().then(users => { + const usersJson = users.toJSON(); + console.log('First user name:', usersJson[0].name); + }); +} + +/* model.trigger(), see http://bookshelfjs.org/#Model-instance-trigger */ + +ship.trigger('fetched'); + +/* model.triggerThen(), see http://bookshelfjs.org/#Model-instance-triggerThen */ + +/* model.unset(), see http://bookshelfjs.org/#Model-instance-unset */ + +/* model.where(), see http://bookshelfjs.org/#Model-instance-where */ + +model.where('favorite_color', '<>', 'green').fetch().then(() => { + //... +}); +// or +model.where('favorite_color', 'red').fetch().then(() => { + //... +}); +// or +model.where({favorite_color: 'red', shoe_size: 12}).fetch().then(() => { + //... +}); + +/* Lodash methods, see http://bookshelfjs.org/#Model-subsection-lodash-methods */ + +/* invert(), see http://lodash.com/docs/#invert */ + +/* keys(), see http://lodash.com/docs/#keys */ + +/* omit(), see http://lodash.com/docs/#omit */ + +/* pairs(), see http://lodash.com/docs/#pairs */ + +/* pick(), see http://lodash.com/docs/#pick */ + +/* values(), see http://lodash.com/docs/#values */ + +/* Events, see http://bookshelfjs.org/#Model-subsection-events */ + +/* model.on("created"), see http://bookshelfjs.org/#Model-event-created */ + +/* model.on("creating"), see http://bookshelfjs.org/#Model-event-creating */ + +/* model.on("destroyed"), see http://bookshelfjs.org/#Model-event-destroyed */ + +/* model.on("destroying"), see http://bookshelfjs.org/#Model-event-destroying */ + +/* model.on("fetched"), see http://bookshelfjs.org/#Model-event-fetched */ + +/* model.on("fetching"), see http://bookshelfjs.org/#Model-event-fetching */ + +/* model.on("saved"), see http://bookshelfjs.org/#Model-event-saved */ + +/* model.on("saving"), see http://bookshelfjs.org/#Model-event-saving */ + +/* model.on("updated"), see http://bookshelfjs.org/#Model-event-updated */ + +/* model.on("updating"), see http://bookshelfjs.org/#Model-event-updating */ + +/* new Model.NoRowsDeletedError(), see http://bookshelfjs.org/#Model-static-NoRowsDeletedError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).destroy({require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NoRowsDeletedError, () => { + console.log('User not found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* new Model.NoRowsUpdatedError(), see http://bookshelfjs.org/#Model-static-NoRowsUpdatedError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).save({}, {patch: true, require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NoRowsUpdatedError, () => { + console.log('User not updated'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* new Model.NotFoundError(), see http://bookshelfjs.org/#Model-static-NotFoundError */ + +// TODO No example provided on Bookshelf website + +new User({id: 1}).fetch({require: true}) +.then(user => { + console.log(user.toJSON()); +}) +.catch(User.NotFoundError, () => { + console.log('User not found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* Collection, see http://bookshelfjs.org/#section-Collection */ + +/* Construction, see http://bookshelfjs.org/#Collection-subsection-construction */ + +/* new Collection(), see http://bookshelfjs.org/#Collection */ + +class Tab extends bookshelf.Model { +} +const tab1 = new Tab(); +const tab2 = new Tab(); +const tab3 = new Tab(); +class TabSet extends bookshelf.Collection { +} +let tabs = new TabSet([tab1, tab2, tab3]); + +/* collection.initialize(), see http://bookshelfjs.org/#Collection-instance-initialize */ + +/* Static, see http://bookshelfjs.org/#Collection-subsection-static */ + +/* Collection.extend(), see http://bookshelfjs.org/#Collection-static-extend */ + +/* Collection.forge(), see http://bookshelfjs.org/#Collection-static-forge */ + +class Accounts extends bookshelf.Collection { + model: Account +} + +var accounts = Accounts.forge([ + {name: 'Person1'}, + {name: 'Person2'} +]); + +Promise.all(accounts.invoke('save')).then(() => { + // collection models should now be saved... +}); + +/* Methods, see http://bookshelfjs.org/#Collection-subsection-methods */ + +/* collection.add(), see http://bookshelfjs.org/#Collection-instance-add */ + +const ships = new bookshelf.Collection; + +ships.add([ + {name: "Flying Dutchman"}, + {name: "Black Pearl"} +]); + +/* collection.at(), see http://bookshelfjs.org/#Collection-instance-at */ + +/* collection.attach(), see http://bookshelfjs.org/#Collection-instance-attach */ + +{ + class Admin extends bookshelf.Model { + } + class Site extends bookshelf.Model { + admins() { + return this.hasMany(Admin); + } + } + var admin1 = new Admin({username: 'user1', password: 'test'}); + var admin2 = new Admin({username: 'user2', password: 'test'}); + + Promise.all([admin1.save(), admin2.save()]) + .then(() => { + return Promise.all([ + new Site({id: 1}).admins().attach([admin1, admin2]), + new Site({id: 2}).admins().attach(admin2) + ]); + }); +} + +/* collection.clone(), see http://bookshelfjs.org/#Collection-instance-clone */ + +/* collection.count(), see http://bookshelfjs.org/#Collection-instance-count */ + +class Shareholder extends bookshelf.Model {} +class Company extends bookshelf.Model { + shareholders() { + return this.hasMany(Shareholder); + } +} + +// select count(*) from shareholders where company_id = 1 and share > 0.1; +Company.forge({id:1}) + .shareholders() + .query('where', 'share', '>', '0.1') + .count() + .then(count => { + assert(count === 3); + }); + +/* collection.create(), see http://bookshelfjs.org/#Collection-instance-create */ + +class Student extends bookshelf.Model {} + +function get(req: express.Request, res: express.Response) { + // FIXME Support proposed ES Rest/Spread properties https://github.com/Microsoft/TypeScript/issues/2103 + //const { courses, ...attributes } = req.body; + const { courses, attributes } = req.body; + + Student.forge(attributes).save().tap(student => + Promise.map(courses, course => (> student.related('courses')).create(course)) + ).then(student => + res.status(200).send(student) + ).catch(error => + res.status(500).send(error.message) + ); +} + +/* collection.detach(), see http://bookshelfjs.org/#Collection-instance-detach */ + +/* collection.fetch(), see http://bookshelfjs.org/#Collection-instance-fetch */ + +/* collection.fetchOne(), see http://bookshelfjs.org/#Collection-instance-fetchOne */ + +{ + class Site extends bookshelf.Model { + authors() { + return this.hasMany(Author); + } + } + + // select * from authors where site_id = 1 and id = 2 limit 1; + new Site({id: 1}) + .authors() + .query({where: {id: 2}}) + .fetchOne() + .then(model => { + // ... + }); +} + +/* collection.findWhere(), see http://bookshelfjs.org/#Collection-instance-findWhere */ + +/* collection.get(), see http://bookshelfjs.org/#Collection-instance-get */ + +const library = new bookshelf.Collection(); +const book = library.get(110); + +/* collection.invokeThen(), see http://bookshelfjs.org/#Collection-instance-invokeThen */ + +const options = {}; +const collection = new bookshelf.Collection(); +collection.invokeThen('save', null, options).then(() => { + // ... all models in the collection have been saved +}); + +collection.invokeThen('destroy', options).then(() => { + // ... all models in the collection have been destroyed +}); + +/* collection.load(), see http://bookshelfjs.org/#Collection-instance-load */ + +/* collection.off(), see http://bookshelfjs.org/#Collection-instance-off */ + +ships.off('fetched') // Remove the 'fetched' event listener + +/* collection.on(), see http://bookshelfjs.org/#Collection-instance-on */ + +ships.on('fetched', (collection, response) => { + // Do something after the data has been fetched from the database +}) + +/* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */ + +/* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */ + +/* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */ + +/* collection.pop(), see http://bookshelfjs.org/#Collection-instance-pop */ + +/* collection.push(), see http://bookshelfjs.org/#Collection-instance-push */ + +/* collection.query(), see http://bookshelfjs.org/#Collection-instance-query */ + +{ + let qb = collection.query(); + qb.where({id: 1}).select().then(resp => { + // ... + }); + + collection.query(qb => { + qb.where('id', '>', 5).andWhere('first_name', '=', 'Test'); + }).fetch() + .then(collection => { + // ... + }); + + collection + .query('where', 'other_id', '=', '5') + .fetch() + .then(collection => { + // ... + }); +} + +/* collection.reduceThen(), see http://bookshelfjs.org/#Collection-instance-reduceThen */ + +/* collection.remove(), see http://bookshelfjs.org/#Collection-instance-remove */ + +/* collection.reset(), see http://bookshelfjs.org/#Collection-instance-reset */ + +/* collection.resetQuery(), see http://bookshelfjs.org/#Collection-instance-resetQuery */ + +/* collection.serialize(), see http://bookshelfjs.org/#Collection-instance-serialize */ + +/* collection.set(), see http://bookshelfjs.org/#Collection-instance-set */ + +class BandMember extends bookshelf.Model {} +const eddie = new BandMember(); +const alex = new BandMember(); +const stone = new BandMember(); +const roth = new BandMember(); +const hagar = new BandMember(); +var vanHalen = new bookshelf.Collection([eddie, alex, stone, roth]); +vanHalen.set([eddie, alex, stone, hagar]); + +/* collection.shift(), see http://bookshelfjs.org/#Collection-instance-shift */ + +/* collection.slice(), see http://bookshelfjs.org/#Collection-instance-slice */ + +/* collection.through(), see http://bookshelfjs.org/#Collection-instance-through */ + +/* collection.toJSON(), see http://bookshelfjs.org/#Collection-instance-toJSON */ + +/* collection.trigger(), see http://bookshelfjs.org/#Collection-instance-trigger */ + +ships.trigger('fetched'); + +/* collection.triggerThen(), see http://bookshelfjs.org/#Collection-instance-triggerThen */ + +/* collection.unshift(), see http://bookshelfjs.org/#Collection-instance-unshift */ + +/* collection.updatePivot(), see http://bookshelfjs.org/#Collection-instance-updatePivot */ + +/* collection.where(), see http://bookshelfjs.org/#Collection-instance-where */ + +/* collection.withPivot(), see http://bookshelfjs.org/#Collection-instance-withPivot */ + +{ + class Comment extends bookshelf.Model {} + class Tag extends bookshelf.Model { + comments() { + return this.belongsToMany(Comment).withPivot(['created_at', 'order']); + } + } +} + +/* Lodash methods, see http://bookshelfjs.org/#Collection-subsection-lodash-methods */ + +/* all(), see http://lodash.com/docs/#all */ + +/* any(), see http://lodash.com/docs/#any */ + +/* chain(), see http://lodash.com/docs/#chain */ + +/* collect(), see http://lodash.com/docs/#collect */ + +/* contains(), see http://lodash.com/docs/#contains */ + +/* countBy(), see http://lodash.com/docs/#countBy */ + +/* detect(), see http://lodash.com/docs/#detect */ + +/* difference(), see http://lodash.com/docs/#difference */ + +/* drop(), see http://lodash.com/docs/#drop */ + +/* each(), see http://lodash.com/docs/#each */ + +/* every(), see http://lodash.com/docs/#every */ + +/* filter(), see http://lodash.com/docs/#filter */ + +/* find(), see http://lodash.com/docs/#find */ + +/* first(), see http://lodash.com/docs/#first */ + +/* foldl(), see http://lodash.com/docs/#foldl */ + +/* foldr(), see http://lodash.com/docs/#foldr */ + +/* forEach(), see http://lodash.com/docs/#forEach */ + +/* groupBy(), see http://lodash.com/docs/#groupBy */ + +/* head(), see http://lodash.com/docs/#head */ + +/* include(), see http://lodash.com/docs/#include */ + +/* indexOf(), see http://lodash.com/docs/#indexOf */ + +/* initial(), see http://lodash.com/docs/#initial */ + +/* inject(), see http://lodash.com/docs/#inject */ + +/* invoke(), see http://lodash.com/docs/#invoke */ + +/* isEmpty(), see http://lodash.com/docs/#isEmpty */ + +/* last(), see http://lodash.com/docs/#last */ + +/* lastIndexOf(), see http://lodash.com/docs/#lastIndexOf */ + +/* map(), see http://lodash.com/docs/#map */ + +// TODO No example provided on Bookshelf website + +{ + class Author extends bookshelf.Model { + get tableName() { return 'author'; } + books() { + return this.belongsToMany(Book); + } + relatedBooks() { + return > this.related('books'); + } + } + new Author({id: 1}).fetch({require: true, withRelated: ['books']}) + .then(author => { + const books = author.relatedBooks(); + const booksJson = books.map(book => book.toJSON()); + }); + + class AuthorOutput { + constructor(bookJson: Object) {} + } + + new Author({id: 1}).fetch({require: true, withRelated: ['books']}) + .then(author => { + const books = author.relatedBooks(); + const booksOutput = books.map(book => new AuthorOutput(book.toJSON())); + }); +} + +/* max(), see http://lodash.com/docs/#max */ + +/* min(), see http://lodash.com/docs/#min */ + +/* reduce(), see http://lodash.com/docs/#reduce */ + +/* reduceRight(), see http://lodash.com/docs/#reduceRight */ + +/* reject(), see http://lodash.com/docs/#reject */ + +/* rest(), see http://lodash.com/docs/#rest */ + +/* select(), see http://lodash.com/docs/#select */ + +/* shuffle(), see http://lodash.com/docs/#shuffle */ + +/* size(), see http://lodash.com/docs/#size */ + +/* some(), see http://lodash.com/docs/#some */ + +/* sortBy(), see http://lodash.com/docs/#sortBy */ + +/* tail(), see http://lodash.com/docs/#tail */ + +/* take(), see http://lodash.com/docs/#take */ + +/* toArray(), see http://lodash.com/docs/#toArray */ + +/* without(), see http://lodash.com/docs/#without */ + +/* Events, see http://bookshelfjs.org/#Collection-subsection-events */ + +/* collection.on("fetched"), see http://bookshelfjs.org/#Collection-event-fetched */ + +/* new Collection.EmptyError(), see http://bookshelfjs.org/#Collection-static-EmptyError */ + +// TODO No example provided on Bookshelf website + +class Users extends bookshelf.Collection { +} +new User({name: 'John'}).fetchAll({require: true}) +.then(users => { + console.log(users.toJSON()); +}) +.catch(Users.EmptyError, () => { + console.log('No user found'); +}) +.catch(error => { + console.log('Internal error:', error); +}); + +/* Events, see http://bookshelfjs.org/#section-Events */ + +/* new Events(), see http://bookshelfjs.org/#Events */ + +/* events.off(), see http://bookshelfjs.org/#Events-instance-off */ + +/* events.on(), see http://bookshelfjs.org/#Events-instance-on */ + +/* events.once(), see http://bookshelfjs.org/#Events-instance-once */ + +/* events.trigger(), see http://bookshelfjs.org/#Events-instance-trigger */ + +/* events.triggerThen(), see http://bookshelfjs.org/#Events-instance-triggerThen */ diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index cf70220840..0ca3a1ebcd 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -6,23 +6,25 @@ /// /// /// +/// declare module 'bookshelf' { - import knex = require('knex'); - import Promise = require('bluebird'); - import Lodash = require('lodash'); + import * as Knex from 'knex'; + import * as Promise from 'bluebird'; + import * as Lodash from 'lodash'; + import * as createError from 'create-error'; interface Bookshelf extends Bookshelf.Events { VERSION : string; - knex : knex; + knex : Knex; Model : typeof Bookshelf.Model; Collection : typeof Bookshelf.Collection; plugin(name: string | string[] | Function, options?: any) : Bookshelf; - transaction(callback : (transaction : knex.Transaction) => T) : Promise; + transaction(callback : (transaction : Knex.Transaction) => T) : T; } - function Bookshelf(knex : knex) : Bookshelf; + function Bookshelf(knex : Knex) : Bookshelf; namespace Bookshelf { abstract class Events { @@ -44,6 +46,13 @@ declare module 'bookshelf' { /** If overriding, must use a getter instead of a plain property. */ idAttribute : string; + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L178 + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L213 + id : any; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L28 + attributes : any; + constructor(attributes? : any, options? : ModelOptions); clear() : T; @@ -54,7 +63,7 @@ declare module 'bookshelf' { has(attribute : string) : boolean; hasChanged(attribute? : string) : boolean; isNew() : boolean; - parse(response : any) : any; + parse(response : Object) : Object; previousAttributes() : any; previous(attribute : string) : any; related>(relation : string) : R | Collection; @@ -88,7 +97,7 @@ declare module 'bookshelf' { belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R; belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection; count(column? : string, options? : SyncOptions) : Promise; - destroy(options? : SyncOptions) : Promise; + destroy(options? : DestroyOptions) : Promise; fetch(options? : FetchOptions) : Promise; fetchAll(options? : FetchAllOptions) : Promise>; hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection; @@ -98,20 +107,35 @@ declare module 'bookshelf' { morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R; morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T; morphTo(name : string, ...target : typeof Model[]) : T; + + // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) + query() : Knex.QueryBuilder; + query(callback : (qb : Knex.QueryBuilder) => void) : T; query(...query : string[]) : T; query(query : {[key : string] : any}) : T; - query(callback : (qb : knex.QueryBuilder) => void) : T; - query() : knex.QueryBuilder; + refresh(options? : FetchOptions) : Promise; resetQuery() : T; - save(key? : string, val? : string, options? : SaveOptions) : Promise; + save(key? : string, val? : any, options? : SaveOptions) : Promise; save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R; where(properties : {[key : string] : any}) : T; where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/errors.js + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/model.js#L1280 + static NotFoundError: createError.Error; + static NoRowsUpdatedError: createError.Error; + static NoRowsDeletedError: createError.Error; } abstract class CollectionBase> extends Events { + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L573 + length : number; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L21 + constructor(models? : T[], options? : CollectionOptions); + add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; at(index : number) : T; clone() : Collection; @@ -127,11 +151,11 @@ declare module 'bookshelf' { remove(model : T, options? : EventOptions) : T; remove(model : T[], options? : EventOptions) : T[]; reset(model : any[], options? : CollectionAddOptions) : T[]; - serialize(options? : SerializeOptions) : any; + serialize(options? : SerializeOptions) : any[]; set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection; shift(options? : EventOptions) : void; slice(begin? : number, end? : number) : void; - toJSON(options? : SerializeOptions) : any; + toJSON(options? : SerializeOptions) : any[]; unshift(model : any, options? : CollectionAddOptions) : void; where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; @@ -177,8 +201,13 @@ declare module 'bookshelf' { keys() : string[]; last() : T; lastIndexOf(value : any, fromIndex? : number) : number; - map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[]; - map(predicate? : R) : T[]; + + // See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1ec3d51/lodash/lodash-3.10.d.ts#L7119 + // See https://github.com/Microsoft/TypeScript/blob/v1.8.10/lib/lib.core.es7.d.ts#L1122 + map(predicate? : Lodash.ListIterator|string, thisArg? : any) : U[]; + map(predicate? : Lodash.DictionaryIterator|string, thisArg? : any) : U[]; + map(predicate? : string) : U[]; + max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; max(predicate? : R) : T; min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T; @@ -208,20 +237,27 @@ declare module 'bookshelf' { /** @deprecated should use `new` objects instead. */ static forge(attributes? : any, options? : ModelOptions) : T; - attach(ids : any[], options? : SyncOptions) : Promise>; + attach(ids : any|any[], options? : SyncOptions) : Promise>; count(column? : string, options? : SyncOptions) : Promise; create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; detach(ids : any[], options? : SyncOptions) : Promise; + detach(options? : SyncOptions) : Promise; fetchOne(options? : CollectionFetchOneOptions) : Promise; load(relations : string|string[], options? : SyncOptions) : Promise>; + + // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) + query() : Knex.QueryBuilder; + query(callback : (qb : Knex.QueryBuilder) => void) : Collection; query(...query : string[]) : Collection; query(query : {[key : string] : any}) : Collection; - query(callback : (qb : knex.QueryBuilder) => void) : Collection; - query() : knex.QueryBuilder; + resetQuery() : Collection; - through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection; + through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : Collection; updatePivot(attributes : any, options? : PivotOptions) : Promise; withPivot(columns : string[]) : Collection; + + // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/collection.js#L389 + static EmptyError: createError.Error; } interface ModelOptions { @@ -231,13 +267,17 @@ declare module 'bookshelf' { } interface LoadOptions extends SyncOptions { - withRelated: string|any|any[]; + withRelated : (string|WithRelatedQuery)[]; } interface FetchOptions extends SyncOptions { require? : boolean; columns? : string|string[]; - withRelated? : string|any|any[]; + withRelated? : (string|WithRelatedQuery)[]; + } + + interface WithRelatedQuery { + [index : string] : (query : Knex.QueryBuilder) => Knex.QueryBuilder; } interface FetchAllOptions extends SyncOptions { @@ -251,6 +291,10 @@ declare module 'bookshelf' { require? : boolean; } + interface DestroyOptions extends SyncOptions { + require? : boolean; + } + interface SerializeOptions { shallow? : boolean; omitPivot? : boolean; @@ -265,7 +309,7 @@ declare module 'bookshelf' { } interface SyncOptions { - transacting? : knex.Transaction; + transacting? : Knex.Transaction; debug? : boolean; } diff --git a/bootstrap.datepicker/bootstrap.datepicker.d.ts b/bootstrap.datepicker/bootstrap.datepicker.d.ts index 686cc6b423..f60a0ffed6 100644 --- a/bootstrap.datepicker/bootstrap.datepicker.d.ts +++ b/bootstrap.datepicker/bootstrap.datepicker.d.ts @@ -15,7 +15,7 @@ * http://bootstrap-datepicker.readthedocs.org/en/release/options.html */ interface DatepickerOptions { - format?: string; + format?: string | DatepickerCustomFormatOptions; weekStart?: number; startDate?: any; endDate?: any; @@ -38,6 +38,11 @@ interface DatepickerOptions { assumeNearbyYear?: any; } +interface DatepickerCustomFormatOptions { + toDisplay?(date: string, format: any, language: any): string; + toValue?(date: string, format: any, language: any): Date; +} + interface DatepickerEventObject extends JQueryEventObject { date: Date; format(format?: string): string; diff --git a/bootstrap/bootstrap-tests.ts b/bootstrap/bootstrap-tests.ts index c497e0abcd..f7cfdeab43 100644 --- a/bootstrap/bootstrap-tests.ts +++ b/bootstrap/bootstrap-tests.ts @@ -44,3 +44,8 @@ $('.typeahead').typeahead({ }); $('#navbar').affix(); + +$('.item').emulateTransitionEnd(2000); + +$.support.transition = false; +console.log(($.support.transition as TransitionEventNames).end === "transitionend"); diff --git a/bootstrap/bootstrap.d.ts b/bootstrap/bootstrap.d.ts index b0e8fbf858..ae84454332 100644 --- a/bootstrap/bootstrap.d.ts +++ b/bootstrap/bootstrap.d.ts @@ -53,7 +53,7 @@ interface PopoverOptions { } interface CollapseOptions { - parent?: any; + parent?: any; toggle?: boolean; } @@ -79,6 +79,10 @@ interface AffixOptions { target?: any; } +interface TransitionEventNames { + end: string; +} + interface JQuery { modal(options?: ModalOptions): JQuery; modal(options?: ModalOptionsBackdropString): JQuery; @@ -114,6 +118,12 @@ interface JQuery { typeahead(options?: TypeaheadOptions): JQuery; affix(options?: AffixOptions): JQuery; + + emulateTransitionEnd(duration: number): JQuery; +} + +interface JQuerySupport { + transition: boolean | TransitionEventNames; } declare module "bootstrap" { diff --git a/browser-pack/browser-pack-tests.ts b/browser-pack/browser-pack-tests.ts new file mode 100644 index 0000000000..4cf20249e8 --- /dev/null +++ b/browser-pack/browser-pack-tests.ts @@ -0,0 +1,33 @@ +/// + +import browserPack = require("browser-pack"); + +module BrowserPackTest { + + export function packIt(opts?: BrowserPack.Options) { + var packOpts: BrowserPack.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts.externalRequireName || "require", + hasExports: opts.hasExports || false, + prelude: opts.prelude || undefined, + preludePath: opts.preludePath || undefined, + raw: opts.raw || false, + sourceMapPrefix: opts.sourceMapPrefix || '//#', + standalone: opts.standalone || undefined, + standaloneModule: opts.standaloneModule || undefined, + }; + + var res = browserPack(); // 'opts' are optional + var res2 = browserPack(packOpts); + + // ensure return value is a stream + var res3 = res.pipe(res2); + + res.on("error", function (err: any) { + console.error("browser-pack error: ", err); + }); + } + +} + +export = BrowserPackTest; \ No newline at end of file diff --git a/browser-pack/browser-pack.d.ts b/browser-pack/browser-pack.d.ts new file mode 100644 index 0000000000..52b96ce134 --- /dev/null +++ b/browser-pack/browser-pack.d.ts @@ -0,0 +1,61 @@ +// Type definitions for browser-pack v6.0.1 +// Project: https://github.com/substack/browser-pack +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** pack node-style source files from a json stream into a browser bundle + */ +declare module BrowserPack { + + export interface Options { + /** Whether the bundle should include require= (or the opts.externalRequireName) so that + * require() is available outside the bundle + */ + hasExports?: boolean; + + /** A string to use in place of 'require' if opts.hasExports is specified, default is 'require' + */ + externalRequireName?: string; + + /** Specify a custom prelude, but know what you're doing first. See the prelude.js file in + * this repo for the default prelude. If you specify a custom prelude, you must also specify + * a valid opts.preludePath to the prelude source file for sourcemaps to work + */ + prelude?: string; + + /** prelude.js path if a custom opts.prelude is specified + */ + preludePath?: string; + + /** Used if opts.preludePath is undefined, this is used to resolve the prelude.js file location, default: 'process.cwd()' + */ + basedir?: string; + + /** if given, the writable end of the stream will expect objects to be written to + * it instead of expecting a stream of json text it will need to parse, default false + */ + raw?: boolean; + + /** External string name to use for UMD, if not provided, UMD declaration is not wrapped around output + */ + standalone?: string; + + /** Sets the internal module name to export for standalone + */ + standaloneModule?: string; + + /** If given and source maps are computed, the opts.sourceMapPrefix string will be used instead of default: '//#' + */ + sourceMapPrefix?: string; + } + +} + +declare module "browser-pack" { + /** pack node-style source files from a json stream into a browser bundle + */ + function browserPack(opts?: BrowserPack.Options): NodeJS.ReadWriteStream; + export = browserPack; +} \ No newline at end of file diff --git a/browser-resolve/browser-resolve-tests.ts b/browser-resolve/browser-resolve-tests.ts new file mode 100644 index 0000000000..071b17a1d2 --- /dev/null +++ b/browser-resolve/browser-resolve-tests.ts @@ -0,0 +1,39 @@ +/// + +import * as browserResolve from 'browser-resolve'; + +function basic_test_async(callback: (err?: Error, resolved?: string) => void) { + browserResolve('typescript', function(error, resolved) { + if (error) { + return callback(error); + } + callback(null, resolved); + }); +} + +function basic_test_sync() { + var resolved = browserResolve.sync('typescript'); +} + +function options_test_async() { + browserResolve('typescript', { + browser: 'jsnext:main', + filename: './browser-resolve/browser-resolve.js', + modules: { + fs: './fs-shim.js' + } + }, function(error, resolved) { + if (error) { + console.error(error); + return; + } + console.log(resolved); + }); +} + +function options_test_sync() { + var resolved = browserResolve.sync('typescript', { + filename: './browser-resolve/browser-resolve.js', + modules: {} + }); +} diff --git a/browser-resolve/browser-resolve.d.ts b/browser-resolve/browser-resolve.d.ts new file mode 100644 index 0000000000..8c1456c8f0 --- /dev/null +++ b/browser-resolve/browser-resolve.d.ts @@ -0,0 +1,61 @@ +// Type definitions for browser-resolve +// Project: https://github.com/defunctzombie/node-browser-resolve +// Definitions by: Mario Nebl +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'browser-resolve' { + import * as resolve from 'resolve'; + + /** + * Callback invoked when resolving asynchronously + * + * @param error + * @param resolved Absolute path to resolved identifier + */ + type resolveCallback = (err?: Error, resolved?: string) => void; + + /** + * Resolve a module path and call cb(err, path [, pkg]) + * + * @param id Identifier to resolve + * @param callback + */ + function browserResolve(id: string, cb: resolveCallback): void; + + /** + * Resolve a module path and call cb(err, path [, pkg]) + * + * @param id Identifier to resolve + * @param options Options to use for resolving, optional. + * @param callback + */ + function browserResolve(id: string, opts: browserResolve.AsyncOpts, cb: resolveCallback): void; + + /** + * Returns a module path + * + * @param id Identifier to resolve + * @param options Options to use for resolving, optional. + */ + function browserResolveSync(id: string, opts?: browserResolve.SyncOpts): string; + + namespace browserResolve { + interface Opts { + // the 'browser' property to use from package.json (defaults to 'browser') + browser?: string; + // the calling filename where the require() call originated (in the source) + filename?: string; + // modules object with id to path mappings to consult before doing manual resolution (use to provide core modules) + modules?: any; + } + + export interface AsyncOpts extends resolve.AsyncOpts, Opts {} + export interface SyncOpts extends resolve.SyncOpts, Opts {} + + export var sync: typeof browserResolveSync; + } + + export = browserResolve +} diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts index 822c941d9f..72bcb6465e 100644 --- a/browser-sync/browser-sync-tests.ts +++ b/browser-sync/browser-sync-tests.ts @@ -1,5 +1,5 @@ /// -import browserSync = require("browser-sync"); +import * as browserSync from "browser-sync"; (() => { //make sure that the interfaces are correctly exposed diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts index 3bc083d1f1..00d234f958 100644 --- a/browser-sync/browser-sync.d.ts +++ b/browser-sync/browser-sync.d.ts @@ -8,10 +8,10 @@ /// declare module "browser-sync" { - import chokidar = require("chokidar"); - import fs = require("fs"); - import http = require("http"); - import mm = require("micromatch"); + import * as chokidar from "chokidar"; + import * as fs from "fs"; + import * as http from "http"; + import * as mm from "micromatch"; namespace browserSync { interface Options { @@ -23,14 +23,14 @@ declare module "browser-sync" { * weinre.port - Default: 8080 * Note: requires at least version 2.0.0 */ - ui?: UIOptions; + ui?: UIOptions | boolean; /** * Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS * & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob * patterns. * Default: false */ - files?: string | string[]; + files?: string | (string | FileCallback)[]; /** * File watching options that get passed along to Chokidar. Check their docs for available options * Default: undefined @@ -245,7 +245,7 @@ declare module "browser-sync" { * Note: requires at least version 1.6.2 */ socket?: SocketOptions; - middleware?: MiddlewareHandler | MiddlewareHandler[]; + middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[]; } interface Hash { @@ -261,6 +261,12 @@ declare module "browser-sync" { }; } + interface FileCallback { + match?: string | string[]; + fn: (event: string, file: string) => any; + options?: chokidar.WatchOptions; + } + interface ServerOptions { /** set base directory */ baseDir?: string | string[]; @@ -274,7 +280,7 @@ declare module "browser-sync" { */ routes?: Hash; /** configure custom middleware */ - middleware?: MiddlewareHandler[]; + middleware?: (MiddlewareHandler | PerRouteMiddleware)[]; } interface ProxyOptions { @@ -289,6 +295,11 @@ declare module "browser-sync" { (req: http.ServerRequest, res: http.ServerResponse, next: Function): any; } + interface PerRouteMiddleware { + route: string; + handle: MiddlewareHandler; + } + interface GhostOptions { clicks?: boolean; scroll?: boolean; diff --git a/bytebuffer/bytebuffer.d.ts b/bytebuffer/bytebuffer.d.ts index e5d267787f..e87fb710d8 100644 --- a/bytebuffer/bytebuffer.d.ts +++ b/bytebuffer/bytebuffer.d.ts @@ -91,7 +91,7 @@ declare class ByteBuffer /** * Data view to manipulate the backing buffer. Becomes null if the backing buffer has a capacity of 0. */ - view: DataView; + view: DataView; /** * Allocates a new ByteBuffer backed by a buffer of the specified capacity. @@ -424,7 +424,7 @@ declare class ByteBuffer /** * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that large or larger. - */ + */ resize( capacity: number ): ByteBuffer; /** @@ -611,6 +611,5 @@ declare class ByteBuffer } declare module 'bytebuffer' { - namespace ByteBuffer {} export = ByteBuffer; } diff --git a/c3/c3-tests.ts b/c3/c3-tests.ts index 5413db82d7..cc15e11abe 100644 --- a/c3/c3-tests.ts +++ b/c3/c3-tests.ts @@ -290,7 +290,7 @@ function legend_examples() { }, item: { onclick: function(id) { /* code */ }, - onmoouseover: function(id) { /* code */ }, + onmouseover: function(id) { /* code */ }, onmouseout: function(id) { /* code */ }, } } diff --git a/c3/c3.d.ts b/c3/c3.d.ts index 32dee37dce..f5159090d2 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -650,7 +650,7 @@ declare namespace c3 { /** * Set mouseover event handler to the legend item. */ - onmoouseover?: (id: any) => void; + onmouseover?: (id: any) => void; /** * Set mouseout event handler to the legend item. */ diff --git a/cachefactory/cachefactory-tests.ts b/cachefactory/cachefactory-tests.ts new file mode 100644 index 0000000000..0c859e749d --- /dev/null +++ b/cachefactory/cachefactory-tests.ts @@ -0,0 +1,34 @@ +/// + +CacheFactory.get('test'); + +CacheFactory.createCache('test', { + deleteOnExpire: 'aggressive', + recycleFreq: 60000 +}); + +let testCache = CacheFactory.get('test'); + +testCache.put('testOne', {title: 'testOne', id: 1}); + +let item = testCache.get('testOne'); + + +let profileCache = CacheFactory('profileCache', { + maxAge: 60 * 60 * 1000, + deleteOnExpire: 'aggressive' +}); + +let localStoragePolyfill = { + getItem: (key: string) => { return ""; }, + setItem: (key: string, value: string) => { }, + removeItem: (key: string) => { } +}; + +let myAwesomeCache = CacheFactory('myAwesomeCache', { + maxAge: 15 * 60 * 1000, + cacheFlushInterval: 60 * 60 * 1000, + deleteOnExpire: 'aggressive', + storageMode: 'localStorage', + storageImpl: localStoragePolyfill +}); \ No newline at end of file diff --git a/cachefactory/cachefactory.d.ts b/cachefactory/cachefactory.d.ts new file mode 100644 index 0000000000..ac416e6837 --- /dev/null +++ b/cachefactory/cachefactory.d.ts @@ -0,0 +1,443 @@ +// Type definitions for CacheFactory 1.4.0 +// Project: https://github.com/jmdobry/CacheFactory +// Definitions by: Vaggelis Mparmpas , Daniel Massa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module CacheFactory { + export interface IStoreImplementation { + getItem(key: string): string; + + setItem(key: string, value: string): void; + + removeItem(key: string): void; + } + + export interface CacheGetOptions { + /* + * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive + * or aggressive mode. Will be passed the key and value of the expired item. + * + * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the + * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired + * item is being removed in the first place. Default: null. + */ + onExpire?(key: string, value: any): any; + } + + export interface CachePutOptions { + /* + * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE. + */ + maxAge?: number; + + /* + * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false. + */ + storeOnReject?: boolean; + + /* + * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false. + */ + storeOnResolve?: boolean; + + created?: Date; + access?: Date; + expires?: Date; + } + + export interface CacheTouchOptions extends CachePutOptions { } + + export interface CacheOptions { + /* + * If set, remove all items from a cache on an interval after the given number of milliseconds. Default: null. + */ + cacheFlushInterval?: number; + + /* + * Maximum number of items a cache can hold. Adding more items than the capacity will cause the cache to operate + * like an LRU cache, removing the least recently used items to stay under capacity. Default: Number.MAX_VALUE. + */ + + capacity?: number; + + /* + * Determines the behavior of a cache when an item expires. Default: none. + * + * Possible values: + * + * none - cache will do nothing when an item expires. + * passive - cache will do nothing when an item expires. Expired items will remain in the cache until requested, + * at which point they are removed, and undefined is returned. + * aggressive - cache will remove expired items as soon as they are discovered. + */ + deleteOnExpire?: string; + + /* + * Determines whether a cache is disabled. Default: false. + */ + disabled?: boolean; + + /* + * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE. + */ + maxAge?: number; + + /* + * Determines how often a cache will scan for expired items when in aggressive mode. Default: 1000 (milliseconds). + */ + recycleFreq?: number; + + /* + * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false. + */ + storeOnReject?: boolean; + + /* + * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false. + */ + storeOnResolve?: boolean; + + /* + * Provide a custom storage medium, e.g. a polyfill for localStorage. Default: null. + * + * Must implement: + * + * setItem - Same API as localStorage.setItem(key, value) + * getItem - Same API as localStorage.getItem(key) + * removeItem - Same API as localStorage.removeItem(key) + */ + storageImpl?: IStoreImplementation; + + /* + * Determines the storage medium used by a cache. Default: memory. + * + * Possible values: + * + * memory - cache will hold data in memory. Data is cleared when the page is refreshed. + * localStorage - cache will hold data in localStorage if available. Data is not cleared when the page is refreshed. + * sessionStorage - cache will hold data in sessionStorage if available. Data is not cleared when the page is refreshed. + */ + storageMode?: string; + + /* + * Determines the namespace of a cache when storageMode is set to localStorage or sessionStorage. Make it a shorter + * string to save space. Default: angular-cache.caches. + */ + storagePrefix?: string; + + /* + * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive + * or aggressive mode. Will be passed the key and value of the expired item. + * + * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the + * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired + * item is being removed in the first place. Default: null. + */ + onExpire?(key: string, value: any): any; + } + + export interface ICache { + + $$id: string; + + /** + * Return the item with the given key.options, if provided, must be an object. + * + * If the cache is in passive mode, then options.onExpire can be a function that will be called with the key + * and value of the requested item if the requested item is expired, with the get call itself returning undefined. + * @param key + * @returns {} + */ + get(key: string, options?: CacheGetOptions): T; + + /** + * Insert the item with the given key and value into the cache.options, if provided, must be an object. + * + * If inserting a promise, options.storeOnReject determines whether to insert the rejection value if the promise + * rejects (overriding the default storeOnReject setting for the cache). If inserting a promise, options.storeOnResolve + * determines whether to insert the resolved value if the promise resolves (overriding the default storeOnResolve setting for the cache). + * + * @param key + * @param value + * @param options + */ + put(key: string, value: T, options?: CachePutOptions): void; + + /** + * Remove and return the item with the given key, if it is in the cache. + * @param key + * @returns {} + */ + remove(key: string): T; + + /** + * Remove all items in the cache. + */ + removeAll(): void; + + /** + * Remove and return all expired items in the cache. + * @returns {} + */ + removeExpired(): { [key: string]: any }; + + /** + * Completely destroy this cache and its data. + * @returns {} + */ + destroy(): void; + + /** + * Returns an object containing information about the cache. + * + * @param key + */ + info(): CacheInfo; + + /** + * Returns an object containing information about the item with the given key, if the item is in the cache. + * + * @param key + */ + info(key: string): CacheItemInfo; + + /** + * Return the keys of all items in the cache as an object. + * @returns {} + */ + keySet(): any; + + /** + * Return the keys of all items in the cache as an array. + * @returns [] + */ + keys(): Array; + + /** + * Enable the cache. + */ + enable(): void; + + /** + * Disable the cache. + */ + disable(): void; + + /** + * cache#touch() will "touch" all items in the cache. + * cache#touch(key) will "touch" the item with the given key. + * + * @param key + */ + touch(key?: string, options?: CacheTouchOptions): void; + + /** + * Set the cacheFlushInterval for the cache. + * @param cacheFlushInterval + */ + setCacheFlushInterval(cacheFlushInterval: number): void; + + /** + * Set the capacity for the cache.Setting this lower than the current item count will result in those items being removed. + * @param capacity + */ + setCapacity(capacity: number): void; + + /** + * Set the deleteOnExpire for the cache. + * @param deleteOnExpire + */ + setDeleteOnExpire(deleteOnExpire: string): void; + + /** + * Set the maxAge for the cache. + */ + setMaxAge(maxAge: number): void; + + /** + * Set the onExpire for the cache. + * @param onExpire + */ + setOnExpire(onExpire: Function): void; + + /** + * Set the recycleFreq for the cache. + * @param recycleFreq + */ + setRecycleFreq(recycleFreq: number): void; + + /** + * Set the storageMode for the cache.This will move data from the current storage medium to the new one. + * @param storageMode + */ + setStorageMode(storageMode: string): void; + + /** + * Set multiple options for the cache at a time.Setting strict to true will reset options for the cache + * that are not specifically set in the options hash to CacheFactoryProvider.defaults. + * @param options + */ + setOptions(options: CacheOptions, strict?: boolean): void; + + /** + * Return the values of all items in the cache as an array. + * @returns Array + */ + values(): Array + } + + export interface ICacheFactory { + + BinaryHeap: IBinaryHeap; + utils: IUtils; + defaults: CacheOptions; + + /** + * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object. + * Any options you pass here will override any default options. + * @param cacheId + * @param options + * @returns ICache + */ + (cacheId: string, options?: CacheOptions): ICache; + + /** + * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object. + * Any options you pass here will override any default options. + * @param cacheId + * @param options + * @returns ICache + */ + createCache(cacheId: string, options?: CacheOptions): ICache; + + /** + * Return the cache with the given cacheId. + * @param cacheId The id of the cache storage. + * @returns ICache + */ + get(cacheId: string, options?: CacheOptions): ICache; + + /** + * Return an object of key- value pairs, the keys being cache ids and the values being the result of .info() being called on each cache. + * @returns CacheInfo + */ + info(): CacheInfo; + + /** + * Return the ids of all registered caches as an object. + * @returns {[key: string]: ICache} + */ + keySet(): { [key: string]: ICache }; + + /** + * Return the ids of all registered caches as an array. + * @returns Array + */ + keys(): Array; + + /** + * Destroy the cache with the given cacheId. + * @param cacheId + */ + destroy(cacheId: string): void; + + /** + * Destroy all registered caches. + */ + destroyAll(): void; + + /** + * Remove all data from all registered caches. + */ + clearAll(): void; + + /** + * Enable all registered caches. + */ + enableAll(): void; + + /** + * Disable all registered caches. + */ + disableAll(): void; + + /** + * Call.touch() on all registered caches. + */ + touchAll(): void; + + /** + * Call.removeExpired() on all registered caches.Returns a hash of any expired items, keyed by cache id. + * @returns {} + */ + removeExpiredFromAll(): Array<{ [key: string]: Array<{ [key: string]: any }> }>; + } + + export interface IUtils { + isNumber(value: any): boolean; + isString(value: any): boolean; + isObject(value: any): boolean; + isFunction(value: any): boolean; + equals(a: any, b: any): boolean; + fromJson(value: any): {} + Promise: any; + } + + export interface HeapItem { + key: string; + accessed: Date; + } + + export interface IBinaryHeap { + (w?: IWeightFunc, c?: ICompareFunc): void; + + heap: Array; + weightFunc: IWeightFunc; + compareFunc: ICompareFunc; + + push(node: HeapItem): void; + pop(): HeapItem; + peek(): HeapItem; + remove(node: HeapItem): HeapItem; + removeAll(): void; + size(): Number; + } + + export interface IWeightFunc { + (x: T): T; + } + + export interface ICompareFunc { + (x: T, y: T): boolean; + } + + export interface CacheInfo { + size: Number; + caches: { [key: string]: any }; + capacity: Number; + maxAge: Number; + deleteOnExpire: string; + onExpire: Function; + cacheFlushInterval: Number; + recycleFreq: Number; + storageMode: string; + storageImpl: IStoreImplementation; + disabled: boolean; + storagePrefix: string; + storeOnResolve: boolean; + storeOnReject: boolean; + } + + export interface CacheItemInfo { + created: Date; + accessed: Date; + expires: Date; + isExpired: boolean; + } +} + +declare var CacheFactory: CacheFactory.ICacheFactory; + +declare module "cachefactory" { + export = CacheFactory; +} \ No newline at end of file diff --git a/chartist/chartist.d.ts b/chartist/chartist.d.ts index 6c679dc1d8..0e92364812 100644 --- a/chartist/chartist.d.ts +++ b/chartist/chartist.d.ts @@ -105,7 +105,7 @@ declare namespace Chartist { plugins?: Array; // all of these plugins seem to be functions with options, but keeping type any for now update(data: Object, options?: T, override?: boolean): void; - detatch(): void; + detach(): void; /** * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. diff --git a/chrome/chrome-app.d.ts b/chrome/chrome-app.d.ts index 1891b960e0..3b63357986 100644 --- a/chrome/chrome-app.d.ts +++ b/chrome/chrome-app.d.ts @@ -685,7 +685,7 @@ declare namespace chrome.usb { interface DeviceEvent extends chrome.events.Event<(device: Device) => void> {} export var onDeviceAdded: DeviceEvent; - export var onDeviceAdded: DeviceEvent; + export var onDeviceRemoved: DeviceEvent; export function getDevices(options: { vendorId?: number, productId?: number, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; export function getUserSelectedDevices(options: { multiple?: boolean, filters?: DeviceFilter[] }, callback: (devices: Device[]) => void): void; diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index cdb48b2767..bdd0271fca 100644 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -6210,7 +6210,7 @@ declare namespace chrome.tabs { * The tab's new favicon URL. * @since Chrome 27. */ - faviconUrl?: string; + favIconUrl?: string; /** * The tab's new title. * @since Chrome 48. diff --git a/ckeditor/ckeditor.d.ts b/ckeditor/ckeditor.d.ts index bba377090f..9d8728338f 100644 --- a/ckeditor/ckeditor.d.ts +++ b/ckeditor/ckeditor.d.ts @@ -641,7 +641,7 @@ declare namespace CKEDITOR { filebrowserImageBrowseLinkUrl?: string; filebrowserImageBrowseUrl?: string; filebrowserImageUploadUrl?: string; - filebrowserUploadUr?: string; + filebrowserUploadUrl?: string; filebrowserWindowFeatures?: string; filebrowserWindowHeight?: number | string; filebrowserWindowWidth?: number | string; diff --git a/co-views/co-views-tests.ts b/co-views/co-views-tests.ts new file mode 100644 index 0000000000..7c05cecde6 --- /dev/null +++ b/co-views/co-views-tests.ts @@ -0,0 +1,26 @@ +/// +/// + +import views = require('co-views'); + +const render = views('views', { + map: { + html: 'swig' + }, + default: 'jade' +}); + +const fileName = 'xxx'; // template file name +const locals = {}; // template locals data + +async function test() { + const html = await render(fileName, locals); + console.log(html); +} + +// or use generator + +// function* test() { +// const html = yield render(fileName, locals); +// console.log(html); +// } diff --git a/co-views/co-views.d.ts b/co-views/co-views.d.ts new file mode 100644 index 0000000000..66de5fbf79 --- /dev/null +++ b/co-views/co-views.d.ts @@ -0,0 +1,68 @@ +// Type definitions for co-views v2.1 +// Project: https://github.com/tj/co-views/ +// Definitions by: devlee +// Definitions: https://github.com/devlee/DefinitelyTyped + +/* =================== USAGE =================== + + import views = require('co-views'); + const render = views('views', { + map: { + html: 'swig' + }, + default: 'jade' + }); + + =============================================== */ + +declare module "co-views" { + + interface EngineMap { + /** + * use for .html files + */ + html: string + } + + interface CoViewsOptions { + + /** + * default extname + */ + ext?: string, + + /** + * default extname + */ + default?: string, + + /** + * engine map + */ + map?: EngineMap, + + /** + * proxy partials + */ + partials?: Object, + + /** + * cache compiled templates + */ + cache?: boolean, + + /** + * common locals data + */ + locals?: Object + } + + /** + * Pass views `dir` and `opts` to return a render function. + */ + function views(dir?: string, opts?: CoViewsOptions): { + (view: string, locals?: Object): any + }; + + export = views; +} diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index bade422821..b1bf33e2d2 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -181,7 +181,7 @@ declare namespace CodeMirror { handle: any; text: string; /** Object mapping gutter IDs to marker elements. */ - gutterMarks: any; + gutterMarkers: any; textClass: string; bgClass: string; wrapClass: string; @@ -220,14 +220,7 @@ declare namespace CodeMirror { /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ - getScrollInfo(): { - left: any; - top: any; - width: any; - height: any; - clientWidth: any; - clientHeight: any; - } + getScrollInfo(): CodeMirror.ScrollInfo; /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ @@ -609,6 +602,15 @@ declare namespace CodeMirror { text: string; } + interface ScrollInfo { + left: any; + top: any; + width: any; + height: any; + clientWidth: any; + clientHeight: any; + } + interface TextMarker { /** Remove the mark. */ clear(): void; @@ -1125,6 +1127,115 @@ declare namespace CodeMirror { severity?: string; to?: Position; } + + /** + * A function that calculates either a two-way or three-way merge between different sets of content. + */ + function MergeView(element: HTMLElement, options?: MergeView.MergeViewEditorConfiguration): MergeView.MergeViewEditor; + + namespace MergeView { + /** + * Options available to MergeView. + */ + interface MergeViewEditorConfiguration extends EditorConfiguration { + /** + * Determines whether the original editor allows editing. Defaults to false. + */ + allowEditingOriginals?: boolean; + + /** + * When true stretches of unchanged text will be collapsed. When a number is given, this indicates the amount + * of lines to leave visible around such stretches (which defaults to 2). Defaults to false. + */ + collapseIdentical?: boolean | number; + + /** + * Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align", + * the smaller chunk is padded to align with the bigger chunk instead. + */ + connect?: string; + + /** + * Callback for when stretches of unchanged text are collapsed. + */ + onCollapse?(mergeView: MergeViewEditor, line: number, size: number, mark: TextMarker): void; + + /** + * Provides original version of the document to be shown on the right of the editor. + */ + orig: any; + + /** + * Provides original version of the document to be shown on the left of the editor. + * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. + */ + origLeft?: any; + + /** + * Provides original version of document to be shown on the right of the editor. + * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight. + */ + origRight?: any; + + /** + * Determines whether buttons that allow the user to revert changes are shown. Defaults to true. + */ + revertButtons?: boolean; + + /** + * When true, changed pieces of text are highlighted. Defaults to true. + */ + showDifferences?: boolean; + } + + interface MergeViewEditor extends Editor { + /** + * Returns the editor instance. + */ + editor(): Editor; + + /** + * Left side of the merge view. + */ + left: DiffView; + leftChunks(): MergeViewDiffChunk; + leftOriginal(): Editor; + + /** + * Right side of the merge view. + */ + right: DiffView; + rightChunks(): MergeViewDiffChunk; + rightOriginal(): Editor; + + /** + * Sets whether or not the merge view should show the differences between the editor views. + */ + setShowDifferences(showDifferences: boolean): void; + } + + /** + * Tracks changes in chunks from oroginal to new. + */ + interface MergeViewDiffChunk { + editFrom: number; + editTo: number; + origFrom: number; + origTo: number; + } + + interface DiffView { + /** + * Forces the view to reload. + */ + forceUpdate(): (mode: string) => void; + + /** + * Sets whether or not the merge view should show the differences between the editor views. + */ + setShowDifferences(showDifferences: boolean): void; + } + } } declare module "codemirror" { diff --git a/combokeys/combokeys-tests.ts b/combokeys/combokeys-tests.ts new file mode 100644 index 0000000000..1a065861ff --- /dev/null +++ b/combokeys/combokeys-tests.ts @@ -0,0 +1,33 @@ + +/// + +import Combokeys = require("combokeys"); + +const combokeys1: Combokeys.Combokeys = new Combokeys(document.createElement('div')); +const combokeys2: Combokeys.Combokeys = new Combokeys(document.createElement('div')); + +combokeys1.bind('ctrl+a', () => {}); +combokeys1.bind('ctrl+z', () => {}, 'keydown'); +combokeys1.bind(['ctrl+a', 'ctrl+shift+a'], () => {}); +combokeys1.bind(['ctrl+a', 'ctrl+shift+a'], () => {}, 'keyup'); + +combokeys1.bindMultiple(['ctrl+a', 'ctrl+shift+a'], () => {}); +combokeys1.bindMultiple(['ctrl+a', 'ctrl+shift+a'], () => {}, 'keyup'); + +const result: boolean = combokeys1.stopCallback(new Event(null), document.createElement('div')); + +combokeys1.unbind('ctrl+a'); +combokeys1.unbind('ctrl+a', 'keydown'); +combokeys1.unbind(['ctrl+a', 'ctrl+shift+a']); +combokeys1.unbind(['ctrl+a', 'ctrl+shift+a'], 'keydown'); + +combokeys1.trigger('ctrl+a'); +combokeys1.trigger('ctrl+a', 'keypress'); + +combokeys1.reset(); + +combokeys1.detach(); + +Combokeys.reset(); + +Combokeys.instances.forEach((combokeys: Combokeys.Combokeys) => combokeys.reset() ); diff --git a/combokeys/combokeys.d.ts b/combokeys/combokeys.d.ts new file mode 100644 index 0000000000..f7e1e5b035 --- /dev/null +++ b/combokeys/combokeys.d.ts @@ -0,0 +1,107 @@ +// Type definitions for Combokeys v2.4.6 +// Project: https://github.com/PolicyStat/combokeys +// Definitions by: Ian Clanton-Thuon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Combokeys { + interface CombokeysStatic { + new (element: Element): Combokeys; + + /** + * all instances of Combokeys + */ + instances: Combokeys[]; + + /** + * reset all instances + */ + reset(): void; + } + + interface Combokeys { + element: Element; + + /** + * binds an event to Combokeys + * + * can be a single key, a combination of keys separated with +, + * an array of keys, or a sequence of keys separated by spaces + * + * be sure to list the modifier keys first to make sure that the + * correct key ends up getting bound (the last key in the pattern) + * + * @param {keys} key combination or combinations + * @param {callback} callback function + * @param {handler} optional - one of "keypress", "keydown", or "keyup" + * @returns void + */ + bind(keys: string | string[], callback: () => void, action?: string): void; + + + /** + * binds multiple combinations to the same callback + * + * @param {keys} key combinations + * @param {callback} callback function + * @param {handler} optional - one of "keypress", "keydown", or "keyup" + * @returns void + */ + bindMultiple(keys: string[], callback: () => void, action?: string): void; + + /** + * unbinds an event to Combokeys + * + * the unbinding sets the callback function of the specified key combo + * to an empty function and deletes the corresponding key in the + * directMap dict. + * + * the keycombo+action has to be exactly the same as + * it was defined in the bind method + * + * @param {keys} key combination or combinations + * @param {action} optional - one of "keypress", "keydown", or "keyup" + * @returns void + */ + unbind(keys: string | string[], action?: string): void; + + /** + * triggers an event that has already been bound + * + * @param {keys} key combination + * @param {action} optional - one of "keypress", "keydown", or "keyup" + * @returns void + */ + trigger(keys: string, action?: string): void; + + /** + * resets the library back to its initial state. This is useful + * if you want to clear out the current keyboard shortcuts and bind + * new ones - for example if you switch to another page + * + * @returns void + */ + reset(): void; + + /** + * should we stop this event before firing off callbacks + * + * @param {e} event + * @param {element} bound element + * @return {boolean} + */ + stopCallback(e: Event, element: Element): boolean; + + /** + * detach all listners from the bound element + * + * @return {void} + */ + detach(): void; + } +} + +declare var combokeys: Combokeys.CombokeysStatic; + +declare module "combokeys" { + export = combokeys; +} diff --git a/common-tags/common-tags-tests.ts b/common-tags/common-tags-tests.ts new file mode 100644 index 0000000000..9114f4414c --- /dev/null +++ b/common-tags/common-tags-tests.ts @@ -0,0 +1,156 @@ +/// + +import * as commonTags from 'common-tags'; + +/* Test Built-in Tags */ + +commonTags.commaLists ` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.commaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let fruits = ['apple', 'orange', 'watermelon']; + +commonTags.html` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.codeBlock` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.source` +
+
    + ${fruits.map(fruit => `
  • ${fruit}
  • `)} + ${'
  • kiwi
  • \n
  • guava
  • '} +
+
+`; + +commonTags.oneLine` + foo + bar + baz +`; + +commonTags.oneLineTrim` + https://news.com/article + ?utm_source=designernews.co +`; + +commonTags.oneLineCommaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineCommaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.inlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commonTags.oneLineInlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +let verb = 'notice'; + +commonTags.stripIndent` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + But we do want to keep this line indented. +`; + +commonTags.stripIndents` + This is a multi-line string. + You'll ${verb} that it is indented. + We don't want to output this indentation. + We don't want to keep this line indented either. +`; + +/* Test Tag Constructor */ + +new commonTags.TemplateTag(); + +const substitutionReplacer = (oldValue : string, newValue : string) => ({ + onSubstitution(substitution : string, resultSoFar : string) { + if (substitution === oldValue) { + return newValue; + } + return substitution; + } +}); + +new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz')); + +new commonTags.TemplateTag( + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +); + +new commonTags.TemplateTag([ + substitutionReplacer('fizz', 'buzz'), + substitutionReplacer('foo', 'bar') +]); + +new commonTags.TemplateTag({}); + +new commonTags.TemplateTag({ + onEndResult: endResult => `${endResult}!` +}); + +new commonTags.TemplateTag({ + onSubstitution: substitution => `${substitution}!`, + onEndResult: endResult => `${endResult}!` +}); + +/* Tests Built-in Transformers */ + +new commonTags.TemplateTag(commonTags.trimResultTransformer()); +new commonTags.TemplateTag(commonTags.trimResultTransformer('left')); +new commonTags.TemplateTag(commonTags.trimResultTransformer('right')); + +new commonTags.TemplateTag(commonTags.stripIndentTransformer()); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial')); +new commonTags.TemplateTag(commonTags.stripIndentTransformer('all')); + +new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar')); + +new commonTags.TemplateTag(commonTags.inlineArrayTransformer()); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'})); +new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'})); + +new commonTags.TemplateTag(commonTags.splitStringTransformer('foo')); diff --git a/common-tags/common-tags.d.ts b/common-tags/common-tags.d.ts new file mode 100644 index 0000000000..aa443ac33d --- /dev/null +++ b/common-tags/common-tags.d.ts @@ -0,0 +1,62 @@ +// Type definitions for common-tags v1.2.1 +// Project: https://github.com/declandewet/common-tags +// Definitions by: Viktor Zozuliak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'common-tags' { + type TemplateTag = (literals: string[], ...placeholders: any[]) => string; + + type TemplateTransformer = { + onSubstitution?: (substitution: string, resultSoFar: string) => string; + onEndResult?: (endResult : string) => string; + } + + /* Built-in Tags */ + export var commaLists: TemplateTag; + + export var commaListsAnd: TemplateTag; + + export var commaListsOr: TemplateTag; + + export var html: TemplateTag; + + export var codeBlock: TemplateTag; + + export var source: TemplateTag; + + export var oneLine: TemplateTag; + + export var oneLineTrim: TemplateTag; + + export var oneLineCommaLists: TemplateTag; + + export var oneLineCommaListsOr: TemplateTag; + + export var oneLineCommaListsAnd: TemplateTag; + + export var inlineLists: TemplateTag; + + export var oneLineInlineLists: TemplateTag; + + export var stripIndent: TemplateTag; + + export var stripIndents: TemplateTag; + + /* New Tag Constructor */ + export var TemplateTag: { + new(): TemplateTag; + new(...transformers: TemplateTransformer[]): TemplateTag; + new(transformers: TemplateTransformer[]): TemplateTag; + }; + + /* Built-in Transformers */ + export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer; + + export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer; + + export var replaceResultTransformer: (replaceWhat: string, replaceWith: string) => TemplateTransformer; + + export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer; + + export var splitStringTransformer: (splitBy: string) => TemplateTransformer; +} diff --git a/component-emitter/component-emitter-tests.ts b/component-emitter/component-emitter-tests.ts new file mode 100644 index 0000000000..e6c6a5b1ab --- /dev/null +++ b/component-emitter/component-emitter-tests.ts @@ -0,0 +1,52 @@ +/// // only for require +/// +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + + +// These are all of the examples from https://www.npmjs.com/package/component-emitter as of June 18, 2016 + +var Emitter = require('component-emitter'); +var emitter = new Emitter; +emitter.emit('something'); + + + + +var user = { name: 'tobi' }; +Emitter(user); + +(user).emit('im a user'); + + + +// this example modified from the one on https://www.npmjs.com/package/component-emitter +var User = Object.create({ + someUserFunction: () => {console.log('someUserFunction called!')} +}) +var another_user = Emitter(User); +another_user.someUserFunction() +another_user.on('hi', () => {console.log('Hi called')}) +another_user.emit('hi') + + +// Additional sample code for this test +function handleSomeRecurringEvent(event_data: any) { + console.log('handle some-recurring-event') +} +emitter.on('some-recurring-event', handleSomeRecurringEvent) + + +emitter.once('some-single-shot-event', (event_data: any) => {console.log('handle some-single-shot-event')}) + + +emitter.off() +emitter.off('some-recurring-event') +emitter.off('some-recurring-event', handleSomeRecurringEvent) + +var event_data = {some: 'data'} +emitter.emit('some-recurring-event') +emitter.emit('some-recurring-event', event_data) + +emitter.listeners('some-recurring-event') + +emitter.hasListeners('some-recurring-event') diff --git a/component-emitter/component-emitter.d.ts b/component-emitter/component-emitter.d.ts new file mode 100644 index 0000000000..28ce4f4bc9 --- /dev/null +++ b/component-emitter/component-emitter.d.ts @@ -0,0 +1,19 @@ +// Type definitions for component-emitter v1.2.1 +// Project: https://www.npmjs.com/package/component-emitter +// Definitions by: Peter Snider +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/emitter-component + + +interface Emitter { + (obj?: Object): Emitter; + on(event: string, listener: Function): Emitter; + once(event: string, listener: Function): Emitter; + off(event?: string, listener?: Function): Emitter; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; +} + +declare module 'component-emitter' { + var Emitter: Emitter; +} diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts index 299e2da4d9..a830fa4881 100644 --- a/cordova/cordova.d.ts +++ b/cordova/cordova.d.ts @@ -35,7 +35,7 @@ interface Cordova { * @param action The action name to call on the native side (generally corresponds to the native class method). * @param args An array of arguments to pass into the native environment. */ - exec(success: () => any, fail: () => any, service: string, action: string, args?: string[]): void; + exec(success: (data: any) => any, fail: (err: any) => any, service: string, action: string, args?: any[]): void; /** Gets the operating system name. */ platformId: string; /** Gets Cordova framework version */ diff --git a/cordova/plugins/NetworkInformation.d.ts b/cordova/plugins/NetworkInformation.d.ts index 4f80fdbb7e..0d49597e3a 100644 --- a/cordova/plugins/NetworkInformation.d.ts +++ b/cordova/plugins/NetworkInformation.d.ts @@ -47,6 +47,7 @@ interface Connection { */ type: string; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; + removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } declare var Connection: { diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts index bc690d434c..965acc6855 100644 --- a/core-js/core-js-tests.ts +++ b/core-js/core-js-tests.ts @@ -500,3 +500,5 @@ s = s.unescapeHTML(); // ############################################################################################# promiseOfVoid = delay(i); + +console.log('core-js version number:', core.version); diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index 16441df233..e9be316364 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -790,8 +790,17 @@ interface PromiseConstructor { * @param values An array of Promises. * @returns A new Promise. */ - all(values: Iterable>): Promise; - + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike, T10 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike, T9 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike, T8 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike, T7 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike, T6 | PromiseLike]): Promise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike , T5 | PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike, T4 | PromiseLike ]): Promise<[T1, T2, T3, T4]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike, T3 | PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [T1 | PromiseLike, T2 | PromiseLike]): Promise<[T1, T2]>; + all(values: Iterable>): Promise; + /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. @@ -1266,6 +1275,8 @@ interface String { declare function delay(msec: number): Promise; declare namespace core { + var version: string; + namespace Reflect { function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any; function construct(target: Function, argumentsList: ArrayLike): any; diff --git a/csv-parse/csv-parse-tests.ts b/csv-parse/csv-parse-tests.ts new file mode 100644 index 0000000000..d64c765ed2 --- /dev/null +++ b/csv-parse/csv-parse-tests.ts @@ -0,0 +1,64 @@ +/// + +import parse = require('csv-parse'); + +function callbackAPITest() { + var input = '#Welcome\n"1","2","3","4"\n"a","b","c","d"'; + parse(input, {comment: '#'}, function(err, output){ + output.should.eql([ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]); + }); +} + +function streamAPITest() { + var output:any = []; + // Create the parser + var parser = parse({delimiter: ':'}); + var record: any; + // Use the writable stream api + parser.on('readable', function(){ + while(record = parser.read()){ + output.push(record); + } + }); + // Catch any error + parser.on('error', function(err: any){ + console.log(err.message); + }); + // When we are done, test that the parsed output matched what expected + parser.on('finish', function(){ + output.should.eql([ + [ 'root','x','0','0','root','/root','/bin/bash' ], + [ 'someone','x','1022','1022','a funny cat','/home/someone','/bin/bash' ] + ]); + }); + // Now that setup is done, write data to the stream + parser.write("root:x:0:0:root:/root:/bin/bash\n"); + parser.write("someone:x:1022:1022:a funny cat:/home/someone:/bin/bash\n"); + // Close the readable stream + parser.end(); +} + +import fs = require('fs'); + +function pipeFunctionTest() { + var transform = require('stream-transform'); + + var output:any = []; + var parser = parse({delimiter: ':'}) + var input = fs.createReadStream('/etc/passwd'); + var transformer = transform(function(record: any[], callback: any){ + setTimeout(function(){ + callback(null, record.join(' ')+'\n'); + }, 500); + }, {parallel: 10}); + input.pipe(parser).pipe(transformer).pipe(process.stdout); +} + +import parseSync = require('csv-parse/lib/sync'); + +function syncApiTest() { + var input = '"key_1","key_2"\n"value 1","value 2"'; + var records = parseSync(input, {columns: true}); + records.should.eql([{ key_1: 'value 1', key_2: 'value 2' }]); +} + diff --git a/csv-parse/csv-parse.d.ts b/csv-parse/csv-parse.d.ts new file mode 100644 index 0000000000..74184ca680 --- /dev/null +++ b/csv-parse/csv-parse.d.ts @@ -0,0 +1,132 @@ +// Type definitions for csv-parse 1.1.0 +// Project: https://github.com/wdavidw/node-csv-parse +// Definitions by: David Muller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "csv-parse/types" { + interface callbackFn { + (err: any, output: any): void + } + + interface nameCallback { + (line1: any[]): boolean | string[] + } + + interface options { + /*** + * Set the field delimiter. One character only, defaults to comma. + */ + delimiter?: string; + + /*** + * String used to delimit record rows or a special value; special constants are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). + */ + rowDelimiter?: string; + /*** + * Optional character surrounding a field, one character only, defaults to double quotes. + */ + quote?: string + + /*** + * Set the escape character, one character only, defaults to double quotes. + */ + escape?: string + + /*** + * List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays. + */ + columns?: any[]|boolean|nameCallback; + + /*** + * Treat all the characters after this one as a comment, default to '' (disabled). + */ + comment?: string + + /*** + * Name of header-record title to name objects by. + */ + objname?: string + + /*** + * Preserve quotes inside unquoted field. + */ + relax?: boolean + + /*** + * Discard inconsistent columns count, default to false. + */ + relax_column_count?: boolean + + /*** + * Dont generate empty values for empty lines. + */ + skip_empty_lines?: boolean + + /*** + * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, used to guard against a wrong delimiter or rowDelimiter, default to 128000 characters. + */ + max_limit_on_data_read?: number + + /*** + * If true, ignore whitespace immediately around the delimiter, defaults to false. Does not remove whitespace in a quoted field. + */ + trim?: boolean + + /*** + * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. Does not remove whitespace in a quoted field. + */ + ltrim?: boolean + + /*** + * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. Does not remove whitespace in a quoted field. + */ + rtrim?: boolean + + /*** + * If true, the parser will attempt to convert read data types to native types. + */ + auto_parse?: boolean + + /*** + * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. + */ + auto_parse_date?: boolean + } + + import * as stream from "stream"; + + interface Parser extends stream.Transform { + __push(line: any): any ; + __write(chars: any, end: any, callback: any): any; + } + + interface ParserConstructor { + new (options: options): Parser; + } + + interface parse { + (input: string, options?: options, callback?: callbackFn): any; + (options: options, callback: callbackFn): any; + (callback: callbackFn): any; + (options?: options): NodeJS.ReadWriteStream; + Parser: ParserConstructor; + } +} + +declare module "csv-parse" { + import { parse as parseIntf } from "csv-parse/types"; + + let parse: parseIntf; + + export = parse; +} + +declare module "csv-parse/lib/sync" { + import { options } from "csv-parse/types"; + + function parse (input: string, options?: options): any; + + export = parse; +} \ No newline at end of file diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index d0e742d9c2..6c4273e4e0 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -29,8 +29,20 @@ declare namespace cucumber { } interface HookScenario{ - attach(text: string, mimeType?: string, callback?: (err?:any) => void): void; - isFailed() : boolean; + getKeyword():string; + getName():string; + getDescription():string; + getUri():string; + getLine():number; + getTags():string[]; + getException():Error; + getAttachments():any[]; + attach(data:any, mimeType?:string, callback?:(err?:any) => void):void; + isSuccessful():boolean; + isFailed():boolean; + isPending():boolean; + isUndefined():boolean; + isSkipped():boolean; } interface HookCode { diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts index c9027b0889..7991dcaa03 100644 --- a/d3/d3-tests.ts +++ b/d3/d3-tests.ts @@ -2706,3 +2706,17 @@ function testMultiUtcFormat() { ["%Y", function() { return true; }] ]); } + +function testEnterSizeEmpty() { + + var selectionSize: number, + emptyStatus: boolean; + + var newNodes = d3.selectAll('.test') + .data(['1', '2', '3']) + .enter(); + + emptyStatus = newNodes.empty(); + selectionSize = newNodes.size(); + +} \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts index c80a922f1f..b35d898522 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -292,17 +292,17 @@ declare namespace d3 { */ datum(): Datum; - /** - * Set the data item for each node in the selection. - * @param value the constant element to use for each node - */ - datum(value: NewDatum): Update; - /** * Derive the data item for each node in the selection. Useful for situations such as the HTML5 'dataset' attribute. * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; + + /** + * Set the data item for each node in the selection. + * @param value the constant element to use for each node + */ + datum(value: NewDatum): Update; /** * Reorders nodes in the selection based on the given comparator. Nodes are re-inserted into the document once sorted. @@ -415,6 +415,9 @@ declare namespace d3 { select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection; call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; + + empty(): boolean; + size(): number; } } @@ -1094,6 +1097,12 @@ declare namespace d3 { export function mean(array: number[]): number; export function mean(array: T[], accessor: (datum: T, index: number) => number): number; + /** + * Compute the median of an array of numbers (the 0.5-quantile). + */ + export function median(array: number[]): number; + export function median(datum: T[], accessor: (datum: T, index: number) => number): number; + export function quantile(array: number[], p: number): number; export function variance(array: number[]): number; @@ -1102,8 +1111,7 @@ declare namespace d3 { export function deviation(array: number[]): number; export function deviation(array: T[], accessor: (datum: T, index: number) => number): number; - export function bisectLeft(array: number[], x: number, lo?: number, hi?: number): number; - export function bisectLeft(array: string[], x: string, lo?: number, hi?: number): number; + export function bisectLeft(array: T[], x: T, lo?: number, hi?: number): number; export var bisect: typeof bisectRight; @@ -3055,6 +3063,8 @@ declare namespace d3 { } export interface Partition { + (root: T): T[]; + nodes(root: T): T[]; links(nodes: T[]): partition.Link[]; diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts new file mode 100644 index 0000000000..1b8d2a24f9 --- /dev/null +++ b/d3kit/d3kit-tests.ts @@ -0,0 +1,1112 @@ +/// +/// +/// +/// + +/* jshint expr: true */ + +var expect = chai.expect; +describe('Skeleton', function(){ + var element: Element, $element: d3.Selection, $svg: d3.Selection, skeleton: d3kit.Skeleton; + + beforeEach(function(done){ + element = document.body.appendChild(document.createElement('div')) as Element; + skeleton = new d3kit.Skeleton(element, null, ['custom1', 'custom2']); + $element = d3.select(element); + $svg = $element.select('svg'); + done(); + }); + + describe('new Skeleton()', function(){ + it('should create inside the element', function(){ + expect($element.select('svg').size()).to.be.equal(1); + }); + it('should create inside inside the element', function(){ + expect($element.select('svg').select('g').size()).to.be.equal(1); + }); + }); + + describe('#getCustomEventNames()', function(){ + it('should return custom event names', function(){ + expect(skeleton.getCustomEventNames()).to.deep.equal(['custom1', 'custom2']); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return event dispatcher', function(){ + expect(skeleton.getDispatcher()).to.be.an('Object'); + expect(skeleton.getDispatcher().data).to.be.a('Function'); + }); + }); + + describe('#getInnerWidth()', function(){ + it('should return width of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(100); + expect(skeleton.getInnerWidth()).to.equal(80); + }); + }); + + describe('#getInnerHeight()', function(){ + it('should return height of the skeleton excluding margin', function(){ + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(100); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + }); + + describe('#getLayerOrganizer()', function(){ + it('should return the LayerOrganizer', function(){ + expect(skeleton.getLayerOrganizer()).to.be.an('Object'); + }); + }); + + describe('#getRootG()', function(){ + it('should return d3 selection of the root ', function(){ + var g = skeleton.getRootG(); + expect(g.size()).to.equal(1); + expect((g[0][0] as Element).tagName).to.equal('g'); + }); + }); + + describe('#getSvg()', function(){ + it('should return d3 selection of the ', function(){ + var svg = skeleton.getSvg(); + expect(svg.size()).to.equal(1); + expect((svg[0][0] as Element).tagName).to.equal('svg'); + }); + }); + + describe('#data(data, doNotDispatch)', function(){ + it('should return data when called without argument', function(){ + skeleton.data({a: 1}); + expect(skeleton.data()).to.deep.equal({a: 1}); + }); + it('should set data when called with at least one argument', function(){ + skeleton.data('test'); + expect(skeleton.data()).to.equal('test'); + }); + it('after setting, should dispatch "data" event', function(done){ + skeleton.on('data.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.data({a: 1}); + }); + it('after setting, should not dispatch "data" event if doNotDispatch is true', function(done){ + skeleton.on('data.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.data({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#options(options, doNotDispatch)', function(){ + it('should return options when called without argument', function(){ + skeleton.options({a: 2}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(2); + }); + it('should set options when called with at least one argument', function(){ + skeleton.options({a: 1}); + expect(skeleton.options()).to.include.keys(['a']); + expect(skeleton.options().a).to.equal(1); + }); + it('should not overwrite but extend existing options when setting', function(){ + skeleton.options({a: 1}); + skeleton.options({b: 2}); + expect(skeleton.options()).to.include.keys(['a', 'b']); + expect(skeleton.options().a).to.equal(1); + expect(skeleton.options().b).to.equal(2); + }); + it('after setting, should dispatch "options" event', function(done){ + skeleton.on('options.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.options({a: 1}); + }); + it('after setting, should not dispatch "options" event if doNotDispatch is true', function(done){ + skeleton.on('options.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.options({a: 1}, true); + setTimeout(done, 100); + }); + }); + + describe('#margin(margin, doNotDispatch)', function(){ + it('should return margin when called without argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + expect(skeleton.margin()).to.deep.equal(margin); + }); + it('should set margin when called with at least one argument', function(){ + var margin = {left: 10, right: 10, top: 10, bottom: 10}; + skeleton.margin(margin); + + skeleton.margin({left: 20}); + expect(skeleton.margin().left).to.equal(20); + expect(skeleton.margin().right).to.equal(10); + skeleton.margin({right: 20}); + expect(skeleton.margin().right).to.equal(20); + skeleton.margin({top: 20}); + expect(skeleton.margin().top).to.equal(20); + skeleton.margin({bottom: 20}); + expect(skeleton.margin().bottom).to.equal(20); + }); + it('should update innerWidth after setting margin', function(){ + skeleton.width(100); + skeleton.margin({left: 10, right:10}); + expect(skeleton.getInnerWidth()).to.equal(80); + skeleton.margin({left: 15, right:15}); + expect(skeleton.getInnerWidth()).to.equal(70); + }); + it('should update innerHeight after setting margin', function(){ + skeleton.height(100); + skeleton.margin({top: 10, bottom:10}); + expect(skeleton.getInnerHeight()).to.equal(80); + skeleton.margin({top: 15, bottom:15}); + expect(skeleton.getInnerHeight()).to.equal(70); + }); + it('should update the root transform/translate', function(){ + skeleton.margin({left: 30, top: 30}); + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(10.5,10.5)'); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.margin({left: 33}); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.margin({left: 33}, true); + setTimeout(done, 100); + }); + }); + + describe('#offset(offset)', function(){ + it('should return offset when called without argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + expect(skeleton.offset()).to.deep.equal(offset); + }); + it('should set offset when called with at least one argument', function(){ + var offset = [1,1]; + skeleton.offset(offset); + skeleton.offset([2,3]); + expect(skeleton.offset()).to.deep.equal([2,3]); + }); + it('should update the root transform/translate', function(){ + skeleton.offset([0.5, 0.5]); + skeleton.margin({left: 10, top: 10}); + skeleton.offset([2,3]); + var translate = skeleton.getRootG().attr('transform'); + expect(translate).to.equal('translate(12,13)'); + }); + }); + + describe('#width(width, doNotDispatch)', function(){ + it('should return width when called without argument', function(){ + var w = $svg.attr('width'); + expect(skeleton.width()).to.equal(+w); + }); + it('should set width when called with Number as the first argument', function(){ + skeleton.width(300); + expect(+$svg.attr('width')).to.equal(300); + }); + it('should set width when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.width('299px'); + expect(+$svg.attr('width')).to.equal(299); + }); + it('should set width to container\'s width when called with "auto" as the first argument', function(){ + var w = element.clientWidth; + skeleton.width('auto'); + expect(+$svg.attr('width')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.width(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.width(200, true); + setTimeout(done, 100); + }); + }); + + describe('#height(height, doNotDispatch)', function(){ + it('should return height when called without argument', function(){ + var w = $svg.attr('height'); + expect(skeleton.height()).to.equal(+w); + }); + it('should set height when called with Number as the first argument', function(){ + skeleton.height(300); + expect(+$svg.attr('height')).to.equal(300); + }); + it('should set height when called with a Number and "px" such as "100px" as the first argument', function(){ + skeleton.height('299px'); + expect(+$svg.attr('height')).to.equal(299); + }); + it('should set height to container\'s height when called with "auto" as the first argument', function(){ + var w = element.clientHeight; + skeleton.height('auto'); + expect(+$svg.attr('height')).to.equal(w); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.height(200); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.height(200, true); + setTimeout(done, 100); + }); + }); + + describe('#dimension(dimension, doNotDispatch)', function(){ + it('should return an array [width, height] when called without argument', function(){ + var dim = [+$svg.attr('width'), +$svg.attr('height')]; + expect(skeleton.dimension()).to.deep.equal(dim); + }); + it('should set width and height of the when called with an array [width, height] as the first argument', function(){ + skeleton.dimension([118, 118]); + expect([+$svg.attr('width'), +$svg.attr('height')]).to.deep.equal([118, 118]); + }); + it('after setting, should dispatch "resize" event', function(done){ + skeleton.on('resize.test', function(){ + // This block should be reached to pass the test. + expect(true).to.be.true; + done(); + }); + skeleton.dimension([150, 150]); + }); + it('after setting, should not dispatch "resize" event if doNotDispatch is true', function(done){ + skeleton.on('resize.test', function(){ + // This block should not be reached. + expect(true).to.be.false; + done(); + }); + skeleton.dimension([150, 150], true); + setTimeout(done, 100); + }); + }); + + describe('#hasData()', function(){ + it('should return true when data are not null nor undefined', function(){ + skeleton.data({}); + expect(skeleton.hasData()).to.be.true; + skeleton.data({test: 1}); + expect(skeleton.hasData()).to.be.true; + skeleton.data([]); + expect(skeleton.hasData()).to.be.true; + skeleton.data(['test']); + expect(skeleton.hasData()).to.be.true; + }); + it('should return false when data are null or undefined', function(){ + skeleton.data(null); + expect(skeleton.hasData()).to.be.false; + skeleton.data(undefined); + expect(skeleton.hasData()).to.be.false; + }); + }); + + describe('#hasNonZeroArea()', function(){ + it('should return true if \'s width & height excluding margin is more than zero', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(80); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(50); + expect(skeleton.hasNonZeroArea()).to.be.true; + }); + it('should return false otherwise', function(){ + skeleton.options({ + margin: {left: 10, right: 10} + }); + skeleton.width(20); + skeleton.options({ + margin: {top: 10, bottom: 20} + }); + skeleton.height(30); + expect(skeleton.hasNonZeroArea()).to.be.false; + }); + }); + + describe('#mixin({})', function(){ + it('should extend this skeleton with new fields/functions', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + expect(skeleton).to.include.keys(['a', 'b']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(2); + }); + it('should overwrite existing fields', function(){ + skeleton.mixin({ + b: 2 + }); + skeleton.mixin({ + b: 3 + }); + expect(skeleton).to.include.keys(['b']); + expect((skeleton).b).to.equal(3); + }); + it('should keep original fields if not overwritten', function(){ + skeleton.mixin({ + a: 1, + b: 2 + }); + skeleton.mixin({ + c: 20, + b: 3 + }); + expect(skeleton).to.include.keys(['a', 'b', 'c']); + expect((skeleton).a).to.equal(1); + expect((skeleton).b).to.equal(3); + expect((skeleton).c).to.equal(20); + }); + }); + + describe('#resizeToFitContainer(mode)', function(){ + it('when mode is "all" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('all'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "both" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('both'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "full" should resize to fit both width and height', function(){ + skeleton.dimension([element.clientWidth/2, element.clientHeight/2]); + var w = element.clientWidth; + var h = element.clientHeight; + skeleton.resizeToFitContainer('full'); + expect(skeleton.dimension()).to.deep.equal([w, h]); + }); + it('when mode is "width" should resize width to fit container but keep original height', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight/2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('width'); + + expect(skeleton.width()).to.equal(Math.floor(w2)); + expect(skeleton.height()).to.equal(Math.floor(h1)); + expect(skeleton.width()).to.not.equal(w1); + expect(skeleton.height()).to.not.equal(h2); + }); + it('when mode is "height" should resize height to fit container but keep original width', function(){ + var w1 = element.clientWidth/2; + var h1 = element.clientHeight*2; + + skeleton.dimension([w1, h1]); + + var w2 = element.clientWidth; + var h2 = element.clientHeight; + + skeleton.resizeToFitContainer('height'); + + expect(skeleton.width()).to.equal(Math.floor(w1)); + expect(skeleton.height()).to.equal(Math.floor(h2)); + expect(skeleton.width()).to.not.equal(w2); + expect(skeleton.height()).to.not.equal(h1); + }); + }); + + describe('#resizeToAspectRatio(ratio)', function(){ + // todo + }); + + describe('#autoResize(mode)', function(){ + it('should return current mode when called without argument', function(){ + skeleton.autoResize(false); + expect(skeleton.autoResize()).to.be.false; + skeleton.autoResize('width'); + expect(skeleton.autoResize()).to.equal('width'); + }); + it('should enable auto resize when set mode to "width/height/both/etc.", similar to parameters of resizeToFitContainer()', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + done(); + }, 500); + }); + it('should disable auto resize when set mode to false', function(done){ + // set initial size + skeleton.width(50); + skeleton.autoResize('width'); + setTimeout(function(){ + expect(skeleton.width()).to.equal(element.clientWidth); + // disable resize and + skeleton.autoResize(false); + skeleton.width(50); + setTimeout(function(){ + expect(skeleton.width()).to.not.equal(element.clientWidth); + done(); + }, 500); + }, 500); + }); + }); + + describe('#autoResizeDetection(detection)', function(){ + // todo + }); + + describe('#autoResizeToAspectRatio(ratio)', function(){ + // todo + }); + + +}); + +describe.only('LayerOrganizer', function(){ + + describe('new LayerOrganizer(container) will create layers as by default', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('svg').append('g'); + layers = new d3kit.LayerOrganizer(container); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('g.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('g.a-layer').size()).to.be.equal(1); + expect(container.select('g.b-layer').size()).to.be.equal(1); + expect(container.select('g.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('g.d-layer').size()).to.be.equal(1); + expect(container.select('g.d-layer g.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('g.f-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.g-layer').size()).to.be.equal(1); + expect(container.select('g.f-layer g.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('g.i-layer').size()).to.be.equal(1); + expect(container.select('g.j-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.i-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.x-layer').size()).to.be.equal(1); + expect(container.select('g.k-layer g.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('g.l-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.m-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.o-layer g.p-layer').size()).to.be.equal(1); + expect(container.select('g.l-layer g.n-layer g.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + + describe('new LayerOrganizer(container, tag) will create layers with the given tag instead of ', function(){ + var container: d3.Selection, layers: d3kit.LayerOrganizer; + before(function(done){ + container = d3.select('body').append('div'); + layers = new d3kit.LayerOrganizer(container, 'div'); + done(); + }); + + describe('#create(names)', function(){ + it('should create single layer given a String', function(){ + layers.create('single'); + expect(container.select('div.single-layer').size()).to.be.equal(1); + }); + + it('should create multiple layers given an array', function(){ + layers.create(['a', 'b', 'c']); + expect(container.select('div.a-layer').size()).to.be.equal(1); + expect(container.select('div.b-layer').size()).to.be.equal(1); + expect(container.select('div.c-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with a String inside', function(){ + layers.create({d: 'e'}); + expect(container.select('div.d-layer').size()).to.be.equal(1); + expect(container.select('div.d-layer div.e-layer').size()).to.be.equal(1); + }); + + it('should create nested layers given a plain Object with an Array inside', function(){ + layers.create({f: ['g', 'h']}); + expect(container.select('div.f-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.g-layer').size()).to.be.equal(1); + expect(container.select('div.f-layer div.h-layer').size()).to.be.equal(1); + }); + + it('should create multiple nested layers given an array of objects', function(){ + layers.create([{'i': ['x']}, {'j': 'x'}, {'k': ['x','y']}]); + expect(container.select('div.i-layer').size()).to.be.equal(1); + expect(container.select('div.j-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.i-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.x-layer').size()).to.be.equal(1); + expect(container.select('div.k-layer div.y-layer').size()).to.be.equal(1); + }); + + it('should create multi-level nested layers given a nested plain Object', function(){ + layers.create({ + l: [ + 'm', + {'n': [ + {'o': ['p']}, 'q' + ]} + ] + }); + expect(container.select('div.l-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.m-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.o-layer div.p-layer').size()).to.be.equal(1); + expect(container.select('div.l-layer div.n-layer div.q-layer').size()).to.be.equal(1); + }); + + }); + + describe('#has(name)', function(){ + it('should be able to check first-level layer', function(){ + expect(layers.has('single')).to.be.true; + expect(layers.has('test')).to.be.false; + }); + it('should be able to check second-level layer', function(){ + expect(layers.has('l.m')).to.be.true; + expect(layers.has('l.x')).to.be.false; + }); + it('should be able to check third-level layer', function(){ + expect(layers.has('l.n.q')).to.be.true; + expect(layers.has('l.n.x')).to.be.false; + }); + }); + + describe('#get(name)', function(){ + it('should be able to get first-level layer', function(){ + expect(layers.get('single')).to.exist; + expect(layers.get('test')).to.be.not.exist; + }); + it('should be able to get second-level layer', function(){ + expect(layers.get('l.m')).to.exist; + expect(layers.get('l.x')).to.not.exist; + }); + it('should be able to get third-level layer', function(){ + expect(layers.get('l.n.o')).to.exist; + expect(layers.get('l.n.x')).to.not.exist; + }); + }); + }); + +}); + +describe('Chartlet', function(){ + interface ConfigureFunction { + (parent: d3kit.Chartlet, child: d3kit.Chartlet): void; + } + var enter: d3kit.ChartletEventFunction, update: d3kit.ChartletEventFunction, exit: d3kit.ChartletEventFunction, chartlet: d3kit.Chartlet; + var customEvents: Array = ['fooEvent']; + var ChildChartlet: () => d3kit.Chartlet; + var ParentChartlet: (configureFunction: ConfigureFunction) => d3kit.Chartlet; + + var callback = function(selection?: d3.Selection, done?: any) { return (sel: d3.Selection) => {done();};}; + beforeEach(function(done){ + ChildChartlet = function() { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + (chartlet).runTest = function (testFunction: any) { + testFunction(chartlet); + }; + return chartlet; + }; + + ParentChartlet = function(configureFunction: ConfigureFunction) { + var chartlet = new d3kit.Chartlet(callback, callback, callback); + var child = ChildChartlet(); + configureFunction(chartlet, child); + (chartlet).runTest = (child).runTest; + return chartlet; + }; + + enter = callback; + update = callback; + exit = callback; + chartlet = new d3kit.Chartlet(enter, update, exit, customEvents); + done(); + }); + + describe('new Chartlet(enter, update, exit, customEvents)', function(){ + it('should create a chartlet', function(){ + expect(chartlet).to.be.an('Object'); + expect(chartlet).to.include.keys(['property', 'on']); + expect(chartlet.enter).to.be.a('Function'); + expect(chartlet.update).to.be.a('Function'); + expect(chartlet.exit).to.be.a('Function'); + expect(function(){ chartlet.enter(); }).to.not.throw(Error); + expect(function(){ chartlet.update(); }).to.not.throw(Error); + expect(function(){ chartlet.exit(); }).to.not.throw(Error); + expect(chartlet.getCustomEventNames()).to.deep.equal(customEvents); + }); + it('arguments "update", "exit" and "customEvents" are optional', function(){ + var comp = new d3kit.Chartlet(enter); + expect(comp).to.be.an('Object'); + expect(comp).to.include.keys(['property', 'on']); + expect(comp.enter).to.be.a('Function'); + expect(comp.update).to.be.a('Function'); + expect(comp.exit).to.be.a('Function'); + expect(function(){ comp.enter(); }).to.not.throw(Error); + expect(function(){ comp.update(); }).to.not.throw(Error); + expect(function(){ comp.exit(); }).to.not.throw(Error); + }); + }); + + describe('#getDispatcher()', function(){ + it('should return a dispatcher', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.exist; + }); + it('returned dispatcher should handle enter/update/exit events', function(){ + var dispatcher = chartlet.getDispatcher(); + expect(dispatcher).to.include.keys(['enterDone', 'updateDone', 'exitDone'].concat(customEvents)); + }); + }); + + describe('#getPropertyValue(name, d, i)', function(){ + it('should return computed value for specified property name, d and i', function(){ + var d = {a: 99}; + var i = 2; + + chartlet.property('foo', 1); + chartlet.property('bar', 'two'); + chartlet.property('baz', function(d:{a:number}, i: number) {return 3;}); + chartlet.property('qux', function(d:{a:number}, i: number) {return 'four';}); + chartlet.property('nux', function(d:{a:number}, i: number) {return d.a * i;}); + + expect(chartlet.getPropertyValue('foo', d, i)).to.equal(1); + expect(chartlet.getPropertyValue('bar', d, i)).to.equal('two'); + expect(chartlet.getPropertyValue('baz', d, i)).to.equal(3); + expect(chartlet.getPropertyValue('qux', d, i)).to.equal('four'); + expect(chartlet.getPropertyValue('nux', d, i)).to.equal(198); + }); + }); + + describe('#property(name, valueOrFn)', function(){ + describe('should act as a getter when called with one argument', function(){ + it('should always return a function', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + }); + it('should return a function that return undefined for unknown property name', function(){ + expect(chartlet.property('unknown name')).to.be.a('Function'); + expect(chartlet.property('unknown name')()).to.equal(undefined); + }); + }); + + describe('should act as a setter when called with two arguments', function(){ + it('should set specified property to a functor of given value', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')).to.be.a('Function'); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('bar', function(){ return 100; }); + expect(chartlet.property('bar')).to.be.a('Function'); + expect(chartlet.property('bar')()).to.equal(100); + }); + it('should overwrite previous value when set property with the same name', function(){ + chartlet.property('foo', 1); + expect(chartlet.property('foo')()).to.equal(1); + chartlet.property('foo', 100); + expect(chartlet.property('foo')()).to.equal(100); + }); + }); + }); + + describe('#on(eventName, listener)', function(){ + it('event "enterDone" should be triggered after chartlet.enter() is completed.', function(done){ + chartlet.on('enterDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.enter(); + }); + it('event "updateDone" should be triggered after chartlet.update() is completed.', function(done){ + chartlet.on('updateDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.update(); + }); + it('event "exitDone" should be triggered after chartlet.exit() is completed.', function(done){ + chartlet.on('exitDone', function(){ return (sel: d3.Selection) => {done();} }); + chartlet.exit(); + }); + }); + + describe('#inheritPropertyFrom(parentChartlet, parentPropertyName, childPropertyName)', function(){ + it('it should cause a child to inherit a parent property', function() { + var parent = ParentChartlet(function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo', 'bar'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('bar', 4, 0)).to.be.equal(8); + }); + }); + + it('it should default to the parent property name', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertyFrom(parent, 'foo'); + }) + .property('foo', function(d:number) {return 2 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 4, 0)).to.be.equal(8); + }); + }); + }); + + describe('#inheritProperties(parentChartlet, parentPropertyNames, childPropertyNames)', function(){ + it('it should cause a child to inherit many parent properties', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz'], ['foo-x', 'bar-x', 'baz-x']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo-x', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar-x', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz-x', 1, 0)).to.be.equal(4); + }); + }); + + it('it should default to the parent property names', function() { + var parent = ParentChartlet( + function(parent: d3kit.Chartlet, child: d3kit.Chartlet) { + child.inheritPropertiesFrom(parent, ['foo', 'bar', 'baz']); + }) + .property('foo', function(d:number) {return 2 * d;}) + .property('bar', function(d:number) {return 3 * d;}) + .property('baz', function(d:number) {return 4 * d;}); + + (parent).runTest(function(child: d3kit.Chartlet) { + expect(child.getPropertyValue('foo', 1, 0)).to.be.equal(2); + expect(child.getPropertyValue('bar', 1, 0)).to.be.equal(3); + expect(child.getPropertyValue('baz', 1, 0)).to.be.equal(4); + }); + }); + }); + + describe('#publishEventsTo(foreignDispatcher)', function(){ + it('should map events to a foreignDispatcher', function(done) { + + var parent = new d3kit.Chartlet(callback, callback, callback, ['foo']); + parent.getDispatcher().on('foo', function(value:number) { + expect(value).to.be.equal(99); + done(); + }); + + var child = new d3kit.Chartlet(callback, callback, callback, ['foo']) + .publishEventsTo(parent.getDispatcher()); + + (child.getDispatcher()).foo(99); + }); + }); +}); + +describe('#createChart', function(){ + var Chart = d3kit.factory.createChart({}, ['test'], function(skeleton: d3kit.Skeleton){ + return skeleton; + }); + + it('should return a function to create a chart', function(){ + expect(Chart).to.be.a('Function'); + }); + + // // Don't think it's possible to define these in a d.ts file; skipping + // it('results should have function getCustomEvents()', function(){ + // expect(Chart.getCustomEvents).to.exist; + // expect(Chart.getCustomEvents()).to.deep.equal(['test']); + // }); +}); + +describe('d3kit.helper', function(){ + + describe('#dasherize(str)', function(){ + it('should convert input to dash-case', function(){ + expect(d3kit.helper.dasherize('camelCase')).to.equal('camel-case'); + }); + }); + + describe('#deepExtend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.deepExtend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.deepExtend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { d: fn1, e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], j: [3,4,5], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#extend(target, src1, src2, ...)', function(){ + it('should copy fields from sources into target', function(){ + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + })).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + + expect(d3kit.helper.extend({}, { + a: 1, + b: 2 + },{ + b: 3, + c: 4 + }, null)).to.deep.equal({ + a: 1, + b: 3, + c: 4 + }); + }); + + it('should copy arrays and functions correctly from sources into target', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: fn1, + b: [1,2] + },{ + b: [3,4], + c: fn2 + })).to.deep.equal({ + a: fn1, + b: [3,4], + c: fn2 + }); + }); + + it('should NOT perform "deep" copy', function(){ + var fn1 = function(d:number){return d + 1;}; + var fn2 = function(d:number){return d + 2;}; + expect(d3kit.helper.extend({}, { + a: { d: fn1 }, + b: [1,2], + c: { f: 3 }, + h: { i: [1,2,3], j: [3,4,5] } + },{ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + })).to.deep.equal({ + a: { e: 2 }, + b: [3,4], + c: { f: 4, g: fn2 }, + h: { i: [2,3,4], k: [3,4,5], l: {m: 2} } + }); + }); + }); + + describe('#isFunction(function)', function(){ + it('should return true if the value is a function', function(){ + var fn1 = function(d:number){return d + 1;}; + function fn2(d:number){return d + 2;} + + expect(d3kit.helper.isFunction(fn1)).to.be.true; + expect(d3kit.helper.isFunction(fn2)).to.be.true; + }); + it('should return false if the value is not a function', function(){ + expect(d3kit.helper.isFunction(0)).to.be.false; + expect(d3kit.helper.isFunction(1)).to.be.false; + expect(d3kit.helper.isFunction(true)).to.be.false; + expect(d3kit.helper.isFunction('what')).to.be.false; + expect(d3kit.helper.isFunction(null)).to.be.false; + expect(d3kit.helper.isFunction(undefined)).to.be.false; + }); + }); + + describe('#isNumber(value)', function(){ + it('should return true for number', function(){ + expect(d3kit.helper.isNumber(1)).to.be.true; + expect(d3kit.helper.isNumber(0)).to.be.true; + expect(d3kit.helper.isNumber(-1)).to.be.true; + }); + it('should return false for string even if it is a number', function(){ + expect(d3kit.helper.isNumber('')).to.be.false; + expect(d3kit.helper.isNumber('1')).to.be.false; + expect(d3kit.helper.isNumber('0')).to.be.false; + expect(d3kit.helper.isNumber('what')).to.be.false; + }); + it('should return false for null and undefined', function(){ + expect(d3kit.helper.isNumber(null)).to.be.false; + expect(d3kit.helper.isNumber(undefined)).to.be.false; + }); + }); +}); + diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit.d.ts new file mode 100644 index 0000000000..4e53472b7b --- /dev/null +++ b/d3kit/d3kit.d.ts @@ -0,0 +1,155 @@ +// Type definitions for d3Kit v1.1.0 +// Project: https://www.npmjs.com/package/d3kit +// Definitions by: Morgan Benton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace d3kit { + + export interface ChartMargin { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + export interface ChartOptions { + margin?: ChartMargin; + offset?: [number,number]; + initialWidth?: number; + initialHeight?: number; + [name: string]: any; + } + + export interface ChartMixin { + [name: string]: any; + } + + export class Skeleton { + + constructor(selector: string|Element, options?: ChartOptions, customEvents?: Array); + + // Getters + getCustomEventNames(): Array; + getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events + getInnerWidth(): number; + getInnerHeight(): number; + getLayerOrganizer(): LayerOrganizer; + getRootG(): d3.Selection; + getSvg(): d3.Selection; + + // Getter/Setters + data(): any; + data(data?: any, doNotDispatch?: boolean): Skeleton; + options(): any; // wish this could be ChartOptions + options(options: ChartOptions, doNotDispatch?: boolean): Skeleton; + margin(): ChartMargin; + margin(margin: ChartMargin, doNotDispatch?: boolean): Skeleton; + offset(): [number, number]; + offset(offset: Array, doNotDispatch?: boolean): Skeleton; + width(): number; + width(value: number|string, doNotDispatch?: boolean): Skeleton; + height(): number; + height(value: number|string, doNotDispatch?: boolean): Skeleton; + dimension(): [number, number]; + dimension(dimension: [number|string, number|string], doNotDispatch?: boolean): Skeleton; + autoResize(mode?: string|boolean): string|boolean|void; + autoResizeDetection(method?:string): string|void; + autoResizeToAspectRatio(ratio?: number|boolean): number|boolean|void; + + // Other functions + on(eventName: string, listener: (...args: Array) => void): void; + hasData(): boolean; + hasNonZeroArea(): boolean; + mixin(fn: ChartMixin): void; + resizeToFitContainer(mode: string|boolean, doNotDispatch?: boolean): void; + resizeToAspectRatio(ratio: number, doNotDispatch?: boolean): void; + } + + interface ChartletPropertyCallback { + (datum?: any, datum_index?: number): any; + } + + export interface ChartletEventFunction { + (sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + } + + export class Chartlet { + + constructor( + enterFunction?: ChartletEventFunction, + updateFunction?: ChartletEventFunction, + exitFunction?: ChartletEventFunction, + customEventName?: Array); + + // Getter functions + getDispatcher(): d3.Dispatch; + getCustomEventNames(): Array; + getPropertyValue(name: string, datum: any, datum_index: number): any; + + // Getter/Setter functions + property(name: string): ChartletPropertyCallback; + property(name: string, value: any): Chartlet; + + // Enter/Update/Exit functions + enter( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + update(sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + exit( sel?: d3.Selection, done?: string): (sel: d3.Selection) => void; + + // Inheritance functions + inheritPropertyFrom(parent_chartlet: Chartlet, parent_property_name: string, child_property_name?: string): void; + inheritPropertiesFrom(parent_chartlet: Chartlet, parent_property_names: Array, child_property_names?: Array): void; + publishEventsTo(dispatcher: d3.Dispatch): Chartlet; + + // Events + on(eventName: string, handlerFunction: ChartletEventFunction): void; + } + + interface LayerConfig { + name?: string, + names?: Array, + sublayers?: LayerConfig + } + + export class LayerOrganizer { + + constructor(container: d3.Selection, tag?: string); + + create(config: string|Array|LayerConfig|Array): d3.Selection|Array>; + get(name: string): d3.Selection; + has(name: string): boolean; + } + + export namespace factory { + export function createChart( + defaultOptions: ChartOptions, + customEvents: Array, + constructor: (skeleton: Skeleton) => void + ): (selector: string|Element, options?: ChartOptions, customEvents?: Array) => Skeleton; + } + + export namespace helper { + export function debounce(fn: (...args: Array) => void, wait: number, immediate: boolean): (...args: Array) => void; + export function extend(target: Object, ...args: Object[]): Object; + export function deepExtend(target: Object, ...args: Object[]): Object; + export function bindMouseEventsToDispatcher(selection: d3.Selection, dispatch: d3.Dispatch, prefix: string): void; + export function removeAllChildren(selection: d3.Selection, noTransition: boolean): d3.Selection; + export function on(element: Element, type: string, listener: (...args: Array) => void): void; + export function off(element: Element, type: string, listener: (...args: Array) => void): void; + export function trim(str: string, characters: string): string; + export function dasherize(str: string): string; + export function $(s: Element|string): Element; + export function $$(s: Array|NodeList): Array; + export function isArray(value: any): boolean; + export function isNumber(value: any): boolean; + export function isObject(value: any): boolean; + export function isElement(o: any): boolean; + export function isFunction(functionToCheck: any): boolean; + } + +} + +declare module 'd3kit' { + export = d3kit; +} \ No newline at end of file diff --git a/d3pie/d3pie-tests.ts b/d3pie/d3pie-tests.ts new file mode 100644 index 0000000000..4d8a38280f --- /dev/null +++ b/d3pie/d3pie-tests.ts @@ -0,0 +1,146 @@ +/// + +let chart = new d3pie('test', + { + header: { + title: { + text: '', + color: '#333333', + fontSize: 18, + font: 'arial' + }, + subtitle: { + color: '#666666', + fontSize: 14, + font: 'arial' + }, + location: 'top-center', + titleSubtitlePadding: 8 + }, + footer: { + text: '', + color: '#666666', + fontSize: 14, + font: 'arial', + location: 'left' + }, + size: { + canvasHeight: 500, + canvasWidth: 500, + pieInnerRadius: 0, + pieOuterRadius: null + }, + data: { + sortOrder: 'none', + smallSegmentGrouping: { + enabled: false, + value: 1, + valueType: 'percentage', + label: 'Other', + color: '#cccccc' + }, + content: [] + }, + labels: { + outer: { + format: 'label', + hideWhenLessThanPercentage: null, + pieDistance: 30 + }, + inner: { + format: 'percentage', + hideWhenLessThanPercentage: null + }, + mainLabel: { + color: '#333333', + font: 'arial', + fontSize: 10 + }, + percentage: { + color: '#dddddd', + font: 'arial', + fontSize: 10, + decimalPlaces: 0 + }, + value: { + color: '#cccc44', + font: 'arial', + fontSize: 10 + }, + lines: { + enabled: true, + style: 'curved', + color: 'segment' // 'segment' or a hex color + } + }, + effects: { + load: { + effect: 'default', // none / default + speed: 1000 + }, + pullOutSegmentOnClick: { + effect: 'bounce', // none / linear / bounce / elastic / back + speed: 300, + size: 10 + }, + highlightSegmentOnMouseover: true, + highlightLuminosity: -0.2 + }, + tooltips: { + enabled: false, + type: 'placeholder', // caption|placeholder + string: '', + placeholderParser: null, + styles: { + fadeInSpeed: 250, + backgroundColor: '#000000', + backgroundOpacity: 0.5, + color: '#efefef', + borderRadius: 2, + font: 'arial', + fontSize: 10, + padding: 4 + } + }, + + misc: { + colors: { + background: null, // transparent + segments: [ + '#2484c1', '#65a620', '#7b6888', '#a05d56', '#961a1a', + '#d8d23a', '#e98125', '#d0743c', '#635222', '#6ada6a', + '#0c6197', '#7d9058', '#207f33', '#44b9b0', '#bca44a', + '#e4a14b', '#a3acb2', '#8cc3e9', '#69a6f9', '#5b388f', + '#546e91', '#8bde95', '#d2ab58', '#273c71', '#98bf6e', + '#4daa4b', '#98abc5', '#cc1010', '#31383b', '#006391', + '#c2643f', '#b0a474', '#a5a39c', '#a9c2bc', '#22af8c', + '#7fcecf', '#987ac6', '#3d3b87', '#b77b1c', '#c9c2b6', + '#807ece', '#8db27c', '#be66a2', '#9ed3c6', '#00644b', + '#005064', '#77979f', '#77e079', '#9c73ab', '#1f79a7' + ], + segmentStroke: '#ffffff' + }, + gradient: { + enabled: false, + percentage: 95, + color: '#000000' + }, + canvasPadding: { + top: 5, + right: 5, + bottom: 5, + left: 5 + }, + pieCenterOffset: { + x: 0, + y: 0 + }, + cssPrefix: null + }, + callbacks: { + onload: null, + onMouseoverSegment: null, + onMouseoutSegment: null, + onClickSegment: null + } + }) \ No newline at end of file diff --git a/d3pie/d3pie.d.ts b/d3pie/d3pie.d.ts new file mode 100644 index 0000000000..2bfe5d6525 --- /dev/null +++ b/d3pie/d3pie.d.ts @@ -0,0 +1,146 @@ +// Type definitions for d3pie 0.1.9 +// Project: https://github.com/benkeen/d3pie +// Definitions by: Petryshyn Sergii +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace d3pie { + interface ID3PieChart { + redraw(): void + openSegment(index: number): void + closeSegment(index: void): void + getOpenSegment(): any + updateProp(propKey: string, value: any): void + destroy(): void + } + + interface ID3PieStyleOptions { + color?: string + fontSize?: number + font?: string + } + + interface ID3PieTextOptions extends ID3PieStyleOptions { + text?: string + } + + interface ID3PieLabelsOptions { + format?: 'label' | 'value' | 'percentage' | 'label-value1' | 'label-value2' | 'label-percentage1' | 'label-percentage2' + hideWhenLessThanPercentage?: number + } + + interface ID3PieOptions { + header?: { + title?: ID3PieTextOptions + subtitle?: ID3PieTextOptions + location?: 'top-center' | 'top-left' | 'pie-center' + titleSubtitlePadding?: number + } + footer?: { location?: 'left' } & ID3PieTextOptions + size?: { + canvasHeight?: number + canvasWidth?: number + pieOuterRadius?: string | number + pieInnerRadius?: string | number + } + data: { + sortOrder?: 'none' | 'random' | 'value-asc' | 'value-desc' | 'label-asc' | 'label-desc' + smallSegmentGrouping?: { + enabled?: boolean + value?: number + valueType?: 'percentage' | 'value' + label?: string + color?: string + } + content: { + label: string + value: number + color?: string + }[] + } + labels?: { + outer?: { pieDistance?: number } & ID3PieLabelsOptions + inner?: ID3PieLabelsOptions + mainLabel?: ID3PieStyleOptions + percentage?: { decimalPlaces?: number } & ID3PieStyleOptions + value?: ID3PieStyleOptions + lines?: { + enabled?: boolean + style?: 'curved' | 'straight' + color?: string + } + truncation?: { + enabled?: boolean + truncateLength?: number + } + formatter?: (context: { + section: 'outer' | 'inner' + value: number + label: string + }) => string + } + effects?: { + load?: { + effect?: 'none' | 'default' + speed?: number + } + pullOutSegmentOnClick?: { + effect?: 'none' | 'linear' | 'bounce' | 'elastic' | 'back' + speed?: number + size?: number + } + highlightSegmentOnMouseover?: boolean + highlightLuminosity?: number + } + tooltips?: { + enabled?: boolean + type?: 'placeholder' | 'caption' + string?: string + placeholderParser?: (index: number, data: { label?: string, percentage?: number, value?: number }) => void + styles?: { + fadeInSpeed?: number + backgroundColor?: string + backgroundOpacity?: number + color?: string + borderRadius?: number + font?: string + fontSize?: number + padding?: number + } + } + misc?: { + colors?: { + background?: string + segments?: string[] + segmentStroke?: string + } + gradient?: { + enabled?: boolean + percentage?: number + color?: string + } + canvasPadding?: { + top?: number + right?: number + bottom?: number + left?: number + } + pieCenterOffset?: { + x?: number + y?: number + } + cssPrefix?: string + } + callbacks?: { + onload?: Function + onMouseoverSegment?: Function + onMouseoutSegment?: Function + onClickSegment?: Function + } + } + + interface ID3PieClass { + new (id: string | HTMLElement, options: ID3PieOptions): ID3PieChart + } +} + +declare const d3pie: d3pie.ID3PieClass \ No newline at end of file diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts index 2ba8675436..d5e712a66c 100644 --- a/dagre-d3/dagre-d3-tests.ts +++ b/dagre-d3/dagre-d3-tests.ts @@ -11,8 +11,12 @@ namespace DagreD3Tests { predecessors["a"] = graph.predecessors("a"); successors["a"] = graph.successors("a"); + graph.transition = (selection: d3.Selection) => { + return d3.transition(); + }; const render = new dagreD3.render(); const svg = d3.select("svg"); + render.arrows()["arrowType"] = (parent: d3.Selection, id: string, edge: Dagre.Edge, type: string) => {}; render(svg, graph); } diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts index 0bc71294c8..9248222e98 100644 --- a/dagre-d3/dagre-d3.d.ts +++ b/dagre-d3/dagre-d3.d.ts @@ -19,10 +19,14 @@ declare namespace Dagre { height: number; predecessors(id: string): string[]; successors(id: string): string[]; + // see source of http://cpettitt.github.io/project/dagre-d3/latest/demo/interactive-demo.html + transition?(selection: d3.Selection): d3.Transition; width: number; } interface Render { + // see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage + arrows (): { [arrowStyleName: string]: (parent: d3.Selection, id: string, edge: Dagre.Edge, type: string) => void }; new (): Render; (selection: d3.Selection, g: Dagre.Graph): void; } diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts new file mode 100644 index 0000000000..ca1f99961c --- /dev/null +++ b/daterangepicker/daterangepicker-tests.ts @@ -0,0 +1,59 @@ +/// + +function tests_simple() { + $('#daterange').daterangepicker(); + $('input[name="daterange"]').daterangepicker({ + timePicker: true, + timePickerIncrement: 30, + locale: { + format: 'MM/DD/YYYY h:mm A' + } + }); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }); + + $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) { + $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); + }); + + + $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) { + $(this).val(''); + }); + + $('#demo').daterangepicker({ + "startDate": "05/06/2016", + "endDate": "05/12/2016" + }, function (start: string, end: string, label: string) { + console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')"); + }); + + $(function() { + + function cb(start: moment.Moment, end: moment.Moment) { + $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY')); + } + cb(moment().subtract(29, 'days'), moment()); + + $('#reportrange').daterangepicker({ + ranges: { + 'Today': [moment(), moment()], + 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], + 'Last 7 Days': [moment().subtract(6, 'days'), moment()], + 'Last 30 Days': [moment().subtract(29, 'days'), moment()], + 'This Month': [moment().startOf('month'), moment().endOf('month')], + 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] + } + }, cb); + +}); +} diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts new file mode 100644 index 0000000000..f3534a197e --- /dev/null +++ b/daterangepicker/daterangepicker.d.ts @@ -0,0 +1,166 @@ +// Type definitions for Date Range Picker v2.1.19 +// Project: http://www.daterangepicker.com/ +// Definitions by: SirMartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +interface JQuery { + daterangepicker(settings?: daterangepicker.Settings): JQuery; + daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; +} + +declare module daterangepicker { + + interface DatepickerEventObject extends JQueryEventObject { + date: Date; + format(format?: string): string; + } + + interface Settings { + /** + * The start of the initially selected date range + */ + startDate?: string | moment.Moment | Date; + /** + * The end of the initially selected date range + */ + endDate?: string | moment.Moment | Date; + /** + * The earliest date a user may select + */ + minDate?: string | moment.Moment | Date; + /** + * The latest date a user may select + */ + maxDate?: string | moment.Moment | Date; + /** + * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months) + */ + dateLimit?: any; + /** + * Show year and month select boxes above calendars to jump to a specific month and year + */ + showDropdowns?: boolean; + /** + * Show localized week numbers at the start of each week on the calendars + */ + showWeekNumbers?: boolean; + /** + * Show ISO week numbers at the start of each week on the calendars + */ + showISOWeekNumbers?: boolean; + /** + * Allow selection of dates with times, not just dates + */ + timePicker?: boolean; + /** + * Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30) + */ + timePickerIncrement?: number; + /** + * Use 24- hour instead of 12- hour times, removing the AM/ PM selection. + */ + timePicker24Hour?: boolean; + /** + * Show seconds in the timePicker. + */ + timePickerSeconds?: boolean; + /** + * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range. + */ + ranges?: any; + /** + * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to + */ + opens?: string; + /** + * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to + */ + drops?: string; + /** + * CSS class names that will be added to all buttons in the picker + */ + buttonClasses?: string[]; + /** + * CSS class string that will be added to the apply button + */ + applyClass?: string; + /** + * CSS class string that will be added to the cancel button + */ + cancelClass?: string; + /** + * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars. + */ + locale?: Locale; + /** + * Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen. + */ + singleDatePicker?: boolean; + /** + * Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected. + */ + autoApply?: boolean; + /** + * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year. + */ + linkedCalendars?: boolean; + /** + * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body' + */ + parentEl?: string; + /** + * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not. + */ + isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean; + /** + * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change. + */ + autoUpdateInput?: boolean; + /** + * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead. + */ + alwaysShowCalendars?: boolean; + } + + interface Locale { + /** + * Text for cancel label. + */ + cancelLabel?: string; + /** + * Text for apply label. + */ + applyLabel?: string; + /** + * Format of the date string. example: 'YYYY-MM-DD' + */ + format?: string; + /** + * Separator between the startDate and endDate in the attached input element. Example: ' - ' + */ + separator?: string; + /** + * Text for the week label. + */ + weekLabel?: string; + /** + * Text for the custom range label. + */ + customRangeLabel?: string; + /** + * The first day of the week (0-6, Sunday to Saturday). + */ + firstDay?: number; + /** + * Weekday names displayed in the header of calendar. + */ + daysOfWeek?: string[]; + /** + * Month names used in the month select boxes. + */ + monthNames?: string[]; + } +} diff --git a/db.js/db.js-tests.ts b/db.js/db.js-tests.ts new file mode 100644 index 0000000000..e2aacb27f0 --- /dev/null +++ b/db.js/db.js-tests.ts @@ -0,0 +1,259 @@ +// Test file for db.js Definition file +/// + +/* Type for use in tests */ + +interface Person { + firstName: string; + lastName: string; + answer: number; + group?: string; +} + +/* Opening/creating a database and connection */ + +var server: DbJs.Server; + +db.open({ + server: 'my-app', + version: 1, + schema: { + people: { + key: { keyPath: 'id', autoIncrement: true }, + indexes: { + firstName: {}, + answer: { unique: true } + } + } + } +}).then(function (s: DbJs.Server) { + server = s; +}); + +var typedStore: DbJs.TypedObjectStoreServer = server['people']; + +/* Basic server operations */ + +var idb = server.getIndexedDB(); +server.close(); + +/* General server/store methods */ + +// Adding items +server.add('people', { + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +typedStore.add({ + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +// Updating +server.update('people', { + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +typedStore.update({ + firstName: 'Aaron', + lastName: 'Powell', + answer: 42 +}).then(function (item) { }); + +// Removing +server.remove('people', 1).then(function (key) { }); +typedStore.remove(1).then(function (key) { }); + +// Clearing +server.clear('people').then(function() { }); +typedStore.clear().then(function() { }); + +// Fetching + +// Getting a single object by key +server.get('people', 5).then(function (results) { }); +typedStore.get(5).then(function (results) { }); + +// Getting a single object by key range + +// With a MongoDB-style range: + +server.get('people', {gte: 1, lt: 3}) + .then(function (results) { }); +typedStore.get({gte: 1, lt: 3}) + .then(function (results) { }); + +// With an IDBKeyRange : + +server.get('people', IDBKeyRange.bound(1, 3, false, true)) + .then(function (results) { }); +typedStore.get(IDBKeyRange.bound(1, 3, false, true)) + .then(function (results) { }); + +// Querying + +// Querying all objects +server.query('people') + .all() + .execute() + .then(function (results) { }); + +typedStore.query() + .all() + .execute() + .then(function (results) { }); + +// Querying using indexes +server.query('people', 'specialProperty') + .all() + .execute() + .then(function (results) { }); + + typedStore.query('specialProperty') + .all() + .execute() + .then(function (results) { }); + +// Filter with property and value +server.query('people') + .filter('firstName', 'Aaron') + .execute() + .then(function (results) { }); + +// Filter with function +server.query('people') + .filter(function(person: any) { return person.group === 'hipster'; }) + .execute() + .then(function (results) { }); + +typedStore.query('people') + .filter(function(person) { return person.group === 'hipster'; }) + .execute() + .then(function (results) { }); + +// Querying with ranges +server.query('people', 'firstName') + .only('Aaron') + .then(function (results) { }); + +server.query('people', 'answer') + .bound(30, 50) + .then(function (results) { }); + +server.query('people', 'firstName') + .range({ eq: 'Aaron' }) + .then(function (results) { }); + +server.query('people', 'answer') + .range({ gte: 30, lte: 50 }) + .then(function (results) { }); + +// Querying for distinct values + server.query('people', 'firstName') + .only('Aaron') + .distinct() + .execute() + .then(function (data) { }); + +// Limiting cursor range +server.query('people', 'firstName') + .all() + .limit(1, 3) + .execute() + .then(function (data) { }); + +// Cursor direction (desc) +server.query('people') + .all() + .desc() + .execute() + .then(function (results) { }); + +// Keys +server.query('people', 'firstName') + .only('Aaron') + .keys() + .execute() + .then(function (results) { }); + +// Mapping +server.query('people', 'age') + .lowerBound(30) + .map(function (value) { + return { + fullName: value.firstName + ' ' + value.lastName, + raw: value + }; + }) + .execute() + .then(function (data) { }); + +// Counting +server.query('people', 'firstName') + .only('Aaron') + .count() + .execute() + .then(function (results) { }); + +// With no arguments (count all items) +server.count().then(function (ct) { }); + +// With a key +server.count('myKey').then(function (ct) { }); + +// With a MongoDB-style range +server.count({gte: 1, lt: 3}).then(function (ct) { }); + +// With an IDBKeyRange range +server.count(IDBKeyRange.bound(1, 3, false, true)).then(function (ct) { }); + +// Atomic updates +server.query('users', 'last_mod') + .lowerBound(new Date().getTime() - 10000) + .modify({ last_mod: new Date().getTime() }) + .execute() + .then(function(results) { }); + +server.query('users', 'changed') + .only(true) + .modify({ changed: false }) + .execute() + .then(function () { }); + +server.query('users', 'name') + .lowerBound('marcy') + .modify({ views: function(profile: any) { return profile.views + 1; } }) + .execute() + .then(function () { }); + +/* Other server methods */ + +// Closing connection +server.close(); + +// Retrieving the indexedDB.open result object in use +var storeNames = server.getIndexedDB().objectStoreNames; + +// Server event handlers + +server.addEventListener('abort', function (e: Event) { }); +server.addEventListener('error', function (err: Event) { }); +server.addEventListener('versionchange', function (e: Event) { }); + +server + .abort(function (e) { }) + .error(function (err) { }) + .versionchange(function (e) { }); + +// Deleting a database +db.delete('dbName').then(function () { }, function (err: Error) { }); +db.delete('dbName').catch(function (err) { }).then(function (ev) { }); + +// Comparing two keys + +db.cmp('key1', 'key2'); diff --git a/db.js/db.js.d.ts b/db.js/db.js.d.ts new file mode 100644 index 0000000000..83e21fa529 --- /dev/null +++ b/db.js/db.js.d.ts @@ -0,0 +1,154 @@ +// Type definitions for db.js v0.14.0 +// Project: https://github.com/aaronpowell/db.js/ +// Definitions by: Chris Wrench +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module DbJs { + interface ErrorListener { + (err: Error): void; + } + + interface OpenOptions { + server: string; + version: number; + schema?: any; + } + + interface DbJsStatic { + open(options: OpenOptions): Promise; + delete(dbName: string): Promise; + cmp(key1: any, key2: any): number; + } + + // Query API + + interface ExecutableQuery { + execute(): Promise; + } + + interface CountableQuery { + count(): ExecutableQuery; + } + + interface KeysQuery extends DescableQuery, ExecutableQuery, FilterableQuery, DistinctableQuery, MappableQuery { + } + + interface KeyableQuery { + keys(): KeysQuery; + } + + interface FilterQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery { + } + + interface FilterableQuery { + filter(index: string, value: TValue): FilterQuery; + filter(filter: (value: T) => boolean): FilterQuery; + } + + interface DescQuery extends KeyableQuery, CountableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery { + } + + interface DescableQuery { + desc(): DescQuery; + } + + interface DistinctQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, ModifiableQuery, MappableQuery, CountableQuery { + } + + interface DistinctableQuery { + distinct(filter?: (value: T) => boolean): DistinctQuery; + } + + interface ModifiableQuery { + modify(filter: (value: T) => boolean): ExecutableQuery; + modify(modifyObj: any): ExecutableQuery; + } + + interface LimitableQuery { + limit(n: any, m: any): ExecutableQuery; + } + + interface MappableQuery { + map(fn: (value: T) => TMap): Query; + } + + interface Query extends Promise, KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery, CountableQuery { + } + + interface IndexQuery extends Query { + only(...args: any[]): Query; + bound(lowerBound: any, upperBound: any): Query; + upperBound(upperBound: any): Query; + lowerBound(lowerBound: any): Query; + range(opts: any): Query; + all(): Query; + } + + interface KeyValuePair { + key: TKey; + item: TValue; + } + + interface BaseServer { + getIndexedDB(): IDBDatabase; + close(): void; + } + + interface IndexAccessibleServer { + [store: string]: TypedObjectStoreServer; + } + + interface ObjectStoreServer { + add(table: string, entity: T): Promise; + add(table: string, ...entities: T[]): Promise; + add(table: string, entity: KeyValuePair): Promise>; + add(table: string, ...entities: KeyValuePair[]): Promise[]>; + update(table: string, entity: T): Promise; + update(table: string, ...entities: T[]): Promise; + update(table: string, entity: KeyValuePair): Promise>; + update(table: string, ...entities: KeyValuePair[]): Promise[]>; + remove(table: string, key: TKey): Promise; + remove(table: string, ...keys: TKey[]): Promise; + clear(table: string): Promise; + get(table: string, key: any): Promise; + query(table: string): IndexQuery; + query(table: string, index: string): IndexQuery; + count(): Promise; + count(keyOrRange: any): Promise; + count(table: string, key: any): Promise; + addEventListener(type: 'abort', listener: (ev: Event) => any): void; + addEventListener(type: 'versionchange', listener: (ev: Event) => any): void; + addEventListener(type: 'error', listener: (err: Error) => any): void; + addEventListener(type: string, listener: EventListener | ErrorListener): void; + abort(listener: (ev: Event) => any): ObjectStoreServer; + versionchange(listener: (ev: Event) => any): ObjectStoreServer; + error(listener: (ev: Error) => any): ObjectStoreServer; + } + + interface TypedObjectStoreServer { + add(entity: T): Promise; + add(...entities: T[]): Promise; + add(entity: KeyValuePair): Promise>; + add(...entities: KeyValuePair[]): Promise[]>; + update(entity: T): Promise; + update(...entities: T[]): Promise; + update(entity: KeyValuePair): Promise>; + update(...entities: KeyValuePair[]): Promise[]>; + remove(key: TKey): Promise; + remove(...keys: TKey[]): Promise; + clear(): Promise; + get(key: any): Promise; + query(): IndexQuery; + query(index: string): IndexQuery; + count(key: any): Promise; + } + + type Server = DbJs.IndexAccessibleServer & DbJs.ObjectStoreServer & DbJs.BaseServer; +} + +declare module "db" { + var db: DbJs.DbJsStatic; + export = db; +} + +declare var db: DbJs.DbJsStatic; diff --git a/devextreme/devextreme-15.2.9.d.ts b/devextreme/devextreme-15.2.9.d.ts new file mode 100644 index 0000000000..3a7d42e05a --- /dev/null +++ b/devextreme/devextreme-15.2.9.d.ts @@ -0,0 +1,7443 @@ +// Type definitions for DevExtreme 15.2.9 +// Project: http://js.devexpress.com/ +// Definitions by: DevExpress Inc. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module DevExpress { + /** A mixin that provides a capability to fire and subscribe to events. */ + export interface EventsMixin { + /** Subscribes to a specified event. */ + on(eventName: string, eventHandler: Function): T; + /** Subscribes to the specified events. */ + on(events: { [eventName: string]: Function; }): T; + /** Detaches all event handlers from the specified event. */ + off(eventName: string): Object; + /** Detaches a particular event handler from the specified event. */ + off(eventName: string, eventHandler: Function): T; + } + /** An object that serves as a namespace for the methods required to perform validation. */ + export module validationEngine { + export interface IValidator { + validate(): ValidatorValidationResult; + reset(): void; + } + export interface ValidatorValidationResult { + isValid: boolean; + name?: string; + value: any; + brokenRule: any; + validationRules: any[]; + } + export interface ValidationGroupValidationResult { + isValid: boolean; + brokenRules: any[]; + validators: IValidator[]; + } + export interface GroupConfig extends EventsMixin { + group: any; + validators: IValidator[]; + validate(): ValidationGroupValidationResult; + reset(): void; + } + /** Provides access to the object that represents the specified validation group. */ + export function getGroupConfig(group: any): GroupConfig + /** Provides access to the object that represents the default validation group. */ + export function getGroupConfig(): GroupConfig + /** Validates rules of the validators that belong to the specified validation group. */ + export function validateGroup(group: any): ValidationGroupValidationResult; + /** Validates rules of the validators that belong to the default validation group. */ + export function validateGroup(): ValidationGroupValidationResult; + /** Resets the values and validation result of the editors that belong to the specified validation group. */ + export function resetGroup(group: any): void; + /** Resets the values and validation result of the editors that belong to the default validation group. */ + export function resetGroup(): void; + /** Validates the rules that are defined within the dxValidator objects that are registered for the specified ViewModel. */ + export function validateModel(model: Object): ValidationGroupValidationResult; + /** Registers all the dxValidator objects by which the fields of the specified ViewModel are extended. */ + export function registerModelForValidation(model: Object) : void; + } + export var hardwareBackButton: JQueryCallback; + /** Processes the hardware back button click. */ + export function processHardwareBackButton(): void; + /** Hides the last displayed overlay widget. */ + export function hideTopOverlay(): boolean; + /** Specifies whether or not the entire application/site supports right-to-left representation. */ + export var rtlEnabled: boolean; + /** Registers a new component in the DevExpress.ui namespace as a jQuery plugin, Angular directive and Knockout binding. */ + export function registerComponent(name: string, componentClass: Object): void; + /** Registers a new component in the specified namespace as a jQuery plugin, Angular directive and Knockout binding. */ + export function registerComponent(name: string, namespace: Object, componentClass: Object): void; + export function requestAnimationFrame(callback: Function): number; + export function cancelAnimationFrame(requestID: number): void; + /** Custom Knockout binding that links an HTML element with a specific action. */ + export class Action { } + /** Used to get URLs that vary in a locally running application and the application running on production. */ + export class EndpointSelector { + constructor(options: { + [key: string]: { + local?: string; + production?: string; + } + }); + /** Returns a local or a productional URL depending on how the application is currently running. */ + urlFor(key: string): string; + } + /** An object that serves as a namespace for the methods that are used to animate UI elements. */ + export module fx { + /** Defines animation options. */ + export interface AnimationOptions { + /** A function called after animation is completed. */ + complete?: (element: JQuery, config: AnimationOptions) => void; + /** A number specifying wait time before animation execution. */ + delay?: number; + /** A number specifying the time period to wait before the animation of the next stagger item starts. */ + staggerDelay?: number; + /** A number specifying the time in milliseconds spent on animation. */ + duration?: number; + /** A string specifying the type of an easing function used for animation. */ + easing?: string; + /** Specifies the initial animation state. */ + from?: any; + /** A function called before animation is started. */ + start?: (element: JQuery, config: AnimationOptions) => void; + /** Specifies a final animation state. */ + to?: any; + /** A string value specifying the animation type. */ + type?: string; + /** Specifies the animation direction for the "slideIn" and "slideOut" animation types. */ + direction?: string; + } + /** Animates the specified element. */ + export function animate(element: HTMLElement, config: AnimationOptions): Object; + /** Returns a value indicating whether the specified element is being animated. */ + export function isAnimating(element: HTMLElement): boolean; + /** Stops the animation. */ + export function stop(element: HTMLElement, jumpToEnd: boolean): void; + } + /** The manager that performs several specified animations at a time. */ + export class TransitionExecutor { + /** Deletes all the animations registered in the Transition Executor by using the enter(elements, animation) and leave(elements, animation) methods. */ + reset(): void; + /** Registers a set of elements that should be animated as "entering" using the specified animation configuration. */ + enter(elements: JQuery, animation: any): void; + /** Registers a set of elements that should be animated as "leaving" using the specified animation configuration. */ + leave(elements: JQuery, animation: any): void; + /** Starts all the animations registered using the enter(elements, animation) and leave(elements, animation) methods beforehand. */ + start(config: Object): JQueryPromise; + /** Stops all started animations. */ + stop(): void; + } + export class AnimationPresetCollection { + /** Resets all the changes made in the animation repository. */ + resetToDefaults(): void; + /** Deletes the specified animation or clears all the animation repository, if an animation name is not passed. */ + clear(name: string): void; + /** Adds the specified animation preset to the animation repository by the specified name. */ + registerPreset(name: string, config: any): void; + /** Applies the changes made in the animation repository. */ + applyChanges(): void; + /** Returns the configuration of the animation found in the animation repository by the specified name for the current device. */ + getPreset(name: string): void; + /** Registers predefined animations in the animation repository. */ + registerDefaultPresets(): void; + } + /** A repository of animations. */ + export var animationPresets: AnimationPresetCollection; + /** The device object defines the device on which the application is running. */ + export interface Device { + /** Indicates whether or not the device platform is Android. */ + android?: boolean; + /** Specifies the type of the device on which the application is running. */ + deviceType?: string; + /** Indicates whether or not the device platform is generic, which means that the application will look and behave according to a generic "light" or "dark" theme. */ + generic?: boolean; + /** Indicates whether or not the device platform is iOS. */ + ios?: boolean; + /** Indicates whether or not the device type is 'phone'. */ + phone?: boolean; + /** Specifies the platform of the device on which the application is running. */ + platform?: string; + /** Indicates whether or not the device type is 'tablet'. */ + tablet?: boolean; + /** Specifies an array with the major and minor versions of the device platform. */ + version?: Array; + /** Indicates whether or not the device platform is Windows. */ + win?: boolean; + /** Specifies a performance grade of the current device. */ + grade?: string; + } + export class Devices implements EventsMixin { + constructor(options: { window: Window }); + /** Overrides actual device information to force the application to operate as if it was running on the specified device. */ + current(deviceName: any): void; + /** Returns information about the current device. */ + current(): Device; + orientationChanged: JQueryCallback; + /** Returns the current device orientation. */ + orientation(): string; + /** Returns real information about the current device regardless of the value passed to the devices.current(deviceName) method. */ + real(): Device; + on(eventName: "orientationChanged", eventHandler: (e: { orientation: string }) => void): Devices; + on(eventName: string, eventHandler: Function): Devices; + on(events: { [eventName: string]: Function; }): Devices; + off(eventName: "orientationChanged"): Devices; + off(eventName: string): Devices; + off(eventName: "orientationChanged", eventHandler: (e: { orientation: string }) => void): Devices; + off(eventName: string, eventHandler: Function): Devices; + } + /** An object that serves as a namespace for the methods and events specifying information on the current device. */ + export var devices: Devices; + /** The position object specifies the widget positioning options. */ + export interface PositionOptions { + /** The target element position that the widget is positioned against. */ + at?: string; + /** The element within which the widget is positioned. */ + boundary?: Element; + /** A string value holding horizontal and vertical offset from the window's boundaries. */ + boundaryOffset?: string; + /** Specifies how to move the widget if it overflows the screen. */ + collision?: any; + /** The position of the widget to align against the target element. */ + my?: string; + /** The target element that the widget is positioned against. */ + of?: HTMLElement; + /** A string value holding horizontal and vertical offset in pixels, separated by a space (e.g., "5 -10"). */ + offset?: string; + } + export interface ComponentOptions { + /** A handler for the initialized event. */ + onInitialized?: Function; + /** A handler for the optionChanged event. */ + onOptionChanged?: Function; + /** A handler for the disposing event. */ + onDisposing?: Function; + } + /** A base class for all components and widgets. */ + export class Component { + constructor(options?: ComponentOptions) + /** Prevents the component from refreshing until the endUpdate method is called. */ + beginUpdate(): void; + /** Enables the component to refresh after the beginUpdate method call. */ + endUpdate(): void; + /** Returns an instance of this component class. */ + instance(): Component; + /** Returns the configuration options of this component. */ + option(): { + [optionKey: string]: any; + }; + /** Sets one or more options of this component. */ + option(options: { + [optionKey: string]: any; + }): void; + /** Gets the value of the specified configuration option of this component. */ + option(optionName: string): any; + /** Sets a value to the specified configuration option of this component. */ + option(optionName: string, optionValue: any): void; + } + export interface DOMComponentOptions extends ComponentOptions { + /** Specifies whether or not the current component supports a right-to-left representation. */ + rtlEnabled?: boolean; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies the width of the widget. */ + width?: any; + } + /** A base class for all components. */ + export class DOMComponent extends Component { + constructor(element: JQuery, options?: DOMComponentOptions); + constructor(element: HTMLElement, options?: DOMComponentOptions); + /** Returns the root HTML element of the widget. */ + element(): JQuery; + /** Specifies the device-dependent default configuration options for this component. */ + static defaultOptions(rule: { + device?: any; + options?: any; + }): void; + } + export module data { + export interface ODataError extends Error { + httpStatus?: number; + errorDetails?: any; + } + export interface StoreOptions { + /** A handler for the modified event. */ + onModified?: () => void; + /** A handler for the modifying event. */ + onModifying?: () => void; + /** A handler for the removed event. */ + onRemoved?: (key: any) => void; + /** A handler for the removing event. */ + onRemoving?: (key: any) => void; + /** A handler for the updated event. */ + onUpdated?: (key: any, values: Object) => void; + /** A handler for the updating event. */ + onUpdating?: (key: any, values: Object) => void; + /** A handler for the loaded event. */ + onLoaded?: (result: Array) => void; + /** A handler for the loading event. */ + onLoading?: (loadOptions: LoadOptions) => void; + /** A handler for the inserted event. */ + onInserted?: (values: Object, key: any) => void; + /** A handler for the inserting event. */ + onInserting?: (values: Object) => void; + /** Specifies the function called when the Store causes an error. */ + errorHandler?: (e: Error) => void; + /** Specifies the key properties within the data associated with the Store. */ + key?: any; + } + export interface LoadOptions { + filter?: Object; + sort?: Object; + select?: Object; + expand?: Object; + group?: Object; + skip?: number; + take?: number; + userData?: Object; + requireTotalCount?: boolean; + } + /** The base class for all Stores. */ + export class Store implements EventsMixin { + constructor(options?: StoreOptions); + /** Returns the data item specified by the key. */ + byKey(key: any): JQueryPromise; + /** Adds an item to the data associated with this Store. */ + insert(values: Object): JQueryPromise; + /** Returns the key expression specified via the key configuration option. */ + key(): any; + /** Returns the key of the Store item that matches the specified object. */ + keyOf(obj: Object): any; + /** Starts loading data. */ + load(obj?: LoadOptions): JQueryPromise; + /** Removes the data item specified by the key. */ + remove(key: any): JQueryPromise; + /** Obtains the total count of items that will be returned by the load() function. */ + totalCount(options?: { + filter?: Object; + group?: Object; + }): JQueryPromise; + /** Updates the data item specified by the key. */ + update(key: any, values: Object): JQueryPromise; + on(eventName: "removing", eventHandler: (key: any) => void): Store; + on(eventName: "removed", eventHandler: (key: any) => void): Store; + on(eventName: "updating", eventHandler: (key: any, values: Object) => void): Store; + on(eventName: "updated", eventHandler: (key: any, values: Object) => void): Store; + on(eventName: "inserting", eventHandler: (values: Object) => void): Store; + on(eventName: "inserted", eventHandler: (values: Object, key: any) => void): Store; + on(eventName: "modifying", eventHandler: () => void): Store; + on(eventName: "modified", eventHandler: () => void): Store; + on(eventName: "loading", eventHandler: (loadOptions: LoadOptions) => void): Store; + on(eventName: "loaded", eventHandler: (result: Array) => void): Store; + on(eventName: string, eventHandler: Function): Store; + on(events: { [eventName: string]: Function; }): Store; + off(eventName: "removing"): Store; + off(eventName: "removed"): Store; + off(eventName: "updating"): Store; + off(eventName: "updated"): Store; + off(eventName: "inserting"): Store; + off(eventName: "inserted"): Store; + off(eventName: "modifying"): Store; + off(eventName: "modified"): Store; + off(eventName: "loading"): Store; + off(eventName: "loaded"): Store; + off(eventName: string): Store; + off(eventName: "removing", eventHandler: (key: any) => void): Store; + off(eventName: "removed", eventHandler: (key: any) => void): Store; + off(eventName: "updating", eventHandler: (key: any, values: Object) => void): Store; + off(eventName: "updated", eventHandler: (key: any, values: Object) => void): Store; + off(eventName: "inserting", eventHandler: (values: Object) => void): Store; + off(eventName: "inserted", eventHandler: (values: Object, key: any) => void): Store; + off(eventName: "modifying", eventHandler: () => void): Store; + off(eventName: "modified", eventHandler: () => void): Store; + off(eventName: "loading", eventHandler: (loadOptions: LoadOptions) => void): Store; + off(eventName: "loaded", eventHandler: (result: Array) => void): Store; + off(eventName: string, eventHandler: Function): Store; + } + export interface ArrayStoreOptions extends StoreOptions { + /** Specifies the array associated with this Store. */ + data?: Array; + } + /** A Store accessing an in-memory array. */ + export class ArrayStore extends Store { + constructor(options?: ArrayStoreOptions); + /** Clears all data associated with the current ArrayStore. */ + clear(): void; + /** Creates the Query object for the underlying array. */ + createQuery(): Query; + } + interface Promise { + then(doneFn?: Function, failFn?: Function, progressFn?: Function): Promise; + } + export interface CustomStoreOptions extends StoreOptions { + /** The user implementation of the byKey(key, extraOptions) method. */ + byKey?: (key: any) => Promise; + /** The user implementation of the insert(values) method. */ + insert?: (values: Object) => Promise; + /** The user implementation of the load(options) method. */ + load?: (options?: LoadOptions) => Promise; + /** The user implementation of the remove(key) method. */ + remove?: (key: any) => Promise; + /** The user implementation of the totalCount(options) method. */ + totalCount?: (options?: { + filter?: Object; + group?: Object; + }) => Promise; + /** The user implementation of the update(key, values) method. */ + update?: (key: any, values: Object) => Promise; + } + /** A Store object that enables you to implement your own data access logic. */ + export class CustomStore extends Store { + constructor(options: CustomStoreOptions); + } + export interface DataSourceOptions { + /** Specifies data filtering conditions. */ + filter?: Object; + /** Specifies data grouping conditions. */ + group?: Object; + /** The item mapping function. */ + map?: (record: any) => any; + /** Specifies the maximum number of items the page can contain. */ + pageSize?: number; + /** Specifies whether a DataSource loads data by pages, or all items at once. */ + paginate?: boolean; + /** The data post processing function. */ + postProcess?: (data: any[]) => any[]; + /** Specifies a value by which the required items are searched. */ + searchExpr?: Object; + /** Specifies the comparison operation used to search for the required items. */ + searchOperation?: string; + /** Specifies the value to which the search expression is compared. */ + searchValue?: Object; + /** Specifies the initial select option value. */ + select?: Object; + /** An array of the strings that represent the names of the navigation properties to be loaded simultaneously with the OData store's entity. */ + expand?: Object; + /** Specifies whether or not the DataSource instance requests the total count of items available in the storage. */ + requireTotalCount?: boolean; + /** Specifies the initial sort option value. */ + sort?: Object; + /** Specifies the underlying Store instance used to access data. */ + store?: any; + /** A handler for the changed event. */ + onChanged?: () => void; + /** A handler for the loadingChanged event. */ + onLoadingChanged?: (isLoading: boolean) => void; + /** A handler for the loadError event. */ + onLoadError?: (e?: Error) => void; + } + export interface OperationPromise extends JQueryPromise { + operationId: number; + } + /** An object that provides access to a data web service or local data storage for collection container widgets. */ + export class DataSource implements EventsMixin { + constructor(url: string); + constructor(data: Array); + constructor(options: CustomStoreOptions); + constructor(options: DataSourceOptions); + /** Disposes all resources associated with this DataSource. */ + dispose(): void; + /** Returns the current filter option value. */ + filter(): Object; + /** Sets the filter option value. */ + filter(filterExpr: Object): void; + /** Returns the current group option value. */ + group(): Object; + /** Sets the group option value. */ + group(groupExpr: Object): void; + /** Indicates whether or not the current page contains fewer items than the number of items specified by the pageSize configuration option. */ + isLastPage(): boolean; + /** Indicates whether or not at least one load() method execution has successfully finished. */ + isLoaded(): boolean; + /** Indicates whether or not the DataSource is currently being loaded. */ + isLoading(): boolean; + /** Returns the array of items currently operated by the DataSource. */ + items(): Array; + /** Returns the key expression. */ + key(): any; + /** Starts loading data. */ + load(): OperationPromise>; + /** Clears currently loaded DataSource items and calls the load() method. */ + reload(): OperationPromise>; + /** Returns an object that would be passed to the load() method of the underlying Store according to the current data shaping option values of the current DataSource instance. */ + loadOptions(): Object; + /** Returns the current pageSize option value. */ + pageSize(): number; + /** Sets the pageSize option value. */ + pageSize(value: number): void; + /** Specifies the index of the currently loaded page. */ + pageIndex(): number; + /** Specifies the index of the page to be loaded during the next load() method execution. */ + pageIndex(newIndex: number): void; + /** Returns the current paginate option value. */ + paginate(): boolean; + /** Sets the paginate option value. */ + paginate(value: boolean): void; + /** Returns the searchExpr option value. */ + searchExpr(): Object; + /** Sets the searchExpr option value. */ + searchExpr(expr: Object): void; + /** Returns the currently specified search operation. */ + searchOperation(): string; + /** Sets the current search operation. */ + searchOperation(op: string): void; + /** Returns the searchValue option value. */ + searchValue(): Object; + /** Sets the searchValue option value. */ + searchValue(value: Object): void; + /** Returns the current select option value. */ + select(): Object; + /** Sets the select option value. */ + select(expr: Object): void; + /** Returns the current requireTotalCount option value. */ + requireTotalCount(): boolean; + /** Sets the requireTotalCount option value. */ + requireTotalCount(value: boolean): void; + /** Returns the current sort option value. */ + sort(): Object; + /** Sets the sort option value. */ + sort(sortExpr: Object): void; + /** Returns the underlying Store instance. */ + store(): Store; + /** Returns the number of data items available in an underlying Store after the last load() operation without paging. */ + totalCount(): number; + cancel(operationId: number): boolean; + on(eventName: "loadingChanged", eventHandler: (isLoading: boolean) => void): DataSource; + on(eventName: "loadError", eventHandler: (e?: Error) => void): DataSource; + on(eventName: "changed", eventHandler: () => void): DataSource; + on(eventName: string, eventHandler: Function): DataSource; + on(events: { [eventName: string]: Function; }): DataSource; + off(eventName: "loadingChanged"): DataSource; + off(eventName: "loadError"): DataSource; + off(eventName: "changed"): DataSource; + off(eventName: string): DataSource; + off(eventName: "loadingChanged", eventHandler: (isLoading: boolean) => void): DataSource; + off(eventName: "loadError", eventHandler: (e?: Error) => void): DataSource; + off(eventName: "changed", eventHandler: () => void): DataSource; + off(eventName: string, eventHandler: Function): DataSource; + } + /** An object used to work with primitive data types not supported by JavaScript when accessing an OData web service. */ + export class EdmLiteral { + /** Creates an EdmLiteral instance and assigns the specified value to it. */ + constructor(value: string); + /** Returns a string representation of the value associated with this EdmLiteral object. */ + valueOf(): string; + } + /** An object used to generate and hold the GUID. */ + export class Guid { + /** Creates a new Guid instance that holds the specified GUID. */ + constructor(value: string); + /** Creates a new Guid instance holding the generated GUID. */ + constructor(); + /** Returns a string representation of the Guid instance. */ + toString(): string; + /** Returns a string representation of the Guid instance. */ + valueOf(): string; + } + export interface LocalStoreOptions extends ArrayStoreOptions { + /** Specifies the time (in miliseconds) after the change operation, before the data is flushed. */ + flushInterval?: number; + /** Specifies whether the data is flushed immediatelly after each change operation, or after the delay specified via the flushInterval option. */ + immediate?: boolean; + /** The unique identifier used to distinguish the data within the HTML5 Web Storage. */ + name?: string; + } + /** A Store providing access to the HTML5 Web Storage. */ + export class LocalStore extends ArrayStore { + constructor(options?: LocalStoreOptions); + /** Removes all data associated with this Store. */ + clear(): void; + } + export interface ODataContextOptions extends ODataStoreOptions { + /** Specifies the list of entities to be accessed via the ODataContext. */ + entities?: Object; + /** Specifies the function called if the ODataContext causes an error. */ + errorHandler?: (e: Error) => void; + } + /** Provides access to the entire OData service. */ + export class ODataContext { + constructor(options?: ODataContextOptions); + /** Initiates the specified WebGet service operation that returns a value. For the information on service operations, refer to the OData documentation. */ + get(operationName: string, params: Object): JQueryPromise; + /** Initiates the specified WebGet service operation that returns nothing. For the information on service operations, refer to the OData documentation. */ + invoke(operationName: string, params: Object, httpMethod: Object): JQueryPromise; + /** Return a special proxy object to describe the entity link. */ + objectLink(entityAlias: string, key: any): Object; + } + export interface ODataStoreOptions extends StoreOptions { + /** A function used to customize a web request before it is sent. */ + beforeSend?: (request: { + url: string; + async: boolean; + method: string; + timeout: number; + params: Object; + payload: Object; + headers: Object; + }) => void; + /** Specifies whether the ODataStore uses the JSONP approach to access non-CORS-compatible remote services. */ + jsonp?: boolean; + /** Specifies the type of the ODataStore key property. The following key types are supported out of the box: String, Int32, Int64, and Guid. */ + keyType?: any; + /** Specifies whether or not dates found in the response are deserialized. */ + deserializeDates?: boolean; + /** Specifies the URL of the data service being accessed via the current ODataContext. */ + url?: string; + /** Specifies the version of the OData protocol used to interact with the data service. */ + version?: number; + /** Specifies the value of the withCredentials field of the underlying jqXHR object. */ + withCredentials?: boolean; + } + /** A Store providing access to a separate OData web service entity. */ + export class ODataStore extends Store { + constructor(options?: ODataStoreOptions); + /** Creates the Query object for the OData endpoint. */ + createQuery(loadOptions: Object): Object; + /** Returns the data item specified by the key. */ + byKey(key: any, extraOptions?: { expand?: Object }): JQueryPromise; + } + /** An universal chainable data query interface object. */ + export interface Query { + /** Calculates a custom summary for the items in the current Query. */ + aggregate(step: (accumulator: any, value: any) => any): JQueryPromise; + /** Calculates a custom summary for the items in the current Query. */ + aggregate(seed: any, step: (accumulator: any, value: any) => any, finalize: (result: any) => any): JQueryPromise; + /** Calculates the average item value for the current Query. */ + avg(getter: Object): JQueryPromise; + /** Finds the item with the maximum getter value. */ + max(getter: Object): JQueryPromise; + /** Finds the item with the maximum value in the Query. */ + max(): JQueryPromise; + /** Finds the item with the minimum value in the Query. */ + min(): JQueryPromise; + /** Finds the item with the minimum getter value. */ + min(getter: Object): JQueryPromise; + /** Calculates the average item value for the current Query, if each Query item has a numeric type. */ + avg(): JQueryPromise; + /** Returns the total count of items in the current Query. */ + count(): JQueryPromise; + /** Executes the Query. */ + enumerate(): JQueryPromise; + /** Filters the current Query data. */ + filter(criteria: Array): Query; + /** Filters the current Query data. */ + filter(predicate: (item: any) => boolean): Query; + /** Groups the current Query data. */ + groupBy(getter: Object): Query; + /** Applies the specified transformation to each item. */ + select(getter: Object): Query; + /** Limits the data item count. */ + slice(skip: number, take?: number): Query; + /** Sorts current Query data. */ + sortBy(getter: Object, desc: boolean): Query; + /** Sorts current Query data. */ + sortBy(getter: Object): Query; + /** Calculates the sum of item getter values in the current Query. */ + sum(getter: Object): JQueryPromise; + /** Calculates the sum of item values in the current Query. */ + sum(): JQueryPromise; + /** Adds one more sorting condition to the current Query. */ + thenBy(getter: Object): Query; + /** Adds one more sorting condition to the current Query. */ + thenBy(getter: Object, desc: boolean): Query; + /** Returns the array of current Query items. */ + toArray(): Array; + } + /** The global data layer error handler. */ + export var errorHandler: (e: Error) => void; + /** Encodes the specified string or array of bytes to base64 encoding. */ + export function base64_encode(input: any): string; + /** Creates a Query instance. */ + export function query(array: Array): Query; + /** Creates a Query instance for accessing the remote service specified by a URL. */ + export function query(url: string, queryOptions: Object): Query; + /** This section describes the utility objects provided by the DevExtreme data layer. */ + export var utils: { + /** Compiles a getter function from the getter expression. */ + compileGetter(expr: any): Function; + /** Compiles a setter function from the setter expression. */ + compileSetter(expr: any): Function; + odata: { + /** Holds key value converters for OData. */ + keyConverters: { + String(value: any): string; + Int32(value: any): number; + Int64(value: any): EdmLiteral; + Guid(value: any): Guid; + Boolean(value: any): boolean; + Single(value: any): EdmLiteral; + Decimal(value: any): EdmLiteral; + }; + } + } + } + /** An object that serves as a namespace for DevExtreme UI widgets as well as for methods implementing UI logic in DevExtreme sites/applications. */ + export module ui { + export interface WidgetOptions extends DOMComponentOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A Boolean value specifying whether or not the widget can respond to user interaction. */ + disabled?: boolean; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + /** Specifies whether or not the widget can be focused. */ + focusStateEnabled?: boolean; + /** Specifies a shortcut key that sets focus on the widget element. */ + accessKey?: string; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + /** Specifies the widget tab index. */ + tabIndex?: number; + /** Specifies the text of the hint displayed for the widget. */ + hint?: string; + } + /** The base class for widgets. */ + export class Widget extends DOMComponent { + constructor(options?: WidgetOptions); + /** Redraws the widget. */ + repaint(): void; + /** Sets focus on the widget. */ + focus(): void; + /** Registers a handler when a specified key is pressed. */ + registerKeyHandler(key: string, handler: Function): void; + } + export interface CollectionWidgetOptions extends WidgetOptions { + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** The time period in milliseconds before the onItemHold event is raised. */ + itemHoldTimeout?: number; + /** An array of items displayed by the widget. */ + items?: Array; + /** The template to be used for rendering items. */ + itemTemplate?: any; + loopItemFocus?: boolean; + /** The text or HTML markup displayed by the widget if the item collection is empty. */ + noDataText?: string; + onContentReady?: any; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** A handler for the itemContextMenu event. */ + onItemContextMenu?: Function; + /** A handler for the itemHold event. */ + onItemHold?: Function; + /** A handler for the itemRendered event. */ + onItemRendered?: Function; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: Function; + /** The index of the currently selected widget item. */ + selectedIndex?: number; + /** The selected item object. */ + selectedItem?: Object; + /** An array of currently selected item objects. */ + selectedItems?: Array; + /** A handler for the itemDeleting event. */ + onItemDeleting?: Function; + /** A handler for the itemDeleted event. */ + onItemDeleted?: Function; + /** A handler for the itemReordered event. */ + onItemReordered?: Function; + } + /** The base class for widgets containing an item collection. */ + export class CollectionWidget extends Widget { + constructor(element: JQuery, options?: CollectionWidgetOptions); + constructor(element: HTMLElement, options?: CollectionWidgetOptions); + selectItem(itemElement: any): void; + unselectItem(itemElement: any): void; + deleteItem(itemElement: any): JQueryPromise; + isItemSelected(itemElement: any): boolean; + reorderItem(itemElement: any, toItemElement: any): JQueryPromise; + } + export interface DataExpressionMixinOptions { + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** Specifies the name of the data source item field whose value is displayed by the widget. */ + displayExpr?: any; + /** Specifies the name of a data source item field whose value is held in the value configuration option. */ + valueExpr?: any; + /** An array of items displayed by the widget. */ + items?: Array; + /** The template to be used for rendering items. */ + itemTemplate?: any; + /** The currently selected value in the widget. */ + value?: Object; + } + export interface EditorOptions extends WidgetOptions { + /** The currently specified value. */ + value?: Object; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + /** A Boolean value specifying whether or not the widget is read-only. */ + readOnly?: boolean; + /** Holds the object that defines the error that occurred during validation. */ + validationError?: Object; + /** Specifies whether the editor's value is valid. */ + isValid?: boolean; + /** Specifies how the message about the validation rules that are not satisfied by this editor's value is displayed. */ + validationMessageMode?: string; + } + /** A base class for editors. */ + export class Editor extends Widget { + /** Resets the editor's value to undefined. */ + reset(): void; + } + /** An object that serves as a namespace for methods displaying a message in an application/site. */ + export var dialog: { + /** Creates an alert dialog message containing a single "OK" button. */ + alert(message: string, title: string): JQueryPromise; + /** Creates a confirm dialog that contains "Yes" and "No" buttons. */ + confirm(message: string, title: string): JQueryPromise; + /** Creates a custom dialog using the options specified by the passed configuration object. */ + custom(options: { title?: string; message?: string; buttons?: Array; }): { + show(): JQueryPromise; + hide(): void; + hide(value: any): void; + }; + }; + /** Creates a toast message. */ + export function notify(message: any, type: string, displayTime: number): void; + /** Creates a toast message. */ + export function notify(options: Object): void; + /** An object that serves as a namespace for the methods that work with DevExtreme CSS Themes. */ + export var themes: { + /** Returns the name of the currently applied theme. */ + current(): string; + /** Changes the current theme to the specified one. */ + current(themeName: string): void; + }; + /** Sets a specified template engine. */ + export function setTemplateEngine(name: string): void; + /** Sets a custom template engine defined via custom compile and render functions. */ + export function setTemplateEngine(options: Object): void; + } + /** An object that serves as a namespace for utility methods that can be helpful when working with the DevExtreme framework and UI widgets. */ + export var utils: { + /** Sets parameters for the viewport meta tag. */ + initMobileViewport(options: { allowZoom?: boolean; allowPan?: boolean; allowSelection?: boolean }): void; + /** Requests that the browser call a specified function to update animation before the next repaint. */ + requestAnimationFrame(callback: Function): number; + /** Cancels an animation frame request scheduled with the requestAnimationFrame method. */ + cancelAnimationFrame(requestID: number): void; + }; + /** An object that serves as a namespace for DevExtreme Data Visualization Widgets. */ + export module viz { + /** Applies a theme for the entire page with several DevExtreme visualization widgets. */ + export function currentTheme(theme: string): void; + /** Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. */ + export function currentTheme(platform: string, colorScheme: string): void; + /** Registers a new theme based on the existing one. */ + export function registerTheme(customTheme: Object, baseTheme: string): void; + /** Applies a predefined or registered custom palette to all visualization widgets at once. */ + export function currentPalette(paletteName: string): void; + /** Obtains the color sets of a predefined or registered palette. */ + export function getPalette(paletteName: string): Object; + /** Registers a new palette. */ + export function registerPalette(paletteName: string, palette: Object): void; + } +} +declare module DevExpress.ui { + export interface dxValidatorOptions extends DOMComponentOptions { + /** An array of validation rules to be checked for the editor with which the dxValidator object is associated. */ + validationRules?: Array; + /** Specifies the editor name to be used in the validation default messages. */ + name?: string; + /** An object that specifies what and when to validate and how to apply the validation result. */ + adapter?: Object; + /** Specifies the validation group the editor will be related to. */ + validationGroup?: string; + /** A handler for the validated event. */ + onValidated?: (params: validationEngine.ValidatorValidationResult) => void; + } + /** A widget that is used to validate the associated DevExtreme editors against the defined validation rules. */ + export class dxValidator extends DOMComponent implements validationEngine.IValidator { + constructor(element: JQuery, options?: dxValidatorOptions); + constructor(element: Element, options?: dxValidatorOptions); + /** Validates the value of the editor that is controlled by the current dxValidator object against the list of the specified validation rules. */ + validate(): validationEngine.ValidatorValidationResult; + /** Resets the value and validation result of the editor associated with the current dxValidator object. */ + reset(): void; + } + /** The widget that is used in the Knockout and Angular approaches to combine the editors to be validated. */ + export class dxValidationGroup extends DOMComponent { + constructor(element: JQuery); + constructor(element: Element); + /** Validates rules of the validators that belong to the current validation group. */ + validate(): validationEngine.ValidationGroupValidationResult; + /** Resets the value and validation result of the editors that are included to the current validation group. */ + reset(): void; + } + export interface dxValidationSummaryOptions extends CollectionWidgetOptions { + /** Specifies the validation group for which summary should be generated. */ + validationGroup?: string; + } + /** A widget for displaying the result of checking validation rules for editors. */ + export class dxValidationSummary extends CollectionWidget { + constructor(element: JQuery, options?: dxValidationSummaryOptions); + constructor(element: Element, options?: dxValidationSummaryOptions); + } + export interface dxResizableOptions extends DOMComponentOptions { + /** Specifies which borders of the widget element are used as a handle. */ + handles?: string; + /** Specifies the lower width boundary for resizing. */ + minWidth?: number; + /** Specifies the upper width boundary for resizing. */ + maxWidth?: number; + /** Specifies the lower height boundary for resizing. */ + minHeight?: number; + /** Specifies the upper height boundary for resizing. */ + maxHeight?: number; + /** A handler for the resizeStart event. */ + onResizeStart?: Function; + /** A handler for the resize event. */ + onResize?: Function; + /** A handler for the resizeEnd event. */ + onResizeEnd?: Function; + } + /** A widget that displays required content in a resizable element. */ + export class dxResizable extends DOMComponent { + constructor(element: JQuery, options?: dxResizableOptions); + constructor(element: Element, options?: dxResizableOptions); + } + export interface dxTooltipOptions extends dxPopoverOptions { + } + /** A tooltip widget. */ + export class dxTooltip extends dxPopover { + constructor(element: JQuery, options?: dxTooltipOptions); + constructor(element: Element, options?: dxTooltipOptions); + } + export interface dxDropDownListOptions extends dxDropDownEditorOptions, DataExpressionMixinOptions { + /** Returns the value currently displayed by the widget. */ + displayValue?: string; + /** The minimum number of characters that must be entered into the text box to begin a search. */ + minSearchLength?: number; + /** Specifies whether or not the widget displays unfiltered values until a user types a number of characters exceeding the minSearchLength option value. */ + showDataBeforeSearch?: boolean; + /** Specifies the name of a data source item field or an expression whose value is compared to the search criterion. */ + searchExpr?: Object; + /** Specifies the binary operation used to filter data. */ + searchMode?: string; + /** Specifies the time delay, in milliseconds, after the last character has been typed in, before a search is executed. */ + searchTimeout?: number; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + /** Specifies DOM event names that update a widget's value. */ + valueChangeEvent?: string; + /** Specifies whether or not the widget supports searching. */ + searchEnabled?: boolean; + /** + * Specifies whether or not the widget displays items by pages. + * @deprecated dataSource.paginate.md + */ + pagingEnabled?: boolean; + /** The text or HTML markup displayed by the widget if the item collection is empty. */ + noDataText?: string; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: Function; + /** A handler for the itemClick event. */ + onItemClick?: Function; + onContentReady?: Function; + } + /** A base class for drop-down list widgets. */ + export class dxDropDownList extends dxDropDownEditor { + constructor(element: JQuery, options?: dxDropDownListOptions); + constructor(element: Element, options?: dxDropDownListOptions); + } + export interface dxToolbarOptions extends CollectionWidgetOptions { + /** The template used to render menu items. */ + menuItemTemplate?: any; + /** Informs the widget about its location in a view HTML markup. */ + renderAs?: string; + } + /** A toolbar widget. */ + export class dxToolbar extends CollectionWidget { + constructor(element: JQuery, options?: dxToolbarOptions); + constructor(element: Element, options?: dxToolbarOptions); + } + export interface dxToastOptions extends dxOverlayOptions { + animation?: fx.AnimationOptions; + /** The time span in milliseconds during which the dxToast widget is visible. */ + displayTime?: number; + height?: any; + /** The dxToast message text. */ + message?: string; + position?: PositionOptions; + shading?: boolean; + /** Specifies the dxToast widget type. */ + type?: string; + width?: any; + closeOnBackButton?: boolean; + /** A Boolean value specifying whether or not the toast is closed if a user swipes it out of the screen boundaries. */ + closeOnSwipe?: boolean; + /** A Boolean value specifying whether or not the toast is closed if a user clicks it. */ + closeOnClick?: boolean; + } + /** The toast message widget. */ + export class dxToast extends dxOverlay { + constructor(element: JQuery, options?: dxToastOptions); + constructor(element: Element, options?: dxToastOptions); + } + export interface dxTextEditorOptions extends EditorOptions { + /** A handler for the change event. */ + onChange?: Function; + /** A handler for the copy event. */ + onCopy?: Function; + /** A handler for the cut event. */ + onCut?: Function; + /** A handler for the enterKey event. */ + onEnterKey?: Function; + /** A handler for the focusIn event. */ + onFocusIn?: Function; + /** A handler for the focusOut event. */ + onFocusOut?: Function; + /** A handler for the input event. */ + onInput?: Function; + /** A handler for the keyDown event. */ + onKeyDown?: Function; + /** A handler for the keyPress event. */ + onKeyPress?: Function; + /** A handler for the keyUp event. */ + onKeyUp?: Function; + /** A handler for the paste event. */ + onPaste?: Function; + /** The text displayed by the widget when the widget value is empty. */ + placeholder?: string; + /** Specifies whether to display the Clear button in the widget. */ + showClearButton?: boolean; + /** Specifies the current value displayed by the widget. */ + value?: any; + /** Specifies DOM event names that update a widget's value. */ + valueChangeEvent?: string; + /** Specifies whether or not the widget checks the inner text for spelling mistakes. */ + spellcheck?: boolean; + /** Specifies HTML attributes applied to the inner input element of the widget. */ + attr?: Object; + /** The read-only option that holds the text displayed by the widget input element. */ + text?: string; + focusStateEnabled?: boolean; + hoverStateEnabled?: boolean; + /** The editor mask that specifies the format of the entered string. */ + mask?: string; + /** Specifies a mask placeholder character. */ + maskChar?: string; + /** Specifies custom mask rules. */ + maskRules?: Object; + /** A message displayed when the entered text does not match the specified pattern. */ + maskInvalidMessage?: string; + /** Specifies whether the value option holds only characters entered by a user or prompt characters as well. */ + useMaskedValue?: boolean; + } + /** A base class for text editing widgets. */ + export class dxTextEditor extends Editor { + constructor(element: JQuery, options?: dxTextEditorOptions); + constructor(element: Element, options?: dxTextEditorOptions); + /** Removes focus from the input element. */ + blur(): void; + /** Sets focus to the input element representing the widget. */ + focus(): void; + } + export interface dxTextBoxOptions extends dxTextEditorOptions { + /** Specifies the maximum number of characters you can enter into the textbox. */ + maxLength?: any; + /** The "mode" attribute value of the actual HTML input element representing the text box. */ + mode?: string; + } + /** A single-line text box widget. */ + export class dxTextBox extends dxTextEditor { + constructor(element: JQuery, options?: dxTextBoxOptions); + constructor(element: Element, options?: dxTextBoxOptions); + } + export interface dxTextAreaOptions extends dxTextBoxOptions { + /** Specifies whether or not the widget checks the inner text for spelling mistakes. */ + spellcheck?: boolean; + } + /** A widget used to display and edit multi-line text. */ + export class dxTextArea extends dxTextBox { + constructor(element: JQuery, options?: dxTextAreaOptions); + constructor(element: Element, options?: dxTextAreaOptions); + } + export interface dxTabsOptions extends CollectionWidgetOptions { + /** Specifies whether the widget enables an end-user to select only a single item or multiple items. */ + selectionMode?: string; + /** Specifies whether or not an end-user can scroll tabs by swiping. */ + scrollByContent?: boolean; + /** Specifies whether or not an end-user can scroll tabs. */ + scrollingEnabled?: boolean; + /** A Boolean value that specifies the availability of navigation buttons. */ + showNavButtons?: boolean; + } + /** A tab strip used to switch between pages. */ + export class dxTabs extends CollectionWidget { + constructor(element: JQuery, options?: dxTabsOptions); + constructor(element: Element, options?: dxTabsOptions); + } + export interface dxTabPanelOptions extends dxMultiViewOptions { + /** A handler for the titleClick event. */ + onTitleClick?: any; + /** A handler for the titleHold event. */ + onTitleHold?: Function; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + /** A Boolean value specifying if the list is scrolled by content. */ + scrollByContent?: boolean; + /** A Boolean value specifying whether to enable or disable scrolling. */ + scrollingEnabled?: boolean; + /** A Boolean value that specifies the availability of navigation buttons. */ + showNavButtons?: boolean; + } + /** A widget used to display a view and to switch between several views by clicking the appropriate tabs. */ + export class dxTabPanel extends dxMultiView { + constructor(element: JQuery, options?: dxTabPanelOptions); + constructor(element: Element, options?: dxTabPanelOptions); + } + export interface dxSelectBoxOptions extends dxDropDownListOptions { + /** Specifies DOM event names that update a widget's value. */ + valueChangeEvent?: string; + /** The template to be used for rendering the widget text field. */ + fieldTemplate?: any; + /** The text that is provided as a hint in the select box editor. */ + placeholder?: string; + /** Specifies whether or not the widget allows an end-user to enter a custom value. */ + fieldEditEnabled?: boolean; + } + /** A widget that allows you to select an item in a dropdown list. */ + export class dxSelectBox extends dxDropDownList { + constructor(element: JQuery, options?: dxSelectBoxOptions); + constructor(element: Element, options?: dxSelectBoxOptions); + } + export interface dxTagBoxOptions extends dxSelectBoxOptions { + /** Holds the list of selected values. */ + values?: Array; + /** A read-only option that holds the last selected value. */ + value?: Object; + } + /** A widget that allows you to select multiple items from a dropdown list. */ + export class dxTagBox extends dxSelectBox { + constructor(element: JQuery, options?: dxTagBoxOptions); + constructor(element: Element, options?: dxTagBoxOptions); + } + export interface dxScrollViewOptions extends dxScrollableOptions { + /** A handler for the pullDown event. */ + onPullDown?: Function; + /** Specifies the text shown in the pullDown panel when pulling the content down lowers the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while pulling the content down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the reachBottom event. */ + onReachBottom?: Function; + /** Specifies the text shown in the pullDown panel displayed when content is scrolled to the bottom. */ + reachBottomText?: string; + /** Specifies the text shown in the pullDown panel displayed when the content is being refreshed. */ + refreshingText?: string; + /** Returns a value indicating if the scrollView content is larger then the widget container. */ + isFull(): boolean; + /** Locks the widget until the release(preventScrollBottom) method is called and executes the function passed to the onPullDown option and the handler assigned to the pullDown event. */ + refresh(): void; + /** Notifies the scroll view that data loading is finished. */ + release(preventScrollBottom: boolean): JQueryPromise; + /** Toggles the loading state of the widget. */ + toggleLoading(showOrHide: boolean): void; + } + /** A widget used to display scrollable content. */ + export class dxScrollView extends dxScrollable { + constructor(element: JQuery, options?: dxScrollViewOptions); + constructor(element: Element, options?: dxScrollViewOptions); + } + export interface dxScrollableLocation { + top?: number; + left?: number; + } + export interface dxScrollableOptions extends DOMComponentOptions { + /** A string value specifying the available scrolling directions. */ + direction?: string; + /** A Boolean value specifying whether or not the widget can respond to user interaction. */ + disabled?: boolean; + /** A handler for the scroll event. */ + onScroll?: Function; + /** Specifies when the widget shows the scrollbar. */ + showScrollbar?: string; + /** A handler for the update event. */ + onUpdated?: Function; + /** Indicates whether to use native or simulated scrolling. */ + useNative?: boolean; + /** A Boolean value specifying whether to enable or disable the bounce-back effect. */ + bounceEnabled?: boolean; + /** A Boolean value specifying whether or not an end-user can scroll the widget content swiping it up or down. */ + scrollByContent?: boolean; + /** A Boolean value specifying whether or not an end-user can scroll the widget content using the scrollbar. */ + scrollByThumb?: boolean; + } + /** A widget used to display scrollable content. */ + export class dxScrollable extends DOMComponent { + constructor(element: JQuery, options?: dxScrollableOptions); + constructor(element: Element, options?: dxScrollableOptions); + /** Returns the height of the scrollable widget in pixels. */ + clientHeight(): number; + /** Returns the width of the scrollable widget in pixels. */ + clientWidth(): number; + /** Returns an HTML element of the widget. */ + content(): JQuery; + /** Scrolls the widget content by the specified number of pixels. */ + scrollBy(distance: number): void; + /** Scrolls widget content by the specified number of pixels in horizontal and vertical directions. */ + scrollBy(distanceObject: dxScrollableLocation): void; + /** Returns the height of the scrollable content in pixels. */ + scrollHeight(): number; + /** Returns the current scroll position against the leftmost position. */ + scrollLeft(): number; + /** Returns how far the scrollable content is scrolled from the top and from the left. */ + scrollOffset(): dxScrollableLocation; + /** Scrolls widget content to the specified position. */ + scrollTo(targetLocation: number): void; + /** Scrolls widget content to a specified position. */ + scrollTo(targetLocation: dxScrollableLocation): void; + /** Scrolls widget content to the specified element. */ + scrollToElement(element: Element): void; + /** Returns the current scroll position against the topmost position. */ + scrollTop(): number; + /** Returns the width of the scrollable content in pixels. */ + scrollWidth(): number; + /** Updates the dimensions of the scrollable contents. */ + update(): void; + } + export interface dxRadioGroupOptions extends EditorOptions, DataExpressionMixinOptions { + activeStateEnabled?: boolean; + /** Specifies the radio group layout. */ + layout?: string; + } + /** A widget that enables a user to select one item within a list of items represented by radio buttons. */ + export class dxRadioGroup extends CollectionWidget { + constructor(element: JQuery, options?: dxRadioGroupOptions); + constructor(element: Element, options?: dxRadioGroupOptions); + } + export interface dxPopupOptions extends dxOverlayOptions { + animation?: fx.AnimationOptions; + /** Specifies whether or not to allow a user to drag the popup window. */ + dragEnabled?: boolean; + /** A Boolean value specifying whether or not to display the widget in full-screen mode. */ + fullScreen?: boolean; + position?: PositionOptions; + /** A Boolean value specifying whether or not to display the title in the popup window. */ + showTitle?: boolean; + /** The title in the overlay window. */ + title?: string; + /** A template to be used for rendering the widget title. */ + titleTemplate?: any; + width?: any; + /** Specifies items displayed on the top or bottom toolbar of the popup window. */ + buttons?: Array; + /** Specifies whether or not the widget displays the Close button. */ + showCloseButton?: boolean; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + } + /** A widget that displays required content in a popup window. */ + export class dxPopup extends dxOverlay { + constructor(element: JQuery, options?: dxPopupOptions); + constructor(element: Element, options?: dxPopupOptions); + } + export interface dxPopoverOptions extends dxPopupOptions { + /** An object defining animation options of the widget. */ + animation?: fx.AnimationOptions; + /** Specifies the height of the widget. */ + height?: any; + /** An object defining widget positioning options. */ + position?: PositionOptions; + shading?: boolean; + /** A Boolean value specifying whether or not to display the title in the overlay window. */ + showTitle?: boolean; + /** The target element associated with a popover. */ + target?: any; + /** Specifies the width of the widget. */ + width?: any; + } + /** A widget that displays the required content in a popup window. */ + export class dxPopover extends dxPopup { + constructor(element: JQuery, options?: dxPopoverOptions); + constructor(element: Element, options?: dxPopoverOptions); + /** Displays the widget for the specified target element. */ + show(target?: any): JQueryPromise; + } + export interface dxOverlayOptions extends WidgetOptions { + /** An object that defines the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** A Boolean value specifying whether or not the widget is closed if a user presses the Back hardware button. */ + closeOnBackButton?: boolean; + /** A Boolean value specifying whether or not the widget is closed if a user clicks outside of the overlapping window. */ + closeOnOutsideClick?: any; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + /** Specifies whether widget content is rendered when the widget is shown or when rendering the widget. */ + deferRendering?: boolean; + /** Specifies whether or not an end-user can drag the widget. */ + dragEnabled?: boolean; + /** Specifies whether or not an end user can resize the widget. */ + resizeEnabled?: boolean; + /** The height of the widget in pixels. */ + height?: any; + /** Specifies the maximum height the widget can reach while resizing. */ + maxHeight?: any; + /** Specifies the maximum width the widget can reach while resizing. */ + maxWidth?: any; + /** Specifies the minimum height the widget can reach while resizing. */ + minHeight?: any; + /** Specifies the minimum width the widget can reach while resizing. */ + minWidth?: any; + /** A handler for the hidden event. */ + onHidden?: Function; + /** A handler for the resizeStart event. */ + onResizeStart?: Function; + /** A handler for the resize event. */ + onResize?: Function; + /** A handler for the resizeEnd event. */ + onResizeEnd?: Function; + /** A handler for the hiding event. */ + onHiding?: Function; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** A Boolean value specifying whether or not the main screen is inactive while the widget is active. */ + shading?: boolean; + /** Specifies the shading color. */ + shadingColor?: string; + /** A handler for the showing event. */ + onShowing?: Function; + /** A handler for the shown event. */ + onShown?: Function; + onContentReady?: Function; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + /** The widget width in pixels. */ + width?: any; + } + /** A widget displaying the required content in an overlay window. */ + export class dxOverlay extends Widget { + constructor(element: JQuery, options?: dxOverlayOptions); + constructor(element: Element, options?: dxOverlayOptions); + /** An HTML element of the widget. */ + content(): JQuery; + /** Hides the widget. */ + hide(): JQueryPromise; + /** Recalculates the overlay's size and position. */ + repaint(): void; + /** Shows the widget. */ + show(): JQueryPromise; + /** Toggles the visibility of the widget. */ + toggle(showing: boolean): JQueryPromise; + /** A static method that specifies the base z-index for all overlay widgets. */ + static baseZIndex(zIndex: number): void; + } + export interface dxNumberBoxOptions extends dxTextEditorOptions { + /** The maximum value accepted by the number box. */ + max?: number; + /** The minimum value accepted by the number box. */ + min?: number; + /** Specifies whether or not to show spin buttons. */ + showSpinButtons?: boolean; + useTouchSpinButtons?: boolean; + /** Specifies by which value the widget value changes when a spin button is clicked. */ + step?: number; + /** The current number box value. */ + value?: number; + /** The "mode" attribute value of the actual HTML input element representing the widget. */ + mode?: string; + } + /** A textbox widget that enables a user to enter numeric values. */ + export class dxNumberBox extends dxTextEditor { + constructor(element: JQuery, options?: dxNumberBoxOptions); + constructor(element: Element, options?: dxNumberBoxOptions); + } + export interface dxNavBarOptions extends dxTabsOptions { + scrollingEnabled?: boolean; + } + /** A widget that contains items used to navigate through application views. */ + export class dxNavBar extends dxTabs { + constructor(element: JQuery, options?: dxNavBarOptions); + constructor(element: Element, options?: dxNavBarOptions); + } + export interface dxMultiViewOptions extends CollectionWidgetOptions { + /** Specifies whether or not to animate the displayed item change. */ + animationEnabled?: boolean; + /** A Boolean value specifying whether or not to scroll back to the first item after the last item is swiped. */ + loop?: boolean; + /** The index of the currently displayed item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to allow users to change the selected index by swiping. */ + swipeEnabled?: boolean; + /** Specifies whether widget content is rendered when the widget is shown or when rendering the widget. */ + deferRendering?: boolean; + } + /** A widget used to display a view and to switch between several views. */ + export class dxMultiView extends CollectionWidget { + constructor(element: JQuery, options?: dxMultiViewOptions); + constructor(element: Element, options?: dxMultiViewOptions); + } + export interface dxMapOptions extends WidgetOptions { + /** Specifies whether or not the widget automatically adjusts center and zoom option values when adding a new marker or route, or when creating a widget if it initially contains markers or routes. */ + autoAdjust?: boolean; + center?: { + /** The latitude location displayed in the center of the widget. */ + lat?: number; + /** The longitude location displayed in the center of the widget. */ + lng?: number; + }; + /** A handler for the click event. */ + onClick?: any; + /** Specifies whether or not map widget controls are available. */ + controls?: boolean; + /** Specifies the height of the widget. */ + height?: any; + /** A key used to authenticate the application within the required map provider. */ + key?: { + /** A key used to authenticate the application within the "Bing" map provider. */ + bing?: string; + /** A key used to authenticate the application within the "Google" map provider. */ + google?: string; + /** A key used to authenticate the application within the "Google Static" map provider. */ + googleStatic?: string; + } + /** A handler for the markerAdded event. */ + onMarkerAdded?: Function; + /** A URL pointing to the custom icon to be used for map markers. */ + markerIconSrc?: string; + /** A handler for the markerRemoved event. */ + onMarkerRemoved?: Function; + /** An array of markers displayed on a map. */ + markers?: Array; + /** The name of the current map data provider. */ + provider?: string; + /** A handler for the ready event. */ + onReady?: Function; + /** A handler for the routeAdded event. */ + onRouteAdded?: Function; + /** A handler for the routeRemoved event. */ + onRouteRemoved?: Function; + /** An array of routes shown on the map. */ + routes?: Array; + /** The type of a map to display. */ + type?: string; + /** Specifies the width of the widget. */ + width?: any; + /** The zoom level of the map. */ + zoom?: number; + } + /** An interactive map widget. */ + export class dxMap extends Widget { + constructor(element: JQuery, options?: dxMapOptions); + constructor(element: Element, options?: dxMapOptions); + /** Adds a marker to the map. */ + addMarker(markerOptions: Object): JQueryPromise; + /** Adds a route to the map. */ + addRoute(routeOptions: Object): JQueryPromise; + /** Removes a marker from the map. */ + removeMarker(marker: Object): JQueryPromise; + /** Removes a route from the map. */ + removeRoute(route: any): JQueryPromise; + } + export interface dxLookupOptions extends dxDropDownListOptions { + /** An object defining widget animation options. */ + animation?: fx.AnimationOptions; + /** The text displayed on the Cancel button. */ + cancelButtonText?: string; + /** The text displayed on the Clear button. */ + clearButtonText?: string; + /** Specifies whether or not the widget cleans the search box when the popup window is displayed. */ + cleanSearchOnOpening?: boolean; + /** A Boolean value specifying whether or not a widget is closed if a user clicks outside of the overlaying window. */ + closeOnOutsideClick?: any; + /** The text displayed on the Apply button. */ + applyButtonText?: string; + /** A Boolean value specifying whether or not to display the lookup in full-screen mode. */ + fullScreen?: boolean; + focusStateEnabled?: boolean; + /** A Boolean value specifying whether or not to group widget items. */ + grouped?: boolean; + /** The name of the template used to display a group header. */ + groupTemplate?: any; + /** The text displayed on the button used to load the next page from the data source. */ + nextButtonText?: string; + /** A handler for the pageLoading event. */ + onPageLoading?: Function; + /** Specifies whether the next page is loaded when a user scrolls the widget to the bottom or when the "next" button is clicked. */ + pageLoadMode?: string; + /** Specifies the text shown in the pullDown panel, which is displayed when the widget is scrolled to the bottom. */ + pageLoadingText?: string; + /** The text displayed by the widget when nothing is selected. */ + placeholder?: string; + /** The height of the widget popup element. */ + popupHeight?: any; + /** The width of the widget popup element. */ + popupWidth?: any; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** Specifies the text displayed in the pullDown panel when the widget is pulled below the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while the list is being pulled down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the pullRefresh event. */ + onPullRefresh?: Function; + /** A Boolean value specifying whether or not the widget supports the "pull down to refresh" gesture. */ + pullRefreshEnabled?: boolean; + /** Specifies the text displayed in the pullDown panel while the widget is being refreshed. */ + refreshingText?: string; + /** A handler for the scroll event. */ + onScroll?: Function; + /** A Boolean value specifying whether or not the search bar is visible. */ + searchEnabled?: boolean; + /** The text that is provided as a hint in the lookup's search bar. */ + searchPlaceholder?: string; + /** A Boolean value specifying whether or not the main screen is inactive while the lookup is active. */ + shading?: boolean; + /** Specifies whether to display the Cancel button in the lookup window. */ + showCancelButton?: boolean; + /** + * A Boolean value specifying whether the widget loads the next page automatically when you reach the bottom of the list or when a button is clicked. + * @deprecated pageLoadMode.md + */ + showNextButton?: boolean; + /** The title of the lookup window. */ + title?: string; + /** A template to be used for rendering the widget title. */ + titleTemplate?: any; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: boolean; + /** Specifies whether or not to show lookup contents in a dxPopover widget. */ + usePopover?: boolean; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + /** A handler for the titleRendered event. */ + onTitleRendered?: Function; + /** A Boolean value specifying whether or not to display the title in the popup window. */ + showPopupTitle?: boolean; + /** The template to be used for rendering the widget text field. */ + fieldTemplate?: any; + } + /** A widget that allows a user to select predefined values from a lookup window. */ + export class dxLookup extends dxDropDownList { + constructor(element: JQuery, options?: dxLookupOptions); + constructor(element: Element, options?: dxLookupOptions); + /** This section lists the data source fields that are used in a default template for lookup drop-down items. */ + } + export interface dxLoadPanelOptions extends dxOverlayOptions { + /** An object defining the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** The delay in milliseconds after which the load panel is displayed. */ + delay?: number; + /** The height of the widget. */ + height?: number; + /** A URL pointing to an image to be used as a load indicator. */ + indicatorSrc?: string; + /** The text displayed in the load panel. */ + message?: string; + /** A Boolean value specifying whether or not to show a load indicator. */ + showIndicator?: boolean; + /** A Boolean value specifying whether or not to show the pane behind the load indicator. */ + showPane?: boolean; + /** The width of the widget. */ + width?: number; + } + /** A widget used to indicate whether or not an element is loading. */ + export class dxLoadPanel extends dxOverlay { + constructor(element: JQuery, options?: dxLoadPanelOptions); + constructor(element: Element, options?: dxLoadPanelOptions); + } + export interface dxLoadIndicatorOptions extends WidgetOptions { + /** Specifies the path to an image used as the indicator. */ + indicatorSrc?: string; + } + /** The widget used to indicate the loading process. */ + export class dxLoadIndicator extends Widget { + constructor(element: JQuery, options?: dxLoadIndicatorOptions); + constructor(element: Element, options?: dxLoadIndicatorOptions); + } + export interface dxListOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not to display a grouped list. */ + grouped?: boolean; + /** The template to be used for rendering item groups. */ + groupTemplate?: any; + onItemDeleting?: Function; + /** A handler for the itemDeleted event. */ + onItemDeleted?: Function; + /** A handler for the groupRendered event. */ + onGroupRendered?: Function; + /** A handler for the itemReordered event. */ + onItemReordered?: Function; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** A handler for the itemSwipe event. */ + onItemSwipe?: Function; + /** The text displayed on the button used to load the next page from the data source. */ + nextButtonText?: string; + /** A handler for the pageLoading event. */ + onPageLoading?: Function; + /** Specifies the text shown in the pullDown panel, which is displayed when the list is scrolled to the bottom. */ + pageLoadingText?: string; + /** Specifies the text displayed in the pullDown panel when the list is pulled below the refresh threshold. */ + pulledDownText?: string; + /** Specifies the text shown in the pullDown panel while the list is being pulled down to the refresh threshold. */ + pullingDownText?: string; + /** A handler for the pullRefresh event. */ + onPullRefresh?: Function; + /** A Boolean value specifying whether or not the widget supports the "pull down to refresh" gesture. */ + pullRefreshEnabled?: boolean; + /** Specifies the text displayed in the pullDown panel while the list is being refreshed. */ + refreshingText?: string; + /** A handler for the scroll event. */ + onScroll?: Function; + /** A Boolean value specifying whether to enable or disable list scrolling. */ + scrollingEnabled?: boolean; + /** Specifies when the widget shows the scrollbar. */ + showScrollbar?: string; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: boolean; + /** A Boolean value specifying whether to enable or disable the bounce-back effect. */ + bounceEnabled?: boolean; + /** A Boolean value specifying if the list is scrolled by content. */ + scrollByContent?: boolean; + /** A Boolean value specifying if the list is scrolled using the scrollbar. */ + scrollByThumb?: boolean; + onItemContextMenu?: Function; + onItemHold?: Function; + /** Specifies whether or not an end-user can collapse groups. */ + collapsibleGroups?: boolean; + /** Specifies whether the next page is loaded when a user scrolls the widget to the bottom or when the "next" button is clicked. */ + pageLoadMode?: string; + /** Specifies whether or not to display controls used to select list items. */ + showSelectionControls?: boolean; + /** Specifies item selection mode. */ + selectionMode?: string; + selectAllText?: string; + onSelectAllChanged?: Function; + /** Specifies the array of items for a context menu called for a list item. */ + menuItems?: Array; + /** Specifies whether an item context menu is shown when a user holds or swipes an item. */ + menuMode?: string; + /** Specifies whether or not an end user can delete list items. */ + allowItemDeleting?: boolean; + /** Specifies the way a user can delete items from the list. */ + itemDeleteMode?: string; + /** Specifies whether or not an end user can reorder list items. */ + allowItemReordering?: boolean; + /** Specifies whether or not to show the loading panel when the DataSource bound to the widget is loading data. */ + indicateLoading?: boolean; + activeStateEnabled?: boolean; + } + /** A list widget. */ + export class dxList extends CollectionWidget { + constructor(element: JQuery, options?: dxListOptions); + constructor(element: Element, options?: dxListOptions); + /** Returns the height of the widget in pixels. */ + clientHeight(): number; + /** Removes the specified item from the list. */ + deleteItem(itemIndex: any): JQueryPromise; + /** Removes the specified item from the list. */ + deleteItem(itemElement: Element): JQueryPromise; + /** Returns a Boolean value that indicates whether or not the specified item is selected. */ + isItemSelected(itemIndex: any): boolean; + /** Returns a Boolean value that indicates whether or not the specified item is selected. */ + isItemSelected(itemElement: Element): boolean; + /** Reloads list data. */ + reload(): void; + /** Moves the specified item to the specified position in the list. */ + reorderItem(itemElement: Element, toItemElement: Element): JQueryPromise; + /** Moves the specified item to the specified position in the list. */ + reorderItem(itemIndex: any, toItemIndex: any): JQueryPromise; + /** Scrolls the list content by the specified number of pixels. */ + scrollBy(distance: number): void; + /** Returns the height of the list content in pixels. */ + scrollHeight(): number; + /** Scrolls list content to the specified position. */ + scrollTo(location: number): void; + /** Scrolls the list to the specified item. */ + scrollToItem(itemElement: Element): void; + /** Scrolls the list to the specified item. */ + scrollToItem(itemIndex: any): void; + /** Returns how far the list content is scrolled from the top. */ + scrollTop(): number; + /** Selects the specified item from the list. */ + selectItem(itemElement: Element): void; + /** Selects the specified item from the list. */ + selectItem(itemIndex: any): void; + /** Deselects the specified item from the list. */ + unselectItem(itemElement: Element): void; + /** Unselects the specified item from the list. */ + unselectItem(itemIndex: any): void; + /** Updates the widget scrollbar according to widget content size. */ + updateDimensions(): JQueryPromise; + /** Expands the specified group. */ + expandGroup(groupIndex: number): JQueryPromise; + /** Collapses the specified group. */ + collapseGroup(groupIndex: number): JQueryPromise; + } + export interface dxGalleryOptions extends CollectionWidgetOptions { + /** The time, in milliseconds, spent on slide animation. */ + animationDuration?: number; + /** Specifies whether or not to animate the displayed item change. */ + animationEnabled?: boolean; + /** A Boolean value specifying whether or not to allow users to switch between items by clicking an indicator. */ + indicatorEnabled?: boolean; + /** A Boolean value specifying whether or not to scroll back to the first item after the last item is swiped. */ + loop?: boolean; + /** The index of the currently active gallery item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to display an indicator that points to the selected gallery item. */ + showIndicator?: boolean; + /** A Boolean value that specifies the availability of the "Forward" and "Back" navigation buttons. */ + showNavButtons?: boolean; + /** The time interval in milliseconds, after which the gallery switches to the next item. */ + slideshowDelay?: number; + /** A Boolean value specifying whether or not to allow users to switch between items by swiping. */ + swipeEnabled?: boolean; + /** Specifies whether or not to display parts of previous and next images along the sides of the current image. */ + wrapAround?: boolean; + /** Specifies if the widget stretches images to fit the total gallery width. */ + stretchImages?: boolean; + /** Specifies the width of an area used to display a single image. */ + initialItemWidth?: number; + } + /** An image gallery widget. */ + export class dxGallery extends CollectionWidget { + constructor(element: JQuery, options?: dxGalleryOptions); + constructor(element: Element, options?: dxGalleryOptions); + /** Shows the specified gallery item. */ + goToItem(itemIndex: number, animation: boolean): JQueryPromise; + /** Shows the next gallery item. */ + nextItem(animation: boolean): JQueryPromise; + /** Shows the previous gallery item. */ + prevItem(animation: boolean): JQueryPromise; + } + export interface dxDropDownEditorOptions extends dxTextBoxOptions { + /** Specifies the current value displayed by the widget. */ + value?: Object; + /** A handler for the closed event. */ + onClosed?: Function; + /** A handler for the opened event. */ + onOpened?: Function; + /** Specifies whether or not the drop-down editor is displayed. */ + opened?: boolean; + /** Specifies whether or not the widget allows an end-user to enter a custom value. */ + fieldEditEnabled?: boolean; + /** Specifies the way an end-user applies the selected value. */ + applyValueMode?: string; + /** Specifies whether widget content is rendered when the widget is shown or when rendering the widget. */ + deferRendering?: boolean; + activeStateEnabled?: boolean; + } + /** A drop-down editor widget. */ + export class dxDropDownEditor extends dxTextBox { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + /** Closes the drop-down editor. */ + close(): void; + /** Opens the drop-down editor. */ + open(): void; + /** Resets the widget's value to null. */ + reset(): void; + /** Returns an <input> element of the widget. */ + field(): JQuery; + /** Returns an HTML element of the popup window content. */ + content(): JQuery; + } + export interface dxDateBoxOptions extends dxTextEditorOptions { + /** A format used to display date/time information. */ + format?: string; + /** A Globalize format string specifying the date display format. */ + formatString?: string; + /** The last date that can be selected within the widget. */ + max?: any; + /** The minimum date that can be selected within the widget. */ + min?: any; + /** The text displayed by the widget when the widget value is not yet specified. This text is also used as a title of the date picker. */ + placeholder?: string; + /** + * Specifies whether or not a user can pick out a date using the drop-down calendar. + * @deprecated Use 'pickerType' option instead. + */ + useCalendar?: boolean; + /** An object or a value, specifying the date and time currently selected using the date box. */ + value?: any; + /** + * Specifies whether or not the widget uses the native HTML input element. + * @deprecated Use 'pickerType' option instead. + */ + useNative?: boolean; + /** Specifies the interval between neighboring values in the popup list in minutes. */ + interval?: number; + /** Specifies the maximum zoom level of a calendar, which is used to pick the date. */ + maxZoomLevel?: string; + /** Specifies the minimal zoom level of a calendar, which is used to pick the date. */ + minZoomLevel?: string; + /** Specifies the type of date/time picker. */ + pickerType?: string; + /** Specifies the message displayed if the typed value is not a valid date or time. */ + invalidDateMessage?: string; + /** Specifies the message displayed if the specified date is later than the max value or earlier than the min value. */ + dateOutOfRangeMessage?: string; + /** The text displayed on the Apply button. */ + applyButtonText?: string; + /** The text displayed on the Cancel button. */ + cancelButtonText?: string; + } + /** A date box widget. */ + export class dxDateBox extends dxDropDownEditor { + constructor(element: JQuery, options?: dxDateBoxOptions); + constructor(element: Element, options?: dxDateBoxOptions); + } + export interface dxCheckBoxOptions extends EditorOptions { + activeStateEnabled?: boolean; + /** Specifies the widget state. */ + value?: boolean; + /** Specifies the text displayed by the check box. */ + text?: string; + } + /** A check box widget. */ + export class dxCheckBox extends Editor { + constructor(element: JQuery, options?: dxCheckBoxOptions); + constructor(element: Element, options?: dxCheckBoxOptions); + } + export interface dxCalendarOptions extends EditorOptions { + activeStateEnabled?: boolean; + /** Specifies a date displayed on the current calendar page. */ + currentDate?: Date; + /** Specifies the first day of a week. */ + firstDayOfWeek?: number; + /** The latest date the widget allows to select. */ + max?: Date; + /** The earliest date the widget allows to select. */ + min?: Date; + /** Specifies whether or not the widget displays a button that selects the current date. */ + showTodayButton?: boolean; + /** Specifies the current calendar zoom level. */ + zoomLevel?: string; + /** Specifies the maximum zoom level of the calendar. */ + maxZoomLevel?: string; + /** Specifies the minimum zoom level of the calendar. */ + minZoomLevel?: string; + /** The template to be used for rendering calendar cells. */ + cellTemplate?: any; + } + /** A calendar widget. */ + export class dxCalendar extends Editor { + constructor(element: JQuery, options?: dxCalendarOptions); + constructor(element: Element, options?: dxCalendarOptions); + } + export interface dxButtonOptions extends WidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A handler for the click event. */ + onClick?: any; + /** Specifies the icon to be displayed on the button. */ + icon?: string; + iconSrc?: string; + /** A template to be used for rendering the dxButton widget. */ + template?: any; + /** The text displayed on the button. */ + text?: string; + /** Specifies the button type. */ + type?: string; + /** Specifies the name of the validation group to be accessed in the click event handler. */ + validationGroup?: string; + } + /** A button widget. */ + export class dxButton extends Widget { + constructor(element: JQuery, options?: dxButtonOptions); + constructor(element: Element, options?: dxButtonOptions); + } + export interface dxBoxOptions extends CollectionWidget { + /** Specifies how widget items are aligned along the main direction. */ + align?: string; + /** Specifies the direction of item positioning in the widget. */ + direction?: string; + /** Specifies how widget items are aligned cross-wise. */ + crossAlign?: string; + } + /** A container widget used to arrange inner elements. */ + export class dxBox extends CollectionWidget { + constructor(element: JQuery, options?: dxBoxOptions); + constructor(element: Element, options?: dxBoxOptions); + } + export interface dxResponsiveBoxOptions extends CollectionWidgetOptions { + /** Specifies the collection of rows for the grid used to position layout elements. */ + rows?: Array; + /** Specifies the collection of columns for the grid used to position layout elements. */ + cols?: Array; + /** Specifies the function returning the screen factor depending on the screen width. */ + screenByWidth?: (width: number) => string; + /** Specifies the screen factor with which all elements are located in a single column. */ + singleColumnScreen?: string; + } + /** A widget used to build an adaptive markup that is dependent on screen resolution. */ + export class dxResponsiveBox extends CollectionWidget { + constructor(element: JQuery, options?: dxBoxOptions); + constructor(element: Element, options?: dxBoxOptions); + } + export interface dxAutocompleteOptions extends dxDropDownListOptions { + /** Specifies the current value displayed by the widget. */ + value?: string; + /** The minimum number of characters that must be entered into the text box to begin a search. */ + minSearchLength?: number; + /** Specifies the maximum count of items displayed by the widget. */ + maxItemCount?: number; + /** Gets the currently selected item. */ + selectedItem?: Object; + } + /** A textbox widget that supports autocompletion. */ + export class dxAutocomplete extends dxDropDownList { + constructor(element: JQuery, options?: dxAutocompleteOptions); + constructor(element: Element, options?: dxAutocompleteOptions); + /** Opens the drop-down editor. */ + open(): void; + /** Closes the drop-down editor. */ + close(): void; + } + export interface dxAccordionOptions extends CollectionWidgetOptions { + /** A number specifying the time in milliseconds spent on the animation of the expanding or collapsing of a panel. */ + animationDuration?: number; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies whether all items can be collapsed or whether at least one item must always be expanded. */ + collapsible?: boolean; + /** Specifies whether the widget can expand several items or only a single item at once. */ + multiple?: boolean; + /** The template to be used for rendering dxAccordion items. */ + itemTemplate?: any; + /** A handler for the itemTitleClick event. */ + onItemTitleClick?: any; + /** A handler for the itemTitleHold event. */ + onItemTitleHold?: Function; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + /** The index number of the currently selected item. */ + selectedIndex?: number; + /** Specifies whether widget content is rendered when the widget is shown or when rendering the widget. */ + deferRendering?: boolean; + } + /** A widget that displays data source items on collapsible panels. */ + export class dxAccordion extends CollectionWidget { + constructor(element: JQuery, options?: dxAccordionOptions); + constructor(element: Element, options?: dxAccordionOptions); + /** Collapses the specified item. */ + collapseItem(index: number): JQueryPromise; + /** Expands the specified item. */ + expandItem(index: number): JQueryPromise; + /** Updates the dimensions of the widget contents. */ + updateDimensions(): JQueryPromise; + } + export interface dxFileUploaderOptions extends EditorOptions { + /** A read-only option that holds a File instance representing the selected file. */ + value?: File; + /** Holds the File instances representing files selected in the widget. */ + values?: Array; + buttonText?: string; + /** The text displayed on the button that opens the file browser. */ + selectButtonText?: string; + /** The text displayed on the button that starts uploading. */ + uploadButtonText?: string; + /** Specifies the text displayed on the area to which an end-user can drop a file. */ + labelText?: string; + /** Specifies the value passed to the name attribute of the underlying input element. */ + name?: string; + /** Specifies whether the widget enables an end-user to select a single file or multiple files. */ + multiple?: boolean; + /** Specifies a file type or several types accepted by the widget. */ + accept?: string; + /** Specifies a target Url for the upload request. */ + uploadUrl?: string; + /** Specifies if an end user can remove a file from the selection and interrupt uploading. */ + allowCanceling?: boolean; + /** Specifies whether or not the widget displays the list of selected files. */ + showFileList?: boolean; + /** Gets the current progress in percentages. */ + progress?: number; + /** The message displayed by the widget when it is ready to upload the specified files. */ + readyToUploadMessage?: string; + /** The message displayed by the widget when uploading is finished. */ + uploadedMessage?: string; + /** The message displayed by the widget on uploading failure. */ + uploadFailedMessage?: string; + /** Specifies how the widget uploads files. */ + uploadMode?: string; + /** A handler for the uploaded event. */ + onUploaded?: Function; + /** A handler for the uploaded event. */ + onProgress?: Function; + /** A handler for the uploadError event. */ + onUploadError?: Function; + /** A handler for the valueChanged event. */ + onValueChanged?: Function; + } + /** A widget used to select and upload a file or multiple files. */ + export class dxFileUploader extends Editor { + constructor(element: JQuery, options?: dxFileUploaderOptions); + constructor(element: Element, options?: dxFileUploaderOptions); + } + export interface dxTrackBarOptions extends EditorOptions { + /** The minimum value the widget can accept. */ + min?: number; + /** The maximum value the widget can accept. */ + max?: number; + /** The current widget value. */ + value?: number; + } + /** A base class for track bar widgets. */ + export class dxTrackBar extends Editor { + constructor(element: JQuery, options?: dxTrackBarOptions); + constructor(element: Element, options?: dxTrackBarOptions); + } + export interface dxProgressBarOptions extends dxTrackBarOptions { + /** Specifies a format for the progress status. */ + statusFormat?: any; + /** Specifies whether or not the widget displays a progress status. */ + showStatus?: boolean; + /** A handler for the complete event. */ + onComplete?: Function; + } + /** A widget used to indicate progress. */ + export class dxProgressBar extends dxTrackBar { + constructor(element: JQuery, options?: dxProgressBarOptions); + constructor(element: Element, options?: dxProgressBarOptions); + } + export interface dxSliderOptions extends dxTrackBarOptions { + activeStateEnabled?: boolean; + /** The slider step size. */ + step?: number; + /** The current slider value. */ + value?: number; + /** Specifies whether or not to highlight a range selected within the widget. */ + showRange?: boolean; + /** Specifies the size of a step by which a slider handle is moved when a user uses the Page up or Page down keyboard shortcuts. */ + keyStep?: number; + /** Specifies options for the slider tooltip. */ + tooltip?: { + /** Specifies whether or not the tooltip is enabled. */ + enabled?: boolean; + /** Specifies format for the tooltip. */ + format?: any; + /** Specifies whether the tooltip is located over or under the slider. */ + position?: string; + /** Specifies whether the widget always shows a tooltip or only when a pointer is over the slider. */ + showMode?: string; + }; + /** Specifies options for labels displayed at the min and max values. */ + label?: { + /** Specifies whether or not slider labels are visible. */ + visible?: boolean; + /** Specifies whether labels are located over or under the scale. */ + position?: string; + /** Specifies a format for labels. */ + format?: any; + }; + } + /** A widget that allows a user to select a numeric value within a given range. */ + export class dxSlider extends dxTrackBar { + constructor(element: JQuery, options?: dxSliderOptions); + constructor(element: Element, options?: dxSliderOptions); + } + export interface dxRangeSliderOptions extends dxSliderOptions { + /** The left edge of the interval currently selected using the range slider. */ + start?: number; + /** The right edge of the interval currently selected using the range slider. */ + end?: number; + } + /** A widget that enables a user to select a range of numeric values. */ + export class dxRangeSlider extends dxSlider { + constructor(element: JQuery, options?: dxRangeSliderOptions); + constructor(element: Element, options?: dxRangeSliderOptions); + } + export interface dxFormItemLabel { + /** Specifies the label text. */ + text?: string; + /** Specifies whether or not the label is visible. */ + visible?: boolean; + /** Specifies whether or not a colon is displayed at the end of the current label. */ + showColon?: boolean; + /** Specifies the location of a label against the editor. */ + location?: string; + /** Specifies the label horizontal alignment. */ + alignment?: string; + } + export interface dxFormItem { + /** Specifies the type of the current item. */ + itemType?: string; + /** Specifies whether or not the current form item is visible. */ + visible?: boolean; + /** Specifies the sequence number of the item in a form, group or tab. */ + visibleIndex?: number; + /** Specifies a CSS class to be applied to the form item. */ + cssClass?: string; + /** Specifies the number of columns spanned by the item. */ + colSpan?: number; + } + export interface dxFormEmptyItem extends dxFormItem { + /** Specifies the form item name. */ + name?: string; + } + export interface dxFormSimpleItem extends dxFormItem { + /** Specifies the path to the formData object field bound to the current form item. */ + dataField?: string; + /** Specifies the form item name. */ + name?: string; + /** Specifies which editor widget is used to display and edit the form item value. */ + editorType?: string; + /** Specifies configuration options for the editor widget of the current form item. */ + editorOptions?: Object; + /** A template to be used for rendering the form item. */ + template?: any; + /** Specifies the help text displayed for the current form item. */ + helpText?: string; + /** Specifies whether the current form item is required. */ + isRequired?: boolean; + /** Specifies options for the form item label. */ + label?: dxFormItemLabel; + /** An array of validation rules to be checked for the form item editor. */ + validationRules?: Array; + } + export interface dxFormGroupItem extends dxFormItem { + /** Specifies the group caption. */ + caption?: string; + /** A template to be used for rendering the group item. */ + template?: any; + /** The count of columns in the group layout. */ + colCount?: number; + /** Specifies whether or not all group item labels are aligned. */ + alignItemLabels?: boolean; + /** Holds an array of form items displayed within the group. */ + items?: Array; + } + export interface dxFormTab { + /** Specifies the tab title. */ + title?: string; + /** The count of columns in the tab layout. */ + colCount?: number; + /** Specifies whether or not labels of items displayed within the current tab are aligned. */ + alignItemLabels?: boolean; + /** Holds an array of form items displayed within the tab. */ + items?: Array; + /** Specifies a badge text for the tab. */ + badge?: string; + /** A Boolean value specifying whether or not the tab can respond to user interaction. */ + disabled?: boolean; + /** Specifies the icon to be displayed on the tab. */ + icon?: string; + /** The template to be used for rendering the tab. */ + tabTemplate?: any; + /** The template to be used for rendering the tab content. */ + template?: any; + } + export interface dxFormTabbedItem extends dxFormItem { + /** Holds a configuration object for the dxTabPanel widget used to display the current form item. */ + tabPanelOptions?: Object; + /** An array of tab configuration objects. */ + tabs?: Array; + } + export interface dxFormOptions extends WidgetOptions { + /** An object providing data for the form. */ + formData?: Object; + /** The count of columns in the form layout. */ + colCount?: any; + /** Specifies the location of a label against the editor. */ + labelLocation?: string; + /** Specifies whether or not all editors on the form are read-only. */ + readOnly?: boolean; + /** A handler for the fieldDataChanged event. */ + onFieldDataChanged?: (e: Object) => void; + /** A handler for the editorEnterKey event. */ + onEditorEnterKey?: (e: Object) => void; + /** Specifies a function that customizes a form item after it has been created. */ + customizeItem?: Function; + /** The minimum column width used for calculating column count in the form layout. */ + minColWidth?: number; + /** Specifies whether or not all root item labels are aligned. */ + alignItemLabels?: boolean; + /** Specifies whether or not item labels in all groups are aligned. */ + alignItemLabelsInAllGroups?: boolean; + /** Specifies whether or not a colon is displayed at the end of form labels. */ + showColonAfterLabel?: boolean; + /** Specifies whether or not the required mark is displayed for required fields. */ + showRequiredMark?: boolean; + /** Specifies whether or not the optional mark is displayed for optional fields. */ + showOptionalMark?: boolean; + /** The text displayed for required fields. */ + requiredMark?: string; + /** The text displayed for optional fields. */ + optionalMark?: string; + /** Specifies the message that is shown for end-users if a required field value is not specified. */ + requiredMessage?: string; + /** Specifies whether or not the total validation summary is displayed on the form. */ + showValidationSummary?: boolean; + /** Holds an array of form items. */ + items?: Array; + /** A Boolean value specifying whether to enable or disable form scrolling. */ + scrollingEnabled?: boolean; + onContentReady?: Function; + } + /** A form widget used to display and edit values of object fields. */ + export class dxForm extends Widget { + constructor(element: JQuery, options?: dxFormOptions); + constructor(element: Element, options?: dxFormOptions); + /** Updates the specified field of the formData object and the corresponding editor on the form. */ + updateData(dataField: string, value: any): void; + /** Updates the specified fields of the formData object and the corresponding editors on the form. */ + updateData(data: Object): void; + /** Updates the value of a form item option. */ + itemOption(field: string, option: string, value: any): void; + /** Updates the values of form item options. */ + itemOption(field: string, options: Object): void; + /** Returns an editor instance associated with the specified formData field. */ + getEditor(field: string): Object; + /** Updates the dimensions of the widget contents. */ + updateDimensions(): JQueryPromise; + /** Validates the values of all editors on the form against the list of the validation rules specified for each form item. */ + validate(): Object; + } +} +interface JQuery { + dxProgressBar(): JQuery; + dxProgressBar(options: "instance"): DevExpress.ui.dxProgressBar; + dxProgressBar(options: string): any; + dxProgressBar(options: string, ...params: any[]): any; + dxProgressBar(options: DevExpress.ui.dxProgressBarOptions): JQuery; + dxSlider(): JQuery; + dxSlider(options: "instance"): DevExpress.ui.dxSlider; + dxSlider(options: string): any; + dxSlider(options: string, ...params: any[]): any; + dxSlider(options: DevExpress.ui.dxSliderOptions): JQuery; + dxRangeSlider(): JQuery; + dxRangeSlider(options: "instance"): DevExpress.ui.dxRangeSlider; + dxRangeSlider(options: string): any; + dxRangeSlider(options: string, ...params: any[]): any; + dxRangeSlider(options: DevExpress.ui.dxRangeSliderOptions): JQuery; + dxFileUploader(): JQuery; + dxFileUploader(options: "instance"): DevExpress.ui.dxFileUploader; + dxFileUploader(options: string): any; + dxFileUploader(options: string, ...params: any[]): any; + dxFileUploader(options: DevExpress.ui.dxFileUploaderOptions): JQuery; + dxValidator(): JQuery; + dxValidator(options: "instance"): DevExpress.ui.dxValidator; + dxValidator(options: string): any; + dxValidator(options: string, ...params: any[]): any; + dxValidator(options: DevExpress.ui.dxValidatorOptions): JQuery; + dxValidationGroup(): JQuery; + dxValidationGroup(options: "instance"): DevExpress.ui.dxValidationGroup; + dxValidationGroup(options: string): any; + dxValidationGroup(options: string, ...params: any[]): any; + dxValidationSummary(): JQuery; + dxValidationSummary(options: "instance"): DevExpress.ui.dxValidationSummary; + dxValidationSummary(options: string): any; + dxValidationSummary(options: string, ...params: any[]): any; + dxValidationSummary(options: DevExpress.ui.dxValidationSummaryOptions): JQuery; + dxTooltip(): JQuery; + dxTooltip(options: "instance"): DevExpress.ui.dxTooltip; + dxTooltip(options: string): any; + dxTooltip(options: string, ...params: any[]): any; + dxTooltip(options: DevExpress.ui.dxTooltipOptions): JQuery; + dxResizable(): JQuery; + dxResizable(options: "instance"): DevExpress.ui.dxResizable; + dxResizable(options: string): any; + dxResizable(options: string, ...params: any[]): any; + dxResizable(options: DevExpress.ui.dxResizableOptions): JQuery; + dxDropDownList(): JQuery; + dxDropDownList(options: "instance"): DevExpress.ui.dxDropDownList; + dxDropDownList(options: string): any; + dxDropDownList(options: string, ...params: any[]): any; + dxDropDownList(options: DevExpress.ui.dxDropDownListOptions): JQuery; + dxToolbar(): JQuery; + dxToolbar(options: "instance"): DevExpress.ui.dxToolbar; + dxToolbar(options: string): any; + dxToolbar(options: string, ...params: any[]): any; + dxToolbar(options: DevExpress.ui.dxToolbarOptions): JQuery; + dxToast(): JQuery; + dxToast(options: "instance"): DevExpress.ui.dxToast; + dxToast(options: string): any; + dxToast(options: string, ...params: any[]): any; + dxToast(options: DevExpress.ui.dxToastOptions): JQuery; + dxTextEditor(): JQuery; + dxTextEditor(options: "instance"): DevExpress.ui.dxTextEditor; + dxTextEditor(options: string): any; + dxTextEditor(options: string, ...params: any[]): any; + dxTextEditor(options: DevExpress.ui.dxTextEditorOptions): JQuery; + dxTextBox(): JQuery; + dxTextBox(options: "instance"): DevExpress.ui.dxTextBox; + dxTextBox(options: string): any; + dxTextBox(options: string, ...params: any[]): any; + dxTextBox(options: DevExpress.ui.dxTextBoxOptions): JQuery; + dxTextArea(): JQuery; + dxTextArea(options: "instance"): DevExpress.ui.dxTextArea; + dxTextArea(options: string): any; + dxTextArea(options: string, ...params: any[]): any; + dxTextArea(options: DevExpress.ui.dxTextAreaOptions): JQuery; + dxTabs(): JQuery; + dxTabs(options: "instance"): DevExpress.ui.dxTabs; + dxTabs(options: string): any; + dxTabs(options: string, ...params: any[]): any; + dxTabs(options: DevExpress.ui.dxTabsOptions): JQuery; + dxTabPanel(): JQuery; + dxTabPanel(options: "instance"): DevExpress.ui.dxTabPanel; + dxTabPanel(options: string): any; + dxTabPanel(options: string, ...params: any[]): any; + dxTabPanel(options: DevExpress.ui.dxTabPanelOptions): JQuery; + dxSelectBox(): JQuery; + dxSelectBox(options: "instance"): DevExpress.ui.dxSelectBox; + dxSelectBox(options: string): any; + dxSelectBox(options: string, ...params: any[]): any; + dxSelectBox(options: DevExpress.ui.dxSelectBoxOptions): JQuery; + dxTagBox(): JQuery; + dxTagBox(options: "instance"): DevExpress.ui.dxTagBox; + dxTagBox(options: string): any; + dxTagBox(options: string, ...params: any[]): any; + dxTagBox(options: DevExpress.ui.dxTagBoxOptions): JQuery; + dxScrollView(): JQuery; + dxScrollView(options: "instance"): DevExpress.ui.dxScrollView; + dxScrollView(options: string): any; + dxScrollView(options: string, ...params: any[]): any; + dxScrollView(options: DevExpress.ui.dxScrollViewOptions): JQuery; + dxScrollable(): JQuery; + dxScrollable(options: "instance"): DevExpress.ui.dxScrollable; + dxScrollable(options: string): any; + dxScrollable(options: string, ...params: any[]): any; + dxScrollable(options: DevExpress.ui.dxScrollableOptions): JQuery; + dxRadioGroup(): JQuery; + dxRadioGroup(options: "instance"): DevExpress.ui.dxRadioGroup; + dxRadioGroup(options: string): any; + dxRadioGroup(options: string, ...params: any[]): any; + dxRadioGroup(options: DevExpress.ui.dxRadioGroupOptions): JQuery; + dxPopup(): JQuery; + dxPopup(options: "instance"): DevExpress.ui.dxPopup; + dxPopup(options: string): any; + dxPopup(options: string, ...params: any[]): any; + dxPopup(options: DevExpress.ui.dxPopupOptions): JQuery; + dxPopover(): JQuery; + dxPopover(options: "instance"): DevExpress.ui.dxPopover; + dxPopover(options: string): any; + dxPopover(options: string, ...params: any[]): any; + dxPopover(options: DevExpress.ui.dxPopoverOptions): JQuery; + dxOverlay(): JQuery; + dxOverlay(options: "instance"): DevExpress.ui.dxOverlay; + dxOverlay(options: string): any; + dxOverlay(options: string, ...params: any[]): any; + dxOverlay(options: DevExpress.ui.dxOverlayOptions): JQuery; + dxNumberBox(): JQuery; + dxNumberBox(options: "instance"): DevExpress.ui.dxNumberBox; + dxNumberBox(options: string): any; + dxNumberBox(options: string, ...params: any[]): any; + dxNumberBox(options: DevExpress.ui.dxNumberBoxOptions): JQuery; + dxNavBar(): JQuery; + dxNavBar(options: "instance"): DevExpress.ui.dxNavBar; + dxNavBar(options: string): any; + dxNavBar(options: string, ...params: any[]): any; + dxNavBar(options: DevExpress.ui.dxNavBarOptions): JQuery; + dxMultiView(): JQuery; + dxMultiView(options: "instance"): DevExpress.ui.dxMultiView; + dxMultiView(options: string): any; + dxMultiView(options: string, ...params: any[]): any; + dxMultiView(options: DevExpress.ui.dxMultiViewOptions): JQuery; + dxMap(): JQuery; + dxMap(options: "instance"): DevExpress.ui.dxMap; + dxMap(options: string): any; + dxMap(options: string, ...params: any[]): any; + dxMap(options: DevExpress.ui.dxMapOptions): JQuery; + dxLookup(): JQuery; + dxLookup(options: "instance"): DevExpress.ui.dxLookup; + dxLookup(options: string): any; + dxLookup(options: string, ...params: any[]): any; + dxLookup(options: DevExpress.ui.dxLookupOptions): JQuery; + dxLoadPanel(): JQuery; + dxLoadPanel(options: "instance"): DevExpress.ui.dxLoadPanel; + dxLoadPanel(options: string): any; + dxLoadPanel(options: string, ...params: any[]): any; + dxLoadPanel(options: DevExpress.ui.dxLoadPanelOptions): JQuery; + dxLoadIndicator(): JQuery; + dxLoadIndicator(options: "instance"): DevExpress.ui.dxLoadIndicator; + dxLoadIndicator(options: string): any; + dxLoadIndicator(options: string, ...params: any[]): any; + dxLoadIndicator(options: DevExpress.ui.dxLoadIndicatorOptions): JQuery; + dxList(): JQuery; + dxList(options: "instance"): DevExpress.ui.dxList; + dxList(options: string): any; + dxList(options: string, ...params: any[]): any; + dxList(options: DevExpress.ui.dxListOptions): JQuery; + dxGallery(): JQuery; + dxGallery(options: "instance"): DevExpress.ui.dxGallery; + dxGallery(options: string): any; + dxGallery(options: string, ...params: any[]): any; + dxGallery(options: DevExpress.ui.dxGalleryOptions): JQuery; + dxDropDownEditor(): JQuery; + dxDropDownEditor(options: "instance"): DevExpress.ui.dxDropDownEditor; + dxDropDownEditor(options: string): any; + dxDropDownEditor(options: string, ...params: any[]): any; + dxDropDownEditor(options: DevExpress.ui.dxDropDownEditorOptions): JQuery; + dxDateBox(): JQuery; + dxDateBox(options: "instance"): DevExpress.ui.dxDateBox; + dxDateBox(options: string): any; + dxDateBox(options: string, ...params: any[]): any; + dxDateBox(options: DevExpress.ui.dxDateBoxOptions): JQuery; + dxCheckBox(): JQuery; + dxCheckBox(options: "instance"): DevExpress.ui.dxCheckBox; + dxCheckBox(options: string): any; + dxCheckBox(options: string, ...params: any[]): any; + dxCheckBox(options: DevExpress.ui.dxCheckBoxOptions): JQuery; + dxBox(): JQuery; + dxBox(options: "instance"): DevExpress.ui.dxBox; + dxBox(options: string): any; + dxBox(options: string, ...params: any[]): any; + dxBox(options: DevExpress.ui.dxBoxOptions): JQuery; + dxButton(): JQuery; + dxButton(options: "instance"): DevExpress.ui.dxButton; + dxButton(options: string): any; + dxButton(options: string, ...params: any[]): any; + dxButton(options: DevExpress.ui.dxButtonOptions): JQuery; + dxCalendar(): JQuery; + dxCalendar(options: "instance"): DevExpress.ui.dxCalendar; + dxCalendar(options: string): any; + dxCalendar(options: string, ...params: any[]): any; + dxCalendar(options: DevExpress.ui.dxCalendarOptions): JQuery; + dxAccordion(): JQuery; + dxAccordion(options: "instance"): DevExpress.ui.dxAccordion; + dxAccordion(options: string): any; + dxAccordion(options: string, ...params: any[]): any; + dxAccordion(options: DevExpress.ui.dxAccordionOptions): JQuery; + dxResponsiveBox(): JQuery; + dxResponsiveBox(options: "instance"): DevExpress.ui.dxResponsiveBox; + dxResponsiveBox(options: string): any; + dxResponsiveBox(options: string, ...params: any[]): any; + dxResponsiveBox(options: DevExpress.ui.dxResponsiveBoxOptions): JQuery; + dxAutocomplete(): JQuery; + dxAutocomplete(options: "instance"): DevExpress.ui.dxAutocomplete; + dxAutocomplete(options: string): any; + dxAutocomplete(options: string, ...params: any[]): any; + dxAutocomplete(options: DevExpress.ui.dxAutocompleteOptions): JQuery; + dxForm(): JQuery; + dxForm(options: "instance"): DevExpress.ui.dxForm; + dxForm(options: string): any; + dxForm(options: string, ...params: any[]): any; + dxForm(options: DevExpress.ui.dxFormOptions): JQuery; +} + +declare module DevExpress.ui { + export interface dxTileViewOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** Specifies the height of the base tile view item. */ + baseItemHeight?: number; + /** Specifies the width of the base tile view item. */ + baseItemWidth?: number; + /** Specifies whether tiles are placed horizontally or vertically. */ + direction?: string; + /** Specifies the height of the widget. */ + height?: any; + /** Specifies the distance in pixels between adjacent tiles. */ + itemMargin?: number; + /** A Boolean value specifying whether or not to display a scrollbar. */ + showScrollbar?: boolean; + } + /** A widget displaying several blocks of data as tiles. */ + export class dxTileView extends CollectionWidget { + constructor(element: JQuery, options?: dxTileViewOptions); + constructor(element: Element, options?: dxTileViewOptions); + /** Returns the current scroll position of the widget content. */ + scrollPosition(): number; + } + export interface dxSwitchOptions extends EditorOptions { + activeStateEnabled?: boolean; + /** Text displayed when the widget is in a disabled state. */ + offText?: string; + /** Text displayed when the widget is in an enabled state. */ + onText?: string; + /** A Boolean value specifying whether the current switch state is "On" or "Off". */ + value?: boolean; + } + /** A switch widget. */ + export class dxSwitch extends Editor { + constructor(element: JQuery, options?: dxSwitchOptions); + constructor(element: Element, options?: dxSwitchOptions); + } + export interface dxSlideOutViewOptions extends WidgetOptions { + /** Specifies the current menu position. */ + menuPosition?: string; + /** Specifies whether or not the menu panel is visible. */ + menuVisible?: boolean; + /** Specifies whether or not the menu is shown when a user swipes the widget content. */ + swipeEnabled?: boolean; + /** A template to be used for rendering menu panel content. */ + menuTemplate?: any; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + } + /** The widget that allows you to slide-out the current view to reveal a custom menu. */ + export class dxSlideOutView extends Widget { + constructor(element: JQuery, options?: dxSlideOutViewOptions); + constructor(element: Element, options?: dxSlideOutViewOptions); + /** Returns an HTML element of the widget menu block. */ + menuContent(): JQuery; + /** Returns an HTML element of the widget content block. */ + content(): JQuery; + /** Displays the widget's menu block. */ + showMenu(): JQueryPromise; + /** Hides the widget's menu block. */ + hideMenu(): JQueryPromise; + /** Toggles the visibility of the widget's menu block. */ + toggleMenuVisibility(): JQueryPromise; + } + export interface dxSlideOutOptions extends CollectionWidgetOptions { + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** A Boolean value specifying whether or not to display a grouped menu. */ + menuGrouped?: boolean; + /** Specifies the current menu position. */ + menuPosition?: string; + /** The name of the template used to display a group header. */ + menuGroupTemplate?: any; + /** The template used to render menu items. */ + menuItemTemplate?: any; + /** A handler for the menuGroupRendered event. */ + onMenuGroupRendered?: Function; + /** A handler for the menuItemRendered event. */ + onMenuItemRendered?: Function; + /** Specifies whether or not the slide-out menu is displayed. */ + menuVisible?: boolean; + /** Indicates whether the menu can be shown/hidden by swiping the widget's main panel. */ + swipeEnabled?: boolean; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + } + /** The widget that allows you to slide-out the current view to reveal an item list. */ + export class dxSlideOut extends CollectionWidget { + constructor(element: JQuery, options?: dxSlideOutOptions); + constructor(element: Element, options?: dxSlideOutOptions); + /** Hides the widget's slide-out menu. */ + hideMenu(): JQueryPromise; + /** Displays the widget's slide-out menu. */ + showMenu(): JQueryPromise; + /** Toggles the visibility of the widget's slide-out menu. */ + toggleMenuVisibility(showing: boolean): JQueryPromise; + } + export interface dxPivotOptions extends CollectionWidgetOptions { + /** The index of the currently active pivot item. */ + selectedIndex?: number; + /** A Boolean value specifying whether or not to allow users to switch between items by swiping. */ + swipeEnabled?: boolean; + /** A template to be used for rendering widget content. */ + contentTemplate?: any; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + } + /** A widget that is similar to a traditional tab control, but optimized for the phone with simplified end-user interaction. */ + export class dxPivot extends CollectionWidget { + constructor(element: JQuery, options?: dxPivotOptions); + constructor(element: Element, options?: dxPivotOptions); + } + export interface dxPanoramaOptions extends CollectionWidgetOptions { + /** An object exposing options for setting a background image for the panorama. */ + backgroundImage?: { + /** Specifies the height of the panorama's background image. */ + height?: number; + /** Specifies the URL of the image that is used as the panorama's background image. */ + url?: string; + /** Specifies the width of the panorama's background image. */ + width?: number; + }; + /** The index of the currently active panorama item. */ + selectedIndex?: number; + /** Specifies the widget content title. */ + title?: string; + } + /** A widget displaying the required content in a long horizontal canvas that extends beyond the frames of the screen. */ + export class dxPanorama extends CollectionWidget { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + } + export interface dxDropDownMenuOptions extends WidgetOptions { + /** A handler for the buttonClick event. */ + onButtonClick?: any; + /** The name of the icon to be displayed by the DropDownMenu button. */ + buttonIcon?: string; + /** The text displayed in the DropDownMenu button. */ + buttonText?: string; + buttonIconSrc?: string; + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** An array of items displayed by the widget. */ + items?: Array; + /** The template to be used for rendering items. */ + itemTemplate?: any; + /** Specifies whether or not to show the drop down menu within a dxPopover widget. */ + usePopover?: boolean; + /** The width of the menu popup in pixels. */ + popupWidth?: any; + /** The height of the menu popup in pixels. */ + popupHeight?: any; + /** Specifies whether or not the drop-down menu is displayed. */ + opened?: boolean; + hoverStateEnabled?: boolean; + activeStateEnabled?: boolean; + } + /** A drop-down menu widget. */ + export class dxDropDownMenu extends Widget { + constructor(element: JQuery, options?: dxDropDownEditorOptions); + constructor(element: Element, options?: dxDropDownEditorOptions); + /** This section lists the data source fields that are used in a default template for drop-down menu items. */ + /** Opens the drop-down menu. */ + open(): void; + /** Closes the drop-down menu. */ + close(): void; + } + export interface dxActionSheetOptions extends CollectionWidgetOptions { + /** A handler for the cancelClick event. */ + onCancelClick?: any; + /** The text displayed in the button that closes the action sheet. */ + cancelText?: string; + /** Specifies whether or not to display the Cancel button in action sheet. */ + showCancelButton?: boolean; + /** A Boolean value specifying whether or not the title of the action sheet is visible. */ + showTitle?: boolean; + /** Specifies the element the action sheet popover points at. */ + target?: any; + /** The title of the action sheet. */ + title?: string; + /** Specifies whether or not to show the action sheet within a dxPopover widget. */ + usePopover?: boolean; + /** A Boolean value specifying whether or not the dxActionSheet widget is visible. */ + visible?: boolean; + } + /** A widget consisting of a set of choices related to a certain task. */ + export class dxActionSheet extends CollectionWidget { + constructor(element: JQuery, options?: dxActionSheetOptions); + constructor(element: Element, options?: dxActionSheetOptions); + /** Hides the widget. */ + hide(): JQueryPromise; + /** Shows the widget. */ + show(): JQueryPromise; + /** Shows or hides the widget depending on the Boolean value passed as the parameter. */ + toggle(showing: boolean): JQueryPromise; + } +} +interface JQuery { + dxTileView(): JQuery; + dxTileView(options: "instance"): DevExpress.ui.dxTileView; + dxTileView(options: string): any; + dxTileView(options: string, ...params: any[]): any; + dxTileView(options: DevExpress.ui.dxTileViewOptions): JQuery; + dxSwitch(): JQuery; + dxSwitch(options: "instance"): DevExpress.ui.dxSwitch; + dxSwitch(options: string): any; + dxSwitch(options: string, ...params: any[]): any; + dxSwitch(options: DevExpress.ui.dxSwitchOptions): JQuery; + dxSlideOut(): JQuery; + dxSlideOut(options: "instance"): DevExpress.ui.dxSlideOut; + dxSlideOut(options: string): any; + dxSlideOut(options: string, ...params: any[]): any; + dxSlideOut(options: DevExpress.ui.dxSlideOutOptions): JQuery; + dxPivot(): JQuery; + dxPivot(options: "instance"): DevExpress.ui.dxPivot; + dxPivot(options: string): any; + dxPivot(options: string, ...params: any[]): any; + dxPivot(options: DevExpress.ui.dxPivotOptions): JQuery; + dxPanorama(): JQuery; + dxPanorama(options: "instance"): DevExpress.ui.dxPanorama; + dxPanorama(options: string): any; + dxPanorama(options: string, ...params: any[]): any; + dxPanorama(options: DevExpress.ui.dxPanoramaOptions): JQuery; + dxActionSheet(): JQuery; + dxActionSheet(options: "instance"): DevExpress.ui.dxActionSheet; + dxActionSheet(options: string): any; + dxActionSheet(options: string, ...params: any[]): any; + dxActionSheet(options: DevExpress.ui.dxActionSheetOptions): JQuery; + dxDropDownMenu(): JQuery; + dxDropDownMenu(options: "instance"): DevExpress.ui.dxDropDownMenu; + dxDropDownMenu(options: string): any; + dxDropDownMenu(options: string, ...params: any[]): any; + dxDropDownMenu(options: DevExpress.ui.dxDropDownMenuOptions): JQuery; +} +declare module DevExpress.data { + export interface XmlaStoreOptions { + /** The HTTP address to an XMLA OLAP server. */ + url?: string; + /** The name of the database associated with the Store. */ + catalog?: string; + /** The cube name. */ + cube?: string; + /** A function used to customize a web request before it is sent. */ + beforeSend?: (request: Object) => void; + } + /** A Store that provides access to an OLAP cube using the XMLA standard. */ + export class XmlaStore { + constructor(options: XmlaStoreOptions); + } + export interface PivotGridField { + index?: number; + /** A boolean value specifying whether or not the field is visible in the pivot grid and the Field Chooser. */ + visible?: boolean; + /** Name of the data source field containing data for the pivot grid field. */ + dataField?: string; + /** A caption that will be displayed in the pivot grid's field chooser to identify the field. */ + caption?: string; + /** Specifies a type of field values. */ + dataType?: string; + /** Specifies how the values of the current field are combined into groups. Cannot be used for the XmlaStore store type. */ + groupInterval?: any; + /** Specifies how to aggregate field data. Cannot be used for the XmlaStore store type. */ + summaryType?: string; + /** Allows you to use a custom aggregate function to calculate the summary values. Cannot be used for the XmlaStore store type. */ + calculateCustomSummary?: (options: { + summaryProcess?: string; + value?: any; + totalValue?: any; + }) => void; + /** Specifies the function that determines how to split data from the data source into ranges for header items. Cannot be used for the XmlaStore store type. */ + selector?: (data: Object) => any; + /** Type of the area where the field is located. */ + area?: string; + /** Index among the other fields displayed within the same area. */ + areaIndex?: number; + /** The name of the folder in which the field is located. */ + displayFolder?: string; + /** The name of the group to which the field belongs. */ + groupName?: string; + /** The index of the field within a group. */ + groupIndex?: number; + /** Specifies the sort order of field values. */ + sortOrder?: string; + /** Specifies how field data should be sorted. Can be used for the XmlaStore store type only. */ + sortBy?: string; + /** Sorts the header items of this field by the summary values of another field. */ + sortBySummaryField?: string; + /** The array of field names that specify a path to column/row whose summary field is used for sorting of this field's header items. */ + sortBySummaryPath?: Array; + /** The filter values for the current field. */ + filterValues?: Array; + /** The filter type for the current field. */ + filterType?: string; + /** Indicates whether all header items of the field's header level are expanded. */ + expanded?: boolean; + /** Specifies whether the field should be treated as a Data Field. */ + isMeasure?: boolean; + /** Specifies a display format for field values. */ + format?: string; + /** Specifies a callback function that returns the text to be displayed in the cells of a field. */ + customizeText?: (cellInfo: { value: any; valueText: string }) => string; + /** Specifies a precision for formatted field values. */ + precision?: number; + /** Specifies how to sort the header items. */ + sortingMethod?: (a: Object, b: Object) => number; + /** Allows an end-user to change sorting options. */ + allowSorting?: boolean; + /** Allows an end-user to sort columns by summary values. */ + allowSortingBySummary?: boolean; + /** Allows an end-user to change filtering options. */ + allowFiltering?: boolean; + /** Allows an end-user to expand/collapse all header items within a header level. */ + allowExpandAll?: boolean; + /** Specifies the absolute width of the field in the pivot grid. */ + width?: number; + /** Specifies the summary post-processing algorithm. */ + summaryDisplayMode?: string; + /** Specifies whether to summarize each next summary value with the previous one by rows or columns. */ + runningTotal?: string; + /** Specifies whether to allow the predefined summary post-processing functions ('absoluteVariation' and 'percentVariation') and runningTotal to take values of different groups into account. */ + allowCrossGroupCalculation?: boolean; + /** Specifies a callback function that allows you to modify summary values after they are calculated. */ + calculateSummaryValue?: (e: Object) => number; + /** Specifies whether or not to display Total values for the field. */ + showTotals?: boolean; + /** Specifies whether or not to display Grand Total values for the field. */ + showGrandTotals?: boolean; + } + export class SummaryCell { + /** Gets the parent cell in a specified direction. */ + parent(direction: string): SummaryCell; + /** Gets all children cells in a specified direction. */ + children(direction: string): Array; + /** Gets a partial Grand Total cell of a row or column. */ + grandTotal(direction: string): SummaryCell; + /** Gets the Grand Total of the entire pivot grid. */ + grandTotal(): SummaryCell; + /** Gets the cell next to the current one in a specified direction. */ + next(direction: string): SummaryCell; + /** Gets the cell next to current in a specified direction. */ + next(direction: string, allowCrossGroup: boolean): SummaryCell; + /** Gets the cell prior to the current one in a specified direction. */ + prev(direction: string): SummaryCell; + /** Gets the cell previous to current in a specified direction. */ + prev(direction: string, allowCrossGroup: boolean): SummaryCell; + /** Gets the child cell in a specified direction. */ + child(direction: string, fieldValue: any): SummaryCell; + /** Gets the cell located by the path of the source cell with one field value changed. */ + slice(field: PivotGridField, value: any): SummaryCell; + /** Gets the header cell of a row or column field to which the current cell belongs. */ + field(area: string): PivotGridField; + /** Gets the value of the current cell. */ + value(): any; + /** Gets the value of the current cell. */ + value(isCalculatedValue: boolean): any; + /** Gets the value of any field linked with the current cell. */ + value(field: PivotGridField): any; + /** Gets the value of any field linked with the current cell. */ + value(field: PivotGridField, isCalculatedValue: boolean): any; + } + export interface PivotGridDataSourceOptions { + /** Specifies the underlying Store instance used to access data. */ + store?: any; + /** Indicates whether or not the automatic field generation from data in the Store is enabled. */ + retrieveFields?: boolean; + /** Specifies data filtering conditions. Cannot be used for the XmlaStore store type. */ + filter?: Object; + /** An array of pivot grid fields. */ + fields?: Array; + /** A handler for the changed event. */ + onChanged?: () => void; + /** A handler for the loadingChanged event. */ + onLoadingChanged?: (isLoading: boolean) => void; + /** A handler for the loadError event. */ + onLoadError?: (e?: Object) => void; + /** A handler for the fieldsPrepared event. */ + onFieldsPrepared?: (e?: Array) => void; + } + /** An object that provides access to data for the dxPivotGrid widget. */ + export class PivotGridDataSource implements EventsMixin { + constructor(options?: PivotGridDataSource); + /** Starts reloading data from any store and updating the data source. */ + reload(): JQueryPromise; + /** Starts updating the data source. Reloads data from the XMLA store only. */ + load(): JQueryPromise; + /** Indicates whether or not the PivotGridDataSource is currently being loaded. */ + isLoading(): boolean; + /** Gets data displayed in a PivotGrid. */ + getData(): Object; + /** Gets all fields within a specified area. */ + getAreaFields(area: string, collectGroups: boolean): Array; + /** Gets all fields from the data source. */ + fields(): Array; + /** Sets the fields option. */ + fields(fields: Array): void; + /** Gets current options of a specified field. */ + field(id: any): PivotGridField; + /** Sets one or more options of a specified field. */ + field(id: any, field: PivotGridField): void; + /** Collapses a specified header item. */ + collapseHeaderItem(area: string, path: Array): void; + /** Expands a specified header item. */ + expandHeaderItem(area: string, path: Array): void; + /** Expands all header items of a field. */ + expandAll(id: any): void; + /** Collapses all header items of a field. */ + collapseAll(id: any): void; + /** Disposes of all resources associated with this PivotGridDataSource. */ + dispose(): void; + /** Gets the current filter expression. Cannot be used for the XmlaStore store type. */ + filter(): Object; + /** Applies a new filter expression. Cannot be used for the XmlaStore store type. */ + filter(filterExpr: Object): void; + /** Provides access to a list of records (facts) that were used to calculate a specific summary. */ + createDrillDownDataSource(options: { + columnPath?: Array; + rowPath?: Array; + dataIndex?: number; + maxRowCount?: number; + customColumns?: Array; + }): DevExpress.data.DataSource; + /** Gets the current PivotGridDataSource state (fields configuration, sorting, filters, expanded headers, etc.) */ + state(): Object; + /** Sets the PivotGridDataSource state. */ + state(state: Object): void; + on(eventName: string, eventHandler: Function): PivotGridDataSource; + on(events: { [eventName: string]: Function; }): PivotGridDataSource; + off(eventName: string): PivotGridDataSource; + off(eventName: string, eventHandler: Function): PivotGridDataSource; + } +} +declare module DevExpress.ui { + export interface dxSchedulerOptions extends WidgetOptions { + /** Specifies a date displayed on the current scheduler view by default. */ + currentDate?: Date; + /** The earliest date the widget allows you to select. */ + min?: Date; + /** The latest date the widget allows you to select. */ + max?: Date; + /** Specifies the view used in the scheduler by default. */ + currentView?: string; + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** Specifies the first day of a week. */ + firstDayOfWeek?: number; + /** The template to be used for rendering appointments. */ + appointmentTemplate?: any; + /** The template to be used for rendering an appointment tooltip. */ + appointmentTooltipTemplate?: any; + /** Lists the views to be available within the scheduler's View Selector. */ + views?: Array; + /** Specifies the resource kinds by which the scheduler's appointments are grouped in a timetable. */ + groups?: Array; + /** Specifies a start hour in the scheduler view's time interval. */ + startDayHour?: number; + /** Specifies an end hour in the scheduler view's time interval. */ + endDayHour?: number; + /** Specifies whether or not the "All-day" panel is visible. */ + showAllDayPanel?: boolean; + /** Specifies cell duration in minutes. */ + cellDuration?: number; + /** Specifies the edit mode for recurring appointments. */ + recurrenceEditMode?: string; + /** Specifies which editing operations an end-user can perform on appointments. */ + editing?: { + /** Specifies whether or not an end-user can add appointments. */ + allowAdding?: boolean; + /** Specifies whether or not an end-user can change appointment options. */ + allowUpdating?: boolean; + /** Specifies whether or not an end-user can delete appointments. */ + allowDeleting?: boolean; + /** Specifies whether or not an end-user can change an appointment duration. */ + allowResizing?: boolean; + /** Specifies whether or not an end-user can drag appointments. */ + allowDragging?: boolean; + } + /** Specifies an array of resources available in the scheduler. */ + resources?: Array<{ + /** Indicates whether or not several resources of this kind can be assigned to an appointment. */ + allowMultiple?: boolean; + /** + * Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. + * @deprecated Use the 'useColorAsDefault' property instead + */ + mainColor?: boolean; + /** Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. */ + useColorAsDefault?: boolean; + /** A data source used to fetch resources to be available in the scheduler. */ + dataSource?: any; + /** Specifies the resource object field whose value is displayed by the Resource editor in the Appointment popup window. */ + displayExpr?: any; + /** Specifies the resource object field that is used as a value of the Resource editor in the Appointment popup window. */ + valueExpr?: any; + /** The name of the appointment object field that specifies a resource of this kind. */ + field?: string; + /** Specifies the label of the Appointment popup window field that allows end users to assign a resource of this kind. */ + label?: string; + }>; + /** A handler for the AppointmentAdding event. */ + onAppointmentAdding?: Function; + /** A handler for the appointmentAdded event. */ + onAppointmentAdded?: Function; + /** A handler for the AppointmentUpdating event. */ + onAppointmentUpdating?: Function; + /** A handler for the appointmentUpdated event. */ + onAppointmentUpdated?: Function; + /** A handler for the AppointmentDeleting event. */ + onAppointmentDeleting?: Function; + /** A handler for the appointmentDeleted event. */ + onAppointmentDeleted?: Function; + /** A handler for the appointmentRendered event. */ + onAppointmentRendered?: Function; + /** A handler for the appointmentClick event. */ + onAppointmentClick?: any; + /** A handler for the appointmentDblClick event. */ + onAppointmentDblClick?: any; + /** A handler for the cellClick event. */ + onCellClick?: any; + /** A handler for the appointmentFormCreated event. */ + onAppointmentFormCreated?: Function; + /** Specifies whether or not an end-user can scroll the view horizontally. */ + horizontalScrollingEnabled?: boolean; + /** Specifies whether a user can switch views using tabs or a drop-down menu. */ + useDropDownViewSwitcher?: boolean; + /** Specifies the name of the data source item field that defines the start of an appointment. */ + startDateExpr?: string; + /** Specifies the name of the data source item field that defines the ending of an appointment. */ + endDateExpr?: string; + /** Specifies the name of the data source item field that holds the subject of an appointment. */ + textExpr?: string; + /** Specifies the name of the data source item field whose value holds the description of the corresponding appointment. */ + descriptionExpr?: string; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding appointment is an all-day appointment. */ + allDayExpr?: string; + /** Specifies the name of the data source item field that defines a recurrence rule for generating recurring appointments. */ + recurrenceRuleExpr?: string; + /** Specifies the name of the data source item field that defines exceptions for the current recurring appointment. */ + recurrenceExceptionExpr?: string; + /** Specifies whether filtering is performed on the server or client side. */ + remoteFiltering?: boolean; + } + /** A widget that displays scheduled data using different views and provides the capability to load, add and edit appointments. */ + export class dxScheduler extends Widget { + constructor(element: JQuery, options?: dxSchedulerOptions); + constructor(element: Element, options?: dxSchedulerOptions); + /** Add the appointment defined by the object passed as a parameter to the data associated with the widget. */ + addAppointment(appointment: Object): void; + /** Updates the appointment specified by the first method parameter by the appointment object specified by the second method parameter in the the data associated with the widget. */ + updateAppointment(target: Object, appointment: Object): void; + /** Deletes the appointment defined by the parameter from the the data associated with the widget. */ + deleteAppointment(appointment: Object): void; + /** Scrolls the scheduler work space to the specified time of the specified day. */ + scrollToTime(hours: number, minutes: number, date: Date): void; + /** Displayes the Appointment Details popup. */ + showAppointmentPopup(appointmentData: Object, createNewAppointment?: boolean, currentAppointmentData?: Object): void; + } + export interface dxColorBoxOptions extends dxDropDownEditorOptions { + /** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */ + applyButtonText?: string; + applyValueMode?: string; + /** Specifies the text displayed on the button that cancels changes and closes the drop-down editor. */ + cancelButtonText?: string; + /** Specifies whether or not the widget value includes the alpha channel component. */ + editAlphaChannel?: boolean; + /** Specifies the size of a step by which a handle is moved using a keyboard shortcut. */ + keyStep?: number; + } + /** A widget used to specify a color value. */ + export class dxColorBox extends dxDropDownEditor { + constructor(element: JQuery, options?: dxColorBoxOptions); + constructor(element: Element, options?: dxColorBoxOptions); + } + export interface HierarchicalCollectionWidgetOptions extends CollectionWidgetOptions { + /** Specifies the name of the data source item field whose value is displayed by the widget. */ + displayExpr?: any; + /** Specifies the name of the data source item field used as a key. */ + keyExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding widget items is selected. */ + selectedExpr?: any; + /** Specifies the name of the data source item field that contains an array of nested items. */ + itemsExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding widget item is disabled. */ + disabledExpr?: any; + /** Specifies the name of the data source item field that holds the key of the parent item. */ + parentIdExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding widget items is expanded. */ + expandedExpr?: any; + hoverStateEnabled?: boolean; + focusStateEnabled?: boolean; + } + export class HierarchicalCollectionWidget extends CollectionWidget { + } + export interface dxTreeViewOptions extends HierarchicalCollectionWidgetOptions { + /** Specifies whether or not to animate item collapsing and expanding. */ + animationEnabled?: boolean; + /** Specifies whether a nested or plain array is used as a data source. */ + dataStructure?: string; + /** Specifies whether or not a user can expand all tree view items by the "*" hot key. */ + expandAllEnabled?: boolean; + /** + * Specifies whether or not a check box is displayed at each tree view item. + * @deprecated Use the showCheckBoxesMode option instead. + */ + showCheckBoxes?: boolean; + /** Specifies the current check boxes display mode. */ + showCheckBoxesMode?: string; + /** Specifies whether or not to select nodes recursively. */ + selectNodesRecursive?: boolean; + /** Specifies whether or not all parent nodes of an initially expanded node are displayed expanded. */ + expandNodesRecursive?: boolean; + /** + * Specifies whether the "Select All" check box is displayed over the tree view. + * @deprecated Use the showCheckBoxesMode option instead. + */ + selectAllEnabled?: boolean; + /** Specifies the text displayed at the "Select All" check box. */ + selectAllText?: string; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node includes child nodes. */ + hasItemsExpr?: any; + /** Specifies if the virtual mode is enabled. */ + virtualModeEnabled?: boolean; + /** Specifies the parent ID value of the root item. */ + rootValue?: any; + /** Specifies the current value used to filter tree view items. */ + searchValue?: string; + /** A string value specifying available scrolling directions. */ + scrollDirection?: string; + /** A handler for the itemSelected event. */ + onItemSelected?: Function; + /** A handler for the itemExpanded event. */ + onItemExpanded?: Function; + /** A handler for the itemCollapsed event. */ + onItemCollapsed?: Function; + onItemClick?: Function; + onItemContextMenu?: Function; + onItemRendered?: Function; + onItemHold?: Function; + } + /** A widget displaying specified data items as a tree. */ + export class dxTreeView extends HierarchicalCollectionWidget { + constructor(element: JQuery, options?: dxTreeViewOptions); + constructor(element: Element, options?: dxTreeViewOptions); + /** Updates the tree view scrollbars according to the current size of the widget content. */ + updateDimensions(): JQueryPromise; + /** Selects the specified item. */ + selectItem(itemElement: any): void; + /** Unselects the specified item. */ + unselectItem(itemElement: any): void; + /** Expands the specified item. */ + expandItem(itemElement: any): void; + /** Collapses the specified item. */ + collapseItem(itemElement: any): void; + /** Returns all nodes of the tree view. */ + getNodes(): Array; + /** Selects all widget items. */ + selectAll(): void; + /** Unselects all widget items. */ + unselectAll(): void; + } + export interface dxMenuBaseOptions extends HierarchicalCollectionWidgetOptions { + /** An object that defines the animation options of the widget. */ + animation?: fx.AnimationOptions; + /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ + activeStateEnabled?: boolean; + /** Specifies the name of the CSS class associated with the menu. */ + cssClass?: string; + /** Holds an array of menu items. */ + items?: Array; + /** Specifies whether or not an item becomes selected if an end-user clicks it. */ + selectionByClick?: boolean; + /** Specifies the selection mode supported by the menu. */ + selectionMode?: string; + /** Specifies options of submenu showing and hiding. */ + showSubmenuMode?: { + /** Specifies the mode name. */ + name?: string; + /** Specifies the delay of submenu show and hiding. */ + delay?: { + /** The time span after which the submenu is shown. */ + show?: number; + /** The time span after which the submenu is hidden. */ + hide?: number; + }; + }; + } + export class dxMenuBase extends HierarchicalCollectionWidget { + constructor(element: JQuery, options?: dxMenuBaseOptions); + constructor(element: Element, options?: dxMenuBaseOptions); + /** Selects the specified item. */ + selectItem(itemElement: any): void; + /** Unselects the specified item. */ + unselectItem(itemElement: any): void; + } + export interface dxMenuOptions extends dxMenuBaseOptions { + /** Specifies whether or not the submenu is hidden when the mouse pointer leaves it. */ + hideSubmenuOnMouseLeave?: boolean; + /** Specifies whether the menu has horizontal or vertical orientation. */ + orientation?: string; + /** Specifies options for showing and hiding the first level submenu. */ + showFirstSubmenuMode?: { + /** Specifies the mode name. */ + name?: string; + /** Specifies the delay in submenu showing and hiding. */ + delay?: { + /** The time span after which the submenu is shown. */ + show?: number; + /** The time span after which the submenu is hidden. */ + hide?: number; + }; + }; + /** Specifies the direction at which the submenus are displayed. */ + submenuDirection?: string; + /** A handler for the submenuHidden event. */ + onSubmenuHidden?: Function; + /** A handler for the submenuHiding event. */ + onSubmenuHiding?: Function; + /** A handler for the submenuShowing event. */ + onSubmenuShowing?: Function; + /** A handler for the submenuShown event. */ + onSubmenuShown?: Function; + } + /** A menu widget. */ + export class dxMenu extends dxMenuBase { + constructor(element: JQuery, options?: dxMenuOptions); + constructor(element: Element, options?: dxMenuOptions); + } + export interface dxContextMenuOptions extends dxMenuBaseOptions { + /** Holds an object that specifies options of alternative menu invocation. */ + alternativeInvocationMode?: { + /** Specifies whether or not the standard context menu invocation (on a right mouse click or on a long tap) is disabled. */ + enabled?: Boolean; + /** Specifies the element used to invoke the context menu. */ + invokingElement?: any; + }; + /** A handler for the hidden event. */ + onHidden?: Function; + /** A handler for the hiding event. */ + onHiding?: Function; + /** A handler for the positioning event. */ + onPositioning?: Function; + /** A handler for the showing event. */ + onShowing?: Function; + /** A handler for the shown event. */ + onShown?: Function; + /** An object defining widget positioning options. */ + position?: PositionOptions; + /** Specifies the direction at which submenus are displayed. */ + submenuDirection?: string; + /** The target element associated with a popover. */ + target?: any; + /** A Boolean value specifying whether or not the widget is visible. */ + visible?: boolean; + } + /** A context menu widget. */ + export class dxContextMenu extends dxMenuBase { + constructor(element: JQuery, options?: dxContextMenuOptions); + constructor(element: Element, options?: dxContextMenuOptions); + /** Toggles the visibility of the widget. */ + toggle(showing: boolean): JQueryPromise; + /** Shows the widget. */ + show(): JQueryPromise; + /** Hides the widget. */ + hide(): JQueryPromise; + } + export interface dxRemoteOperations { + /** Specifies whether or not filtering must be performed on the server side. */ + filtering?: boolean; + /** Specifies whether or not paging must be performed on the server side. */ + paging?: boolean; + /** Specifies whether or not sorting must be performed on the server side. */ + sorting?: boolean; + /** Specifies whether or not grouping must be performed on the server side. */ + grouping?: boolean; + /** Specifies whether or not summaries calculation must be performed on the server side. */ + summary?: boolean; + } + export interface dxDataGridRow { + /** The data object represented by the row. */ + data: Object; + /** The key of the data object represented by the row. */ + key: any; + /** The visible index of the row. */ + rowIndex: number; + /** The type of the row. */ + rowType: string; + } + export interface dxDataGridColumn { + /** Specifies the content alignment within column cells. */ + alignment?: string; + /** Specifies whether the values in a column can be edited at runtime. Setting this option makes sense only when editing is enabled for a grid. */ + allowEditing?: boolean; + /** Specifies whether or not a column can be used for filtering grid records. Setting this option makes sense only when the filter row and column header filtering are visible. */ + allowFiltering?: boolean; + /** Specifies whether or not to allow filtering by this column using its header. */ + allowHeaderFiltering?: boolean; + /** Specifies whether or not the column can be anchored to a grid edge by end users. Setting this option makes sense only when the columnFixing | enabled option is set to true. */ + allowFixing?: boolean; + /** Specifies if a column can be used for searching grid records. Setting this option makes sense only when the search panel is visible. */ + allowSearch?: boolean; + /** Specifies whether a column can be used for grouping grid records at runtime. Setting this option makes sense only when the group panel is visible. */ + allowGrouping?: boolean; + /** Specifies whether or not a column can be hidden by a user. Setting this option makes sense only when the column chooser is visible. */ + allowHiding?: boolean; + /** Specifies whether or not a particular column can be used in column reordering. Setting this option makes sense only when the allowColumnReordering option is set to true. */ + allowReordering?: boolean; + /** Specifies whether or not a particular column can be resized by a user. Setting this option makes sense only when the allowColumnResizing option is true. */ + allowResizing?: boolean; + /** Specifies whether grid records can be sorted by a specific column at runtime. Setting this option makes sense only when the sorting mode differs from none. */ + allowSorting?: boolean; + /** Specifies whether groups appear expanded or not when records are grouped by a specific column. Setting this option makes sense only when grouping is allowed for this column. */ + autoExpandGroup?: boolean; + /** Specifies a callback function that returns a value to be displayed in a column cell. */ + calculateCellValue?: (rowData: Object) => string; + /** Specifies a callback function to be invoked after the cell value is edited by an end-user and before the new value is saved to the data source. */ + setCellValue?: (rowData: Object, value: any) => void; + /** Specifies a callback function that defines filters for customary calculated grid cells. */ + calculateFilterExpression?: (filterValue: any, selectedFilterOperation: string, target: string) => Array; + /** Specifies a caption for a column. */ + caption?: string; + /** Specifies a custom template for grid column cells. */ + cellTemplate?: any; + /** Specifies a CSS class to be applied to a column. */ + cssClass?: string; + /** Specifies how to get a value to be displayed in a cell when it is not in an editing state. */ + calculateDisplayValue?: any; + /** Specifies a field name or a function that returns a field name or a value to be used for grouping column cells. */ + calculateGroupValue?: any; + /** Specifies a field name or a function that returns a field name or a value to be used for sorting column cells. */ + calculateSortValue?: any; + /** Specifies a callback function that returns the text to be displayed in the cells of a column. */ + customizeText?: (cellInfo: { value: any; valueText: string }) => string; + /** Specifies the field of a data source that provides data for a column. */ + dataField?: string; + /** Specifies the required type of column values. */ + dataType?: string; + /** Specifies a custom template for the cell of a grid column when it is in an editing state. */ + editCellTemplate?: any; + /** Specifies configuration options for the editor widget of the current column. */ + editorOptions?: Object; + /** Specifies whether HTML tags are displayed as plain text or applied to the values of the column. */ + encodeHtml?: boolean; + /** In a boolean column, replaces all false items with a specified text. */ + falseText?: string; + /** Specifies the set of available filter operations. */ + filterOperations?: Array; + /** Specifies a filter value for a column. */ + filterValue?: any; + /** Specifies initial filter values for the column's header filter. */ + filterValues?: Array; + /** Specifies whether to include or exclude the records with the values selected in the column's header filter. */ + filterType?: string; + /** Indicates whether the column takes part in horizontal grid scrolling or is anchored to a grid edge. */ + fixed?: boolean; + /** Specifies the grid edge to which the column is anchored. */ + fixedPosition?: string; + /** Specifies a format for the values displayed in a column. */ + format?: string; + /** Specifies a custom template for the group cell of a grid column. */ + groupCellTemplate?: any; + /** Specifies the index of a column when grid records are grouped by the values of this column. */ + groupIndex?: number; + /** Specifies a custom template for the header of a grid column. */ + headerCellTemplate?: any; + /** Specifies options of a lookup column. */ + lookup?: { + /** Specifies whether or not a user can nullify values of a lookup column. */ + allowClearing?: boolean; + /** Specifies the data source providing data for a lookup column. */ + dataSource?: any; + /** Specifies the expression defining the data source field whose values must be displayed. */ + displayExpr?: any; + /** Specifies the expression defining the data source field whose values must be replaced. */ + valueExpr?: string; + }; + /** Specifies column-level options for filtering using a column header filter. */ + headerFilter?: { + /** Specifies the data source to be used for the header filter. */ + dataSource?: any; + /** Specifies how header filter values should be combined into groups. */ + groupInterval?: any; + }; + /** Specifies a precision for formatted values displayed in a column. */ + precision?: number; + /** Specifies a filter operation applied to a column. */ + selectedFilterOperation?: string; + /** Specifies whether or not the column displays its values by using editors. */ + showEditorAlways?: boolean; + /** Specifies whether or not to display the column when grid records are grouped by it. */ + showWhenGrouped?: boolean; + /** Specifies the index of a column when grid records are sorted by the values of this column. */ + sortIndex?: number; + /** Specifies the initial sort order of column values. */ + sortOrder?: string; + /** In a boolean column, replaces all true items with a specified text. */ + trueText?: string; + /** Specifies whether a column is visible or not. */ + visible?: boolean; + /** Specifies the sequence number of the column in the grid. */ + visibleIndex?: number; + /** Specifies a column width in pixels or percentages. */ + width?: any; + /** Specifies an array of validation rules to be checked when updating column cell values. */ + validationRules?: Array; + /** Specifies whether or not to display the header of a hidden column in the column chooser. */ + showInColumnChooser?: boolean; + /** Specifies the identifier of the column. */ + name?: string; + /** The form item configuration object. Used only when the editing mode is "form". */ + formItem?: DevExpress.ui.dxFormItem; + } + export interface dxDataGridOptions extends WidgetOptions { + /** Specifies whether the outer borders of the grid are visible or not. */ + showBorders?: boolean; + /** Indicates whether to show the error row for the grid. */ + errorRowEnabled?: boolean; + /** A handler for the rowValidating event. */ + onRowValidating?: (e: Object) => void; + /** A handler for the contextMenuPreparing event. */ + onContextMenuPreparing?: (e: Object) => void; + /** A handler for the initNewRow event. */ + onInitNewRow?: (e: { data: Object }) => void; + /** A handler for the rowInserted event. */ + onRowInserted?: (e: { data: Object; key: any }) => void; + /** A handler for the rowInserting event. */ + onRowInserting?: (e: { data: Object; cancel: any }) => void; + /** A handler for the rowRemoved event. */ + onRowRemoved?: (e: { data: Object; key: any }) => void; + /** A handler for the rowRemoving event. */ + onRowRemoving?: (e: { data: Object; key: any; cancel: any }) => void; + /** A handler for the rowUpdated event. */ + onRowUpdated?: (e: { data: Object; key: any }) => void; + /** A handler for the rowUpdating event. */ + onRowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: any }) => void; + /** Enables a hint that appears when a user hovers the mouse pointer over a cell with truncated content. */ + cellHintEnabled?: boolean; + /** Specifies whether or not grid columns can be reordered by a user. */ + allowColumnReordering?: boolean; + /** Specifies whether or not grid columns can be resized by a user. */ + allowColumnResizing?: boolean; + /** A handler for the cellClick event. */ + onCellClick?: any; + /** A handler for the cellHoverChanged event. */ + onCellHoverChanged?: (e: Object) => void; + /** A handler for the cellPrepared event. */ + onCellPrepared?: (e: Object) => void; + /** Specifies whether or not the width of grid columns depends on column content. */ + columnAutoWidth?: boolean; + /** Specifies the options of a column chooser. */ + columnChooser?: { + /** Specifies text displayed by the column chooser panel when it does not contain any columns. */ + emptyPanelText?: string; + /** Specifies whether a user can invoke the column chooser or not. */ + enabled?: boolean; + /** Specifies the height of the column chooser panel. */ + height?: number; + /** Specifies text displayed in the title of the column chooser panel. */ + title?: string; + /** Specifies the width of the column chooser panel. */ + width?: number; + }; + /** Specifies options for column fixing. */ + columnFixing?: { + /** Indicates if column fixing is enabled. */ + enabled?: boolean; + /** Contains options that specify texts for column-fixing related commands in the column header's context menu. */ + texts?: { + /** Specifies text for a context menu item that fixes the column for which the context menu is invoked. */ + fix?: string; + /** Specifies text for a context menu item that unfixes the column for which the context menu is invoked. */ + unfix?: string; + /** Specifies text for a context menu subitem that fixes a column, for which the context menu is invoked, to the left grid edge. */ + leftPosition?: string; + /** Specifies text for a context menu subitem that fixes a column, for which the context menu is invoked, to the right grid edge. */ + rightPosition?: string; + }; + }; + /** Specifies options for filtering using a column header filter. */ + headerFilter?: { + /** Indicates whether or not the column header filter button is visible. */ + visible?: boolean; + /** Specifies the height of the dropdown menu invoked when using a column header filter. */ + height?: number; + /** Specifies the width of the dropdown menu invoked when using a column header filter. */ + width?: number; + /** Contains options that specify texts for the dropdown menu invoked when you use a column header filter. */ + texts?: { + /** Specifies text for the item specifying an empty value in the column header filter's dropdown menu. */ + emptyValue?: string; + /** Specifies text for a button that closes the column header filter's dropdown menu and applies specified filtering. */ + ok?: string; + /** Specifies text for a button that closes the column header filter's dropdown menu without applying performed selection. */ + cancel?: string; + } + }; + /** An array of grid columns. */ + columns?: Array; + onContentReady?: Function; + /** Specifies a function that customizes grid columns after they are created. */ + customizeColumns?: (columns: Array) => void; + /** Specifies a data source for the grid. */ + dataSource?: any; + /** Specifies whether or not to enable data caching. */ + cacheEnabled?: boolean; + /** A handler for the editingStart event. */ + onEditingStart?: (e: { + data: Object; + key: any; + cancel: boolean; + column: dxDataGridColumn + }) => void; + /** A handler for the editorPrepared event. */ + onEditorPrepared?: (e: Object) => void; + /** A handler for the editorPreparing event. */ + onEditorPreparing?: (e: Object) => void; + /** Contains options that specify how grid content can be changed. */ + editing?: { + editMode?: string; + editEnabled?: boolean; + insertEnabled?: boolean; + removeEnabled?: boolean; + /** Specifies how grid values can be edited manually. */ + mode?: string; + /** Specifies whether or not grid records can be edited at runtime. */ + allowUpdating?: boolean; + /** Specifies whether or not new grid records can be added at runtime. */ + allowAdding?: boolean; + /** Specifies whether or not grid records can be deleted at runtime. */ + allowDeleting?: boolean; + /** The form configuration object. Used only when the editing mode is "form". */ + form?: DevExpress.ui.dxFormOptions; + /** Contains options that specify texts for editing-related grid controls. */ + texts?: { + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Save" button. Setting this option makes sense only when the editMode option is set to batch. */ + saveAllChanges?: string; + /** Specifies text for a cancel button displayed when a row is in the editing state. Setting this option makes sense only when the allowUpdating option is set to true. */ + cancelRowChanges?: string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Revert" button. Setting this option makes sense only when the editMode option is set to batch. */ + cancelAllChanges?: string; + /** Specifies a message to be displayed by a confirmation window. Setting this option makes sense only when the edit mode is "row". */ + confirmDeleteMessage?: string; + /** Specifies text to be displayed in the title of a confirmation window. Setting this option makes sense only when the edit mode is "row". */ + confirmDeleteTitle?: string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Cancel changes" button. Setting this option makes sense only when the editMode option is set to cell and the validation capabilities are enabled. */ + validationCancelChanges?: string; + /** Specifies text for a button that deletes a row from a grid. Setting this option makes sense only when the allowDeleting option is set to true. */ + deleteRow?: string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the "Add" button. Setting this option makes sense only when the allowAdding option is true. */ + addRow?: string; + /** Specifies text for a button that turns a row into the editing state. Setting this option makes sense only when the allowUpdating option is set to true. */ + editRow?: string; + /** Specifies text for a save button displayed when a row is in the editing state. Setting this option makes sense only when the allowUpdating option is set to true. */ + saveRowChanges?: string; + /** Specifies text for a button that recovers a deleted row. Setting this option makes sense only if the grid uses the batch edit mode and the allowDeleting option is set to true. */ + undeleteRow?: string; + }; + }; + /** Specifies filter row options. */ + filterRow?: { + /** Specifies when to apply a filter. */ + applyFilter?: string; + /** Specifies text for the hint that pops up when a user hovers the mouse pointer over the "Apply Filter" button. */ + applyFilterText?: string; + /** Specifies descriptions for filter operations. */ + operationDescriptions?: { + "=": string; + "<>": string; + "<": string; + "<=": string; + ">": string; + ">=": string; + "startswith": string; + "contains": string; + "notcontains": string; + "endswith": string; + }; + /** Specifies text for the reset operation in a filter list. */ + resetOperationText?: string; + /** Specifies text for the operation of clearing the applied filter when a select box is used. */ + showAllText?: string; + /** Specifies text for the range start in the 'between' filter type. */ + betweenStartText?: string; + /** Specifies text for the range end in the 'between' filter type. */ + betweenEndText?: string; + /** Specifies whether or not an icon that allows the user to choose a filter operation is visible. */ + showOperationChooser?: boolean; + /** Specifies whether the filter row is visible or not. */ + visible?: boolean; + }; + /** Specifies the behavior of grouped grid records. */ + grouping?: { + /** Specifies whether the user can collapse grouped records in a grid or not. */ + allowCollapsing?: boolean; + /** Specifies whether groups appear expanded or not. */ + autoExpandAll?: boolean; + /** Specifies the message displayed in a group row when the corresponding group is continued from the previous page. */ + groupContinuedMessage?: string; + /** Specifies the message displayed in a group row when the corresponding group continues on the next page. */ + groupContinuesMessage?: string; + }; + /** Specifies options that configure the group panel. */ + groupPanel?: { + /** Specifies whether columns can be dragged onto or from the group panel. */ + allowColumnDragging?: boolean; + /** Specifies text displayed by the group panel when it does not contain any columns. */ + emptyPanelText?: string; + /** Specifies whether the group panel is visible or not. */ + visible?: boolean; + }; + /** Specifies options configuring the load panel. */ + loadPanel?: { + /** Specifies whether to show the load panel or not. */ + enabled?: boolean; + /** Specifies the height of the load panel in pixels. */ + height?: number; + /** Specifies a URL pointing to an image to be used as a loading indicator. */ + indicatorSrc?: string; + /** Specifies whether or not a loading indicator must be displayed on the load panel. */ + showIndicator?: boolean; + /** Specifies whether or not the pane of the load panel must be displayed. */ + showPane?: boolean; + /** Specifies text displayed by the load panel. */ + text?: string; + /** Specifies the width of the load panel in pixels. */ + width?: number; + }; + /** Specifies text displayed when a grid does not contain any records. */ + noDataText?: string; + /** Specifies the options of a grid pager. */ + pager?: { + /** Specifies the page sizes that can be selected at runtime. */ + allowedPageSizes?: any; + /** Specifies whether to show the page size selector or not. */ + showPageSizeSelector?: boolean; + /** Specifies whether to show the pager or not. */ + visible?: any; + /** Specifies the text accompanying the page navigator. */ + infoText?: string; + /** Specifies whether or not to display the text accompanying the page navigator. This text is specified by the infoText option. */ + showInfo?: boolean; + /** Specifies whether or not to display buttons that switch the grid to the previous or next page. */ + showNavigationButtons?: boolean; + }; + /** Specifies paging options. */ + paging?: { + /** Specifies whether dxDataGrid loads data page by page or all at once. */ + enabled?: boolean; + /** Specifies the grid page that should be displayed by default. */ + pageIndex?: number; + /** Specifies the size of grid pages. */ + pageSize?: number; + }; + /** Specifies whether or not grid rows must be shaded in a different way. */ + rowAlternationEnabled?: boolean; + /** Specifies whether to enable two-way data binding. */ + twoWayBindingEnabled?: boolean; + /** A handler for the rowClick event. */ + onRowClick?: any; + /** A handler for the rowPrepared event. */ + onRowPrepared?: (e: Object) => void; + /** Specifies a custom template for grid rows. */ + rowTemplate?: any; + /** A configuration object specifying scrolling options. */ + scrolling?: { + /** Specifies the scrolling mode. */ + mode?: string; + /** Specifies whether or not a grid must preload pages adjacent to the current page when using virtual scrolling. */ + preloadEnabled?: boolean; + /** Specifies whether or not the widget uses native scrolling. */ + useNative?: any; + /** Specifies the scrollbar display policy. */ + showScrollbar?: string; + /** Specifies whether or not the scrolling by content is enabled. */ + scrollByContent?: boolean; + /** Specifies whether or not the scrollbar thumb scrolling enabled. */ + scrollByThumb?: boolean; + }; + /** Specifies options of the search panel. */ + searchPanel?: { + /** Specifies whether or not search strings in the located grid records should be highlighted. */ + highlightSearchText?: boolean; + /** Specifies text displayed by the search panel when no search string was typed. */ + placeholder?: string; + /** Specifies whether the search panel is visible or not. */ + visible?: boolean; + /** Specifies the width of the search panel in pixels. */ + width?: number; + /** Sets a search string for the search panel. */ + text?: string; + }; + /** Specifies the operations that must be performed on the server side. */ + remoteOperations?: any; + /** Allows you to sort groups according to the values of group summary items. */ + sortByGroupSummaryInfo?: Array<{ + /** Specifies the group summary item whose values must be used to sort groups. */ + summaryItem?: string; + /** Specifies the identifier of the column that must be used in grouping so that sorting by group summary item values be applied. */ + groupColumn?: string; + /** Specifies the sort order of group summary item values. */ + sortOrder?: string; + }>; + /** Allows you to build a master-detail interface in the grid. */ + masterDetail?: { + /** Enables an end-user to expand/collapse detail sections. */ + enabled?: boolean; + /** Specifies whether detail sections appear expanded or collapsed. */ + autoExpandAll?: boolean; + /** Specifies the template for detail sections. */ + template?: any; + }; + /** Specifies options for exporting grid data. */ + export?: { + /** Indicates if the export feature is enabled in the grid. */ + enabled?: boolean; + /** Specifies a default name for the file to which grid data is exported. */ + fileName?: string; + /** Specifies whether to enable Excel filtering for the exported data in the resulting XLSX file. */ + excelFilterEnabled?: boolean; + /** Specifies whether to enable word wrapping for the exported data in the resulting XLSX file. */ + excelWrapTextEnabled?: boolean; + /** Specifies the URL of the server-side proxy that streams the resulting file to the end user to enable export in IE8, IE9 and Safari browsers. */ + proxyUrl?: string; + /** Indicates whether to allow end users to export not only the data displayed in the grid, but the selected rows only. */ + allowExportSelectedData?: boolean; + /** Contains options that specify texts for the export-related commands and hints. */ + texts?: { + /** Specifies text for the Export button when this button invokes a dropdown menu so you can choose the required export format. */ + exportTo?: string; + /** Specifies text for the Export button's hint when this button exports to the XSLX format without invoking the drop-down menu. */ + exportToExcel?: string; + /** Specifies text for the item in the Export dropdown menu that exports grid data to Excel. */ + excelFormat?: string; + /** Specifies text for the option in the Export dropdown menu that allows you to choose whether to export all the grid data or the selected rows only. */ + selectedRows?: string; + } + }; + /** Specifies the keys of the records that must appear selected initially. */ + selectedRowKeys?: Array; + /** Specifies options of runtime selection. */ + selection?: { + /** Specifies the checkbox row display policy in the multiple mode. */ + showCheckBoxesMode?: string; + /** Specifies whether the user can select all grid records at once. */ + allowSelectAll?: boolean; + /** Specifies the selection mode. */ + mode?: string; + }; + /** A handler for the dataErrorOccured event. */ + onDataErrorOccurred?: (e: { error: Error }) => void; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: (e: { + currentSelectedRowKeys: Array; + currentDeselectedRowKeys: Array; + selectedRowKeys: Array; + selectedRowsData: Array; + }) => void; + /** A handler for the exporting event. */ + onExporting?: (e: { + fileName: string; + cancel: boolean; + }) => void; + /** A handler for the fileSaving event. */ + onFileSaving?: (e: { + fileName: string; + format: string; + data: any; + cancel: boolean; + }) => void; + /** A handler for the exported event. */ + onExported?: (e: Object) => void; + /** A handler for the keyDown event. */ + onKeyDown?: (e: Object) => void; + /** A handler for the rowExpanding event. */ + onRowExpanding?: (e: Object) => void; + /** A handler for the rowExpanded event. */ + onRowExpanded?: (e: Object) => void; + /** A handler for the rowCollapsing event. */ + onRowCollapsing?: (e: Object) => void; + /** A handler for the rowCollapsed event. */ + onRowCollapsed?: (e: Object) => void; + /** Specifies whether column headers are visible or not. */ + showColumnHeaders?: boolean; + /** Specifies whether or not vertical lines separating one grid column from another are visible. */ + showColumnLines?: boolean; + /** Specifies whether or not horizontal lines separating one grid row from another are visible. */ + showRowLines?: boolean; + /** Specifies options of runtime sorting. */ + sorting?: { + /** Specifies text for the context menu item that sets an ascending sort order in a column. */ + ascendingText?: string; + /** Specifies text for the context menu item that resets sorting settings for a column. */ + clearText?: string; + /** Specifies text for the context menu item that sets a descending sort order in a column. */ + descendingText?: string; + /** Specifies the runtime sorting mode. */ + mode?: string; + }; + /** Specifies options of state storing. */ + stateStoring?: { + /** Specifies a callback function that performs specific actions on state loading. */ + customLoad?: () => JQueryPromise; + /** Specifies a callback function that performs specific actions on state saving. */ + customSave?: (state: Object) => void; + /** Specifies whether or not a grid saves its state. */ + enabled?: boolean; + /** Specifies the delay between the last change of a grid state and the operation of saving this state in milliseconds. */ + savingTimeout?: number; + /** Specifies a unique key to be used for storing the grid state. */ + storageKey?: string; + /** Specifies the type of storage to be used for state storing. */ + type?: string; + }; + /** Specifies the options of the grid summary. */ + summary?: { + /** Contains options that specify text patterns for summary items. */ + texts?: { + /** Specifies a pattern for the 'sum' summary items when they are displayed in the parent column. */ + sum?: string; + /** Specifies a pattern for the 'sum' summary items displayed in a group row or in any other column rather than the parent one. */ + sumOtherColumn?: string; + /** Specifies a pattern for the 'min' summary items when they are displayed in the parent column. */ + min?: string; + /** Specifies a pattern for the 'min' summary items displayed in a group row or in any other column rather than the parent one. */ + minOtherColumn?: string; + /** Specifies a pattern for the 'max' summary items when they are displayed in the parent column. */ + max?: string; + /** Specifies a pattern for the 'max' summary items displayed in a group row or in any other column rather than the parent one. */ + maxOtherColumn?: string; + /** Specifies a pattern for the 'avg' summary items when they are displayed in the parent column. */ + avg?: string; + /** Specifies a pattern for the 'avg' summary items displayed in a group row or in any other column rather than the parent one. */ + avgOtherColumn?: string; + /** Specifies a pattern for the 'count' summary items. */ + count?: string; + }; + /** Specifies items of the group summary. */ + groupItems?: Array<{ + /** Specifies the identifier of a summary item. */ + name?: string; + /** Specifies the column that provides data for a group summary item. */ + column?: string; + /** Customizes the text to be displayed in the summary item. */ + customizeText?: (itemInfo: { + value: any; + valueText: string; + }) => string; + /** Specifies a pattern for the summary item text. */ + displayFormat?: string; + /** Specifies a precision for the summary item value of a numeric format. */ + precision?: number; + /** Specifies whether or not a summary item must be displayed in the group footer. */ + showInGroupFooter?: boolean; + /** Indicates whether to display group summary items in parentheses after the group row header or to align them by the corresponding columns within the group row. */ + alignByColumn?: boolean; + /** Specifies the column that must hold the summary item when this item is displayed in the group footer or aligned by a column in the group row. */ + showInColumn?: string; + /** Specifies how to aggregate data for a summary item. */ + summaryType?: string; + /** Specifies a format for the summary item value. */ + valueFormat?: string; + /** Specifies whether or not to skip empty strings, null and undefined values when calculating a summary. */ + skipEmptyValues?: boolean; + }>; + /** Specifies items of the total summary. */ + totalItems?: Array<{ + /** Specifies the identifier of a summary item. */ + name?: string; + /** Specifies the alignment of a summary item. */ + alignment?: string; + /** Specifies the column that provides data for a summary item. */ + column?: string; + /** Specifies a CSS class to be applied to a summary item. */ + cssClass?: string; + /** Customizes the text to be displayed in the summary item. */ + customizeText?: (itemInfo: { + value: any; + valueText: string; + }) => string; + /** Specifies a pattern for the summary item text. */ + displayFormat?: string; + /** Specifies a precision for the summary item value of a numeric format. */ + precision?: number; + /** Specifies the column that must hold the summary item. */ + showInColumn?: string; + /** Specifies how to aggregate data for a summary item. */ + summaryType?: string; + /** Specifies a format for the summary item value. */ + valueFormat?: string; + /** Specifies whether or not to skip empty strings, null and undefined values when calculating a summary. */ + skipEmptyValues?: boolean; + }>; + /** Specifies whether or not to skip empty strings, null and undefined values when calculating a summary. */ + skipEmptyValues?: boolean; + /** Allows you to use a custom aggregate function to calculate the value of a summary item. */ + calculateCustomSummary?: (options: { + component: dxDataGrid; + name?: string; + value: any; + totalValue: any; + summaryProcess: string + }) => void; + }; + /** Specifies whether text that does not fit into a column should be wrapped. */ + wordWrapEnabled?: boolean; + } + /** A data grid widget. */ + export class dxDataGrid extends Widget { + constructor(element: JQuery, options?: dxDataGridOptions); + constructor(element: Element, options?: dxDataGridOptions); + /** Ungroups grid records. */ + clearGrouping(): void; + /** Clears sorting settings of all grid columns at once. */ + clearSorting(): void; + /** Allows you to obtain a cell by its row index and the data field of its column. */ + getCellElement(rowIndex: number, dataField: string): any; + /** Allows you to obtain a cell by its row index and the visible index of its column. */ + getCellElement(rowIndex: number, visibleColumnIndex: number): any; + /** Returns the current state of the grid. */ + state(): Object; + /** Sets the grid state. */ + state(state: Object): void; + /** Allows you to obtain the row index by a data key. */ + getRowIndexByKey(key: any): number; + /** Allows you to obtain the data key by a row index. */ + getKeyByRowIndex(rowIndex: number): any; + /** Adds a new column to a grid. */ + addColumn(columnOptions: dxDataGridColumn): void; + /** Removes the column from the grid. */ + deleteColumn(id: any): void; + /** Displays the load panel. */ + beginCustomLoading(messageText: string): void; + /** Discards changes made in a grid. */ + cancelEditData(): void; + /** Checks whether or not the grid contains unsaved changes. */ + hasEditData(): boolean; + /** Clears all the filters of a specific type applied to grid records. */ + clearFilter(): void; + /** Deselects all grid records. */ + clearSelection(): void; + /** Draws the cell being edited from the editing state. Use this method when the edit mode is batch. */ + closeEditCell(): void; + /** Collapses groups or master rows in a grid. */ + collapseAll(groupIndex?: number): void; + /** Returns the number of data columns in a grid. */ + columnCount(): number; + /** Returns the value of a specific column option. */ + columnOption(id: any, optionName: string): any; + /** Sets an option of a specific column. */ + columnOption(id: any, optionName: string, optionValue: any): void; + /** Returns the options of a column by an identifier. */ + columnOption(id: any): Object; + /** Sets several options of a column at once. */ + columnOption(id: any, options: Object): void; + /** Sets a specific cell into the editing state. */ + editCell(rowIndex: number, visibleColumnIndex: number): void; + /** Sets a specific cell into the editing state. */ + editCell(rowIndex: number, dataField: string): void; + /** Sets a specific row into the editing state. */ + editRow(rowIndex: number): void; + /** Gets the cell value. */ + cellValue(rowIndex: number, dataField: string): any; + /** Gets the cell value. */ + cellValue(rowIndex: number, visibleColumnIndex: number): any; + /** Sets the cell value. */ + cellValue(rowIndex: number, dataField: string, value: any): void; + /** Sets the cell value. */ + cellValue(rowIndex: number, visibleColumnIndex: number, value: any): void; + /** Hides the load panel. */ + endCustomLoading(): void; + /** Expands groups or master rows in a grid. */ + expandAll(groupIndex: number): void; + /** Allows you to find out whether a specific group or master row is expanded or collapsed. */ + isRowExpanded(key: any): boolean; + /** Allows you to expand a specific group or master row by its key. */ + expandRow(key: any): void; + /** Allows you to collapse a specific group or master row by its key. */ + collapseRow(key: any): void; + /** Applies a filter to the grid's data source. */ + filter(filterExpr?: any): void; + /** Returns a filter expression applied to the grid's data source using the filter(filterExpr) method. */ + filter(): any; + /** Returns a filter expression applied to the grid using all possible scenarious. */ + getCombinedFilter(): any; + /** Gets the keys of currently selected grid records. */ + getSelectedRowKeys(): Array; + /** Gets the data objects of currently selected grid records. */ + getSelectedRowsData(): Array; + /** Hides the column chooser panel. */ + hideColumnChooser(): void; + /** Adds a new data row to a grid. */ + addRow(): void; + /** + * Adds a new data row to a grid. + * @deprecated Use the addRow() method instead. + */ + insertRow(): void; + /** Returns the key corresponding to the passed data object. */ + keyOf(obj: Object): any; + /** Switches a grid to a specified page. */ + pageIndex(newIndex: number): void; + /** Gets the index of the current page. */ + pageIndex(): number; + /** Sets the page size. */ + pageSize(value: number): void; + /** Gets the current page size. */ + pageSize(): number; + /** Refreshes grid data. */ + refresh(): void; + /** Removes a specific row from a grid. */ + deleteRow(rowIndex: number): void; + /** + * Removes a specific row from a grid. + * @deprecated Use the deleteRow() method instead. + */ + removeRow(rowIndex: number): void; + /** Saves changes made in a grid. */ + saveEditData(): void; + /** Searches grid records by a search string. */ + searchByText(text: string): void; + /** Selects all grid records. */ + selectAll(): void; + /** Deselects the rows that are currently selected within the applied filter. */ + deselectAll(): void; + /** Selects specific grid records. */ + selectRows(keys: Array, preserve: boolean): void; + /** Deselects specific grid records. */ + deselectRows(keys: Array): void; + /** Selects grid rows by indexes. */ + selectRowsByIndexes(indexes: Array): void; + /** Allows you to find out whether a row is selected or not. */ + isRowSelected(key: any): boolean; + /** Invokes the column chooser panel. */ + showColumnChooser(): void; + startSelectionWithCheckboxes(): boolean; + /** Returns the number of records currently held by a grid. */ + totalCount(): number; + /** Recovers a row deleted in the batch edit mode. */ + undeleteRow(rowIndex: number): void; + /** Allows you to obtain a data object by its key. */ + byKey(key: any): JQueryPromise; + /** Gets the value of a total summary item. */ + getTotalSummaryValue(summaryItemName: string): any; + /** Exports grid data to Excel. */ + exportToExcel(selectionOnly: boolean): void; + /** Updates the grid to the size of its content. */ + updateDimensions(): void; + /** Focuses the specified cell element in the grid. */ + focus(element?: JQuery): void; + } + export interface dxPivotGridOptions extends WidgetOptions { + onContentReady?: Function; + /** Specifies a data source for the pivot grid. */ + dataSource?: any; + useNativeScrolling?: any; + /** A configuration object specifying scrolling options. */ + scrolling?: { + /** Specifies the scrolling mode. */ + mode?: string; + /** Specifies whether or not the widget uses native scrolling. */ + useNative?: any; + }; + /** Allows an end-user to change sorting options. */ + allowSorting?: boolean; + /** Allows an end-user to sort columns by summary values. */ + allowSortingBySummary?: boolean; + /** Allows an end-user to change filtering options. */ + allowFiltering?: boolean; + /** Allows an end-user to expand/collapse all header items within a header level. */ + allowExpandAll?: boolean; + /** Specifies whether to display the Total rows. */ + showRowTotals?: boolean; + /** Specifies whether to display the Grand Total row. */ + showRowGrandTotals?: boolean; + /** Specifies whether to display the Total columns. */ + showColumnTotals?: boolean; + /** Specifies whether to display the Grand Total column. */ + showColumnGrandTotals?: boolean; + /** Specifies whether or not to hide rows and columns with no data. */ + hideEmptySummaryCells?: boolean; + /** Specifies where to show the total rows or columns. */ + showTotalsPrior?: string; + /** Specifies whether the outer borders of the grid are visible or not. */ + showBorders?: boolean; + /** The Field Chooser configuration options. */ + fieldChooser?: { + /** Enables or disables the field chooser. */ + enabled?: boolean; + /** Specifies the field chooser layout. */ + layout?: number; + /** Specifies the text to display as a title of the field chooser popup window. */ + title?: string; + /** Specifies the field chooser width. */ + width?: number; + /** Specifies the field chooser height. */ + height?: number; + /** Strings that can be changed or localized in the pivot grid's integrated Field Chooser. */ + texts?: { + /** The string to display instead of Row Fields. */ + rowFields?: string; + /** The string to display instead of Column Fields. */ + columnFields?: string; + /** The string to display instead of Data Fields. */ + dataFields?: string; + /** The string to display instead of Filter Fields. */ + filterFields?: string; + /** The string to display instead of All Fields. */ + allFields?: string; + }; + } + /** Strings that can be changed or localized in the dxPivotGrid widget. */ + texts?: { + /** The string to display as a header of the Grand Total row and column. */ + grandTotal?: string; + /** The string to display as a header of the Total row and column. */ + total?: string; + /** Specifies the text displayed when a pivot grid does not contain any fields. */ + noData?: string; + /** The string to display as a Show Field Chooser context menu item. */ + showFieldChooser?: string; + /** The string to display as an Expand All context menu item. */ + expandAll?: string; + /** The string to display as a Collapse All context menu item. */ + collapseAll?: string; + /** The string to display as a Sort Column by Summary Value context menu item. */ + sortColumnBySummary?: string; + /** The string to display as a Sort Row by Summary Value context menu item. */ + sortRowBySummary?: string; + /** The string to display as a Remove All Sorting context menu item. */ + removeAllSorting?: string; + /** The string to display as an Export to Excel file context menu item. */ + exportToExcel?: string; + }; + /** Specifies options configuring the load panel. */ + loadPanel?: { + /** Enables or disables the load panel. */ + enabled?: boolean; + /** Specifies the height of the load panel. */ + height?: number; + /** Specifies the URL pointing to an image that will be used as a load indicator. */ + indicatorSrc?: string; + /** Specifies whether or not to show a load indicator. */ + showIndicator?: boolean; + /** Specifies whether or not to show load panel background. */ + showPane?: boolean; + /** Specifies the text to display inside a load panel. */ + text?: string; + /** Specifies the width of the load panel. */ + width?: number; + }; + /** A handler for the cellClick event. */ + onCellClick?: (e: any) => void; + /** A handler for the cellPrepared event. */ + onCellPrepared?: (e: any) => void; + /** A handler for the contextMenuPreparing event. */ + onContextMenuPreparing?: (e: Object) => void; + /** Specifies options for exporting pivot grid data. */ + export?: { + /** Indicates whether the export feature is enabled for the pivot grid. */ + enabled?: boolean; + /** Specifies a default name for the file to which grid data is exported. */ + fileName?: string; + /** Specifies the URL of the server-side proxy that streams the resulting file to the end user to enable export in IE8, IE9 and Safari browsers. */ + proxyUrl?: string; + }; + /** A handler for the exporting event. */ + onExporting?: (e: { + fileName: string; + cancel: boolean; + }) => void; + /** A handler for the fileSaving event. */ + onFileSaving?: (e: { + fileName: string; + format: string; + data: any; + cancel: boolean; + }) => void; + /** A handler for the exported event. */ + onExported?: (e: Object) => void; + /** A configuration object specifying options related to state storing. */ + stateStoring?: { + /** Specifies a callback function that performs specific actions on state loading. */ + customLoad?: () => JQueryPromise; + /** Specifies a callback function that performs specific actions on state saving. */ + customSave?: (gridState: Object) => void; + /** Specifies whether or not a grid saves its state. */ + enabled?: boolean; + /** Specifies the delay between the last change of a grid state and the operation of saving this state in milliseconds. */ + savingTimeout?: number; + /** Specifies a unique key to be used for storing the grid state. */ + storageKey?: string; + /** Specifies the type of storage to be used for state storing. */ + type?: string; + }; + } + /** A data summarization widget for multi-dimensional data analysis and data mining. */ + export class dxPivotGrid extends Widget { + constructor(element: JQuery, options?: dxPivotGridOptions); + constructor(element: Element, options?: dxPivotGridOptions); + /** Gets the PivotGridDataSource instance. */ + getDataSource(): DevExpress.data.PivotGridDataSource; + /** Gets the dxPopup instance of the field chooser window. */ + getFieldChooserPopup(): DevExpress.ui.dxPopup; + /** Updates the widget to the size of its content. */ + updateDimensions(): void; + /** Exports pivot grid data to the Excel file. */ + exportToExcel(): void; + } + export interface dxPivotGridFieldChooserOptions extends WidgetOptions { + /** Specifies the height of the widget. */ + height?: any; + /** Specifies the field chooser layout. */ + layout?: number; + /** The data source of a dxPivotGrid widget. */ + dataSource?: DevExpress.data.PivotGridDataSource; + onContentReady?: Function; + /** Strings that can be changed or localized in the dxPivotGridFieldChooser widget. */ + texts?: { + /** The string to display instead of Row Fields. */ + rowFields?: string; + /** The string to display instead of Column Fields. */ + columnFields?: string; + /** The string to display instead of Data Fields. */ + dataFields?: string; + /** The string to display instead of Filter Fields. */ + filterFields?: string; + /** The string to display instead of All Fields. */ + allFields?: string; + }; + } + /** A complementary widget for dxPivotGrid that allows you to manage data displayed in the dxPivotGrid. */ + export class dxPivotGridFieldChooser extends Widget { + constructor(element: JQuery, options?: dxPivotGridFieldChooserOptions); + constructor(element: Element, options?: dxPivotGridFieldChooserOptions); + /** Updates the widget to the size of its content. */ + updateDimensions(): void; + } +} +interface JQuery { + dxTreeView(): JQuery; + dxTreeView(options: "instance"): DevExpress.ui.dxTreeView; + dxTreeView(options: string): any; + dxTreeView(options: string, ...params: any[]): any; + dxTreeView(options: DevExpress.ui.dxTreeViewOptions): JQuery; + dxMenuBase(): JQuery; + dxMenuBase(options: "instance"): DevExpress.ui.dxMenuBase; + dxMenuBase(options: string): any; + dxMenuBase(options: string, ...params: any[]): any; + dxMenuBase(options: DevExpress.ui.dxMenuBaseOptions): JQuery; + dxMenu(): JQuery; + dxMenu(options: "instance"): DevExpress.ui.dxMenu; + dxMenu(options: string): any; + dxMenu(options: string, ...params: any[]): any; + dxMenu(options: DevExpress.ui.dxMenuOptions): JQuery; + dxContextMenu(): JQuery; + dxContextMenu(options: "instance"): DevExpress.ui.dxContextMenu; + dxContextMenu(options: string): any; + dxContextMenu(options: string, ...params: any[]): any; + dxContextMenu(options: DevExpress.ui.dxContextMenuOptions): JQuery; + dxColorBox(): JQuery; + dxColorBox(options: "instance"): DevExpress.ui.dxColorBox; + dxColorBox(options: string): any; + dxColorBox(options: string, ...params: any[]): any; + dxColorBox(options: DevExpress.ui.dxColorBoxOptions): JQuery; + dxDataGrid(): JQuery; + dxDataGrid(options: "instance"): DevExpress.ui.dxDataGrid; + dxDataGrid(options: string): any; + dxDataGrid(options: string, ...params: any[]): any; + dxDataGrid(options: DevExpress.ui.dxDataGridOptions): JQuery; + dxPivotGrid(): JQuery; + dxPivotGrid(options: "instance"): DevExpress.ui.dxPivotGrid; + dxPivotGrid(options: string): any; + dxPivotGrid(options: string, ...params: any[]): any; + dxPivotGrid(options: DevExpress.ui.dxPivotGridOptions): JQuery; + dxPivotGridFieldChooser(): JQuery; + dxPivotGridFieldChooser(options: "instance"): DevExpress.ui.dxPivotGridFieldChooser; + dxPivotGridFieldChooser(options: string): any; + dxPivotGridFieldChooser(options: string, ...params: any[]): any; + dxPivotGridFieldChooser(options: DevExpress.ui.dxPivotGridFieldChooserOptions): JQuery; + dxScheduler(): JQuery; + dxScheduler(options: "instance"): DevExpress.ui.dxScheduler; + dxScheduler(options: string): any; + dxScheduler(options: string, ...params: any[]): any; + dxScheduler(options: DevExpress.ui.dxSchedulerOptions): JQuery; +} +declare module DevExpress.framework { + /** An object used to store information on the views displayed in an application. */ + export class ViewCache { + viewRemoved: JQueryCallback; + /** Removes all the viewInfo objects from the cache. */ + clear(): void; + /** Obtains a viewInfo object from the cache by the specified key. */ + getView(key: string): Object; + /** Checks whether or not a viewInfo object is contained in the view cache under the specified key. */ + hasView(key: string): boolean; + /** Removes a viewInfo object from the cache by the specified key. */ + removeView(key: string): Object; + /** Adds the specified viewInfo object to the cache under the specified key. */ + setView(key: string, viewInfo: Object): void; + } + export interface dxCommandOptions extends DOMComponentOptions { + /** Specifies an action performed when the execute() method of the command is called. */ + onExecute?: any; + /** Indicates whether or not the widget that displays this command is disabled. */ + disabled?: boolean; + /** Specifies whether the current command is rendered when a view is being rendered or after a view is shown. */ + renderStage?: string; + /** Specifies the name of the icon shown inside the widget associated with this command. */ + icon?: string; + iconSrc?: string; + /** The identifier of the command. */ + id?: string; + /** Specifies the title of the widget associated with this command. */ + title?: string; + /** Specifies the type of the button, if the command is rendered as a dxButton widget. */ + type?: string; + /** A Boolean value specifying whether or not the widget associated with this command is visible. */ + visible?: boolean; + } + /** A markup component used to define markup options for a command. */ + export class dxCommand extends DOMComponent { + constructor(element: JQuery, options: dxCommandOptions); + constructor(options: dxCommandOptions); + /** Executes the action associated with this command. */ + execute(): void; + } + /** An object responsible for routing. */ + export class Router { + /** Adds a routing rule to the list of registered rules. */ + register(pattern: string, defaults?: Object, constraints?: Object): void; + /** Decodes the specified URI to an object using the registered routing rules. */ + parse(uri: string): Object; + /** Formats an object to a URI. */ + format(obj: Object): string; + } + export interface StateManagerOptions { + /** A storage to which the state manager saves the application state. */ + storage?: Object; + } + /** An object used to store the current application state. */ + export class StateManager { + constructor(options?: StateManagerOptions); + /** Adds an object that implements an interface of a state source to the state manager's collection of state sources. */ + addStateSource(stateSource: Object): void; + /** Removes a specified state source from the state manager's collection of state sources. */ + removeStateSource(stateSource: Object): void; + /** Saves the current application state. */ + saveState(): void; + /** Restores the application state that has been saved by the saveState() method to the state storage. */ + restoreState(): void; + /** Removes the application state that has been saved by the saveState() method to the state storage. */ + clearState(): void; + } + export module html { + export var layoutSets: Array; + export var animationSets: { [animationSetName: string]: AnimationSet }; + export interface AnimationSet { + [animationName: string]: any + } + export interface HtmlApplicationOptions { + /** Specifies where the commands that are defined in the application's views must be displayed. */ + commandMapping?: Object; + /** Specifies whether or not view caching is disabled. */ + disableViewCache?: boolean; + /** An array of layout controllers that should be used to show application views in the current navigation context. */ + layoutSet?: any; + /** Specifies the animation presets that are used to animate different UI elements in the current application. */ + animationSet?: AnimationSet; + /** Specifies whether the current application must behave as a mobile or web application. */ + mode?: string; + /** Specifies the object that represents a root namespace of the application. */ + namespace?: Object; + /** Specifies application behavior when the user navigates to a root view. */ + navigateToRootViewMode?: string; + /** An array of dxCommand configuration objects used to define commands available from the application's global navigation. */ + navigation?: Array; + /** A state manager to be used in the application. */ + stateManager?: StateManager; + /** Specifies the storage to be used by the application's state manager to store the application state. */ + stateStorage?: Object; + /** Indicates whether on not to use the title of the previously displayed view as text on the Back button. */ + useViewTitleAsBackText?: boolean; + /** A custom view cache to be used in the application. */ + viewCache?: Object; + /** Specifies a limit for the views that can be cached. */ + viewCacheSize?: number; + /** Specifies the current version of application templates. */ + templatesVersion?: string; + /** Specifies options for the viewport meta tag of a mobile browser. */ + viewPort?: JQuery; + /** A custom router to be used in the application. */ + router?: Router; + } + /** An object used to manage views, as well as control the application life cycle. */ + export class HtmlApplication implements EventsMixin { + constructor(options: HtmlApplicationOptions); + afterViewSetup: JQueryCallback; + beforeViewSetup: JQueryCallback; + initialized: JQueryCallback; + navigating: JQueryCallback; + navigatingBack: JQueryCallback; + resolveLayoutController: JQueryCallback; + resolveViewCacheKey: JQueryCallback; + viewDisposed: JQueryCallback; + viewDisposing: JQueryCallback; + viewHidden: JQueryCallback; + viewRendered: JQueryCallback; + viewShowing: JQueryCallback; + viewShown: JQueryCallback; + /** Provides access to the ViewCache object. */ + viewCache: ViewCache; + /** An array of dxCommand components that are created based on the application's navigation option value. */ + navigation: Array; + /** Provides access to the StateManager object. */ + stateManager: StateManager; + /** Provides access to the Router object. */ + router: Router; + /** Navigates to the URI preceding the current one in the navigation history. */ + back(): void; + /** Returns a Boolean value indicating whether or not backwards navigation is currently possible. */ + canBack(): boolean; + /** Calls the clearState() method of the application's StateManager object. */ + clearState(): void; + /** Creates global navigation commands. */ + createNavigation(navigationConfig: Array): void; + /** Returns an HTML template of the specified view. */ + getViewTemplate(viewName: string): JQuery; + /** Returns a configuration object used to create a dxView component for a specified view. */ + getViewTemplateInfo(viewName: string): Object; + /** Adds a specified HTML template to a collection of view or layout templates. */ + loadTemplates(source: any): JQueryPromise; + /** Navigates to the specified URI. */ + navigate(uri?: any, options?: Object): void; + /** Renders navigation commands to the navigation command containers that are located in the layouts used in the application. */ + renderNavigation(): void; + /** Calls the restoreState() method of the application's StateManager object. */ + restoreState(): void; + /** Calls the saveState method of the application's StateManager object. */ + saveState(): void; + /** Provides access to the object that defines the current context to be considered when choosing an appropriate template for a view. */ + templateContext(): Object; + on(eventName: "initialized", eventHandler: () => void): HtmlApplication; + on(eventName: "afterViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "beforeViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "navigating", eventHandler: (e: { + currentUri: string; + uri: string; + cancel: boolean; + options: { + root: boolean; + target: string; + direction: string; + rootInDetailPane: boolean; + modal: boolean; + }; + }) => void): HtmlApplication; + on(eventName: "navigatingBack", eventHandler: (e: { + cancel: boolean; + isHardwareButton: boolean; + }) => void): HtmlApplication; + on(eventName: "resolveLayoutController", eventHandler: (e: { + viewInfo: Object; + layoutController: Object; + availableLayoutControllers: Array; + }) => void): HtmlApplication; + on(eventName: "resolveViewCacheKey", eventHandler: (e: { + key: string; + navigationItem: Object; + routeData: Object; + }) => void): HtmlApplication; + on(eventName: "viewDisposed", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewDisposing", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewHidden", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewRendered", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + on(eventName: "viewShowing", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + on(eventName: "viewShown", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + on(eventName: string, eventHandler: Function): HtmlApplication; + on(events: { [eventName: string]: Function; }): HtmlApplication; + off(eventName: "initialized"): HtmlApplication; + off(eventName: "afterViewSetup"): HtmlApplication; + off(eventName: "beforeViewSetup"): HtmlApplication; + off(eventName: "navigating"): HtmlApplication; + off(eventName: "navigatingBack"): HtmlApplication; + off(eventName: "resolveLayoutController"): HtmlApplication; + off(eventName: "resolveViewCacheKey"): HtmlApplication; + off(eventName: "viewDisposed"): HtmlApplication; + off(eventName: "viewDisposing"): HtmlApplication; + off(eventName: "viewHidden"): HtmlApplication; + off(eventName: "viewRendered"): HtmlApplication; + off(eventName: "viewShowing"): HtmlApplication; + off(eventName: "viewShown"): HtmlApplication; + off(eventName: string): HtmlApplication; + off(eventName: "initialized", eventHandler: () => void): HtmlApplication; + off(eventName: "afterViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "beforeViewSetup", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "navigating", eventHandler: (e: { + currentUri: string; + uri: string; + cancel: boolean; + options: { + root: boolean; + target: string; + direction: string; + rootInDetailPane: boolean; + modal: boolean; + }; + }) => void): HtmlApplication; + off(eventName: "navigatingBack", eventHandler: (e: { + cancel: boolean; + isHardwareButton: boolean; + }) => void): HtmlApplication; + off(eventName: "resolveLayoutController", eventHandler: (e: { + viewInfo: Object; + layoutController: Object; + availableLayoutControllers: Array; + }) => void): HtmlApplication; + off(eventName: "resolveViewCacheKey", eventHandler: (e: { + key: string; + navigationItem: Object; + routeData: Object; + }) => void): HtmlApplication; + off(eventName: "viewDisposed", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewDisposing", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewHidden", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewRendered", eventHandler: (e: { + viewInfo: Object; + }) => void): HtmlApplication; + off(eventName: "viewShowing", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + off(eventName: "viewShown", eventHandler: (e: { + viewInfo: Object; + direction: string; + }) => void): HtmlApplication; + off(eventName: string, eventHandler: Function): HtmlApplication; + } + } +} +declare module DevExpress.viz.core { + /** + * Applies a theme for the entire page with several DevExtreme visualization widgets. + * @deprecated Use the DevExpress.viz.currentTheme(theme) method instead. + */ + export function currentTheme(theme: string): void; + /** + * Applies a new theme (with the color scheme defined separately) for the entire page with several DevExtreme visualization widgets. + * @deprecated Use the DevExpress.viz.currentTheme(platform, colorScheme) method instead. + */ + export function currentTheme(platform: string, colorScheme: string): void; + /** + * Registers a new theme based on the existing one. + * @deprecated Use the DevExpress.viz.registerTheme(customTheme, baseTheme) method instead. + */ + export function registerTheme(customTheme: Object, baseTheme: string): void; + /** + * Applies a predefined or registered custom palette to all visualization widgets at once. + * @deprecated Use the DevExpress.viz.currentPalette(paletteName) method instead. + */ + export function currentPalette(paletteName: string): void; + /** + * Obtains the color sets of a predefined or registered palette. + * @deprecated Use the DevExpress.viz.getPalette(paletteName) method instead. + */ + export function getPalette(paletteName: string): Object; + /** + * Registers a new palette. + * @deprecated Use the DevExpress.viz.registerPalette(paletteName, palette) method instead. + */ + export function registerPalette(paletteName: string, palette: Object): void; + export interface Border { + /** Sets a border color for a selected series. */ + color?: string; + /** Sets border visibility for a selected series. */ + visible?: boolean; + /** Sets a border width for a selected series. */ + width?: number; + } + export interface DashedBorder extends Border { + /** Specifies a dash style for the border of a selected series point. */ + dashStyle?: string; + } + export interface DashedBorderWithOpacity extends DashedBorder { + /** Specifies the opacity of the tooltip's border. */ + opacity?: number; + } + export interface Font { + /** Specifies the font color for a strip label. */ + color?: string; + /** Specifies the font family for a strip label. */ + family?: string; + /** Specifies the font opacity for a strip label. */ + opacity?: number; + /** Specifies the font size for a strip label. */ + size?: any; + /** Specifies the font weight for the text displayed in strips. */ + weight?: number; + } + export interface Hatching { + direction?: string; + /** Specifies the opacity of hatching lines. */ + opacity?: number; + /** Specifies the distance between hatching lines in pixels. */ + step?: number; + /** Specifies the width of hatching lines in pixels. */ + width?: number; + } + export interface Margins { + /** Specifies the distance in pixels between the bottom side of the title and the surrounding widget elements. */ + bottom?: number; + /** Specifies the distance in pixels between the left side of the title and the surrounding widget elements. */ + left?: number; + /** Specifies the distance between the right side of the title and surrounding widget elements in pixels. */ + right?: number; + /** Specifies the distance between the top side of the title and surrounding widget elements in pixels. */ + top?: number; + } + export interface Size { + /** Specifies the width of the widget. */ + width?: number; + /** Specifies the height of the widget. */ + height?: number; + } + export interface Title { + /** Specifies font options for the title. */ + font?: viz.core.Font; + /** Specifies the widget title's horizontal position. */ + horizontalAlignment?: string; + /** Specifies the widget title's position in the vertical direction. */ + verticalAlignment?: string; + /** Specifies the distance between the title and surrounding widget elements in pixels. */ + margin?: viz.core.Margins; + /** Specifies the height of the space reserved for the title. */ + placeholderSize?: number; + /** Specifies text for the title. */ + text?: string; + /** Specifies a subtitle for the widget. */ + subtitle?: { + /** Specifies font options for the subtitle. */ + font?: viz.core.Font; + /** Specifies text for the subtitle. */ + text?: string; + } + } + export interface Tooltip { + /** Specifies the length of the tooltip's arrow in pixels. */ + arrowLength?: number; + /** Specifies the appearance of the tooltip's border. */ + border?: viz.core.DashedBorderWithOpacity; + /** Specifies a color for the tooltip. */ + color?: string; + /** Specifies the z-index for tooltips. */ + zIndex?: number; + /** Specifies the container to draw tooltips inside of it. */ + container?: any; + /** Specifies text and appearance of a set of tooltips. */ + customizeTooltip?: (arg: Object) => { color?: string; text?: string }; + /** Specifies whether or not the tooltip is enabled. */ + enabled?: boolean; + /** Specifies font options for the text displayed by the tooltip. */ + font?: Font; + /** Specifies a format for the text displayed by the tooltip. */ + format?: string; + /** Specifies the opacity of a tooltip. */ + opacity?: number; + /** Specifies a distance from the tooltip's left/right boundaries to the inner text in pixels. */ + paddingLeftRight?: number; + /** Specifies a distance from the tooltip's top/bottom boundaries to the inner text in pixels. */ + paddingTopBottom?: number; + /** Specifies a precision for formatted values displayed by the tooltip. */ + precision?: number; + /** Specifies options of the tooltip's shadow. */ + shadow?: { + /** Specifies the blur distance of the tooltip's shadow. */ + blur?: number; + /** Specifies the color of the tooltip's shadow. */ + color?: string; + /** Specifies the horizontal offset of the tooltip's shadow relative to the tooltip in pixels. */ + offsetX?: number; + /** Specifies the vertical offset of the tooltip's shadow relative to the tooltip in pixels. */ + offsetY?: number; + /** Specifies the opacity of the tooltip's shadow. */ + opacity?: number; + }; + } + export interface Animation { + /** Determines how long animation runs. */ + duration?: number; + /** Specifies the animation easing mode. */ + easing?: string; + /** Indicates whether or not animation is enabled. */ + enabled?: boolean; + } + export interface LoadingIndicator { + /** Specifies a color for the loading indicator background. */ + backgroundColor?: string; + /** Specifies font options for the loading indicator text. */ + font?: viz.core.Font; + /** Specifies whether to show the loading indicator or not. */ + show?: boolean; + /** Specifies a text to be displayed by the loading indicator. */ + text?: string; + } + export interface LegendBorder extends viz.core.DashedBorderWithOpacity { + /** Specifies a radius for the corners of the legend border. */ + cornerRadius?: number; + } + export interface BaseLegend { + /** Specifies the color of the legend's background. */ + backgroundColor?: string; + /** Specifies legend border settings. */ + border?: viz.core.LegendBorder; + /** Specifies how many columns must be taken to arrange legend items. */ + columnCount?: number; + /** Specifies the spacing between a pair of neighboring legend columns in pixels. */ + columnItemSpacing?: number; + /** Specifies font options for legend items. */ + font?: viz.core.Font; + /** Specifies the legend's position on the map. */ + horizontalAlignment?: string; + /** Specifies the alignment of legend items. */ + itemsAlignment?: string; + /** Specifies the position of text relative to the item marker. */ + itemTextPosition?: string; + /** Specifies the distance between the legend and the container borders in pixels. */ + margin?: viz.core.Margins; + /** Specifies the size of item markers in the legend in pixels. */ + markerSize?: number; + /** Specifies whether to arrange legend items horizontally or vertically. */ + orientation?: string; + /** Specifies the spacing between the legend left/right border and legend items in pixels. */ + paddingLeftRight?: number; + /** Specifies the spacing between the legend top/bottom border and legend items in pixels. */ + paddingTopBottom?: number; + /** Specifies how many rows must be taken to arrange legend items. */ + rowCount?: number; + /** Specifies the spacing between a pair of neighboring legend rows in pixels. */ + rowItemSpacing?: number; + /** Specifies the legend's position on the map. */ + verticalAlignment?: string; + /** Specifies whether or not the legend is visible on the map. */ + visible?: boolean; + } + export interface BaseWidgetOptions extends DOMComponentOptions { + /** A handler for the drawn event. */ + onDrawn?: (e: { + component: BaseWidget; + element: Element; + }) => void; + /** A handler for the incidentOccurred event. */ + onIncidentOccurred?: ( + component: BaseWidget, + element: Element, + target: { + id: string; + type: string; + args: any; + text: string; + widget: string; + version: string; + } + ) => void; + /** Notifies a widget that it is embedded into an HTML page that uses a path modifier. */ + pathModified?: boolean; + /** Specifies whether or not the widget supports right-to-left representation. */ + rtlEnabled?: boolean; + /** Sets the name of the theme to be used in the widget. */ + theme?: string; + } + /** This section describes options and methods that are common to all widgets. */ + export class BaseWidget extends DOMComponent { + /** Returns the widget's SVG markup. */ + svg(): string; + } +} +declare module DevExpress.viz.charts { + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface BaseSeries { + /** Provides information about the state of the series object. */ + fullState: number; + /** Returns the type of the series. */ + type: string; + /** Unselects all the selected points of the series. The points are displayed in an initial style. */ + clearSelection(): void; + /** Gets the color of a particular series. */ + getColor(): string; + /** Gets points from the series point collection based on the specified argument. */ + getPointsByArg(pointArg: any): Array; + /** Gets a point from the series point collection based on the specified point position. */ + getPointByPos(positionIndex: number): Object; + /** Selects the series. The series is displayed in a 'selected' style until another series is selected or the current series is deselected programmatically. */ + select(): void; + /** Selects the specified point. The point is displayed in a 'selected' style. */ + selectPoint(point: BasePoint): void; + /** Deselects the specified point. The point is displayed in an initial style. */ + deselectPoint(point: BasePoint): void; + /** Returns an array of all points in the series. */ + getAllPoints(): Array; + /** Returns visible series points. */ + getVisiblePoints(): Array; + /** Returns the name of the series. */ + name: string; + /** Returns the tag of the series. */ + tag: string; + /** Hides a series. */ + hide(): void; + /** Provides information about the hover state of a series. */ + isHovered(): boolean; + /** Provides information about the selection state of a series. */ + isSelected(): boolean; + /** Provides information about the visibility state of a series. */ + isVisible(): boolean; + /** Makes a particular series visible. */ + show(): void; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface BasePoint { + /** Provides information about the state of the point object. */ + fullState: number; + /** Returns the point's argument value that was set in the data source. */ + originalArgument: any; + /** Returns the point's value that was set in the data source. */ + originalValue: any; + /** Returns the tag of the point. */ + tag: string; + /** Deselects the point. */ + clearSelection(): void; + /** Gets the color of a particular point. */ + getColor(): string; + /** Hides the tooltip of the point. */ + hideTooltip(): void; + /** Provides information about the hover state of a point. */ + isHovered(): boolean; + /** Provides information about the selection state of a point. */ + isSelected(): boolean; + /** Selects the point. The point is displayed in a 'selected' style until another point is selected or the current point is deselected programmatically. */ + select(): void; + /** Shows the tooltip of the point. */ + showTooltip(): void; + /** Allows you to obtain the label of a series point. */ + getLabel(): any; + /** Returns the series object to which the point belongs. */ + series: BaseSeries; + } + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface ChartSeries extends BaseSeries { + /** Returns the name of the series pane. */ + pane: string; + /** Returns the name of the value axis of the series. */ + axis: string; + selectPoint(point: ChartPoint): void; + deselectPoint(point: ChartPoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface ChartPoint extends BasePoint { + /** Contains the close value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalCloseValue: any; + /** Contains the high value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalHighValue: any; + /** Contains the low value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalLowValue: any; + /** Contains the first value of the point. This field is useful for points belonging to a series of the range area or range bar type only. */ + originalMinValue: any; + /** Contains the open value of the point. This field is useful for points belonging to a series of the candle stick or stock type only. */ + originalOpenValue: any; + /** Contains the size of the bubble as it was set in the data source. This field is useful for points belonging to a series of the bubble type only. */ + size: any; + /** Gets the parameters of the point's minimum bounding rectangle (MBR). */ + getBoundingRect(): { x: number; y: number; width: number; height: number; }; + series: ChartSeries; + } + /** This section describes the methods that can be used in code to manipulate the Label object. */ + export interface Label { + /** Gets the parameters of the label's minimum bounding rectangle (MBR). */ + getBoundingRect(): { x: number; y: number; width: number; height: number; }; + /** Hides the point label. */ + hide(): void; + /** Shows the point label. */ + show(): void; + } + export interface PieSeries extends BaseSeries { + selectPoint(point: PiePoint): void; + deselectPoint(point: PiePoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface PiePoint extends BasePoint { + /** Gets the percentage value of the specific point. */ + percent: any; + /** Provides information about the visibility state of a point. */ + isVisible(): boolean; + /** Makes a specific point visible. */ + show(): void; + /** Hides a specific point. */ + hide(): void; + series: PieSeries; + } + /** This section describes the fields and methods that can be used in code to manipulate the Series object. */ + export interface PolarSeries extends BaseSeries { + /** Returns the name of the value axis of the series. */ + axis: string; + selectPoint(point: PolarPoint): void; + deselectPoint(point: PolarPoint): void; + getAllPoints(): Array; + getVisiblePoints(): Array; + } + /** This section describes the methods that can be used in code to manipulate the Point object. */ + export interface PolarPoint extends BasePoint { + series: PolarSeries; + } + export interface Strip { + /** Specifies a color for a strip. */ + color?: string; + /** An object that defines the label configuration options of a strip. */ + label?: { + /** Specifies the text displayed in a strip. */ + text?: string; + }; + /** Specifies a start value for a strip. */ + startValue?: any; + /** Specifies an end value for a strip. */ + endValue?: any; + } + export interface BaseSeriesConfigLabel { + /** Specifies a format for arguments displayed by point labels. */ + argumentFormat?: string; + /** Specifies a precision for formatted point arguments displayed in point labels. */ + argumentPrecision?: number; + /** Specifies a background color for point labels. */ + backgroundColor?: string; + /** Specifies border options for point labels. */ + border?: viz.core.DashedBorder; + /** Specifies connector options for series point labels. */ + connector?: { + /** Specifies the color of label connectors. */ + color?: string; + /** Indicates whether or not label connectors are visible. */ + visible?: boolean; + /** Specifies the width of label connectors. */ + width?: number; + }; + /** Specifies a callback function that returns the text to be displayed by point labels. */ + customizeText?: (pointInfo: Object) => string; + /** Specifies font options for the text displayed in point labels. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed by point labels. */ + format?: string; + position?: string; + /** Specifies a precision for formatted point values displayed in point labels. */ + precision?: number; + /** Specifies the angle used to rotate point labels from their initial position. */ + rotationAngle?: number; + /** Specifies the visibility of point labels. */ + visible?: boolean; + } + export interface SeriesConfigLabel extends BaseSeriesConfigLabel { + /** Specifies whether or not to show a label when the point has a zero value. */ + showForZeroValues?: boolean; + } + export interface ChartSeriesConfigLabel extends SeriesConfigLabel { + /** Specifies how to align point labels relative to the corresponding data points that they represent. */ + alignment?: string; + /** Specifies how to shift point labels horizontally from their initial positions. */ + horizontalOffset?: number; + /** Specifies how to shift point labels vertically from their initial positions. */ + verticalOffset?: number; + /** Specifies a precision for the percentage values displayed in the labels of a full-stacked-like series. */ + percentPrecision?: number; + } + export interface BaseCommonSeriesConfig { + /** Specifies the data source field that provides arguments for series points. */ + argumentField?: string; + axis?: string; + /** An object defining the label configuration options for a series in the dxChart widget. */ + label?: ChartSeriesConfigLabel; + /** Specifies border options for point labels. */ + border?: viz.core.DashedBorder; + /** Specifies a series color. */ + color?: string; + /** Specifies the dash style of the series' line. */ + dashStyle?: string; + hoverMode?: string; + hoverStyle?: { + /** An object defining the border options for a hovered series. */ + border?: viz.core.DashedBorder; + /**

Sets a color for a series when it is hovered over.

*/ + color?: string; + /** Specifies the dash style for the line in a hovered series. */ + dashStyle?: string; + hatching?: viz.core.Hatching; + /** Specifies the width of a line in a hovered series. */ + width?: number; + }; + /** Specifies whether a chart ignores null data points or not. */ + ignoreEmptyPoints?: boolean; + /** Specifies how many points are acceptable to be in a series to display all labels for these points. Otherwise, the labels will not be displayed. */ + maxLabelCount?: number; + /** Specifies the minimal length of a displayed bar in pixels. */ + minBarSize?: number; + /** Specifies opacity for a series. */ + opacity?: number; + /** Specifies the series elements to highlight when the series is selected. */ + selectionMode?: string; + selectionStyle?: { + /** An object defining the border options for a selected series. */ + border?: viz.core.DashedBorder; + /** Sets a color for a series when it is selected. */ + color?: string; + /** Specifies the dash style for the line in a selected series. */ + dashStyle?: string; + hatching?: viz.core.Hatching; + /** Specifies the width of a line in a selected series. */ + width?: number; + }; + /** Specifies whether or not to show the series in the chart's legend. */ + showInLegend?: boolean; + /** Specifies the name of the stack where the values of the _stackedBar_ series must be located. */ + stack?: string; + /** Specifies the name of the data source field that provides data about a point. */ + tagField?: string; + /** Specifies the data source field that provides values for series points. */ + valueField?: string; + /** Specifies the visibility of a series. */ + visible?: boolean; + /** Specifies a line width. */ + width?: number; + /** Configures error bars. */ + valueErrorBar?: { + /** Specifies whether error bars must be displayed in full or partially. */ + displayMode?: string; + /** Specifies the data field that provides data for low error values. */ + lowValueField?: string; + /** Specifies the data field that provides data for high error values. */ + highValueField?: string; + /** Specifies how error bar values must be calculated. */ + type?: string; + /** Specifies the value to be used for generating error bars. */ + value?: number; + /** Specifies the color of error bars. */ + color?: string; + /** Specifies the opacity of error bars. */ + opacity?: number; + /** Specifies the length of the lines that indicate the error bar edges. */ + edgeLength?: number; + /** Specifies the width of the error bar line. */ + lineWidth?: number; + }; + } + export interface CommonPointOptions { + /** Specifies border options for points in the line and area series. */ + border?: viz.core.Border; + /** Specifies the points color. */ + color?: string; + /** Specifies what series points to highlight when a point is hovered over. */ + hoverMode?: string; + /** An object defining configuration options for a hovered point. */ + hoverStyle?: { + /** An object defining the border options for a hovered point. */ + border?: viz.core.Border; + /** Sets a color for a point when it is hovered over. */ + color?: string; + /** Specifies the diameter of a hovered point in the series that represents data points as symbols (not as bars for instance). */ + size?: number; + }; + /** Specifies what series points to highlight when a point is selected. */ + selectionMode?: string; + /** An object defining configuration options for a selected point. */ + selectionStyle?: { + /** An object defining the border options for a selected point. */ + border?: viz.core.Border; + /**

Sets a color for a point when it is selected.

*/ + color?: string; + /** Specifies the diameter of a selected point in the series that represents data points as symbols (not as bars for instance). */ + size?: number; + }; + /** Specifies the point diameter in pixels for those series that represent data points as symbols (not as bars for instance). */ + size?: number; + /** Specifies a symbol for presenting points of the line and area series. */ + symbol?: string; + visible?: boolean; + } + export interface ChartCommonPointOptions extends CommonPointOptions { + /** An object specifying the parameters of an image that is used as a point marker. */ + image?: { + /** Specifies the height of an image that is used as a point marker. */ + height?: any; + /** Specifies a URL leading to the image to be used as a point marker. */ + url?: any; + /** Specifies the width of an image that is used as a point marker. */ + width?: any; + }; + } + export interface PolarCommonPointOptions extends CommonPointOptions { + /** An object specifying the parameters of an image that is used as a point marker. */ + image?: { + /** Specifies the height of an image that is used as a point marker. */ + height?: number; + /** Specifies a URL leading to the image to be used as a point marker. */ + url?: string; + /** Specifies the width of an image that is used as a point marker. */ + width?: number; + }; + } + /** An object that defines configuration options for chart series. */ + export interface CommonSeriesConfig extends BaseCommonSeriesConfig { + /** Specifies the data source field that provides a 'close' value for a _candleStick_ or _stock_ series. */ + closeValueField?: string; + /** Specifies a radius for bar corners. */ + cornerRadius?: number; + /** Specifies the data source field that provides a 'high' value for a _candleStick_ or _stock_ series. */ + highValueField?: string; + /** Specifies the color for the body (rectangle) of a _candleStick_ series. */ + innerColor?: string; + /** Specifies the data source field that provides a 'low' value for a _candleStick_ or _stock_ series. */ + lowValueField?: string; + /** Specifies the data source field that provides an 'open' value for a _candleStick_ or _stock_ series. */ + openValueField?: string; + /** Specifies the pane that will be used to display a series. */ + pane?: string; + /** An object defining configuration options for points in line-, scatter- and area-like series. */ + point?: ChartCommonPointOptions; + /** Specifies the data source field that provides values for one end of a range series. To set the data source field for the other end of the range series, use the rangeValue2Field property. */ + rangeValue1Field?: string; + /** Specifies the data source field that provides values for the second end of a range series. To set the data source field for the other end of the range series, use the rangeValue1Field property. */ + rangeValue2Field?: string; + /** Specifies reduction options for the stock or candleStick series. */ + reduction?: { + /** Specifies a color for the points whose reduction level price is lower in comparison to the value in the previous point. */ + color?: string; + /** Specifies for which price level (open, high, low or close) to enable reduction options in the series. */ + level?: string; + }; + /** Specifies the data source field that defines the size of bubbles. */ + sizeField?: string; + } + export interface CommonSeriesSettings extends CommonSeriesConfig { + /**

An object that specifies configuration options for all series of the area type in the chart.

*/ + area?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _bar_ type in the chart. */ + bar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the bubble type in the chart. */ + bubble?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _candleStick_ type in the chart. */ + candlestick?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedArea_ type in the chart. */ + fullstackedarea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Full-Stacked Spline Area type in the chart. */ + fullstackedsplinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedBar_ type in the chart. */ + fullstackedbar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _fullStackedLine_ type in the chart. */ + fullstackedline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Full-Stacked Spline type in the chart. */ + fullstackedspline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _line_ type in the chart. */ + line?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _rangeArea_ type in the chart. */ + rangearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _rangeBar_ type in the chart. */ + rangebar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _scatter_ type in the chart. */ + scatter?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _spline_ type in the chart. */ + spline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _splineArea_ type in the chart. */ + splinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedArea_ type in the chart. */ + stackedarea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Stacked Spline Area type in the chart. */ + stackedsplinearea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedBar_ type in the chart. */ + stackedbar?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedLine_ type in the chart. */ + stackedline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the Stacked Spline type in the chart. */ + stackedspline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stepArea_ type in the chart. */ + steparea?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stepLine_ type in the chart. */ + stepline?: CommonSeriesConfig; + /** An object that specifies configuration options for all series of the _stock_ type in the chart. */ + stock?: CommonSeriesConfig; + /** Sets a series type. */ + type?: string; + } + export interface SeriesConfig extends CommonSeriesConfig { + /** Specifies the name that identifies the series. */ + name?: string; + /** Specifies data about a series. */ + tag?: any; + /** Sets the series type. */ + type?: string; + } + /** An object that defines configuration options for polar chart series. */ + export interface CommonPolarSeriesConfig extends BaseCommonSeriesConfig { + /** Specifies whether or not to close the chart by joining the end point with the first point. */ + closed?: boolean; + label?: SeriesConfigLabel; + point?: PolarCommonPointOptions; + } + export interface CommonPolarSeriesSettings extends CommonPolarSeriesConfig { + /** An object that specifies configuration options for all series of the area type in the chart. */ + area?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _bar_ type in the chart. */ + bar?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _line_ type in the chart. */ + line?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _scatter_ type in the chart. */ + scatter?: CommonPolarSeriesConfig; + /** An object that specifies configuration options for all series of the _stackedBar_ type in the chart. */ + stackedbar?: CommonPolarSeriesConfig; + /** Sets a series type. */ + type?: string; + } + export interface PolarSeriesConfig extends CommonPolarSeriesConfig { + /** Specifies the name that identifies the series. */ + name?: string; + /** Specifies data about a series. */ + tag?: any; + /** Sets the series type. */ + type?: string; + } + export interface PieSeriesConfigLabel extends BaseSeriesConfigLabel { + /** Specifies how to shift labels from their initial position in a radial direction in pixels. */ + radialOffset?: number; + /** Specifies a precision for the percentage values displayed in labels. */ + percentPrecision?: number; + } + /** An object that defines configuration options for chart series. */ + export interface CommonPieSeriesConfig { + /** Specifies the data source field that provides arguments for series points. */ + argumentField?: string; + /** Specifies the required type for series arguments. */ + argumentType?: string; + /** An object defining the series border configuration options. */ + border?: viz.core.DashedBorder; + /** Specifies a series color. */ + color?: string; + /** Specifies the chart elements to highlight when a series is hovered over. */ + hoverMode?: string; + /** An object defining configuration options for a hovered series. */ + hoverStyle?: { + /** An object defining the border options for a hovered series. */ + border?: viz.core.DashedBorder; + /** Sets a color for the series when it is hovered over. */ + color?: string; + /** Specifies the hatching options to be applied when a point is hovered over. */ + hatching?: viz.core.Hatching; + }; + /** + * Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. + * @deprecated use the 'innerRadius' option instead + */ + innerRadius?: number; + /** An object defining the label configuration options. */ + label?: PieSeriesConfigLabel; + /** Specifies how many points are acceptable to be in a series to display all labels for these points. Otherwise, the labels will not be displayed. */ + maxLabelCount?: number; + /** Specifies a minimal size of a displayed pie segment. */ + minSegmentSize?: number; + /** + * Specifies the direction in which the dxPieChart series points are located. + * @deprecated use the 'segmentsDirection' option instead + */ + segmentsDirection?: string; + /**

Specifies the chart elements to highlight when the series is selected.

*/ + selectionMode?: string; + /** An object defining configuration options for the series when it is selected. */ + selectionStyle?: { + /** An object defining the border options for a selected series. */ + border?: viz.core.DashedBorder; + /** Sets a color for a series when it is selected. */ + color?: string; + /** Specifies the hatching options to be applied when a point is selected. */ + hatching?: viz.core.Hatching; + }; + /** Specifies chart segment grouping options. */ + smallValuesGrouping?: { + /** Specifies the name of the grouped chart segment. This name represents the segment in the chart legend. */ + groupName?: string; + /** Specifies the segment grouping mode. */ + mode?: string; + /** Specifies a threshold for segment values. */ + threshold?: number; + /** Specifies how many segments must not be grouped. */ + topCount?: number; + }; + /** + * Specifies a start angle for a pie chart in arc degrees. + * @deprecated use the 'startAngle' option instead + */ + startAngle?: number; + /**

Specifies the name of the data source field that provides data about a point.

*/ + tagField?: string; + /** Specifies the data source field that provides values for series points. */ + valueField?: string; + } + export interface CommonPieSeriesSettings extends CommonPieSeriesConfig { + /** + * Specifies the type of the pie chart series. + * @deprecated use the 'type' option instead + */ + type?: string; + } + export interface PieSeriesConfig extends CommonPieSeriesConfig { + /** + * Sets the series type. + * @deprecated use the 'type' option instead + */ + type?: string; + /** Specifies the name that identifies the series. */ + name?: string; + /** Specifies data about a series. */ + tag?: any; + } + export interface SeriesTemplate { + /** Specifies a callback function that returns a series object with individual series settings. */ + customizeSeries?: (seriesName: string) => SeriesConfig; + /** Specifies a data source field that represents the series name. */ + nameField?: string; + } + export interface PolarSeriesTemplate { + /** Specifies a callback function that returns a series object with individual series settings. */ + customizeSeries?: (seriesName: string) => PolarSeriesConfig; + /** Specifies a data source field that represents the series name. */ + nameField?: string; + } + export interface ChartCommonConstantLineLabel { + /** Specifies font options for a constant line label. */ + font?: viz.core.Font; + /** Specifies the position of the constant line label relative to the chart plot. */ + position?: string; + /** Indicates whether or not to display labels for the axis constant lines. */ + visible?: boolean; + } + export interface PolarCommonConstantLineLabel { + /** Indicates whether or not to display labels for the axis constant lines. */ + visible?: boolean; + /** Specifies font options for a constant line label. */ + font?: viz.core.Font; + } + export interface ConstantLineStyle { + /** Specifies a color for a constant line. */ + color?: string; + /** Specifies a dash style for a constant line. */ + dashStyle?: string; + /** Specifies a constant line width in pixels. */ + width?: number; + } + export interface ChartCommonConstantLineStyle extends ConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartCommonConstantLineLabel; + /** Specifies the space between the constant line label and the left/right side of the constant line. */ + paddingLeftRight?: number; + /** Specifies the space between the constant line label and the top/bottom side of the constant line. */ + paddingTopBottom?: number; + } + export interface PolarCommonConstantLineStyle extends ConstantLineStyle { + /** An object defining constant line label options. */ + label?: PolarCommonConstantLineLabel; + } + export interface CommonAxisLabel { + /** Specifies font options for axis labels. */ + font?: viz.core.Font; + /** Specifies the spacing between an axis and its labels in pixels. */ + indentFromAxis?: number; + /** Indicates whether or not axis labels are visible. */ + visible?: boolean; + } + export interface ChartCommonAxisLabel extends CommonAxisLabel { + /** Specifies the label's position relative to the tick (grid line). */ + alignment?: string; + /** Specifies the overlap resolving algorithm to be applied to axis labels. */ + overlappingBehavior?: { + /** Specifies how to arrange axis labels. */ + mode?: string; + /** Specifies the angle used to rotate axis labels. */ + rotationAngle?: number; + /** Specifies the spacing that must be set between staggered rows when the 'stagger' algorithm is applied. */ + staggeringSpacing?: number; + }; + } + export interface PolarCommonAxisLabel extends CommonAxisLabel { + /** Specifies the overlap resolving algorithm to be applied to axis labels. */ + overlappingBehavior?: string; + } + export interface CommonAxisTitle { + /** Specifies font options for an axis title. */ + font?: viz.core.Font; + /** Specifies a margin for an axis title in pixels. */ + margin?: number; + } + export interface BaseCommonAxisSettings { + /** Specifies the color of the line that represents an axis. */ + color?: string; + /** Specifies whether ticks/grid lines of a discrete axis are located between labels or cross the labels. */ + discreteAxisDivisionMode?: string; + /** An object defining the configuration options for the grid lines of an axis in the dxPolarChart widget. */ + grid?: { + /** Specifies a color for grid lines. */ + color?: string; + /** Specifies an opacity for grid lines. */ + opacity?: number; + /** Indicates whether or not the grid lines of an axis are visible. */ + visible?: boolean; + /** Specifies the width of grid lines. */ + width?: number; + }; + /** Specifies the options of the minor grid. */ + minorGrid?: { + /** Specifies a color for the lines of the minor grid. */ + color?: string; + /** Specifies an opacity for the lines of the minor grid. */ + opacity?: number; + /** Indicates whether the minor grid is visible or not. */ + visible?: boolean; + /** Specifies a width for the lines of the minor grid. */ + width?: number; + }; + /** Indicates whether or not an axis is inverted. */ + inverted?: boolean; + /** Specifies the opacity of the line that represents an axis. */ + opacity?: number; + /** Indicates whether or not to set ticks/grid lines of a continuous axis of the 'date-time' type at the beginning of each date-time interval. */ + setTicksAtUnitBeginning?: boolean; + /** An object defining the configuration options for axis ticks. */ + tick?: { + /** Specifies ticks color. */ + color?: string; + /** Specifies tick opacity. */ + opacity?: number; + /** Indicates whether or not ticks are visible on an axis. */ + visible?: boolean; + /** Specifies tick width. */ + width?: number; + /** Specifies tick length. */ + length?: number; + }; + /** Specifies the options of the minor ticks. */ + minorTick?: { + /** Specifies a color for the minor ticks. */ + color?: string; + /** Specifies an opacity for the minor ticks. */ + opacity?: number; + /** Indicates whether or not the minor ticks are displayed on an axis. */ + visible?: boolean; + /** Specifies minor tick width. */ + width?: number; + /** Specifies minor tick length. */ + length?: number; + }; + /** Indicates whether or not the line that represents an axis in a chart is visible. */ + visible?: boolean; + /** Specifies the width of the line that represents an axis in the chart. */ + width?: number; + } + export interface ChartCommonAxisSettings extends BaseCommonAxisSettings { + /** Specifies the appearance of all the widget's constant lines. */ + constantLineStyle?: ChartCommonConstantLineStyle; + /** An object defining the label configuration options that are common for all axes in the dxChart widget. */ + label?: ChartCommonAxisLabel; + /** Specifies a coefficient that determines the spacing between the maximum series point and the axis. */ + maxValueMargin?: number; + /** Specifies a coefficient that determines the spacing between the minimum series point and the axis. */ + minValueMargin?: number; + /** Specifies, in pixels, the space reserved for an axis. */ + placeholderSize?: number; + /** An object defining configuration options for strip style. */ + stripStyle?: { + /** An object defining the configuration options for a strip label style. */ + label?: { + /** Specifies font options for a strip label. */ + font?: viz.core.Font; + /** Specifies the label's position on a strip. */ + horizontalAlignment?: string; + /** Specifies a label's position on a strip. */ + verticalAlignment?: string; + }; + /** Specifies the spacing, in pixels, between the left/right strip border and the strip label. */ + paddingLeftRight?: number; + /** Specifies the spacing, in pixels, between the top/bottom strip borders and the strip label. */ + paddingTopBottom?: number; + }; + /** An object defining the title configuration options that are common for all axes in the dxChart widget. */ + title?: CommonAxisTitle; + /** Indicates whether or not to display series with indents from axis boundaries. */ + valueMarginsEnabled?: boolean; + } + export interface PolarCommonAxisSettings extends BaseCommonAxisSettings { + /** Specifies the appearance of all the widget's constant lines. */ + constantLineStyle?: PolarCommonConstantLineStyle; + /** An object defining the label configuration options that are common for all axes in the dxPolarChart widget. */ + label?: PolarCommonAxisLabel; + /** An object defining configuration options for strip style. */ + stripStyle?: { + /** An object defining the configuration options for a strip label style. */ + label?: { + /** Specifies font options for a strip label. */ + font?: viz.core.Font; + }; + }; + } + export interface ChartConstantLineLabel extends ChartCommonConstantLineLabel { + /** Specifies the horizontal alignment of a constant line label. */ + horizontalAlignment?: string; + /** Specifies the vertical alignment of a constant line label. */ + verticalAlignment?: string; + /** Specifies the text to be displayed in a constant line label. */ + text?: string; + } + export interface PolarConstantLineLabel extends PolarCommonConstantLineLabel { + /** Specifies the text to be displayed in a constant line label. */ + text?: string; + } + export interface AxisLabel { + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a label on the value axis. */ + customizeHint?: (argument: { value: any; valueText: string }) => string; + /** Specifies a callback function that returns the text to be displayed in value axis labels. */ + customizeText?: (argument: { value: any; valueText: string }) => string; + /** Specifies a format for the text displayed by axis labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the axis labels. */ + precision?: number; + } + export interface ChartAxisLabel extends ChartCommonAxisLabel, AxisLabel { } + export interface PolarAxisLabel extends PolarCommonAxisLabel, AxisLabel { } + export interface AxisTitle extends CommonAxisTitle { + /** Specifies the text for the value axis title. */ + text?: string; + } + export interface ChartConstantLineStyle extends ChartCommonConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartConstantLineLabel; + } + export interface ChartConstantLine extends ChartConstantLineStyle { + /** An object defining constant line label options. */ + label?: ChartConstantLineLabel; + /** Specifies a value to be displayed by a constant line. */ + value?: any; + } + export interface PolarConstantLine extends PolarCommonConstantLineStyle { + /** An object defining constant line label options. */ + label?: PolarConstantLineLabel; + /** Specifies a value to be displayed by a constant line. */ + value?: any; + } + export interface Axis { + /** Specifies a coefficient for dividing the value axis. */ + axisDivisionFactor?: number; + /** Specifies the order in which discrete values are arranged on the value axis. */ + categories?: Array; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic axis. */ + logarithmBase?: number; + /** Specifies an interval between axis ticks/grid lines. */ + tickInterval?: any; + /** Specifies the interval between minor ticks. */ + minorTickInterval?: any; + /** Specifies the number of minor ticks between two neighboring major ticks. */ + minorTickCount?: number; + /** Specifies the required type of the value axis. */ + type?: string; + /** Specifies the pane on which the current value axis will be displayed. */ + pane?: string; + /** Specifies options for value axis strips. */ + strips?: Array; + } + export interface ChartAxis extends ChartCommonAxisSettings, Axis { + /** Defines an array of the value axis constant lines. */ + constantLines?: Array; + /** Specifies the appearance options for the constant lines of the value axis. */ + constantLineStyle?: ChartCommonConstantLineStyle; + /** Specifies options for value axis labels. */ + label?: ChartAxisLabel; + /** Specifies the maximum value on the value axis. */ + max?: any; + /** Specifies the minimum value on the value axis. */ + min?: any; + /** Specifies the position of the value axis on a chart. */ + position?: string; + /** Specifies the title for a value axis. */ + title?: AxisTitle; + } + export interface PolarAxis extends PolarCommonAxisSettings, Axis { + /** Defines an array of the value axis constant lines. */ + constantLines?: Array; + /** Specifies options for value axis labels. */ + label?: PolarAxisLabel; + } + export interface ArgumentAxis { + /** Specifies the desired type of axis values. */ + argumentType?: string; + /** Specifies the elements that will be highlighted when the argument axis is hovered over. */ + hoverMode?: string; + } + export interface ChartArgumentAxis extends ChartAxis, ArgumentAxis { } + export interface PolarArgumentAxis extends PolarAxis, ArgumentAxis { + /** Specifies the angle in arc degrees to which the argument axis should be rotated. The positive values rotate the axis clockwise. */ + startAngle?: number; + /** Specifies whether or not to display the first point at the angle specified by the startAngle option. */ + firstPointOnStartAngle?: boolean; + /** Specifies the value to be used as the origin for the argument axis. */ + originValue?: number; + /** Specifies the period of the argument values in the data source. */ + period?: number; + } + export interface ValueAxis { + /** Specifies the name of the value axis. */ + name?: string; + /** Specifies whether or not to indicate a zero value on the value axis. */ + showZero?: boolean; + /** Specifies the desired type of axis values. */ + valueType?: string; + } + export interface ChartValueAxis extends ChartAxis, ValueAxis { + /** Specifies the spacing, in pixels, between multiple value axes in a chart. */ + multipleAxesSpacing?: number; + /** Specifies the value by which the chart's value axes are synchronized. */ + synchronizedValue?: number; + } + export interface PolarValueAxis extends PolarAxis, ValueAxis { + /** Indicates whether to display series with indents from axis boundaries. */ + valueMarginsEnabled?: boolean; + /** Specifies a coefficient that determines the spacing between the maximum series point and the axis. */ + maxValueMargin?: number; + /** Specifies a coefficient that determines the spacing between the minimum series point and the axis. */ + minValueMargin?: number; + tick?: { + visible?: boolean; + } + } + export interface CommonPane { + /** Specifies a background color in a pane. */ + backgroundColor?: string; + /** Specifies the border options of a chart's pane. */ + border?: PaneBorder; + } + export interface Pane extends CommonPane { + /** Specifies the name of a pane. */ + name?: string; + } + export interface PaneBorder extends viz.core.DashedBorderWithOpacity { + /** Specifies the bottom border's visibility state in a pane. */ + bottom?: boolean; + /** Specifies the left border's visibility state in a pane. */ + left?: boolean; + /** Specifies the right border's visibility state in a pane. */ + right?: boolean; + /** Specifies the top border's visibility state in a pane. */ + top?: boolean; + } + export interface ChartAnimation extends viz.core.Animation { + /** Specifies the maximum series point count in the chart that the animation supports. */ + maxPointCountSupported?: number; + } + export interface BaseChartTooltip extends viz.core.Tooltip { + /** Specifies a format for arguments of the chart's series points. */ + argumentFormat?: string; + /** Specifies a precision for formatted arguments displayed in tooltips. */ + argumentPrecision?: number; + /** Specifies a precision for a percent value displayed in tooltips for stacked series and dxPieChart series. */ + percentPrecision?: number; + } + export interface BaseChartOptions extends viz.core.BaseWidgetOptions { + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + /** Specifies the width of the widget that is small enough for the layout to begin adapting. */ + width?: number; + /** Specifies the height of the widget that is small enough for the layout to begin adapting. */ + height?: number; + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Specifies animation options. */ + animation?: ChartAnimation; + /** Specifies a callback function that returns an object with options for a specific point label. */ + customizeLabel?: (labelInfo: Object) => Object; + /** Specifies a callback function that returns an object with options for a specific point. */ + customizePoint?: (pointInfo: Object) => Object; + /** Specifies a data source for the chart. */ + dataSource?: any; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies options of a dxChart's (dxPieChart's) legend. */ + legend?: core.BaseLegend; + /** Specifies the blank space between the chart's extreme elements and the boundaries of the area provided for the widget (see size) in pixels. */ + margin?: viz.core.Margins; + /** Sets the name of the palette to be used in the chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */ + palette?: any; + /** A handler for the done event. */ + onDone?: (e: { + component: BaseChart; + element: Element; + }) => void; + /** A handler for the pointClick event. */ + onPointClick?: any; + /** A handler for the pointHoverChanged event. */ + onPointHoverChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + /** A handler for the pointSelectionChanged event. */ + onPointSelectionChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + /** Specifies whether a single point or multiple points can be selected in the chart. */ + pointSelectionMode?: string; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies options for the dxChart and dxPieChart widget series. */ + series?: any; + /** Specifies the size of the widget in pixels. */ + size?: viz.core.Size; + /** Specifies a title for the chart. */ + title?: viz.core.Title; + /** Specifies tooltip options. */ + tooltip?: BaseChartTooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: BaseChart; + element: Element; + target: BasePoint; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: BaseChart; + element: Element; + target: BasePoint; + }) => void; + } + /** A base class for all chart widgets included in the ChartJS library. */ + export class BaseChart extends viz.core.BaseWidget { + /** Deselects the chart's selected series. The series is displayed in an initial style. */ + clearSelection(): void; + /** Gets the current size of the widget. */ + getSize(): { width: number; height: number }; + /** Returns an array of all series in the chart. */ + getAllSeries(): Array; + /** Gets a series within the chart's series collection by the specified name (see the name option). */ + getSeriesByName(seriesName: string): BaseSeries; + /** Gets a series within the chart's series collection by its position number. */ + getSeriesByPos(seriesIndex: number): BaseSeries; + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Hides all widget tooltips. */ + hideTooltip(): void; + /** Redraws a widget. */ + render(renderOptions?: { + force?: boolean; + animate?: boolean; + asyncSeriesRendering?: boolean; + }): void; + } + export interface AdvancedLegend extends core.BaseLegend { + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a legend item. */ + customizeHint?: (seriesInfo: { seriesName: string; seriesIndex: number; seriesColor: string; }) => string; + /**

Specifies a callback function that returns the text to be displayed by legend items.

*/ + customizeText?: (seriesInfo: { seriesName: string; seriesIndex: number; seriesColor: string; }) => string; + /** Specifies what series elements to highlight when a corresponding item in the legend is hovered over. */ + hoverMode?: string; + } + export interface AdvancedOptions extends BaseChartOptions { + /** A handler for the argumentAxisClick event. */ + onArgumentAxisClick?: any; + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** An object providing options for managing data from a data source. */ + dataPrepareSettings?: { + /** Specifies whether or not to validate the values from a data source. */ + checkTypeForAllData?: boolean; + /** Specifies whether or not to convert the values from a data source into the data type of an axis. */ + convertToAxisDataType?: boolean; + /** Specifies how to sort the series points. */ + sortingMethod?: any; + }; + /** A handler for the legendClick event. */ + onLegendClick?: any; + /** A handler for the seriesClick event. */ + onSeriesClick?: any; + /** A handler for the seriesHoverChanged event. */ + onSeriesHoverChanged?: (e: { + component: BaseChart; + element: Element; + target: TSeries; + }) => void; + /** A handler for the seriesSelectionChanged event. */ + onSeriesSelectionChanged?: (e: { + component: BaseChart; + element: Element; + target: TSeries; + }) => void; + /** Specifies whether a single series or multiple series can be selected in the chart. */ + seriesSelectionMode?: string; + /** Specifies how the chart must behave when series point labels overlap. */ + resolveLabelOverlapping?: string; + /** Specifies whether or not all bars in a series must have the same angle, or may have different angles if any points in other series are missing. */ + equalBarWidth?: boolean; + /** Specifies a common bar width as a percentage from 0 to 1. */ + barWidth?: number; + /** Forces the widget to treat negative values as zeroes. Applies to stacked-like series only. */ + negativesAsZeroes?: boolean; + } + export interface Legend extends AdvancedLegend { + /** Specifies whether the legend is located outside or inside the chart's plot. */ + position?: string; + } + export interface ChartTooltip extends BaseChartTooltip { + /** Specifies whether the tooltip must be located in the center of a bar or on its edge. Applies to the Bar and Bubble series. */ + location?: string; + /** Specifies the kind of information to display in a tooltip. */ + shared?: boolean; + } + export interface dxChartOptions extends AdvancedOptions { + adaptiveLayout?: { + keepLabels?: boolean; + }; + /** Indicates whether or not to synchronize value axes when they are displayed on a single pane. */ + synchronizeMultiAxes?: boolean; + /** Specifies whether or not to filter the series points depending on their quantity. */ + useAggregation?: boolean; + /** Indicates whether or not to adjust a value axis to the current minimum and maximum values of a zoomed chart. */ + adjustOnZoom?: boolean; + /** Specifies argument axis options for the dxChart widget. */ + argumentAxis?: ChartArgumentAxis; + /** An object defining the configuration options that are common for all axes of the dxChart widget. */ + commonAxisSettings?: ChartCommonAxisSettings; + /** An object defining the configuration options that are common for all panes in the dxChart widget. */ + commonPaneSettings?: CommonPane; + /** An object defining the configuration options that are common for all series of the dxChart widget. */ + commonSeriesSettings?: CommonSeriesSettings; + /** An object that specifies the appearance options of the chart crosshair. */ + crosshair?: { + /** Specifies a color for the crosshair lines. */ + color?: string; + /** Specifies a dash style for the crosshair lines. */ + dashStyle?: string; + /** Specifies whether to enable the crosshair or not. */ + enabled?: boolean; + /** Specifies the opacity of the crosshair lines. */ + opacity?: number; + /** Specifies the width of the crosshair lines. */ + width?: number; + /** Specifies the appearance of the horizontal crosshair line. */ + horizontalLine?: CrosshaierWithLabel; + /** Specifies the appearance of the vertical crosshair line. */ + verticalLine?: CrosshaierWithLabel; + /** Specifies the options of the crosshair labels. */ + label?: { + /** Specifies a color for the background of the crosshair labels. */ + backgroundColor?: string; + /** Specifies whether the crosshair labels are visible or not. */ + visible?: boolean; + /** Specifies font options for the text of the crosshair labels. */ + font?: viz.core.Font; + /** Specifies the format of the values displayed by crosshair labels. */ + format?: string; + /** Specifies a precision for formatted values. */ + precision?: number; + /** Customizes the text displayed by the crosshair labels. */ + customizeText?: (info: { value: any; valueText: string; point: ChartPoint; }) => string; + } + }; + /** Specifies a default pane for the chart series. */ + defaultPane?: string; + /** Specifies a coefficient determining the diameter of the largest bubble. */ + maxBubbleSize?: number; + /** Specifies the diameter of the smallest bubble measured in pixels. */ + minBubbleSize?: number; + /** Defines the dxChart widget's pane(s). */ + panes?: Array; + /** Swaps the axes round so that the value axis becomes horizontal and the argument axes becomes vertical. */ + rotated?: boolean; + /** Specifies the options of a chart's legend. */ + legend?: Legend; + /** Specifies options for dxChart widget series. */ + series?: Array; + /** Defines options for the series template. */ + seriesTemplate?: SeriesTemplate; + /** Specifies tooltip options. */ + tooltip?: ChartTooltip; + /** Specifies value axis options for the dxChart widget. */ + valueAxis?: Array; + /** Enables scrolling in your chart. */ + scrollingMode?: string; + /** Enables zooming in your chart. */ + zoomingMode?: string; + /** Specifies the settings of the scroll bar. */ + scrollBar?: { + /** Specifies whether the scroll bar is visible or not. */ + visible?: boolean; + /** Specifies the spacing between the scroll bar and the chart's plot in pixels. */ + offset?: number; + /** Specifies the color of the scroll bar. */ + color?: string; + /** Specifies the width of the scroll bar in pixels. */ + width?: number; + /** Specifies the opacity of the scroll bar. */ + opacity?: number; + /** Specifies the position of the scroll bar in the chart. */ + position?: string; + }; + } + /** A widget used to embed charts into HTML JS applications. */ + export class dxChart extends BaseChart { + constructor(element: JQuery, options?: dxChartOptions); + constructor(element: Element, options?: dxChartOptions); + /** Sets the specified start and end values for the chart's argument axis. */ + zoomArgument(startValue: any, endValue: any): void; + } + interface CrosshaierWithLabel extends viz.core.DashedBorderWithOpacity { + /** Configures the label that belongs to the horizontal crosshair line. */ + label?: { + /** Specifies a color for the background of the label that belongs to the horizontal crosshair line. */ + backgroundColor?: string; + /** Specifies whether the label of the horizontal crosshair line is visible or not. */ + visible?: boolean; + /** Specifies font options for the text of the label that belongs to the horizontal crosshair line. */ + font?: viz.core.Font; + /** Specifies the format of the values displayed by crosshair labels. */ + format?: string; + /** Specifies a precision for formatted values. */ + precision?: number; + /** Customizes the text displayed by the crosshair label that accompany the horizontal line. */ + customizeText?: (info: { value: any; valueText: string; point: ChartPoint; }) => string; + } + } + export interface PolarChartTooltip extends BaseChartTooltip { + /** Specifies the kind of information to display in a tooltip. */ + shared?: boolean; + } + export interface dxPolarChartOptions extends AdvancedOptions { + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + width?: number; + height?: number; + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Indicates whether or not to display a "spider web". */ + useSpiderWeb?: boolean; + /** Specifies argument axis options for the dxPolarChart widget. */ + argumentAxis?: PolarArgumentAxis; + /** An object defining the configuration options that are common for all axes of the dxPolarChart widget. */ + commonAxisSettings?: PolarCommonAxisSettings; + /** An object defining the configuration options that are common for all series of the dxPolarChart widget. */ + commonSeriesSettings?: CommonPolarSeriesSettings; + /** Specifies the options of a chart's legend. */ + legend?: AdvancedLegend; + /** Specifies options for dxPolarChart widget series. */ + series?: Array; + /** Defines options for the series template. */ + seriesTemplate?: PolarSeriesTemplate; + /** Specifies tooltip options. */ + tooltip?: PolarChartTooltip; + /** Specifies value axis options for the dxPolarChart widget. */ + valueAxis?: PolarValueAxis; + } + /** A chart widget displaying data in a polar coordinate system. */ + export class dxPolarChart extends BaseChart { + constructor(element: JQuery, options?: dxPolarChartOptions); + constructor(element: Element, options?: dxPolarChartOptions); + } + export interface PieLegend extends core.BaseLegend { + /** Specifies what chart elements to highlight when a corresponding item in the legend is hovered over. */ + hoverMode?: string; + /** Specifies the text for a hint that appears when a user hovers the mouse pointer over a legend item. */ + customizeHint?: (pointInfo: { pointName: string; pointIndex: number; pointColor: string; }) => string; + /** Specifies a callback function that returns the text to be displayed by a legend item. */ + customizeText?: (pointInfo: { pointName: string; pointIndex: number; pointColor: string; }) => string; + } + export interface dxPieChartOptions extends BaseChartOptions { + /** Specifies adaptive layout options. */ + adaptiveLayout?: { + /** Specifies whether or not point labels can be hidden when the layout is adapting. */ + keepLabels?: boolean; + }; + /** Specifies dxPieChart legend options. */ + legend?: PieLegend; + /** Specifies options for the series of the dxPieChart widget. */ + series?: Array; + /** Specifies the diameter of the pie. */ + diameter?: number; + /** Specifies the direction that the pie chart segments will occupy. */ + segmentsDirection?: string; + /** Specifies the angle in arc degrees from which the first segment of a pie chart should start. */ + startAngle?: number; + /** Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. The value should be between 0 and 1. */ + innerRadius?: number; + /** A handler for the legendClick event. */ + onLegendClick?: any; + /** Specifies how a chart must behave when series point labels overlap. */ + resolveLabelOverlapping?: string; + /** An object defining the configuration options that are common for all series of the dxPieChart widget. */ + commonSeriesSettings?: CommonPieSeriesSettings; + /** Specifies the type of the pie chart series. */ + type?: string; + } + /** A circular chart widget for HTML JS applications. */ + export class dxPieChart extends BaseChart { + constructor(element: JQuery, options?: dxPieChartOptions); + constructor(element: Element, options?: dxPieChartOptions); + /** + * Provides access to the dxPieChart series. + * @deprecated ..\..\BaseChart\3 Methods\getAllSeries().md + */ + getSeries(): PieSeries; + } +} +interface JQuery { + dxChart(options?: DevExpress.viz.charts.dxChartOptions): JQuery; + dxChart(methodName: string, ...params: any[]): any; + dxChart(methodName: "instance"): DevExpress.viz.charts.dxChart; + dxPieChart(options?: DevExpress.viz.charts.dxPieChartOptions): JQuery; + dxPieChart(methodName: string, ...params: any[]): any; + dxPieChart(methodName: "instance"): DevExpress.viz.charts.dxPieChart; + dxPolarChart(options?: DevExpress.viz.charts.dxPolarChartOptions): JQuery; + dxPolarChart(methodName: string, ...params: any[]): any; + dxPolarChart(methodName: "instance"): DevExpress.viz.charts.dxPolarChart; +} +declare module DevExpress.viz.gauges { + export interface BaseRangeContainer { + /** Specifies a range container's background color. */ + backgroundColor?: string; + /** Specifies the offset of the range container from an invisible scale line in pixels. */ + offset?: number; + /** Sets the name of the palette or an array of colors to be used for coloring the gauge range container. */ + palette?: any; + /** An array of objects representing ranges contained in the range container. */ + ranges?: Array<{ startValue: number; endValue: number; color: string }>; + /** Specifies a color of a range. */ + color?: string; + /** Specifies an end value of a range. */ + endValue?: number; + /** Specifies a start value of a range. */ + startValue?: number; + } + export interface ScaleTick { + /** Specifies the color of the scale's minor ticks. */ + color?: string; + /** + * Specifies an array of custom minor ticks. + * @deprecated ..\customMinorTicks.md + */ + customTickValues?: Array; + /** Specifies the length of the scale's minor ticks. */ + length?: number; + /** + * Indicates whether automatically calculated minor ticks are visible or not. + * @deprecated This functionality in not more available + */ + showCalculatedTicks?: boolean; + /** + * Specifies an interval between minor ticks. + * @deprecated ..\minorTickInterval.md + */ + tickInterval?: number; + /** Indicates whether scale minor ticks are visible or not. */ + visible?: boolean; + /** Specifies the width of the scale's minor ticks. */ + width?: number; + } + export interface ScaleMajorTick extends ScaleTick { + /** + * Specifies whether or not to expand the current major tick interval if labels overlap each other. + * @deprecated ..\label\overlappingBehavior\useAutoArrangement.md + */ + useTicksAutoArrangement?: boolean; + } + export interface ScaleMinorTick extends ScaleTick { + /** Specifies the opacity of the scale's minor ticks. */ + opacity?: number; + } + export interface BaseScaleLabel { + /** Specifies whether or not scale labels should be colored similarly to their corresponding ranges in the range container. */ + useRangeColors?: boolean; + /** Specifies a callback function that returns the text to be displayed in scale labels. */ + customizeText?: (scaleValue: { value: number; valueText: string }) => string; + /** Specifies the overlap resolving options to be applied to scale labels. */ + overlappingBehavior?: { + /** Specifies whether or not to expand the current major tick interval if labels overlap each other. */ + useAutoArrangement?: boolean; + /** Specifies what label to hide in case of overlapping. */ + hideFirstOrLast?: string; + }; + /** Specifies font options for the text displayed in the scale labels of the gauge. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in scale labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the scale labels. */ + precision?: number; + /** Specifies whether or not scale labels are visible on the gauge. */ + visible?: boolean; + } + export interface BaseScale { + /** Specifies the end value for the scale of the gauge. */ + endValue?: number; + /** + * Specifies whether or not to hide the first scale label. + * @deprecated This functionality in not more available + */ + hideFirstLabel?: boolean; + /** + * Specifies whether or not to hide the first major tick on the scale. + * @deprecated This functionality in not more available + */ + hideFirstTick?: boolean; + /** + * Specifies whether or not to hide the last scale label. + * @deprecated This functionality in not more available + */ + hideLastLabel?: boolean; + /** + * Specifies whether or not to hide the last major tick on the scale. + * @deprecated This functionality in not more available + */ + hideLastTick?: boolean; + /** Specifies an interval between major ticks. */ + tickInterval?: number; + /** Specifies an interval between minor ticks. */ + minorTickInterval?: number; + /** Specifies an array of custom major ticks. */ + customTicks?: Array; + /** Specifies an array of custom minor ticks. */ + customMinorTicks?: Array; + /** Specifies common options for scale labels. */ + label?: BaseScaleLabel; + /** + * Specifies options of the gauge's major ticks. + * @deprecated ..\tick\tick.md + */ + majorTick?: ScaleMajorTick; + /** Specifies options of the gauge's major ticks. */ + tick?: { + /** Specifies the color of the scale's major ticks. */ + color?: string; + /** Specifies the length of the scale's major ticks. */ + length?: number; + /** Indicates whether scale major ticks are visible or not. */ + visible?: boolean; + /** Specifies the width of the scale's major ticks. */ + width?: number; + /** Specifies the opacity of the scale's major ticks. */ + opacity?: number; + }; + /** Specifies options of the gauge's minor ticks. */ + minorTick?: ScaleMinorTick; + /** Specifies the start value for the scale of the gauge. */ + startValue?: number; + } + export interface BaseValueIndicator { + /** Specifies the type of subvalue indicators. */ + type?: string; + /** Specifies the background color for the indicator of the rangeBar type. */ + backgroundColor?: string; + /** Specifies the base value for the indicator of the rangeBar type. */ + baseValue?: number; + /** Specifies a color of the indicator. */ + color?: string; + /** Specifies the range bar size for an indicator of the rangeBar type. */ + size?: number; + text?: { + /** Specifies a callback function that returns the text to be displayed in an indicator. */ + customizeText?: (indicatedValue: { value: number; valueText: string }) => string; + font?: viz.core.Font; + /** Specifies a format for the text displayed in an indicator. */ + format?: string; + /** Specifies the range bar's label indent in pixels. */ + indent?: number; + /** Specifies a precision for the formatted value displayed by an indicator. */ + precision?: number; + }; + offset?: number; + length?: number; + width?: number; + /** Specifies the length of an arrow for the indicator of the textCloud type in pixels. */ + arrowLength?: number; + /** Sets the array of colors to be used for coloring subvalue indicators. */ + palette?: Array; + /** Specifies the distance between the needle and the center of a gauge for the indicator of a needle-like type. */ + indentFromCenter?: number; + /** Specifies the second color for the indicator of the twoColorNeedle type. */ + secondColor?: string; + /** Specifies the length of a twoNeedleColor type indicator tip as a percentage. */ + secondFraction?: number; + /** Specifies the spindle's diameter in pixels for the indicator of a needle-like type. */ + spindleSize?: number; + /** Specifies the inner diameter in pixels, so that the spindle has the shape of a ring. */ + spindleGapSize?: number; + /** Specifies the orientation of the rangeBar indicator on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + /** Specifies the orientation of the rangeBar indicator on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + } + export interface SharedGaugeOptions { + /** Specifies animation options. */ + animation?: viz.core.Animation; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies the size of the widget in pixels. */ + size?: viz.core.Size; + /** + * Specifies a subtitle for the widget. + * @deprecated ..\..\..\BaseGauge\1 Configuration\title\subtitle\subtitle.md + */ + subtitle?: { + /** + * Specifies font options for the subtitle. + * @deprecated ..\..\title\subtitle\font\font.md + */ + font?: viz.core.Font; + /** + * Specifies a text for the subtitle. + * @deprecated ..\title\subtitle\text.md + */ + text?: string; + }; + /** Specifies a title for a gauge. */ + title?: { + /** Specifies font options for the title. */ + font?: viz.core.Font; + /** + * Specifies a title's position on the gauge. + * @deprecated basegaugeoptions_title_verticalAlignment and basegaugeoptions_title_horizontalAlignment + */ + position?: string; + /** Specifies the distance between the title and surrounding gauge elements in pixels. */ + margin?: viz.core.Margins; + /** Specifies the height of the space reserved for the title. */ + placeholderSize?: number; + /** Specifies the gauge title's position in the vertical direction. */ + verticalAlignment?: string; + /** Specifies the gauge title's horizontal position. */ + horizontalAlignment?: string; + /** Specifies text for the title. */ + text?: string; + /** Specifies a subtitle for the widget. */ + subtitle?: { + /** Specifies font options for the subtitle. */ + font?: viz.core.Font; + /** Specifies text for the subtitle. */ + text?: string; + } + }; + /** Specifies options for gauge tooltips. */ + tooltip?: viz.core.Tooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: dxBaseGauge; + element: Element; + target: {}; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: dxBaseGauge; + element: Element; + target: {}; + }) => void; + } + export interface BaseGaugeOptions extends viz.core.BaseWidgetOptions, SharedGaugeOptions { + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** Specifies the blank space in pixels between the widget's extreme elements and the boundaries of the area provided for the widget (see the size option). */ + margin?: viz.core.Margins; + /** Specifies options of the gauge's range container. */ + rangeContainer?: BaseRangeContainer; + /** Specifies a gauge's scale options. */ + scale?: BaseScale; + /** Specifies the appearance options of subvalue indicators. */ + subvalueIndicator?: BaseValueIndicator; + /** Specifies a set of subvalues to be designated by the subvalue indicators. */ + subvalues?: Array; + /** Specifies the main value on a gauge. */ + value?: number; + /** Specifies the appearance options of the value indicator. */ + valueIndicator?: BaseValueIndicator; + } + /** A gauge widget. */ + export class dxBaseGauge extends viz.core.BaseWidget { + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(): void; + /** Returns the main gauge value. */ + value(): number; + /** Updates a gauge value. */ + value(value: number): void; + /** Returns an array of gauge subvalues. */ + subvalues(): Array; + /** Updates gauge subvalues. */ + subvalues(subvalues: Array): void; + } + export interface LinearRangeContainer extends BaseRangeContainer { + /** Specifies the orientation of the range container on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + /** Specifies the orientation of a range container on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + /** Specifies the width of the range container's start and end boundaries in the dxLinearGauge widget. */ + width?: any; + /** Specifies an end width of a range container. */ + end?: number; + /** Specifies a start width of a range container. */ + start?: number; + } + export interface LinearScaleLabel extends BaseScaleLabel { + /** Specifies the spacing between scale labels and ticks. */ + indentFromTick?: number; + } + export interface LinearScale extends BaseScale { + /** Specifies the orientation of scale ticks on a vertically oriented dxLinearGauge widget. */ + horizontalOrientation?: string; + label?: LinearScaleLabel; + /** Specifies the orientation of scale ticks on a horizontally oriented dxLinearGauge widget. */ + verticalOrientation?: string; + } + export interface dxLinearGaugeOptions extends BaseGaugeOptions { + /** Specifies the options required to set the geometry of the dxLinearGauge widget. */ + geometry?: { + /** Indicates whether to display the dxLinearGauge widget vertically or horizontally. */ + orientation?: string; + }; + /** Specifies gauge range container options. */ + rangeContainer?: LinearRangeContainer; + scale?: LinearScale; + } + /** A widget that represents a gauge with a linear scale. */ + export class dxLinearGauge extends dxBaseGauge { + constructor(element: JQuery, options?: dxLinearGaugeOptions); + constructor(element: Element, options?: dxLinearGaugeOptions); + } + export interface CircularRangeContainer extends BaseRangeContainer { + /** Specifies the orientation of the range container in the dxCircularGauge widget. */ + orientation?: string; + /** Specifies the range container's width in pixels. */ + width?: number; + } + export interface CircularScaleLabel extends BaseScaleLabel { + /** Specifies the spacing between scale labels and ticks. */ + indentFromTick?: number; + } + export interface CircularScale extends BaseScale { + label?: CircularScaleLabel; + /** Specifies the orientation of scale ticks. */ + orientation?: string; + } + export interface dxCircularGaugeOptions extends BaseGaugeOptions { + /** Specifies the options required to set the geometry of the dxCircularGauge widget. */ + geometry?: { + /** Specifies the end angle of the circular gauge's arc. */ + endAngle?: number; + /** Specifies the start angle of the circular gauge's arc. */ + startAngle?: number; + }; + /** Specifies gauge range container options. */ + rangeContainer?: CircularRangeContainer; + scale?: CircularScale; + } + /** A widget that represents a gauge with a circular scale. */ + export class dxCircularGauge extends dxBaseGauge { + constructor(element: JQuery, options?: dxCircularGaugeOptions); + constructor(element: Element, options?: dxCircularGaugeOptions); + } + export interface dxBarGaugeOptions extends viz.core.BaseWidgetOptions, SharedGaugeOptions { + /** Specifies a color for the remaining segment of the bar's track. */ + backgroundColor?: string; + /** Specifies a distance between bars in pixels. */ + barSpacing?: number; + /** Specifies a base value for bars. */ + baseValue?: number; + /** Specifies an end value for the gauge's invisible scale. */ + endValue?: number; + /** Defines the shape of the gauge's arc. */ + geometry?: { + /** Specifies the end angle of the bar gauge's arc. */ + endAngle?: number; + /** Specifies the start angle of the bar gauge's arc. */ + startAngle?: number; + }; + /** Specifies the options of the labels that accompany gauge bars. */ + label?: { + /** Specifies a color for the label connector text. */ + connectorColor?: string; + /** Specifies the width of the label connector in pixels. */ + connectorWidth?: number; + /** Specifies a callback function that returns a text for labels. */ + customizeText?: (barValue: { value: number; valueText: string }) => string; + /** Specifies font options for bar labels. */ + font?: viz.core.Font; + /** Specifies a format for bar labels. */ + format?: string; + /** Specifies the distance between the upper bar and bar labels in pixels. */ + indent?: number; + /** Specifies a precision for the formatted value displayed by labels. */ + precision?: number; + /** Specifies whether bar labels appear on a gauge or not. */ + visible?: boolean; + }; + /** Sets the name of the palette or an array of colors to be used for coloring the gauge range container. */ + palette?: string; + /** Defines the radius of the bar that is closest to the center relatively to the radius of the topmost bar. */ + relativeInnerRadius?: number; + /** Specifies a start value for the gauge's invisible scale. */ + startValue?: number; + /** Specifies the array of values to be indicated on a bar gauge. */ + values?: Array; + } + /** A circular bar widget. */ + export class dxBarGauge extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxBarGaugeOptions); + constructor(element: Element, options?: dxBarGaugeOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws the widget. */ + render(): void; + /** Returns an array of gauge values. */ + values(): Array; + /** Updates the values displayed by a gauge. */ + values(values: Array): void; + } +} +interface JQuery { + dxLinearGauge(options?: DevExpress.viz.gauges.dxLinearGaugeOptions): JQuery; + dxLinearGauge(methodName: string, ...params: any[]): any; + dxLinearGauge(methodName: "instance"): DevExpress.viz.gauges.dxLinearGauge; + dxCircularGauge(options?: DevExpress.viz.gauges.dxCircularGaugeOptions): JQuery; + dxCircularGauge(methodName: string, ...params: any[]): any; + dxCircularGauge(methodName: "instance"): DevExpress.viz.gauges.dxCircularGauge; + dxBarGauge(options?: DevExpress.viz.gauges.dxBarGaugeOptions): JQuery; + dxBarGauge(methodName: string, ...params: any[]): any; + dxBarGauge(methodName: "instance"): DevExpress.viz.gauges.dxBarGauge; +} +declare module DevExpress.viz.rangeSelector { + export interface dxRangeSelectorOptions extends viz.core.BaseWidgetOptions { + /** Specifies the options for the range selector's background. */ + background?: { + /** Specifies the background color for the dxRangeSelector. */ + color?: string; + /** Specifies image options. */ + image?: { + /** Specifies a location for the image in the background of a range selector. */ + location?: string; + /** Specifies the image's URL. */ + url?: string; + }; + /** Indicates whether or not the background (background color and/or image) is visible. */ + visible?: boolean; + }; + /** Specifies a title for the range selector. */ + title?: viz.core.Title; + /** Specifies the dxRangeSelector's behavior options. */ + behavior?: { + /** Indicates whether or not you can swap sliders. */ + allowSlidersSwap?: boolean; + /** Indicates whether or not animation is enabled. */ + animationEnabled?: boolean; + /** Specifies when to call the onSelectedRangeChanged function. */ + callSelectedRangeChanged?: string; + /** Indicates whether or not an end user can specify the range using a mouse, without the use of sliders. */ + manualRangeSelectionEnabled?: boolean; + /** Indicates whether or not an end user can shift the selected range to the required location on a scale by clicking. */ + moveSelectedRangeByClick?: boolean; + /** Indicates whether to snap a slider to ticks. */ + snapToTicks?: boolean; + }; + /** Specifies the options required to display a chart as the range selector's background. */ + chart?: { + /** Specifies a coefficient for determining an indent from the bottom background boundary to the lowest chart point. */ + bottomIndent?: number; + /** An object defining the common configuration options for the chart’s series. */ + commonSeriesSettings?: viz.charts.CommonSeriesSettings; + /** An object providing options for managing data from a data source. */ + dataPrepareSettings?: { + /** Specifies whether or not to validate values from a data source. */ + checkTypeForAllData?: boolean; + /** Specifies whether or not to convert the values from a data source into the data type of an axis. */ + convertToAxisDataType?: boolean; + /** Specifies how to sort series points. */ + sortingMethod?: any; + }; + /** Specifies whether all bars in a series must have the same width, or may have different widths if any points in other series are missing. */ + equalBarWidth?: boolean; + /** Specifies a common bar width as a percentage from 0 to 1. */ + barWidth?: number; + /** Forces the widget to treat negative values as zeroes. Applies to stacked-like series only. */ + negativesAsZeroes?: boolean; + /** Sets the name of the palette to be used in the range selector's chart. Alternatively, an array of colors can be set as a custom palette to be used within this chart. */ + palette?: any; + /** An object defining the chart’s series. */ + series?: Array; + /** Defines options for the series template. */ + seriesTemplate?: viz.charts.SeriesTemplate; + /** Specifies a coefficient for determining an indent from the background's top boundary to the topmost chart point. */ + topIndent?: number; + /** Specifies whether or not to filter the series points depending on their quantity. */ + useAggregation?: boolean; + /** Specifies options for the chart's value axis. */ + valueAxis?: { + /** Indicates whether or not the chart's value axis must be inverted. */ + inverted?: boolean; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic value axis. */ + logarithmBase?: number; + /** Specifies the maximum value of the chart's value axis. */ + max?: number; + /** Specifies the minimum value of the chart's value axis. */ + min?: number; + /** Specifies the type of the value axis. */ + type?: string; + /** Specifies the desired type of axis values. */ + valueType?: string; + }; + }; + /** Specifies the color of the parent page element. */ + containerBackgroundColor?: string; + /** Specifies a data source for the scale values and for the chart at the background. */ + dataSource?: any; + /** Specifies the data source field that provides data for the scale. */ + dataSourceField?: string; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** Specifies the blank space in pixels between the dxRangeSelector widget's extreme elements and the boundaries of the area provided for the widget (see size). */ + margin?: viz.core.Margins; + /** Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates. */ + redrawOnResize?: boolean; + /** Specifies options of the range selector's scale. */ + scale?: { + /** Specifies the scale's end value. */ + endValue?: any; + /** Specifies common options for scale labels. */ + label?: { + /** Specifies a callback function that returns the text to be displayed in scale labels. */ + customizeText?: (scaleValue: { value: any; valueText: string; }) => string; + /** Specifies font options for the text displayed in the range selector's scale labels. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in scale labels. */ + format?: string; + /** Specifies a precision for the formatted value displayed in the scale labels. */ + precision?: number; + /** Specifies a spacing between scale labels and the background bottom edge. */ + topIndent?: number; + /** Specifies whether or not the scale's labels are visible. */ + visible?: boolean; + }; + /** Specifies the value to be raised to a power when generating ticks for a logarithmic scale. */ + logarithmBase?: number; + /** + * Specifies an interval between major ticks. + * @deprecated ..\tickInterval\tickInterval.md + */ + majorTickInterval?: any; + /** Specifies an interval between axis ticks. */ + tickInterval?: any; + /** Specifies options for the date-time scale's markers. */ + marker?: { + /** Defines the options that can be set for the text that is displayed by the scale markers. */ + label?: { + /** Specifies a callback function that returns the text to be displayed in scale markers. */ + customizeText?: (markerValue: { value: any; valueText: string }) => string; + /** Specifies a format for the text displayed in scale markers. */ + format?: string; + }; + /** Specifies the height of the marker's separator. */ + separatorHeight?: number; + /** Specifies the space between the marker label and the marker separator. */ + textLeftIndent?: number; + /** Specifies the space between the marker's label and the top edge of the marker's separator. */ + textTopIndent?: number; + /** Specified the indent between the marker and the scale lables. */ + topIndent?: number; + /** Indicates whether scale markers are visible. */ + visible?: boolean; + }; + /** Specifies the maximum range that can be selected. */ + maxRange?: any; + /** Specifies the number of minor ticks between neighboring major ticks. */ + minorTickCount?: number; + /** Specifies an interval between minor ticks. */ + minorTickInterval?: any; + /** Specifies the minimum range that can be selected. */ + minRange?: any; + /** Specifies the height of the space reserved for the scale in pixels. */ + placeholderHeight?: number; + /** Indicates whether or not to set ticks of a date-time scale at the beginning of each date-time interval. */ + setTicksAtUnitBeginning?: boolean; + /** Specifies whether or not to show ticks for the boundary scale values, when neither major ticks nor minor ticks are created for these values. */ + showCustomBoundaryTicks?: boolean; + /** + * Indicates whether or not to show minor ticks on the scale. + * @deprecated minorTick\visible.md + */ + showMinorTicks?: boolean; + /** Specifies the scale's start value. */ + startValue?: any; + /** Specifies options defining the appearance of scale ticks. */ + tick?: { + /** Specifies the color of scale ticks (both major and minor ticks). */ + color?: string; + /** Specifies the opacity of scale ticks (both major and minor ticks). */ + opacity?: number; + /** Specifies the width of the scale's ticks (both major and minor ticks). */ + width?: number; + }; + /** Specifies options of the range selector's minor ticks. */ + minorTick?: { + /** Specifies the color of the scale's minor ticks. */ + color?: string; + /** Specifies the opacity of the scale's minor ticks. */ + opacity?: number; + /** Specifies the width of the scale's minor ticks. */ + width?: number; + /** Indicates whether scale minor ticks are visible or not. */ + visible?: boolean; + }; + /** Specifies the type of the scale. */ + type?: string; + /** Specifies whether or not to expand the current tick interval if labels overlap each other. */ + useTicksAutoArrangement?: boolean; + /** Specifies the type of values on the scale. */ + valueType?: string; + /** Specifies the order of arguments on a discrete scale. */ + categories?: Array; + }; + /** Specifies the range to be selected when displaying the dxRangeSelector. */ + selectedRange?: { + /** Specifies the start value of the range to be selected when displaying the dxRangeSelector widget on a page. */ + startValue?: any; + /** Specifies the end value of the range to be selected when displaying the dxRangeSelector widget on a page. */ + endValue?: any; + }; + /** Specifies the color of the selected range. */ + selectedRangeColor?: string; + /** Range selector's indent options. */ + indent?: { + /** Specifies range selector's left indent. */ + left?: number; + /** Specifies range selector's right indent. */ + right?: number; + }; + /** A handler for the selectedRangeChanged event. */ + onSelectedRangeChanged?: (e: { + startValue: any; + endValue: any; + component: dxRangeSelector; + element: Element; + }) => void; + /** Specifies range selector shutter options. */ + shutter?: { + /** Specifies shutter color. */ + color?: string; + /** Specifies the opacity of the color of shutters. */ + opacity?: number; + }; + /** Specifies in pixels the size of the dxRangeSelector widget. */ + size?: viz.core.Size; + /** Specifies the appearance of the range selector's slider handles. */ + sliderHandle?: { + /** Specifies the color of the slider handles. */ + color?: string; + /** Specifies the opacity of the slider handles. */ + opacity?: number; + /** Specifies the width of the slider handles. */ + width?: number; + }; + /** Defines the options of the range selector slider markers. */ + sliderMarker?: { + /** Specifies the color of the slider markers. */ + color?: string; + /** Specifies a callback function that returns the text to be displayed by slider markers. */ + customizeText?: (scaleValue: { value: any; valueText: any; }) => string; + /** Specifies font options for the text displayed by the range selector slider markers. */ + font?: viz.core.Font; + /** Specifies a format for the text displayed in slider markers. */ + format?: string; + /** Specifies the color used for the slider marker text when the currently selected range does not match the minRange and maxRange values. */ + invalidRangeColor?: string; + /** + * Specifies the empty space between the marker's border and the marker’s text. + * @deprecated Use the 'paddingTopBottom' and 'paddingLeftRight' options instead + */ + padding?: number; + /** Specifies the empty space between the marker's top and bottom borders and the marker's text. */ + paddingTopBottom?: number; + /** Specifies the empty space between the marker's left and right borders and the marker's text. */ + paddingLeftRight?: number; + /** Specifies the placeholder height of the slider marker. */ + placeholderHeight?: number; + /** + * Specifies in pixels the height and width of the space reserved for the range selector slider markers. + * @deprecated Use the 'placeholderHeight' and 'indent' options instead + */ + placeholderSize?: { + /** Specifies the height of the placeholder for the left and right slider markers. */ + height?: number; + /** Specifies the width of the placeholder for the left and right slider markers. */ + width?: { + /** Specifies the width of the left slider marker's placeholder. */ + left?: number; + /** Specifies the width of the right slider marker's placeholder. */ + right?: number; + }; + }; + /** Specifies a precision for the formatted value displayed in slider markers. */ + precision?: number; + /** Indicates whether or not the slider markers are visible. */ + visible?: boolean; + }; + } + /** A widget that allows end users to select a range of values on a scale. */ + export class dxRangeSelector extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxRangeSelectorOptions); + constructor(element: Element, options?: dxRangeSelectorOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(skipChartAnimation?: boolean): void; + /** Returns the currently selected range. */ + getSelectedRange(): { startValue: any; endValue: any; }; + /** Sets a specified range. */ + setSelectedRange(selectedRange: { startValue: any; endValue: any; }): void; + } +} +interface JQuery { + dxRangeSelector(options?: DevExpress.viz.rangeSelector.dxRangeSelectorOptions): JQuery; + dxRangeSelector(methodName: string, ...params: any[]): any; + dxRangeSelector(methodName: "instance"): DevExpress.viz.rangeSelector.dxRangeSelector; +} +declare module DevExpress.viz.map { + /** This section describes the fields and methods that can be used in code to manipulate the Layer object. */ + export interface MapLayer { + /** The name of the layer. */ + name: string; + /** The layer index in the layers array. */ + index: number; + /** The layer type. Can be "area", "line" or "marker". */ + type: string; + /** The type of the layer elements. */ + elementType: string; + /** Gets all layer elements. */ + getElements(): Array; + /** Deselects all layer elements. */ + clearSelection(): void; + } + /** This section describes the fields and methods that can be used in code to manipulate the Layer Element object. */ + export interface MapLayerElement { + /** The parent layer of the layer element. */ + layer: MapLayer; + /** Gets the layer element coordinates. */ + coordinates(): Object; + /** Sets the value of an attribute. */ + attribute(name: string, value: any): void; + /** Gets the value of an attribute. */ + attribute(name: string): any; + /** Gets the selection state of the layer element. */ + selected(): boolean; + /** Sets the selection state of the layer element. */ + selected(state: boolean): void; + /** Applies the layer element settings and updates element appearance. */ + applySettings(settings: any): void; + } + /** + * This section describes the fields and methods that can be used in code to manipulate the Area object. + * @deprecated Use the "Layer Element" instead + */ + export interface Area { + /** + * Contains the element type. + * @deprecated ..\..\Layer\2 Fields\type.md + */ + type: string; + /** + * Return the value of an attribute. + * @deprecated ..\..\Layer Element\3 Methods\attribute(name_value).md + */ + attribute(name: string): any; + /** + * Provides information about the selection state of an area. + * @deprecated Use the "selected()" method of the Layer Element + */ + selected(): boolean; + /** + * Sets a new selection state for an area. + * @deprecated Use the "selected(state)" method of the Layer Element + */ + selected(state: boolean): void; + /** + * Applies the area settings specified as a parameter and updates the area appearance. + * @deprecated ..\..\Layer Element\3 Methods\applySettings(settings).md + */ + applySettings(settings: any): void; + } + /** + * This section describes the fields and methods that can be used in code to manipulate the Markers object. + * @deprecated Use the "Layer Element" instead + */ + export interface Marker { + /** + * Contains the descriptive text accompanying the map marker. + * @deprecated Get the text with the "attribute" method (using the "layers.label.dataField" value) + */ + text: string; + /** + * Contains the type of the element. + * @deprecated ..\..\Layer\2 Fields\type.md + */ + type: string; + /** + * Contains the URL of an image map marker. + * @deprecated Get the url with the "attribute" method (using the "layers.dataField" value) + */ + url: string; + /** + * Contains the value of a bubble map marker. + * @deprecated Get the value with the "attribute" method (using the "layers.dataField" value) + */ + value: number; + /** + * Contains the values of a pie map marker. + * @deprecated Get the values with the "attribute" method (using the "layers.dataField" value) + */ + values: Array; + /** + * Returns the value of an attribute. + * @deprecated ..\..\Layer Element\3 Methods\attribute(name_value).md + */ + attribute(name: string): any; + /** + * Returns the coordinates of a specific marker. + * @deprecated ..\..\Layer Element\3 Methods\coordinates().md + */ + coordinates(): Array; + /** + * Provides information about the selection state of a marker. + * @deprecated Use the "selected()" method of the Layer Element + */ + selected(): boolean; + /** + * Sets a new selection state for a marker. + * @deprecated Use the "selected(state)" method of the Layer Element + */ + selected(state: boolean): void; + /** + * Applies the marker settings specified as a parameter and updates marker appearance. + * @deprecated ..\..\Layer Element\3 Methods\applySettings(settings).md + */ + applySettings(settings: any): void; + } + export interface MapLayerSettings { + /** Specifies the layer name. */ + name?: string; + /** Specifies layer type. */ + type?: string; + /** Specifies the type of a marker element. Setting this option makes sense only if the layer type is "marker". */ + elementType?: string; + /** Specifies a data source for the layer. */ + data?: any; + /** Specifies the line width (for layers of a line type) or width of the layer elements border in pixels. */ + borderWidth?: number; + /** Specifies a color for the border of the layer elements. */ + borderColor?: string; + /** Specifies a color for layer elements. */ + color?: string; + /** Specifies a color for the border of the layer element when it is hovered over. */ + hoveredBorderColor?: string; + /** Specifies the pixel-measured line width (for layers of a line type) or width for the border of the layer element when it is hovered over. */ + hoveredBorderWidth?: number; + /** Specifies a color for a layer element when it is hovered over. */ + hoveredColor?: string; + /** Specifies a pixel-measured line width (for layers of a line type) or width for the border of the layer element when it is selected. */ + selectedBorderWidth?: number; + /** Specifies a color for the border of the layer element when it is selected. */ + selectedBorderColor?: string; + /** Specifies a color for the layer element when it is selected. */ + selectedColor?: string; + /** Specifies the layer opacity (from 0 to 1). */ + opacity?: number; + /** Specifies the size of markers. Setting this option makes sense only if the layer type is "marker" and the elementType is "dot", "pie" or "image". */ + size?: number; + /** Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if the layer type is "marker". */ + minSize?: number; + /** Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if the layer type is "marker". */ + maxSize?: number; + /** Specifies whether or not to change the appearance of a layer element when it is hovered over. */ + hoverEnabled?: boolean; + /** Specifies whether single or multiple map elements can be selected on a vector map. */ + selectionMode?: string; + /** Specifies the name of the palette or a custom range of colors to be used for coloring a layer. */ + palette?: any; + /** Specifies the number of colors in a palette. */ + paletteSize?: number; + /** Allows you to paint layer elements with similar attributes in the same color. */ + colorGroups?: Array; + /** Specifies the field that provides data to be used for coloring of layer elements. */ + colorGroupingField?: string; + /** Allows you to display bubbles with similar attributes in the same size. Setting this option makes sense only if the layer type is "marker" and the elementType is "bubble". */ + sizeGroups?: Array; + /** Specifies the field that provides data to be used for sizing bubble markers. Setting this option makes sense only if the layer type is "marker" and the elementType is "bubble". */ + sizeGroupingField?: string; + /** Specifies the name of the attribute containing marker data. Setting this option makes sense only if the layer type is "marker" and the elementType is "bubble", "pie" or "image". */ + dataField?: string; + /** Specifies the function that customizes each layer element individually. */ + customize?: (eleemnts: Array) => void; + /** Specifies marker label options. */ + label?: { + /** The name of the data attribute containing marker texts. */ + dataField?: string; + /** Enables marker labels. */ + enabled?: boolean; + /** Specifies font options for marker labels. */ + font?: viz.core.Font; + }; + } + export interface AreaSettings { + /** + * Specifies the width of the area border in pixels. + * @deprecated ..\layers\borderWidth.md + */ + borderWidth?: number; + /** + * Specifies a color for the area border. + * @deprecated ..\layers\borderColor.md + */ + borderColor?: string; + /** + * Specifies a color for an area. + * @deprecated ..\layers\color.md + */ + color?: string; + /** + * Specifies the function that customizes each area individually. + * @deprecated ..\layers\customize.md + */ + customize?: (areaInfo: Area) => AreaSettings; + /** + * Specifies a color for the area border when the area is hovered over. + * @deprecated ..\layers\hoveredBorderColor.md + */ + hoveredBorderColor?: string; + /** + * Specifies the pixel-measured width of the area border when the area is hovered over. + * @deprecated ..\layers\hoveredBorderWidth.md + */ + hoveredBorderWidth?: number; + /** + * Specifies a color for an area when this area is hovered over. + * @deprecated ..\layers\hoveredColor.md + */ + hoveredColor?: string; + /** + * Specifies whether or not to change the appearance of an area when it is hovered over. + * @deprecated ..\layers\hoverEnabled.md + */ + hoverEnabled?: boolean; + /** + * Configures area labels. + * @deprecated ..\..\layers\label\label.md + */ + label?: { + /** + * Specifies the data field that provides data for area labels. + * @deprecated ..\..\layers\label\dataField.md + */ + dataField?: string; + /** + * Enables area labels. + * @deprecated ..\..\layers\label\enabled.md + */ + enabled?: boolean; + /** + * Specifies font options for area labels. + * @deprecated ..\..\..\layers\label\font\font.md + */ + font?: viz.core.Font; + }; + /** + * Specifies the name of the palette or a custom range of colors to be used for coloring a map. + * @deprecated ..\layers\palette.md + */ + palette?: any; + /** + * Specifies the number of colors in a palette. + * @deprecated ..\layers\paletteSize.md + */ + paletteSize?: number; + /** + * Allows you to paint areas with similar attributes in the same color. + * @deprecated ..\layers\colorGroups.md + */ + colorGroups?: Array; + /** + * Specifies the field that provides data to be used for coloring areas. + * @deprecated ..\layers\colorGroupingField.md + */ + colorGroupingField?: string; + /** + * Specifies a color for the area border when the area is selected. + * @deprecated ..\layers\selectedBorderColor.md + */ + selectedBorderColor?: string; + /** + * Specifies a color for an area when this area is selected. + * @deprecated ..\layers\selectedColor.md + */ + selectedColor?: string; + /** + * Specifies the pixel-measured width of the area border when the area is selected. + * @deprecated ..\layers\selectedBorderWidth.md + */ + selectedBorderWidth?: number; + /** + * Specifies whether single or multiple areas can be selected on a vector map. + * @deprecated ..\layers\selectionMode.md + */ + selectionMode?: string; + } + export interface MarkerSettings { + /** + * Specifies a color for the marker border. + * @deprecated ..\layers\borderColor.md + */ + borderColor?: string; + /** + * Specifies the width of the marker border in pixels. + * @deprecated ..\layers\borderWidth.md + */ + borderWidth?: number; + /** + * Specifies a color for a marker of the dot or bubble type. + * @deprecated ..\layers\color.md + */ + color?: string; + /** + * Specifies the function that customizes each marker individually. + * @deprecated ..\layers\customize.md + */ + customize?: (markerInfo: Marker) => MarkerSettings; + /** + * Specifies the pixel-measured width of the marker border when the marker is hovered over. + * @deprecated ..\layers\hoveredBorderWidth.md + */ + hoveredBorderWidth?: number; + /** + * Specifies a color for the marker border when the marker is hovered over. + * @deprecated ..\layers\hoveredBorderColor.md + */ + hoveredBorderColor?: string; + /** + * Specifies a color for a marker of the dot or bubble type when this marker is hovered over. + * @deprecated ..\layers\hoveredColor.md + */ + hoveredColor?: string; + /** + * Specifies whether or not to change the appearance of a marker when it is hovered over. + * @deprecated ..\layers\hoverEnabled.md + */ + hoverEnabled?: boolean; + /** + * Specifies marker label options. + * @deprecated ..\..\layers\label\label.md + */ + label?: { + /** + * Enables marker labels. + * @deprecated ..\..\layers\label\enabled.md + */ + enabled?: boolean; + /** + * Specifies font options for marker labels. + * @deprecated ..\..\..\layers\label\font\font.md + */ + font?: viz.core.Font; + }; + /** + * Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if you use markers of the bubble type. + * @deprecated ..\layers\maxSize.md + */ + maxSize?: number; + /** + * Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if you use markers of the bubble type. + * @deprecated ..\layers\minSize.md + */ + minSize?: number; + /** + * Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. + * @deprecated ..\layers\opacity.md + */ + opacity?: number; + /** + * Specifies the pixel-measured width of the marker border when the marker is selected. + * @deprecated ..\layers\selectedBorderWidth.md + */ + selectedBorderWidth?: number; + /** + * Specifies a color for the marker border when the marker is selected. + * @deprecated ..\layers\selectedBorderColor.md + */ + selectedBorderColor?: string; + /** + * Specifies a color for a marker of the dot or bubble type when this marker is selected. + * @deprecated ..\layers\selectedColor.md + */ + selectedColor?: string; + /** + * Specifies whether a single or multiple markers can be selected on a vector map. + * @deprecated ..\layers\selectionMode.md + */ + selectionMode?: string; + /** + * Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. + * @deprecated ..\layers\size.md + */ + size?: number; + /** + * Specifies the type of markers to be used on the map. + * @deprecated ..\layers\elementType.md + */ + type?: string; + /** + * Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. + * @deprecated ..\layers\palette.md + */ + palette?: any; + /** + * Allows you to paint markers with similar attributes in the same color. + * @deprecated ..\layers\colorGroups.md + */ + colorGroups?: Array; + /** + * Specifies the field that provides data to be used for coloring markers. + * @deprecated ..\layers\colorGroupingField.md + */ + colorGroupingField?: string; + /** + * Allows you to display bubbles with similar attributes in the same size. + * @deprecated ..\layers\sizeGroups.md + */ + sizeGroups?: Array; + /** + * Specifies the field that provides data to be used for sizing bubble markers. + * @deprecated ..\layers\sizeGroupingField.md + */ + sizeGroupingField?: string; + } + export interface dxVectorMapOptions extends viz.core.BaseWidgetOptions { + /** + * An object specifying options for the map areas. + * @deprecated Use the 'layers' option instead + */ + areaSettings?: AreaSettings; + /** Specifies the options for the map background. */ + background?: { + /** Specifies a color for the background border. */ + borderColor?: string; + /** Specifies a color for the background. */ + color?: string; + }; + /** Specifies options for dxVectorMap widget layers. */ + layers?: Array; + /** Specifies the map projection. */ + projection?: Object; + /** Specifies the positioning of a map in geographical coordinates. */ + bounds?: Array; + /** Specifies the options of the control bar. */ + controlBar?: { + /** Specifies a color for the outline of the control bar elements. */ + borderColor?: string; + /** Specifies a color for the inner area of the control bar elements. */ + color?: string; + /** Specifies whether or not to display the control bar. */ + enabled?: boolean; + /** Specifies the margin of the control bar in pixels. */ + margin?: number; + /** Specifies the position of the control bar. */ + horizontalAlignment?: string; + /** Specifies the position of the control bar. */ + verticalAlignment?: string; + /** Specifies the opacity of the Control_Bar. */ + opacity?: number; + }; + /** Specifies the appearance of the loading indicator. */ + loadingIndicator?: viz.core.LoadingIndicator; + /** + * Specifies a data source for the map area. + * @deprecated Use the 'layers.data' option instead + */ + mapData?: any; + /** + * Specifies a data source for the map markers. + * @deprecated Use the 'layers.data' option instead + */ + markers?: any; + /** + * An object specifying options for the map markers. + * @deprecated Use the 'layers' option instead + */ + markerSettings?: MarkerSettings; + /** Specifies the size of the dxVectorMap widget. */ + size?: viz.core.Size; + /** Specifies a title for the vector map. */ + title?: viz.core.Title; + /** Specifies tooltip options. */ + tooltip?: viz.core.Tooltip; + /** Configures map legends. */ + legends?: Array; + /** Specifies whether or not the map should respond when a user rolls the mouse wheel. */ + wheelEnabled?: boolean; + /** Specifies whether the map should respond to touch gestures. */ + touchEnabled?: boolean; + /** Disables the zooming capability. */ + zoomingEnabled?: boolean; + /** Specifies the geographical coordinates of the center for a map. */ + center?: Array; + /** A handler for the centerChanged event. */ + onCenterChanged?: (e: { + center: Array; + component: dxVectorMap; + element: Element; + }) => void; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: dxVectorMap; + element: Element; + target: {}; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: dxVectorMap; + element: Element; + target: {}; + }) => void; + /** Specifies a number that is used to zoom a map initially. */ + zoomFactor?: number; + /** Specifies a map's maximum zoom factor. */ + maxZoomFactor?: number; + /** A handler for the zoomFactorChanged event. */ + onZoomFactorChanged?: (e: { + component: dxVectorMap; + element: Element; + zoomFactor: number; + }) => void; + /** A handler for the click event. */ + onClick?: any; + /** A handler for the selectionChanged event. */ + onSelectionChanged?: (e: { + component: dxVectorMap; + element: Element; + target: MapLayerElement; + }) => void; + /** + * A handler for the areaClick event. + * @deprecated Use the 'onClick' option instead + */ + onAreaClick?: any; + /** + * A handler for the areaSelectionChanged event. + * @deprecated Use the 'onSelectionChanged' option instead + */ + onAreaSelectionChanged?: (e: { + target: Area; + component: dxVectorMap; + element: Element; + }) => void; + /** + * A handler for the markerClick event. + * @deprecated Use the 'onClick' option instead + */ + onMarkerClick?: any; + /** + * A handler for the markerSelectionChanged event. + * @deprecated Use the 'onSelecitonChanged' option instead + */ + onMarkerSelectionChanged?: (e: { + target: Marker; + component: dxVectorMap; + element: Element; + }) => void; + /** Disables the panning capability. */ + panningEnabled?: boolean; + } + export interface Legend extends viz.core.BaseLegend { + /** Specifies the color of item markers in the legend. The specified color applied only when the legend uses 'size' source. */ + markerColor?: string; + /** Specifies text for legend items. */ + customizeText?: (itemInfo: { start: number; end: number; index: number; color: string; size: number; }) => string; + /** Specifies text for a hint that appears when a user hovers the mouse pointer over the text of a legend item. */ + customizeHint?: (itemInfo: { start: number; end: number; index: number; color: string; size: number }) => string; + /** Specifies the source of data for the legend. */ + source?: { + /** Specifies a layer to which the legend belongs. */ + layer?: string; + /** Specifies the type of the legend grouping. */ + grouping?: string; + } + } + /** A vector map widget. */ + export class dxVectorMap extends viz.core.BaseWidget { + constructor(element: JQuery, options?: dxVectorMapOptions); + constructor(element: Element, options?: dxVectorMapOptions); + /** Displays the loading indicator. */ + showLoadingIndicator(): void; + /** Conceals the loading indicator. */ + hideLoadingIndicator(): void; + /** Redraws a widget. */ + render(): void; + /** Gets the current coordinates of the map center. */ + center(): Array; + /** Sets the coordinates of the map center. */ + center(centerCoordinates: Array): void; + /** + * Deselects all the selected areas on a map. The areas are displayed in their initial style after. + * @deprecated Use the 'clearSelection' method on a layer instead + */ + clearAreaSelection(): void; + /** + * Deselects all the selected markers on a map. The markers are displayed in their initial style after. + * @deprecated Use the 'clearSelection' method on a layer instead + */ + clearMarkerSelection(): void; + /** Deselects all the selected area and markers on a map at once. The areas and markers are displayed in their initial style after. */ + clearSelection(): void; + /** Converts client area coordinates into map coordinates. */ + convertCoordinates(x: number, y: number): Array; + /** Gets all map layers. */ + getLayers(): Array; + /** Gets the layer by its index. */ + getLayerByIndex(index: number): MapLayer; + /** Gets the layer by its name. */ + getLayerByName(name: string): MapLayer; + /** + * Returns an array with all the map areas. + * @deprecated Use the 'getElements' method on a layer instead + */ + getAreas(): Array; + /** + * Returns an array with all the map markers. + * @deprecated Use the 'getElements' method on a layer instead + */ + getMarkers(): Array; + /** Gets the current coordinates of the map viewport. */ + viewport(): Array; + /** Sets the coordinates of the map viewport. */ + viewport(viewportCoordinates: Array): void; + /** Gets the current value of the map zoom factor. */ + zoomFactor(): number; + /** Sets the value of the map zoom factor. */ + zoomFactor(zoomFactor: number): void; + } + export var projection: ProjectionCreator; + export interface ProjectionCreator { + /** Creates a new projection. */ + (data: { + to?: (coordinates: Array) => Array; + from?: (coordinates: Array) => Array; + aspectRatio?: number; + }): Object; + /** Gets the default or custom projection from the projection storage. */ + get(name: string): Object; + /** Adds a new projection to the internal projections storage. */ + add(name: string, projection: Object): void; + } +} +interface JQuery { + dxVectorMap(options?: DevExpress.viz.map.dxVectorMapOptions): JQuery; + dxVectorMap(methodName: string, ...params: any[]): any; + dxVectorMap(methodName: "instance"): DevExpress.viz.map.dxVectorMap; +} +declare module DevExpress.viz.sparklines { + export interface SparklineTooltip extends viz.core.Tooltip { + /** + * Specifies how a tooltip is horizontally aligned relative to the graph. + * @deprecated Tooltip alignment is no more available. + */ + horizontalAlignment?: string; + /** + * Specifies how a tooltip is vertically aligned relative to the graph. + * @deprecated Tooltip alignment is no more available. + */ + verticalAlignment?: string; + } + export interface BaseSparklineOptions extends viz.core.BaseWidgetOptions { + /** Specifies the blank space between the widget's extreme elements and the boundaries of the area provided for the widget in pixels. */ + margin?: viz.core.Margins; + /** Specifies the size of the widget. */ + size?: viz.core.Size; + /** Specifies tooltip options. */ + tooltip?: SparklineTooltip; + /** A handler for the tooltipShown event. */ + onTooltipShown?: (e: { + component: BaseSparkline; + element: Element; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: BaseSparkline; + element: Element; + }) => void; + } + /** Overridden by descriptions for particular widgets. */ + export class BaseSparkline extends viz.core.BaseWidget { + /** Redraws a widget. */ + render(): void; + } + export interface dxBulletOptions extends BaseSparkline { + /** Specifies a color for the bullet bar. */ + color?: string; + /** Specifies an end value for the invisible scale. */ + endScaleValue?: number; + /** Specifies whether or not to show the target line. */ + showTarget?: boolean; + /** Specifies whether or not to show the line indicating zero on the invisible scale. */ + showZeroLevel?: boolean; + /** Specifies a start value for the invisible scale. */ + startScaleValue?: number; + /** Specifies the value indicated by the target line. */ + target?: number; + /** Specifies a color for both the target and zero level lines. */ + targetColor?: string; + /** Specifies the width of the target line. */ + targetWidth?: number; + /** Specifies the primary value indicated by the bullet bar. */ + value?: number; + } + /** A bullet graph widget. */ + export class dxBullet extends BaseSparkline { + constructor(element: JQuery, options?: dxBulletOptions); + constructor(element: Element, options?: dxBulletOptions); + } + export interface dxSparklineOptions extends BaseSparklineOptions { + /** Specifies the data source field that provides arguments for a sparkline. */ + argumentField?: string; + /** Sets a color for the bars indicating negative values. Available for a sparkline of the bar type only. */ + barNegativeColor?: string; + /** Sets a color for the bars indicating positive values. Available for a sparkline of the bar type only. */ + barPositiveColor?: string; + /** Specifies a data source for the sparkline. */ + dataSource?: Array; + /** Sets a color for the boundary of both the first and last points on a sparkline. */ + firstLastColor?: string; + /** Specifies whether a sparkline ignores null data points or not. */ + ignoreEmptyPoints?: boolean; + /** Sets a color for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineColor?: string; + /** Specifies a width for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineWidth?: number; + /** Sets a color for the bars indicating the values that are less than the winloss threshold. Available for a sparkline of the winloss type only. */ + lossColor?: string; + /** Sets a color for the boundary of the maximum point on a sparkline. */ + maxColor?: string; + /** Sets a color for the boundary of the minimum point on a sparkline. */ + minColor?: string; + /** Sets a color for points on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointColor?: string; + /** Specifies the diameter of sparkline points in pixels. Available for the sparklines of line- and area-like types. */ + pointSize?: number; + /** Specifies a symbol to use as a point marker on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointSymbol?: string; + /** Specifies whether or not to indicate both the first and last values on a sparkline. */ + showFirstLast?: boolean; + /** Specifies whether or not to indicate both the minimum and maximum values on a sparkline. */ + showMinMax?: boolean; + /** Determines the type of a sparkline. */ + type?: string; + /** Specifies the data source field that provides values for a sparkline. */ + valueField?: string; + /** Sets a color for the bars indicating the values greater than a winloss threshold. Available for a sparkline of the winloss type only. */ + winColor?: string; + /** Specifies a value that serves as a threshold for the sparkline of the winloss type. */ + winlossThreshold?: number; + /** Specifies the minimum value of the sparkline value axis. */ + minValue?: number; + /** Specifies the maximum value of the sparkline's value axis. */ + maxValue?: number; + } + /** A sparkline widget. */ + export class dxSparkline extends BaseSparkline { + constructor(element: JQuery, options?: dxSparklineOptions); + constructor(element: Element, options?: dxSparklineOptions); + } +} +interface JQuery { + dxBullet(options?: DevExpress.viz.sparklines.dxBulletOptions): JQuery; + dxBullet(methodName: string, ...params: any[]): any; + dxBullet(methodName: "instance"): DevExpress.viz.sparklines.dxBullet; + dxSparkline(options?: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; + dxSparkline(methodName: string, ...params: any[]): any; + dxSparkline(methodName: "instance"): DevExpress.viz.sparklines.dxSparkline; +} diff --git a/devextreme/devextreme.d.ts b/devextreme/devextreme.d.ts index 3a7d42e05a..d8b1149efd 100644 --- a/devextreme/devextreme.d.ts +++ b/devextreme/devextreme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for DevExtreme 15.2.9 +// Type definitions for DevExtreme 15.2.10 // Project: http://js.devexpress.com/ // Definitions by: DevExpress Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -192,19 +192,19 @@ declare module DevExpress { /** The position object specifies the widget positioning options. */ export interface PositionOptions { /** The target element position that the widget is positioned against. */ - at?: string; + at?: any; /** The element within which the widget is positioned. */ - boundary?: Element; - /** A string value holding horizontal and vertical offset from the window's boundaries. */ - boundaryOffset?: string; + boundary?: Object; + /** Specifies the horizontal and vertical offset from the window's boundaries. */ + boundaryOffset?: any; /** Specifies how to move the widget if it overflows the screen. */ collision?: any; /** The position of the widget to align against the target element. */ - my?: string; + my?: any; /** The target element that the widget is positioned against. */ - of?: HTMLElement; - /** A string value holding horizontal and vertical offset in pixels, separated by a space (e.g., "5 -10"). */ - offset?: string; + of?: Object; + /** Specifies horizontal and vertical offset in pixels. */ + offset?: any; } export interface ComponentOptions { /** A handler for the initialized event. */ @@ -243,6 +243,8 @@ declare module DevExpress { height?: any; /** Specifies the width of the widget. */ width?: any; + /** A bag for holding any options that require two-way binding (Angular approach specific) */ + bindingOptions?: { [key: string]: any; }; } /** A base class for all components. */ export class DOMComponent extends Component { @@ -371,6 +373,8 @@ declare module DevExpress { then(doneFn?: Function, failFn?: Function, progressFn?: Function): Promise; } export interface CustomStoreOptions extends StoreOptions { + /** Specifies whether or not the store combines the search expression with the filter expression. */ + useDefaultSearch?: boolean; /** The user implementation of the byKey(key, extraOptions) method. */ byKey?: (key: any) => Promise; /** The user implementation of the insert(values) method. */ @@ -414,6 +418,8 @@ declare module DevExpress { select?: Object; /** An array of the strings that represent the names of the navigation properties to be loaded simultaneously with the OData store's entity. */ expand?: Object; + /** The bag of custom parameters passed to the query executed when the DataSource load operation is invoked. */ + customQueryParams?: Object; /** Specifies whether or not the DataSource instance requests the total count of items available in the storage. */ requireTotalCount?: boolean; /** Specifies the initial sort option value. */ @@ -477,7 +483,7 @@ declare module DevExpress { /** Returns the searchExpr option value. */ searchExpr(): Object; /** Sets the searchExpr option value. */ - searchExpr(expr: Object): void; + searchExpr(...expr: Object[]): void; /** Returns the currently specified search operation. */ searchOperation(): string; /** Sets the current search operation. */ @@ -502,6 +508,7 @@ declare module DevExpress { store(): Store; /** Returns the number of data items available in an underlying Store after the last load() operation without paging. */ totalCount(): number; + /** Cancels the load operation associated with the specified identifier. */ cancel(operationId: number): boolean; on(eventName: "loadingChanged", eventHandler: (isLoading: boolean) => void): DataSource; on(eventName: "loadError", eventHandler: (e?: Error) => void): DataSource; @@ -913,7 +920,7 @@ declare module DevExpress.ui { /** Specifies whether or not the widget displays unfiltered values until a user types a number of characters exceeding the minSearchLength option value. */ showDataBeforeSearch?: boolean; /** Specifies the name of a data source item field or an expression whose value is compared to the search criterion. */ - searchExpr?: Object; + searchExpr?: any; /** Specifies the binary operation used to filter data. */ searchMode?: string; /** Specifies the time delay, in milliseconds, after the last character has been typed in, before a search is executed. */ @@ -926,7 +933,7 @@ declare module DevExpress.ui { searchEnabled?: boolean; /** * Specifies whether or not the widget displays items by pages. - * @deprecated dataSource.paginate.md + * @deprecated Use the DataSource paging opportunities instead. */ pagingEnabled?: boolean; /** The text or HTML markup displayed by the widget if the item collection is empty. */ @@ -954,7 +961,12 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxToolbarOptions); } export interface dxToastOptions extends dxOverlayOptions { - animation?: fx.AnimationOptions; + animation?: { + /** An object that defines the animation options used when the widget is being shown. */ + show?: fx.AnimationOptions; + /** An object that defines the animation options used when the widget is being hidden. */ + hide?: fx.AnimationOptions; + }; /** The time span in milliseconds during which the dxToast widget is visible. */ displayTime?: number; height?: any; @@ -1130,6 +1142,11 @@ declare module DevExpress.ui { reachBottomText?: string; /** Specifies the text shown in the pullDown panel displayed when the content is being refreshed. */ refreshingText?: string; + } + /** A widget used to display scrollable content. */ + export class dxScrollView extends dxScrollable { + constructor(element: JQuery, options?: dxScrollViewOptions); + constructor(element: Element, options?: dxScrollViewOptions); /** Returns a value indicating if the scrollView content is larger then the widget container. */ isFull(): boolean; /** Locks the widget until the release(preventScrollBottom) method is called and executes the function passed to the onPullDown option and the handler assigned to the pullDown event. */ @@ -1139,11 +1156,6 @@ declare module DevExpress.ui { /** Toggles the loading state of the widget. */ toggleLoading(showOrHide: boolean): void; } - /** A widget used to display scrollable content. */ - export class dxScrollView extends dxScrollable { - constructor(element: JQuery, options?: dxScrollViewOptions); - constructor(element: Element, options?: dxScrollViewOptions); - } export interface dxScrollableLocation { top?: number; left?: number; @@ -1211,8 +1223,27 @@ declare module DevExpress.ui { constructor(element: JQuery, options?: dxRadioGroupOptions); constructor(element: Element, options?: dxRadioGroupOptions); } + export interface dxPopupButtonOptions { + /** Specifies whether or not a toolbar item must be displayed disabled. */ + disabled?: boolean; + /** Specifies html code inserted into the toolbar item element. */ + html?: string; + /** Specifies a location for the item on the toolbar. */ + location?: string; + /** Specifies a configuration object for the widget that presents a toolbar item. */ + options?: Object; + /** Specifies an item template that should be used to render this item only. */ + template?: any; + /** Specifies text displayed for the toolbar item. */ + text?: string; + /** Specifies whether the item is displayed on a top or bottom toolbar. */ + toolbar?: string; + /** Specifies whether or not a widget item must be displayed. */ + visible?: boolean; + /** A widget that presents a toolbar item. */ + widget?: string; + } export interface dxPopupOptions extends dxOverlayOptions { - animation?: fx.AnimationOptions; /** Specifies whether or not to allow a user to drag the popup window. */ dragEnabled?: boolean; /** A Boolean value specifying whether or not to display the widget in full-screen mode. */ @@ -1226,7 +1257,7 @@ declare module DevExpress.ui { titleTemplate?: any; width?: any; /** Specifies items displayed on the top or bottom toolbar of the popup window. */ - buttons?: Array; + buttons?: Array; /** Specifies whether or not the widget displays the Close button. */ showCloseButton?: boolean; /** A handler for the titleRendered event. */ @@ -1238,8 +1269,13 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxPopupOptions); } export interface dxPopoverOptions extends dxPopupOptions { - /** An object defining animation options of the widget. */ - animation?: fx.AnimationOptions; + /** An object that defines the animation options of the widget. */ + animation?: { + /** An object that defines the animation options used when the widget is being shown. */ + show?: fx.AnimationOptions; + /** An object that defines the animation options used when the widget is being hidden. */ + hide?: fx.AnimationOptions; + }; /** Specifies the height of the widget. */ height?: any; /** An object defining widget positioning options. */ @@ -1261,7 +1297,12 @@ declare module DevExpress.ui { } export interface dxOverlayOptions extends WidgetOptions { /** An object that defines the animation options of the widget. */ - animation?: fx.AnimationOptions; + animation?: { + /** An object that defines the animation options used when the widget is being shown. */ + show?: fx.AnimationOptions; + /** An object that defines the animation options used when the widget is being hidden. */ + hide?: fx.AnimationOptions; + }; /** A Boolean value specifying whether or not the widget is closed if a user presses the Back hardware button. */ closeOnBackButton?: boolean; /** A Boolean value specifying whether or not the widget is closed if a user clicks outside of the overlapping window. */ @@ -1435,8 +1476,14 @@ declare module DevExpress.ui { removeRoute(route: any): JQueryPromise; } export interface dxLookupOptions extends dxDropDownListOptions { - /** An object defining widget animation options. */ - animation?: fx.AnimationOptions; + applyValueMode?: string; + /** An object that defines widget animation options. */ + animation?: { + /** An object that defines the animation options used when the widget is being shown. */ + show?: fx.AnimationOptions; + /** An object that defines the animation options used when the widget is being hidden. */ + hide?: fx.AnimationOptions; + }; /** The text displayed on the Cancel button. */ cancelButtonText?: string; /** The text displayed on the Clear button. */ @@ -1492,7 +1539,7 @@ declare module DevExpress.ui { showCancelButton?: boolean; /** * A Boolean value specifying whether the widget loads the next page automatically when you reach the bottom of the list or when a button is clicked. - * @deprecated pageLoadMode.md + * @deprecated Use the pageLoadMode option instead. */ showNextButton?: boolean; /** The title of the lookup window. */ @@ -1516,7 +1563,6 @@ declare module DevExpress.ui { export class dxLookup extends dxDropDownList { constructor(element: JQuery, options?: dxLookupOptions); constructor(element: Element, options?: dxLookupOptions); - /** This section lists the data source fields that are used in a default template for lookup drop-down items. */ } export interface dxLoadPanelOptions extends dxOverlayOptions { /** An object defining the animation options of the widget. */ @@ -1550,6 +1596,13 @@ declare module DevExpress.ui { constructor(element: JQuery, options?: dxLoadIndicatorOptions); constructor(element: Element, options?: dxLoadIndicatorOptions); } + /** An object containing items for a context menu called for a list item. */ + export interface ListOptionsMenuItem { + /** Specifies the menu item text. */ + text?: string; + /** Specifies the function called when the menu item is clicked. */ + action?: (itemElement: Element, itemData: any) => void; + } export interface dxListOptions extends CollectionWidgetOptions { /** A Boolean value specifying whether or not to display a grouped list. */ grouped?: boolean; @@ -1609,7 +1662,7 @@ declare module DevExpress.ui { selectAllText?: string; onSelectAllChanged?: Function; /** Specifies the array of items for a context menu called for a list item. */ - menuItems?: Array; + menuItems?: Array; /** Specifies whether an item context menu is shown when a user holds or swipes an item. */ menuMode?: string; /** Specifies whether or not an end user can delete list items. */ @@ -1751,14 +1804,14 @@ declare module DevExpress.ui { placeholder?: string; /** * Specifies whether or not a user can pick out a date using the drop-down calendar. - * @deprecated Use 'pickerType' option instead. + * @deprecated Use the pickerType option instead. */ useCalendar?: boolean; /** An object or a value, specifying the date and time currently selected using the date box. */ value?: any; /** * Specifies whether or not the widget uses the native HTML input element. - * @deprecated Use 'pickerType' option instead. + * @deprecated Use the pickerType option instead. */ useNative?: boolean; /** Specifies the interval between neighboring values in the popup list in minutes. */ @@ -1801,10 +1854,12 @@ declare module DevExpress.ui { currentDate?: Date; /** Specifies the first day of a week. */ firstDayOfWeek?: number; + /** An object or a value, specifying the date and time currently selected in the calendar. */ + value?: any; /** The latest date the widget allows to select. */ - max?: Date; + max?: any; /** The earliest date the widget allows to select. */ - min?: Date; + min?: any; /** Specifies whether or not the widget displays a button that selects the current date. */ showTodayButton?: boolean; /** Specifies the current calendar zoom level. */ @@ -1843,7 +1898,7 @@ declare module DevExpress.ui { constructor(element: JQuery, options?: dxButtonOptions); constructor(element: Element, options?: dxButtonOptions); } - export interface dxBoxOptions extends CollectionWidget { + export interface dxBoxOptions extends CollectionWidgetOptions { /** Specifies how widget items are aligned along the main direction. */ align?: string; /** Specifies the direction of item positioning in the widget. */ @@ -2189,6 +2244,8 @@ declare module DevExpress.ui { updateDimensions(): JQueryPromise; /** Validates the values of all editors on the form against the list of the validation rules specified for each form item. */ validate(): Object; + /** Resets the editor's value to undefined. */ + resetValues(): void; } } interface JQuery { @@ -2577,7 +2634,6 @@ declare module DevExpress.ui { export class dxDropDownMenu extends Widget { constructor(element: JQuery, options?: dxDropDownEditorOptions); constructor(element: Element, options?: dxDropDownEditorOptions); - /** This section lists the data source fields that are used in a default template for drop-down menu items. */ /** Opens the drop-down menu. */ open(): void; /** Closes the drop-down menu. */ @@ -2850,7 +2906,7 @@ declare module DevExpress.data { declare module DevExpress.ui { export interface dxSchedulerOptions extends WidgetOptions { /** Specifies a date displayed on the current scheduler view by default. */ - currentDate?: Date; + currentDate?: any; /** The earliest date the widget allows you to select. */ min?: Date; /** The latest date the widget allows you to select. */ @@ -2898,7 +2954,7 @@ declare module DevExpress.ui { allowMultiple?: boolean; /** * Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. - * @deprecated Use the 'useColorAsDefault' property instead + * @deprecated Use the useColorAsDefault option instead. */ mainColor?: boolean; /** Indicates whether or not resources of this kind have priority in the color identification of the appointments that have resources of different kinds assigned. */ @@ -3017,7 +3073,7 @@ declare module DevExpress.ui { expandAllEnabled?: boolean; /** * Specifies whether or not a check box is displayed at each tree view item. - * @deprecated Use the showCheckBoxesMode option instead. + * @deprecated Use the showCheckBoxesMode options instead. */ showCheckBoxes?: boolean; /** Specifies the current check boxes display mode. */ @@ -3028,7 +3084,7 @@ declare module DevExpress.ui { expandNodesRecursive?: boolean; /** * Specifies whether the "Select All" check box is displayed over the tree view. - * @deprecated Use the showCheckBoxesMode option instead. + * @deprecated Use the showCheckBoxesMode options instead. */ selectAllEnabled?: boolean; /** Specifies the text displayed at the "Select All" check box. */ @@ -3077,7 +3133,12 @@ declare module DevExpress.ui { } export interface dxMenuBaseOptions extends HierarchicalCollectionWidgetOptions { /** An object that defines the animation options of the widget. */ - animation?: fx.AnimationOptions; + animation?: { + /** An object that defines the animation options used when the widget is being shown. */ + show?: fx.AnimationOptions; + /** An object that defines the animation options used when the widget is being hidden. */ + hide?: fx.AnimationOptions; + }; /** A Boolean value specifying whether or not the widget changes its state when interacting with a user. */ activeStateEnabled?: boolean; /** Specifies the name of the CSS class associated with the menu. */ @@ -3927,7 +3988,7 @@ declare module DevExpress.ui { deleteRow(rowIndex: number): void; /** * Removes a specific row from a grid. - * @deprecated Use the deleteRow() method instead. + * @deprecated Use the deleteRow(rowIndex) method instead. */ removeRow(rowIndex: number): void; /** Saves changes made in a grid. */ @@ -5196,7 +5257,7 @@ declare module DevExpress.viz.charts { }; /** * Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. - * @deprecated use the 'innerRadius' option instead + * @deprecated Use the innerRadius option instead. */ innerRadius?: number; /** An object defining the label configuration options. */ @@ -5207,7 +5268,7 @@ declare module DevExpress.viz.charts { minSegmentSize?: number; /** * Specifies the direction in which the dxPieChart series points are located. - * @deprecated use the 'segmentsDirection' option instead + * @deprecated Use the segmentsDirection option instead. */ segmentsDirection?: string; /**

Specifies the chart elements to highlight when the series is selected.

*/ @@ -5234,7 +5295,7 @@ declare module DevExpress.viz.charts { }; /** * Specifies a start angle for a pie chart in arc degrees. - * @deprecated use the 'startAngle' option instead + * @deprecated Use the startAngle option instead. */ startAngle?: number; /**

Specifies the name of the data source field that provides data about a point.

*/ @@ -5245,14 +5306,14 @@ declare module DevExpress.viz.charts { export interface CommonPieSeriesSettings extends CommonPieSeriesConfig { /** * Specifies the type of the pie chart series. - * @deprecated use the 'type' option instead + * @deprecated Use the type option instead. */ type?: string; } export interface PieSeriesConfig extends CommonPieSeriesConfig { /** * Sets the series type. - * @deprecated use the 'type' option instead + * @deprecated Use the type option instead. */ type?: string; /** Specifies the name that identifies the series. */ @@ -5525,7 +5586,7 @@ declare module DevExpress.viz.charts { /** Specifies the position of the value axis on a chart. */ position?: string; /** Specifies the title for a value axis. */ - title?: AxisTitle; + title?: any; } export interface PolarAxis extends PolarCommonAxisSettings, Axis { /** Defines an array of the value axis constant lines. */ @@ -5952,7 +6013,7 @@ declare module DevExpress.viz.charts { constructor(element: Element, options?: dxPieChartOptions); /** * Provides access to the dxPieChart series. - * @deprecated ..\..\BaseChart\3 Methods\getAllSeries().md + * @deprecated Use the getAllSeries() method instead. */ getSeries(): PieSeries; } @@ -5990,19 +6051,19 @@ declare module DevExpress.viz.gauges { color?: string; /** * Specifies an array of custom minor ticks. - * @deprecated ..\customMinorTicks.md + * @deprecated Use the scale | customMinorTicks option instead. */ customTickValues?: Array; /** Specifies the length of the scale's minor ticks. */ length?: number; /** * Indicates whether automatically calculated minor ticks are visible or not. - * @deprecated This functionality in not more available + * @deprecated This feature is no longer available. */ showCalculatedTicks?: boolean; /** * Specifies an interval between minor ticks. - * @deprecated ..\minorTickInterval.md + * @deprecated Use the scale | minorTickInterval option instead. */ tickInterval?: number; /** Indicates whether scale minor ticks are visible or not. */ @@ -6013,7 +6074,7 @@ declare module DevExpress.viz.gauges { export interface ScaleMajorTick extends ScaleTick { /** * Specifies whether or not to expand the current major tick interval if labels overlap each other. - * @deprecated ..\label\overlappingBehavior\useAutoArrangement.md + * @deprecated Use the overlappingBehavior | useAutoArrangement option instead. */ useTicksAutoArrangement?: boolean; } @@ -6047,22 +6108,22 @@ declare module DevExpress.viz.gauges { endValue?: number; /** * Specifies whether or not to hide the first scale label. - * @deprecated This functionality in not more available + * @deprecated This feature is no longer available. */ hideFirstLabel?: boolean; /** * Specifies whether or not to hide the first major tick on the scale. - * @deprecated This functionality in not more available + * @deprecated This feature is no longer available. */ hideFirstTick?: boolean; /** * Specifies whether or not to hide the last scale label. - * @deprecated This functionality in not more available + * @deprecated This feature is no longer available. */ hideLastLabel?: boolean; /** * Specifies whether or not to hide the last major tick on the scale. - * @deprecated This functionality in not more available + * @deprecated This feature is no longer available. */ hideLastTick?: boolean; /** Specifies an interval between major ticks. */ @@ -6077,7 +6138,7 @@ declare module DevExpress.viz.gauges { label?: BaseScaleLabel; /** * Specifies options of the gauge's major ticks. - * @deprecated ..\tick\tick.md + * @deprecated Use the tick option instead. */ majorTick?: ScaleMajorTick; /** Specifies options of the gauge's major ticks. */ @@ -6153,17 +6214,17 @@ declare module DevExpress.viz.gauges { size?: viz.core.Size; /** * Specifies a subtitle for the widget. - * @deprecated ..\..\..\BaseGauge\1 Configuration\title\subtitle\subtitle.md + * @deprecated Use the title | subtitle option instead. */ subtitle?: { /** * Specifies font options for the subtitle. - * @deprecated ..\..\title\subtitle\font\font.md + * @deprecated Use the title | subtitle | font option instead. */ font?: viz.core.Font; /** * Specifies a text for the subtitle. - * @deprecated ..\title\subtitle\text.md + * @deprecated Use the title | subtitle | text option instead. */ text?: string; }; @@ -6173,7 +6234,7 @@ declare module DevExpress.viz.gauges { font?: viz.core.Font; /** * Specifies a title's position on the gauge. - * @deprecated basegaugeoptions_title_verticalAlignment and basegaugeoptions_title_horizontalAlignment + * @deprecated Use the horizontalAlignment and verticalAlignment options instead. */ position?: string; /** Specifies the distance between the title and surrounding gauge elements in pixels. */ @@ -6350,7 +6411,7 @@ declare module DevExpress.viz.gauges { visible?: boolean; }; /** Sets the name of the palette or an array of colors to be used for coloring the gauge range container. */ - palette?: string; + palette?: any; /** Defines the radius of the bar that is closest to the center relatively to the radius of the topmost bar. */ relativeInnerRadius?: number; /** Specifies a start value for the gauge's invisible scale. */ @@ -6500,7 +6561,7 @@ declare module DevExpress.viz.rangeSelector { logarithmBase?: number; /** * Specifies an interval between major ticks. - * @deprecated ..\tickInterval\tickInterval.md + * @deprecated Use the tickInterval option instead. */ majorTickInterval?: any; /** Specifies an interval between axis ticks. */ @@ -6541,7 +6602,7 @@ declare module DevExpress.viz.rangeSelector { showCustomBoundaryTicks?: boolean; /** * Indicates whether or not to show minor ticks on the scale. - * @deprecated minorTick\visible.md + * @deprecated Use the minorTick | visible option instead. */ showMinorTicks?: boolean; /** Specifies the scale's start value. */ @@ -6630,7 +6691,7 @@ declare module DevExpress.viz.rangeSelector { invalidRangeColor?: string; /** * Specifies the empty space between the marker's border and the marker’s text. - * @deprecated Use the 'paddingTopBottom' and 'paddingLeftRight' options instead + * @deprecated Use the paddingTopBottom and paddingLeftRight options instead. */ padding?: number; /** Specifies the empty space between the marker's top and bottom borders and the marker's text. */ @@ -6641,7 +6702,7 @@ declare module DevExpress.viz.rangeSelector { placeholderHeight?: number; /** * Specifies in pixels the height and width of the space reserved for the range selector slider markers. - * @deprecated Use the 'placeholderHeight' and 'indent' options instead + * @deprecated Use the placeholderHeight and indent options instead. */ placeholderSize?: { /** Specifies the height of the placeholder for the left and right slider markers. */ @@ -6716,88 +6777,88 @@ declare module DevExpress.viz.map { } /** * This section describes the fields and methods that can be used in code to manipulate the Area object. - * @deprecated Use the "Layer Element" instead + * @deprecated Use the Layer Element instead. */ export interface Area { /** * Contains the element type. - * @deprecated ..\..\Layer\2 Fields\type.md + * @deprecated Use the Layer | type instead. */ type: string; /** * Return the value of an attribute. - * @deprecated ..\..\Layer Element\3 Methods\attribute(name_value).md + * @deprecated Use the Layer Element | attribute(name, value) method instead. */ attribute(name: string): any; /** * Provides information about the selection state of an area. - * @deprecated Use the "selected()" method of the Layer Element + * @deprecated Use the Layer Element | selected() method instead. */ selected(): boolean; /** * Sets a new selection state for an area. - * @deprecated Use the "selected(state)" method of the Layer Element + * @deprecated Use the Layer Element | selected(state) method instead. */ selected(state: boolean): void; /** * Applies the area settings specified as a parameter and updates the area appearance. - * @deprecated ..\..\Layer Element\3 Methods\applySettings(settings).md + * @deprecated Use the Layer Element | applySettings(settings) method instead. */ applySettings(settings: any): void; } /** * This section describes the fields and methods that can be used in code to manipulate the Markers object. - * @deprecated Use the "Layer Element" instead + * @deprecated Use the Layer Element instead. */ export interface Marker { /** * Contains the descriptive text accompanying the map marker. - * @deprecated Get the text with the "attribute" method (using the "layers.label.dataField" value) + * @deprecated Get the text using the Layer Element | attribute(name) method. The name parameter value for text is set at the dataField option. */ text: string; /** * Contains the type of the element. - * @deprecated ..\..\Layer\2 Fields\type.md + * @deprecated Use the Layer | type instead. */ type: string; /** * Contains the URL of an image map marker. - * @deprecated Get the url with the "attribute" method (using the "layers.dataField" value) + * @deprecated Get the image URL using the Layer Element | attribute(name) method. The name parameter value for the image URL is set at the dataField option. */ url: string; /** * Contains the value of a bubble map marker. - * @deprecated Get the value with the "attribute" method (using the "layers.dataField" value) + * @deprecated Get the bubble value using the Layer Element | attribute(name) method. The name parameter for the bubble value is set at the dataField option. */ value: number; /** * Contains the values of a pie map marker. - * @deprecated Get the values with the "attribute" method (using the "layers.dataField" value) + * @deprecated Get the pie values using the Layer Element | attribute(name) method. The name parameter for pie values is set at the dataField option. */ values: Array; /** * Returns the value of an attribute. - * @deprecated ..\..\Layer Element\3 Methods\attribute(name_value).md + * @deprecated Use the Layer Element | attribute(name, value) method instead. */ attribute(name: string): any; /** * Returns the coordinates of a specific marker. - * @deprecated ..\..\Layer Element\3 Methods\coordinates().md + * @deprecated Use the Layer Element | coordinates() method instead. */ coordinates(): Array; /** * Provides information about the selection state of a marker. - * @deprecated Use the "selected()" method of the Layer Element + * @deprecated Use the Layer Element | selected() method instead. */ selected(): boolean; /** * Sets a new selection state for a marker. - * @deprecated Use the "selected(state)" method of the Layer Element + * @deprecated Use the Layer Element | selected(state) method instead. */ selected(state: boolean): void; /** * Applies the marker settings specified as a parameter and updates marker appearance. - * @deprecated ..\..\Layer Element\3 Methods\applySettings(settings).md + * @deprecated Use the Layer Element | applySettings(settings) method instead. */ applySettings(settings: any): void; } @@ -6809,7 +6870,7 @@ declare module DevExpress.viz.map { /** Specifies the type of a marker element. Setting this option makes sense only if the layer type is "marker". */ elementType?: string; /** Specifies a data source for the layer. */ - data?: any; + dataSource?: any; /** Specifies the line width (for layers of a line type) or width of the layer elements border in pixels. */ borderWidth?: number; /** Specifies a color for the border of the layer elements. */ @@ -6858,7 +6919,7 @@ declare module DevExpress.viz.map { customize?: (eleemnts: Array) => void; /** Specifies marker label options. */ label?: { - /** The name of the data attribute containing marker texts. */ + /** The name of the dataSource attribute containing marker texts. */ dataField?: string; /** Enables marker labels. */ enabled?: boolean; @@ -6869,238 +6930,238 @@ declare module DevExpress.viz.map { export interface AreaSettings { /** * Specifies the width of the area border in pixels. - * @deprecated ..\layers\borderWidth.md + * @deprecated Use the layers | borderWidth option instead. */ borderWidth?: number; /** * Specifies a color for the area border. - * @deprecated ..\layers\borderColor.md + * @deprecated Use the layers | borderColor option instead. */ borderColor?: string; /** * Specifies a color for an area. - * @deprecated ..\layers\color.md + * @deprecated Use the layers | color option instead. */ color?: string; /** * Specifies the function that customizes each area individually. - * @deprecated ..\layers\customize.md + * @deprecated Use the layers | customize option instead. */ customize?: (areaInfo: Area) => AreaSettings; /** * Specifies a color for the area border when the area is hovered over. - * @deprecated ..\layers\hoveredBorderColor.md + * @deprecated Use the layers | hoveredBorderColor option instead. */ hoveredBorderColor?: string; /** * Specifies the pixel-measured width of the area border when the area is hovered over. - * @deprecated ..\layers\hoveredBorderWidth.md + * @deprecated Use the layers | hoveredBorderWidth option instead. */ hoveredBorderWidth?: number; /** * Specifies a color for an area when this area is hovered over. - * @deprecated ..\layers\hoveredColor.md + * @deprecated Use the layers | hoveredColor option instead. */ hoveredColor?: string; /** * Specifies whether or not to change the appearance of an area when it is hovered over. - * @deprecated ..\layers\hoverEnabled.md + * @deprecated Use the layers | hoverEnabled option instead. */ hoverEnabled?: boolean; /** * Configures area labels. - * @deprecated ..\..\layers\label\label.md + * @deprecated Use the layers | label option instead. */ label?: { /** * Specifies the data field that provides data for area labels. - * @deprecated ..\..\layers\label\dataField.md + * @deprecated Use the layers | label | dataField option instead. */ dataField?: string; /** * Enables area labels. - * @deprecated ..\..\layers\label\enabled.md + * @deprecated Use the layers | label | enabled option instead. */ enabled?: boolean; /** * Specifies font options for area labels. - * @deprecated ..\..\..\layers\label\font\font.md + * @deprecated Use the layers | label | font option instead. */ font?: viz.core.Font; }; /** * Specifies the name of the palette or a custom range of colors to be used for coloring a map. - * @deprecated ..\layers\palette.md + * @deprecated Use the layers | palette option instead. */ palette?: any; /** * Specifies the number of colors in a palette. - * @deprecated ..\layers\paletteSize.md + * @deprecated Use the layers | paletteSize option instead. */ paletteSize?: number; /** * Allows you to paint areas with similar attributes in the same color. - * @deprecated ..\layers\colorGroups.md + * @deprecated Use the layers | colorGroups option instead. */ colorGroups?: Array; /** * Specifies the field that provides data to be used for coloring areas. - * @deprecated ..\layers\colorGroupingField.md + * @deprecated Use the layers | colorGroupingField option instead. */ colorGroupingField?: string; /** * Specifies a color for the area border when the area is selected. - * @deprecated ..\layers\selectedBorderColor.md + * @deprecated Use the layers | selectedBorderColor option instead. */ selectedBorderColor?: string; /** * Specifies a color for an area when this area is selected. - * @deprecated ..\layers\selectedColor.md + * @deprecated Use the layers | selectedColor option instead. */ selectedColor?: string; /** * Specifies the pixel-measured width of the area border when the area is selected. - * @deprecated ..\layers\selectedBorderWidth.md + * @deprecated Use the layers | selectedBorderWidth option instead. */ selectedBorderWidth?: number; /** * Specifies whether single or multiple areas can be selected on a vector map. - * @deprecated ..\layers\selectionMode.md + * @deprecated Use the layers | selectionMode option instead. */ selectionMode?: string; } export interface MarkerSettings { /** * Specifies a color for the marker border. - * @deprecated ..\layers\borderColor.md + * @deprecated Use the layers | borderColor option instead. */ borderColor?: string; /** * Specifies the width of the marker border in pixels. - * @deprecated ..\layers\borderWidth.md + * @deprecated Use the layers | borderWidth option instead. */ borderWidth?: number; /** * Specifies a color for a marker of the dot or bubble type. - * @deprecated ..\layers\color.md + * @deprecated Use the layers | color option instead. */ color?: string; /** * Specifies the function that customizes each marker individually. - * @deprecated ..\layers\customize.md + * @deprecated Use the layers | customize option instead. */ customize?: (markerInfo: Marker) => MarkerSettings; /** * Specifies the pixel-measured width of the marker border when the marker is hovered over. - * @deprecated ..\layers\hoveredBorderWidth.md + * @deprecated Use the layers | hoveredBorderWidth option instead. */ hoveredBorderWidth?: number; /** * Specifies a color for the marker border when the marker is hovered over. - * @deprecated ..\layers\hoveredBorderColor.md + * @deprecated Use the layers | hoveredBorderColor option instead. */ hoveredBorderColor?: string; /** * Specifies a color for a marker of the dot or bubble type when this marker is hovered over. - * @deprecated ..\layers\hoveredColor.md + * @deprecated Use the layers | hoveredColor option instead. */ hoveredColor?: string; /** * Specifies whether or not to change the appearance of a marker when it is hovered over. - * @deprecated ..\layers\hoverEnabled.md + * @deprecated Use the layers | hoverEnabled option instead. */ hoverEnabled?: boolean; /** * Specifies marker label options. - * @deprecated ..\..\layers\label\label.md + * @deprecated Use the layers | label option instead. */ label?: { /** * Enables marker labels. - * @deprecated ..\..\layers\label\enabled.md + * @deprecated Use the layers | label | enabled option instead. */ enabled?: boolean; /** * Specifies font options for marker labels. - * @deprecated ..\..\..\layers\label\font\font.md + * @deprecated Use the layers | label | font option instead. */ font?: viz.core.Font; }; /** * Specifies the pixel-measured diameter of the marker that represents the biggest value. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated ..\layers\maxSize.md + * @deprecated Use the layers | maxSize option instead. */ maxSize?: number; /** * Specifies the pixel-measured diameter of the marker that represents the smallest value. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated ..\layers\minSize.md + * @deprecated Use the layers | minSize option instead. */ minSize?: number; /** * Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. - * @deprecated ..\layers\opacity.md + * @deprecated Use the layers | opacity option instead. */ opacity?: number; /** * Specifies the pixel-measured width of the marker border when the marker is selected. - * @deprecated ..\layers\selectedBorderWidth.md + * @deprecated Use the layers | selectedBorderWidth option instead. */ selectedBorderWidth?: number; /** * Specifies a color for the marker border when the marker is selected. - * @deprecated ..\layers\selectedBorderColor.md + * @deprecated Use the layers | selectedBorderColor option instead. */ selectedBorderColor?: string; /** * Specifies a color for a marker of the dot or bubble type when this marker is selected. - * @deprecated ..\layers\selectedColor.md + * @deprecated Use the layers | selectedColor option instead. */ selectedColor?: string; /** * Specifies whether a single or multiple markers can be selected on a vector map. - * @deprecated ..\layers\selectionMode.md + * @deprecated Use the layers | selectionMode option instead. */ selectionMode?: string; /** * Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. - * @deprecated ..\layers\size.md + * @deprecated Use the layers | size option instead. */ size?: number; /** * Specifies the type of markers to be used on the map. - * @deprecated ..\layers\elementType.md + * @deprecated Use the layers | elementType option instead. */ type?: string; /** * Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. - * @deprecated ..\layers\palette.md + * @deprecated Use the layers | palette option instead. */ palette?: any; /** * Allows you to paint markers with similar attributes in the same color. - * @deprecated ..\layers\colorGroups.md + * @deprecated Use the layers | colorGroups option instead. */ colorGroups?: Array; /** * Specifies the field that provides data to be used for coloring markers. - * @deprecated ..\layers\colorGroupingField.md + * @deprecated Use the layers | colorGroupingField option instead. */ colorGroupingField?: string; /** * Allows you to display bubbles with similar attributes in the same size. - * @deprecated ..\layers\sizeGroups.md + * @deprecated Use the layers | sizeGroups option instead. */ sizeGroups?: Array; /** * Specifies the field that provides data to be used for sizing bubble markers. - * @deprecated ..\layers\sizeGroupingField.md + * @deprecated Use the layers | sizeGroupingField option instead. */ sizeGroupingField?: string; } export interface dxVectorMapOptions extends viz.core.BaseWidgetOptions { /** * An object specifying options for the map areas. - * @deprecated Use the 'layers' option instead + * @deprecated Use the "area" type element of the layers array. */ areaSettings?: AreaSettings; /** Specifies the options for the map background. */ @@ -7130,24 +7191,24 @@ declare module DevExpress.viz.map { horizontalAlignment?: string; /** Specifies the position of the control bar. */ verticalAlignment?: string; - /** Specifies the opacity of the Control_Bar. */ + /** Specifies the opacity of the control bar. */ opacity?: number; }; /** Specifies the appearance of the loading indicator. */ loadingIndicator?: viz.core.LoadingIndicator; /** * Specifies a data source for the map area. - * @deprecated Use the 'layers.data' option instead + * @deprecated Use the layers | dataSource option instead. */ mapData?: any; /** * Specifies a data source for the map markers. - * @deprecated Use the 'layers.data' option instead + * @deprecated Use the layers | dataSource option instead. */ markers?: any; /** * An object specifying options for the map markers. - * @deprecated Use the 'layers' option instead + * @deprecated Use the "marker" type element of the layers array. */ markerSettings?: MarkerSettings; /** Specifies the size of the dxVectorMap widget. */ @@ -7204,12 +7265,12 @@ declare module DevExpress.viz.map { }) => void; /** * A handler for the areaClick event. - * @deprecated Use the 'onClick' option instead + * @deprecated Use the onClick option instead. */ onAreaClick?: any; /** * A handler for the areaSelectionChanged event. - * @deprecated Use the 'onSelectionChanged' option instead + * @deprecated Use the onSelectionChanged option instead. */ onAreaSelectionChanged?: (e: { target: Area; @@ -7218,12 +7279,12 @@ declare module DevExpress.viz.map { }) => void; /** * A handler for the markerClick event. - * @deprecated Use the 'onClick' option instead + * @deprecated Use the onClick option instead. */ onMarkerClick?: any; /** * A handler for the markerSelectionChanged event. - * @deprecated Use the 'onSelecitonChanged' option instead + * @deprecated Use the onSelecitonChanged option instead. */ onMarkerSelectionChanged?: (e: { target: Marker; @@ -7264,12 +7325,12 @@ declare module DevExpress.viz.map { center(centerCoordinates: Array): void; /** * Deselects all the selected areas on a map. The areas are displayed in their initial style after. - * @deprecated Use the 'clearSelection' method on a layer instead + * @deprecated Use the layer's clearSelection() method instead. */ clearAreaSelection(): void; /** * Deselects all the selected markers on a map. The markers are displayed in their initial style after. - * @deprecated Use the 'clearSelection' method on a layer instead + * @deprecated Use the layer's clearSelection() method instead. */ clearMarkerSelection(): void; /** Deselects all the selected area and markers on a map at once. The areas and markers are displayed in their initial style after. */ @@ -7284,12 +7345,12 @@ declare module DevExpress.viz.map { getLayerByName(name: string): MapLayer; /** * Returns an array with all the map areas. - * @deprecated Use the 'getElements' method on a layer instead + * @deprecated Use the layer's getElements() method instead. */ getAreas(): Array; /** * Returns an array with all the map markers. - * @deprecated Use the 'getElements' method on a layer instead + * @deprecated Use the layer's getElements() method instead. */ getMarkers(): Array; /** Gets the current coordinates of the map viewport. */ @@ -7324,12 +7385,12 @@ declare module DevExpress.viz.sparklines { export interface SparklineTooltip extends viz.core.Tooltip { /** * Specifies how a tooltip is horizontally aligned relative to the graph. - * @deprecated Tooltip alignment is no more available. + * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. */ horizontalAlignment?: string; /** * Specifies how a tooltip is vertically aligned relative to the graph. - * @deprecated Tooltip alignment is no more available. + * @deprecated Tooltip alignment is no longer useful because the tooltips are aligned automatically. */ verticalAlignment?: string; } @@ -7389,7 +7450,7 @@ declare module DevExpress.viz.sparklines { /** Sets a color for the bars indicating positive values. Available for a sparkline of the bar type only. */ barPositiveColor?: string; /** Specifies a data source for the sparkline. */ - dataSource?: Array; + dataSource?: any; /** Sets a color for the boundary of both the first and last points on a sparkline. */ firstLastColor?: string; /** Specifies whether a sparkline ignores null data points or not. */ @@ -7440,4 +7501,4 @@ interface JQuery { dxSparkline(options?: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; dxSparkline(methodName: string, ...params: any[]): any; dxSparkline(methodName: "instance"): DevExpress.viz.sparklines.dxSparkline; -} +} \ No newline at end of file diff --git a/df-visible/df-visible-tests.ts b/df-visible/df-visible-tests.ts new file mode 100644 index 0000000000..c5a8f1bf2b --- /dev/null +++ b/df-visible/df-visible-tests.ts @@ -0,0 +1,35 @@ +/// + +// https://github.com/customd/jquery-visible/blob/master/examples/demo-basic.html +$(function(){ + + // Add the spans to the container element. + $('#container dt').each(function(){ $(this).append(''); }); + + // Trigger the + $('#detect').on('click',function(){ + + // Select the detection type. + var detectPartial = $('#detect_type').val() == 'partial'; + + // Loop over each container, and check if it's visible. + $('#container dt').each(function(){ + + // Is this element visible onscreen? + var visible = $(this).visible( detectPartial ); + + // Set the visible status into the span. + $(this).find('span').text( visible ? 'Onscreen' : 'Offscreen' ).toggleClass('visible',visible); + }); + }); +}); + +// https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery +// Check both vertical, and horizontal at once +$('#element').visible(true, false, 'both'); + +// Check only horizontal +$('#element').visible(true, false, 'horizontal'); + +// Check only vertical +$('#element').visible(true, false, 'vertical'); diff --git a/df-visible/df-visible.d.ts b/df-visible/df-visible.d.ts new file mode 100644 index 0000000000..b8d05fe360 --- /dev/null +++ b/df-visible/df-visible.d.ts @@ -0,0 +1,18 @@ +// Type definitions for jquery-visible +// Project: https://github.com/customd/jquery-visible +// Definitions by: Andrey Lipatkin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type Direction = "horizontal" | "vertical" | "both"; + +interface JQuery { + /** + * Gets the value of a setting. + * @param details Which setting to consider. + * @param callback The callback parameter should be a function that looks like this: + * function(object details) {...}; + */ + visible(partial?: boolean, hidden?: boolean, direction?: Direction): boolean; +} diff --git a/dhtmlxgantt/dhtmlxgantt-tests.ts b/dhtmlxgantt/dhtmlxgantt-tests.ts index 1bfc7a089f..dd05b50bff 100644 --- a/dhtmlxgantt/dhtmlxgantt-tests.ts +++ b/dhtmlxgantt/dhtmlxgantt-tests.ts @@ -30,4 +30,8 @@ gantt.load("/data/events"); //events gantt.attachEvent("onBeforeLightbox", function (id?: string) { gantt.showTask(id); -}); \ No newline at end of file +}); + +//gantt enterprise +var gantt2 = Gantt.getGanttInstance(); +gantt2.config.api_date = "format"; \ No newline at end of file diff --git a/dhtmlxgantt/dhtmlxgantt.d.ts b/dhtmlxgantt/dhtmlxgantt.d.ts index f9ec6808cd..a9542cc00f 100644 --- a/dhtmlxgantt/dhtmlxgantt.d.ts +++ b/dhtmlxgantt/dhtmlxgantt.d.ts @@ -1,9 +1,12 @@ -// Type definitions for dhtmlxGantt 2.0 +// Type definitions for dhtmlxGantt 4.0.0 // Project: http://dhtmlx.com/docs/products/dhtmlxGantt // Definitions by: Maksim Kozhukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface GanttCallback { (...args: any[]) : any } +type GanttEventName ='onAfterAutoSchedule'|'onAfterBatchUpdate'|'onAfterLightbox'|'onAfterLinkAdd'|'onAfterLinkDelete'|'onAfterLinkUpdate'|'onAfterRedo'|'onAfterTaskAdd'|'onAfterTaskAutoSchedule'|'onAfterTaskDelete'|'onAfterTaskDrag'|'onAfterTaskMove'|'onAfterTaskUpdate'|'onAfterUndo'|'onAjaxError'|'onBeforeAutoSchedule'|'onBeforeBatchUpdate'|'onBeforeCollapse'|'onBeforeDataRender'|'onBeforeExpand'|'onBeforeGanttReady'|'onBeforeGanttRender'|'onBeforeLightbox'|'onBeforeLinkAdd'|'onBeforeLinkDelete'|'onBeforeLinkDisplay'|'onBeforeLinkUpdate'|'onBeforeParse'|'onBeforeRedo'|'onBeforeRowDragEnd'|'onBeforeTaskAdd'|'onBeforeTaskAutoSchedule'|'onBeforeTaskChanged'|'onBeforeTaskDelete'|'onBeforeTaskDisplay'|'onBeforeTaskDrag'|'onBeforeTaskMove'|'onBeforeTaskSelected'|'onBeforeTaskUpdate'|'onBeforeUndo'|'onCircularLinkError'|'onClear'|'onCollapse'|'onColumnResize'|'onColumnResizeEnd'|'onColumnResizeStart'|'onContextMenu'|'onDataRender'|'onEmptyClick'|'onError'|'onExpand'|'onGanttReady'|'onGanttRender'|'onGanttScroll'|'onGridHeaderClick'|'onGridResize'|'onGridResizeEnd'|'onGridResizeStart'|'onLightbox'|'onLightboxButton'|'onLightboxCancel'|'onLightboxChange'|'onLightboxDelete'|'onLightboxSave'|'onLinkClick'|'onLinkDblClick'|'onLinkIdChange'|'onLinkValidation'|'onLoadEnd'|'onLoadStart'|'onMouseMove'|'onOptionsLoad'|'onParse'|'onRowDragEnd'|'onRowDragStart'|'onScaleAdjusted'|'onScaleClick'|'onTaskClick'|'onTaskClosed'|'onTaskCreated'|'onTaskDblClick'|'onTaskDrag'|'onTaskIdChange'|'onTaskLoading'|'onTaskOpened'|'onTaskRowClick'|'onTaskSelected'|'onTaskUnselected'|'onTemplatesReady'; + interface GanttTemplates{ /** * specifies the format of dates that are set by means of API methods. Used to parse incoming dates @@ -12,10 +15,11 @@ interface GanttTemplates{ api_date(date: Date): string; /** - * specifies the format of dates in the "Start time" column + * specifies the content of start date or end date columns in grid * @param date the date which needs formatting + * @param task the task object */ - date_grid(date: Date): string; + date_grid(date: Date, task: any): string; /** * specifies the date format of the time scale (X-Axis) @@ -30,7 +34,7 @@ interface GanttTemplates{ * @param to the id of the target task( 'null' or 'undefined', if the target task isn't specified yet) * @param to_start true, if the link is being dragged to the start of the target task, false - if
to the end of the task */ - drag_link(from: any, from_start: boolean, to: any, to_start: boolean): string; + drag_link(from: string|number, from_start: boolean, to: string|number, to_start: boolean): string; /** * specifies the CSS class that will be applied to the link receiver (pop-up circle near the task bar) @@ -39,7 +43,7 @@ interface GanttTemplates{ * @param to the id of the target task( 'null' or 'undefined', if the target task isn't specified yet) * @param to_start true, if the link is being dragged to the start of the target task, false - if
to the end of the task */ - drag_link_class(from: any, from_start: boolean, to: any, to_start: boolean): string; + drag_link_class(from: string|number, from_start: boolean, to: string|number, to_start: boolean): string; /** * specifies the custom content inserted before the labels of child items in the tree column @@ -47,6 +51,12 @@ interface GanttTemplates{ */ grid_blank(task: any): string; + /** + * specifies the format of dates in the "Start time" column + * @param date the date which needs formatting + */ + grid_date_format(date: Date): string; + /** * specifies the icon of child items in the tree column * @param task the task object @@ -61,10 +71,10 @@ interface GanttTemplates{ /** * specifies the CSS class that will be applied to the headers of the table's columns - * @param column the column's configuration object - * @param config the column's id ('name' attribute) + * @param columnName the column's name (as specified in the "name" property of the column object) + * @param column column object (as specified in the gantt.config.columns config) */ - grid_header_class(column: any, config: string): string; + grid_header_class(columnName: string, column: any): string; /** * specifies the indent of the child items in a branch (in the tree column) @@ -106,6 +116,14 @@ interface GanttTemplates{ */ progress_text(start: Date, end: Date, task: any): string; + /** + * specifies the CSS class that will be applied to the pop-up edit form + * @param start the date when a task is scheduled to begin + * @param end the date when a task is scheduled to be completed + * @param task the task object + */ + quick_info_class(start: Date, end: Date, task: any): void; + /** * specifies the content of the pop-up edit form * @param start the date when a task is scheduled to begin @@ -131,11 +149,17 @@ interface GanttTemplates{ quick_info_title(start: Date, end: Date, task: any): string; /** - * specifies the CSS class that will be applied to the time scale of the timeline area + * specifies the CSS class that will be applied to cells of the time scale of the timeline area * @param date the date of a cell */ scale_cell_class(date: Date): string; + /** + * specifies the CSS class that will be applied to the time scale + * @param scale the scale's configuration object + */ + scale_row_class(scale: any): string; + /** * specifies the CSS class that will be applied to the cells of the timeline area * @param item the task object assigned to the row @@ -181,6 +205,12 @@ interface GanttTemplates{ */ task_time(start: Date, end: Date, task: any): string; + /** + * specifies the dates of unscheduled tasks + * @param task the task object + */ + task_unscheduled_time(task: any): void; + /** * specifies the format of the drop-down time selector in the lightbox * @param date the date which needs formatting @@ -227,35 +257,83 @@ interface GanttTemplates{ * @param end the date when a task is scheduled to be completed * @param task the task object */ - leftside_text(start: Date, end: Date, task: any): string; + leftside_text(start: Date, end: Date, task: any): string; + + /** + * specifies the lightbox's header + * @param start_date the date when a task is scheduled to begin + * @param end_date the date when a task is scheduled to be completed + * @param task the task's object + */ + lightbox_header(start_date: Date, end_date: Date, task: any): string; + } interface GanttConfigOptions{ /** - * sets the date format that will be used by the addTask() method to -parse the start_date, end_date properties in case they are specified as strings + * sets the date format for addTask() method to */ api_date: string; + /** + * enables auto scheduling + */ + auto_scheduling: boolean; + + /** + * allows or forbids creation of links from parent tasks (projects) to their children + */ + auto_scheduling_descendant_links: boolean; + + /** + * defines whether gantt will do autoscheduling on data loading + */ + auto_scheduling_initial: boolean; + + /** + * enables the auto scheduling mode, in which tasks will always be rescheduled to the earliest possible date + */ + auto_scheduling_strict: boolean; + /** * enables automatic adjusting of the grid's columns to the grid's width */ autofit: boolean; + /** + * forces the Gantt chart to automatically change its size to show all tasks without scrolling + */ + autosize: boolean|string; + + /** + * sets the minimum width (in pixels) that the Gantt chart can take in the horizontal 'autosize' mode + */ + autosize_min_width: number; + + /** + * enables the dynamic loading in the Gantt chart + */ + branch_loading: boolean; + /** * stores a collection of buttons resided in the left bottom corner of the lightbox */ - buttons_left: any; + buttons_left: any[]; /** * stores a collection of buttons resided in the right bottom corner of the lightbox */ - buttons_right: any; + buttons_right: any[]; /** * configures the columns of the table */ - columns: any; + columns: any[]; + + /** + * enables adjusting the task's start and end dates to the work time (while dragging) + */ + correct_work_time: boolean; /** * sets the format of dates in the "Start time" column of the table @@ -313,12 +391,17 @@ parse the start_date, end_date properties in case they are specified as strings duration_step: number; /** - * sets the duration unit in milliseconds + * sets the duration unit */ - duration_unit: number; + duration_unit: string; /** - * sets the end value of the time scale (X–Axis) + * changes the name of a property that affects the editing ability of tasks/links in the read-only Gantt chart + */ + editable_property: string; + + /** + * sets the end value of the time scale */ end_date: Date; @@ -327,16 +410,51 @@ parse the start_date, end_date properties in case they are specified as strings */ fit_tasks: boolean; + /** + * makes the grid resizable by dragging the right grid's border + */ + grid_resize: boolean; + + /** + * sets the name of the attribute of the grid resizer's DOM element + */ + grid_resizer_attribute: string; + + /** + * sets the name of the attribute of the column resizer's DOM element. The attribute presents the column's index + */ + grid_resizer_column_attribute: string; + /** * sets the maximum width of the grid */ grid_width: number; + /** + * shows the critical path in the chart + */ + highlight_critical_path: boolean; + + /** + * specifies whether sub-scales shall use the scale_cell_class template by default + */ + inherit_scale_class: boolean; + /** * sets whether the timeline area will be initially scrolled to display the earliest task */ initial_scroll: boolean; + /** + * 'says' to preserve the initial grid's width during resizing the columns within + */ + keep_grid_width: boolean; + + /** + * sets the name of the attribute of the task layer's DOM element + */ + layer_attribute: string; + /** * specifies the lightbox object */ @@ -373,7 +491,7 @@ parse the start_date, end_date properties in case they are specified as strings links: any; /** - * sets the minimum width for a column + * sets the minimum width for a column in the timeline area */ min_column_width: number; @@ -382,26 +500,76 @@ parse the start_date, end_date properties in case they are specified as strings */ min_duration: number; + /** + * sets the minumum width for the grid (in pixels) while being resized + */ + min_grid_column_width: number; + + /** + * enables/disables multi-task selection in the Gantt chart + */ + multiselect: boolean; + + /** + * specifies whether multi-task selection will be available within one or any level + */ + multiselect_one_level: boolean; + + /** + * openes all branches initially + */ + open_tree_initially: boolean; + /** * activates the 'branch' mode that allows dragging tasks only within the parent branch */ order_branch: boolean; + /** + * activates the 'branch' mode that allows dragging tasks within the whole gantt + */ + order_branch_free: boolean; + + /** + * preserves the current position of the vertical and horizontal scrolls while re-drawing the gantt chart + */ + preserve_scroll: boolean; + + /** + * specifies whether the gantt container should block the mousewheel event, or should it be propagated up to the window element + */ + prevent_default_scroll: boolean; + /** * defines whether the task form will appear from the left/right side of the screen or near the selected task */ quick_info_detached: boolean; /** - * stores a collection of buttons resided in the pop-up edit form + * stores a collection of buttons resided in the pop-up task's details form */ - quickinfo_buttons: any; + quickinfo_buttons: any[]; /** * activates the read-only mode for the Gantt chart */ readonly: boolean; + /** + * changes the name of a property that affects the read-only behaviour of tasks/links + */ + readonly_property: string; + + /** + * enables the Redo functionality for the gantt + */ + redo: boolean; + + /** + * sets the id of the virtual root element + */ + root_id: string|number; + /** * enables rounding the task's start and end dates to the nearest scale marks */ @@ -417,11 +585,21 @@ parse the start_date, end_date properties in case they are specified as strings */ scale_height: number; + /** + * sets the minimal scale unit (in case multiple scales are used) as the interval of leading/closing empty space + */ + scale_offset_minimal: boolean; + /** * sets the unit of the time scale (X-Axis) */ scale_unit: string; + /** + * specifies whether the timeline area shall be scrolled while selecting to display the selected task + */ + scroll_on_click: boolean; + /** * enables selection of tasks in the Gantt chart */ @@ -433,17 +611,67 @@ parse the start_date, end_date properties in case they are specified as strings server_utc: boolean; /** - * enables showing a progress/spinner while data is loading + * shows the chart (timeline) area of the Gantt chart + */ + show_chart: boolean; + + /** + * enables showing error alerts in case of unexpected behavior + */ + show_errors: boolean; + + /** + * shows the grid area of the Gantt chart + */ + show_grid: boolean; + + /** + * enables/disables displaying links in the Gantt chart + */ + show_links: boolean; + + /** + * shows/hides markers on the page + */ + show_markers: boolean; + + /** + * enables displaying of the progress inside the task bars */ show_progress: boolean; + /** + * activates/disables the 'quick_info' extension (pop-up task's details form) + */ + show_quick_info: boolean; + + /** + * enables/disables displaying column borders in the chart area + */ + show_task_cells: boolean; + + /** + * enables showing unscheduled tasks + */ + show_unscheduled: boolean; + + /** + * hides non-working time from the time scale + */ + skip_off_time: boolean; + + /** + * enables the smart rendering mode for gantt's tasks and links rendering + */ + smart_rendering: boolean; + /** * enables sorting in the table */ sort: boolean; /** - * sets the start value of the time scale (X–Axis) + * sets the start value of the time scale */ start_date: Date; @@ -452,6 +680,11 @@ parse the start_date, end_date properties in case they are specified as strings */ start_on_monday: boolean; + /** + * generates a background image for the timeline area instead of rendering actual columns' and rows' lines + */ + static_background: boolean; + /** * sets the step of the time scale (X-Axis) */ @@ -460,7 +693,7 @@ parse the start_date, end_date properties in case they are specified as strings /** * specifies the second time scale(s) */ - subscales: any; + subscales: any[]; /** * sets the name of the attribute that will specify the id of the task's HTML element @@ -492,6 +725,21 @@ parse the start_date, end_date properties in case they are specified as strings */ time_step: number; + /** + * sets the length of time, in milliseconds, before the tooltip hides + */ + tooltip_hide_timeout: number; + + /** + * sets the the right (if positive) offset of the tooltip's position + */ + tooltip_offset_x: number; + + /** + * sets the the top (if positive) offset of the tooltip's position + */ + tooltip_offset_y: number; + /** * sets the timeout in milliseconds before the tooltip is displayed for a task */ @@ -500,19 +748,59 @@ parse the start_date, end_date properties in case they are specified as strings /** * enables/disables the touch support for the Gantt chart */ - touch: any; + touch: boolean|string; /** * defines the time period in milliseconds that is used to differ the long touch gesture from the scroll gesture */ - touch_drag: any; + touch_drag: number|boolean; + + /** + * enables/disables vibration while moving tasks on touch devices + */ + touch_feedback: boolean; + + /** + * redefines functions responsible for displaying different types of tasks + */ + type_renderers: any; + + /** + * stores the names of lightbox's structures (used for different types of tasks) + */ + types: any; + + /** + * enables the Undo functionality for the gantt + */ + undo: boolean; + + /** + * sets the actions that the Undo operation will revert + */ + undo_actions: any; + + /** + * sets the number of steps that should be reverted by the undo method + */ + undo_steps: number; + + /** + * sets the types of entities for which the Undo operation will be applied + */ + undo_types: any; + + /** + * enables calculating the duration of tasks in working time instead of calendar time + */ + work_time: boolean; /** * sets the date format that is used to parse data from the data set */ - xml_date: string; -} + xml_date: string; +} interface GanttDateHelpers{ add(origin: Date, count: number, unit: string): Date; @@ -578,6 +866,13 @@ interface GanttLocale{ labels: GanttLocaleLabels; } +interface GanttEnterprise{ + /** + * Creates a new instance of Gantt + */ + getGanttInstance(): GanttStatic; +} + interface GanttStatic{ templates: GanttTemplates; config: GanttConfigOptions; @@ -592,109 +887,289 @@ interface GanttStatic{ * adds a new dependency link * @param link the link object */ - addLink(link: any): any; + addLink(link: any): string|number; + + /** + * displayes an additional layer with custom elements for a link in the timeline area + * @param func a render function or a config object + */ + addLinkLayer(func: GanttCallback|any): string; + + /** + * adds a marker to the timeline area + * @param marker the marker's configuration object + */ + addMarker(marker: any): string; /** * adds a new task * @param task the task object * @param parent the parent's id + * @param index optional, the position the task will be added into (0 or greater) */ - addTask(task: any, parent: string): any; + addTask(task: any, parent: string, index?: number): string|number; + + /** + * displayes an additional layer with custom elements for a task in the timeline area + * @param func a render function or a config object + */ + addTaskLayer(func: GanttCallback|any): string; + + /** + * calls an alert message box + * @param config the alert box's configuration + */ + alert(config: any): void; + + /** + * if the specified expression is false, an errorMessage is shown in the red popup at the top right corner of the screen + * @param expression true to assert the expression, false - if assertion fails + * @param errorMessage an error message that will be shown in the red popup + */ + assert(expression: boolean, errorMessage: string): void; /** * attaches the handler to an inner event of dhtmlxGantt * @param name the event's name, case-insensitive * @param handler the handler function */ - attachEvent(name: string, handler: (...args: any[])=>any): any; + attachEvent(name: GanttEventName, handler: GanttCallback): string; + + /** + * recalculates the schedule of the project + */ + autoSchedule(): void; + + /** + * updates multiple tasks/links at once + * @param callback the callback function + */ + batchUpdate(callback: GanttCallback): void; + + /** + * creates a new function that, when called, has its this keyword set to the provided value + * @param method the target function + * @param thisArg the value to be passed as the this parameter to the target function when the bound function is called + */ + bind(method: GanttCallback, thisArg: any): GanttCallback; + + /** + * calculates the duration of a task + * @param start the date when a task is scheduled to begin + * @param end the date when a task is scheduled to be completed + */ + calculateDuration(start: Date, end: Date): number; + + /** + * calculates the end date of a task + * @param start the date when a task is scheduled to begin + * @param duration the duration of a task + * @param unit the time unit of the duration + */ + calculateEndDate(start: Date, duration: number, unit: string): Date; + + /** + * calculates the level of a task + * @param task the task's object + */ + calculateTaskLevel(task: any): number; /** * calls an inner event * @param name the event's name, case-insensitive * @param params an array of the event-related data */ - callEvent(name: string, params: any): boolean; + callEvent(name: string, params: any[]): boolean; + + /** + * changes the name of the lighbox's structure defined for of the task + * @param id the task id + */ + changeLightboxType(id: string|number): void; /** * changes the link's id * @param id the current link's id * @param new_id the new link's id */ - changeLinkId(id: any, new_id: any); + changeLinkId(id: string|number, new_id: string|number): void; /** * changes the task's id * @param id the current task's id * @param new_id the new task's id */ - changeTaskId(id: any, new_id: any); + changeTaskId(id: string|number, new_id: string|number): void; /** * checks whether an event has some handler(s) specified * @param name the event's name */ - checkEvent(name: string): boolean; + checkEvent(name: GanttEventName): boolean; /** * removes all tasks from the Gantt chart */ - clearAll(); + clearAll(): void; /** * closes the branch with the specified id - * @param id the branch id + * @param id the branch id */ - close(id : any); + close(id: string|number): void; + + /** + * collapses gantt from the full screen mode to the normal mode + */ + collapse(): void; + + /** + * calls a confirm message box + * @param config the confirm box's configuration + */ + confirm(config: any): void; + + /** + * creates a deep copy of provided object + * @param task the object that needs to be copied + */ + copy(task: any): any; + + /** + * recalculates the task duration in the work time + * @param task the task's object + */ + correctTaskWorkTime(task: any): void; + + /** + * adds a new task and opens the lightbox to confirm + * @param task the task object + * @param parent the parent's id + * @param index optional, the position the task will be added into (0 or greater) + */ + createTask(task: any, parent: string, index?: number): string|number; + + /** + * dataProcessor constructor + * @param url url to the data feed + */ + dataProcessor(url: string): void; + + /** + * gets the date of the specified horizontal position in the chart area + * @param pos the relative horizontal position you want to know the date of + */ + dateFromPos(pos: number): void; + + /** + * returns false if the provided argument is undefined, otherwise true + * @param task the object that should be checked + */ + defined(task: any): boolean; /** * deletes the specified dependency link * @param id the dependency link's id */ - deleteLink(id: any); + deleteLink(id: string|number): void; + + /** + * deletes the specified marker + * @param markerId the marker's id + */ + deleteMarker(markerId: string): void; /** * deletes the specified task * @param id the task's id */ - deleteTask(id: string); + deleteTask(id: string): void; /** - * detaches all handlers from events (which were attached before by the attachEvent() method) + * detaches all events from dhtmlxGantt (both custom and inner) */ - detachAllEvents(); + detachAllEvents(): void; /** * detaches a handler from an event (which was attached before by the attachEvent() method) * @param id the event's id */ - detachEvent(id: string); + detachEvent(id: string): void; /** - * iterates over specified tasks of the Gantt chart - * @param code a function that will iterate over tasks. Takes a task object as a parameter + * iterates over all selected tasks in the Gantt chart + * @param code a function that will iterate over tasks. Takes a task id as a parameter + */ + eachSelectedTask(code: GanttCallback): void; + + /** + * iterates over specified tasks in the Gantt chart + * @param code a function that will iterate over tasks. Takes a task object as a parameter * @param parent the parent id. If specified, the function will iterate over childs of the
specified parent * @param master the object, that 'this' will refer to */ - eachTask(code : (...args: any[])=>any, parent?: any, master?: any); + eachTask(code: GanttCallback, parent?: string|number, master?: any): void; + + /** + * attaches an event handler to an HTML element + * @param node the HTML node or its id + * @param event the name of an HTML event (without the 'on' prefix) + * @param handler the event handler + * @param master an object that the this keyword refers to + */ + event(node: HTMLElement|string, event: string, handler: GanttCallback, master?: any): string; + + /** + * removes an event handler from an HTML element + * @param id the id of an event handler + */ + eventRemove(id: string): void; + + /** + * expands gantt to the full screen mode + */ + expand(): void; /** * returns the 1st-level child tasks of the specified parent branch * @param id the parent branch's id */ - getChildren(id: any): any; + getChildren(id: string|number): any[]; + + /** + * returns the closest working time + * @param config the configuration object + */ + getClosestWorkTime(config: any): Date; /** * get the index of a task in the tree * @param id the task id */ - getGlobalTaskIndex(id: any); + getGlobalTaskIndex(id: string|number): void; + + /** + * gets the configuration object of a column + * @param name the column's name + */ + getGridColumn(name: string): any; + + /** + * gets columns of the Gantt chart + */ + getGridColumns(): 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 task's data property to
assign the select's option to the task */ - getLabel(property: string, key: any); + getLabel(property: string, key: string|number): void; + + /** + * returns the id of the last selected task + */ + getLastSelectedTask(): string|number; /** * gets the lightbox's HTML object element @@ -707,6 +1182,11 @@ interface GanttStatic{ */ getLightboxSection(name: string): any; + /** + * returns the name of the active lighbox's structure + */ + getLightboxType(): string; + /** * returns values of the lightbox's sections */ @@ -716,25 +1196,64 @@ interface GanttStatic{ * returns the dependency link object by the specified id * @param id the link id */ - getLink(id: any): any; + getLink(id: string|number): any; + + /** + * returns the number of all dependency links presented in the Gantt chart + */ + getLinkCount(): number; /** * returns the HTML element of the specified dependency link * @param id the link id */ - getLinkNode(id: any): HTMLElement; + getLinkNode(id: string|number): HTMLElement; + + /** + * returns all links presented in the Gantt chart + */ + getLinks(): any[]; + + /** + * gets the marker's object + * @param markerId the marker's id + */ + getMarker(markerId: string): any; /** * returns the id of the next item (no matter what the level of nesting is: the same or different) * @param id the task id */ - getNext(id: any): any; + getNext(id: string|number): string|number; + + /** + * returns the id of the next task of the same level + * @param id the task id + */ + getNextSibling(id: string|number): string|number; + + /** + * returns the id of the parent task + * @param id the task id + */ + getParent(id: string|number): string|number; /** * returns the id of the previous item (no matter what the level of nesting is: the same or different) * @param id the task id */ - getPrev(id: any): any; + getPrev(id: string|number): string|number; + + /** + * returns the id of the previous task of the same level + * @param id the task id + */ + getPrevSibling(id: string|number): string|number; + + /** + * returns the stack of stored redo commands + */ + getRedoStack(): any[]; /** * returns the scroll position @@ -744,65 +1263,130 @@ interface GanttStatic{ /** * returns the id of the selected task */ - getSelectedId(): any; + getSelectedId(): string|number; + + /** + * returns an array of the currently selected tasks + */ + getSelectedTasks(): any[]; + + /** + * returns siblings of the specified task (including itself) + * @param id the task id + */ + getSiblings(id: string|number): any[]; + + /** + * checks how much time (in the current duration unit) a task has before it starts to affect other tasks + * @param task1 the object of the 1st task to check the slack for + * @param task2 the object of the 2nd task to check the slack for + */ + getSlack(task1: any, task2: any): number|string; /** * gets the current state of the Gantt chart */ getState(): any; + /** + * calculates the combined start/end dates of tasks nested in a project or another task + * @param task_id the task's id, api/gantt_root_id_config.md will be used if not specified + */ + getSubtaskDates(task_id?: string|number): any; + /** * returns the task object * @param id the task id */ - getTask(id: any): any; + getTask(id: string|number): any; /** * returns a collection of tasks which occur during the specified period * @param from the start date of the period * @param to the end date of the period */ - getTaskByTime(from?: Date, to?: Date): any; + getTaskByTime(from?: Date, to?: Date): any[]; + + /** + * gets the number of tasks that are currently loaded in the gantt + */ + getTaskCount(): number; /** * get the index of a task in the branch * @param id the task id */ - getTaskIndex(id: any): number; + getTaskIndex(id: string|number): number; /** * returns the HTML element of the task bar * @param id the task id */ - getTaskNode(id: any): HTMLElement; + getTaskNode(id: string|number): HTMLElement; + + /** + * calculates the position and size of the task's DOM element in the timeline area + * @param task the task object + * @param from the start date of the item + * @param to the end date of the item + */ + getTaskPosition(task: any, from: Date, to: Date): any; /** * returns the HTML element of the task row in the table * @param id the task id */ - getTaskRowNode(id: any): HTMLElement; + getTaskRowNode(id: string|number): HTMLElement; + + /** + * gets the top position of the task's DOM element in the timeline area + * @param id the task's id + */ + getTaskTop(id: number|string): number; + + /** + * returns the stack of stored undo commands + */ + getUndoStack(): any[]; + + /** + * gets the number of tasks visible on the screen (those that are not collapsed) + */ + getVisibleTaskCount(): number; + + /** + * returns the working hours of the specified date + * @param date a date to check + */ + getWorkHours(date: Date): any[]; + + /** + * groups tasks by the specified task's attribute + * @param config the grouping configuration object + */ + groupBy(config: any): void; /** * checks whether the specified item has child tasks * @param id the task id */ - hasChild(id: any): boolean; + hasChild(id: string|number): boolean; /** * hides the lightbox modal overlay that blocks interactions with the remaining screen * @param box an element to hide */ - hideCover(box?: HTMLElement); + hideCover(box?: HTMLElement): void; /** * closes the lightbox if it's currently active */ - hideLightbox(); + hideLightbox(): void; /** * hides the pop-up task form (if it's currently active) */ - hideQuickInfo(); + hideQuickInfo(): void; /** * constructor. Initializes a dhtmlxGantt object @@ -810,7 +1394,26 @@ interface GanttStatic{ * @param from the start value of the time scale (X–Axis) * @param to the end value of the time scale (X–Axis) */ - init(container: any, from?: Date, to?: Date); + init(container: string|HTMLElement, from?: Date, to?: Date): void; + + /** + * checks whether a task is a child of other task + * @param childId the id of a task that you want to check as a child + * @param parentId the id of a task that you want to check as a parent + */ + isChildOf(childId: string|number, parentId: string|number): boolean; + + /** + * checks whether the specified link is critical + * @param link the link's object + */ + isCriticalLink(link: any): boolean; + + /** + * checks whether the specified task is critical + * @param task the task's object + */ + isCriticalTask(task: any): boolean; /** * checks whether the specified link is correct @@ -822,19 +1425,38 @@ interface GanttStatic{ * checks whether the specified link exists * @param id the link id */ - isLinkExists(id: any): boolean; + isLinkExists(id: string|number): boolean; + + /** + * checks whether the specified task is currently selected + * @param task the task's id + */ + isSelectedTask(task: string|number): boolean; /** * checks whether the specified task exists * @param id the task id */ - isTaskExists(id: any): boolean; + isTaskExists(id: string|number): boolean; /** * checks whether the specifies task is currently rendered in the Gantt chart * @param id the task's id */ - isTaskVisible(id: any): boolean; + isTaskVisible(id: string|number): boolean; + + /** + * checks if the task is unscheduled + * @param task the task's object + */ + isUnscheduledTask(task: any): boolean; + + /** + * checks whether the specified date is working or not + * @param date a date to check + * @param timeunit a time unit: 'hour' or 'day'.
If not specified, the value of 'gantt.config.duration_unit' is used + */ + isWorkTime(date: Date, timeunit: string): boolean; /** * loads data to the gantt from an external data source @@ -842,148 +1464,270 @@ interface GanttStatic{ * @param type ('json', 'xml', 'oldxml') the data type. The default value - 'json' * @param callback the callback function */ - load(url: string, type?: string, callback?: (...args: any[])=>any); + load(url: string, type?: string, callback?: GanttCallback): void; /** * gets the id of a task from the specified HTML event * @param e a native event */ - locate(e: Event): string; + locate(e: Event): string|number; + + /** + * calls a message box of the specified type + * @param config the message box's configuration + */ + message(config: any): void; + + /** + * adds properties of the 'source' object into the 'target' object + * @param target the target object + * @param source the source object + * @param force if true, properties of the 'source' will overwrite matching properties of the 'target', if there are any. If false, properties that already exist in the 'target' will be omitted + */ + mixin(target: any, source: any, force: boolean): void; + + /** + * calls a modalbox + * @param config the modal box' configuration + */ + modalbox(config: any): void; /** * moves a task to a new position * @param sid the id of the task to move - * @param tindex the index of the position that the task will be moved to
(the index in the whole tree) + * @param tindex the index of the position that the task will be moved to
(the index within a branch) * @param parent the parent id. If specified, the tindex will refer to the index in the
'parent' branch */ - moveTask(sid: any, tindex: number, parent?: any); + moveTask(sid: string|number, tindex: number, parent?: string|number): void; /** * opens the branch with the specified id * @param id the branch id */ - open(id: any); + open(id: string|number): void; /** * loads data from a client-side resource * @param url a string or object which represents data * @param type ( 'json', 'xml' ) the data type. The default value - 'json' */ - parse(url: any, type?: string); + parse(url: string|any, type?: string): void; + + /** + * gets the relative horizontal position of the specified date in the chart area + * @param date a date you want to know the position of + */ + posFromDate(date: Date): void; + + /** + * applies the reverted changes to the gantt once again + */ + redo(): void; /** * refreshes data in the Gantt chart */ - refreshData(); + refreshData(): void; /** * refreshes the specifies link * @param id the link id */ - refreshLink(id: any); + refreshLink(id: string|number): void; /** * refreshes the task and its related links * @param id the task id */ - refreshTask(id: any); + refreshTask(id: string|number): void; + + /** + * removes the specified layer related to a link + * @param layerId a DOM element that will be displayed in the layer + */ + removeLinkLayer(layerId: string): void; + + /** + * removes the specified layer related to a task + * @param layerId a DOM element that will be displayed in the layer + */ + removeTaskLayer(layerId: string): void; /** * renders the whole Gantt chart */ - render(); + render(): void; + + /** + * updates all markers on the page + */ + renderMarkers(): void; /** * removes the current lightbox's HTML object element */ - resetLightbox(); + resetLightbox(): void; + + /** + * re-calculates the duration of a project task depending on dates its childs + * @param task the task's object + */ + resetProjectDates(task: any): void; + + /** + * re-calculates the skin's settings from the related attached skin CSS file + */ + resetSkin(): void; /** * forces the lightbox to resize */ - resizeLightbox(); + resizeLightbox(): void; + + /** + * rounds the specified date to the nearest date in the time scale + * @param date the Date object to round + */ + roundDate(date: Date): Date; + + /** + * rounds the start and end task's dates to the nearest dates in the time scale + * @param task the task object + */ + roundTaskDates(task: any): void; /** * scrolls the Gantt container to the specified position - * @param x the value of the horizontal scroll - * @param y the value of the vertical scroll + * @param x the value of the horizontal scroll or 'null' (to not display the horizontal scroll) + * @param y the value of the vertical scroll or 'null' (to not display the vertical scroll) */ - scrollTo(x: number, y: number); + scrollTo(x: number, y: number): void; /** * selects the specified task * @param id the task id */ - selectTask(id: any): any; + selectTask(id: string|number): string|number; /** - * serializes the data into JSON or XML format. + * serializes the data into JSON or XML format * @param type the format that the data will be serialized into.
Possible values: 'json' (default ), 'xml'. */ - serialize(type?: string); + serialize(type?: string): void; /** * returns a list of options * @param list_name the name of a list * @param options an array of options */ - serverList(list_name: string, options?: any); + serverList(list_name: string, options?: any[]): void; + + /** + * set the parent for a task + * @param task the task id + * @param pid the parent task id + */ + setParent(task: number|string, pid: number|string): void; /** * resizes the Gantt chart */ - setSizes(); + setSizes(): void; + + /** + * sets the working time for the Gantt chart + * @param config the configuration object of a time span + */ + setWorkTime(config: any): void; /** * shows the lightbox modal overlay that blocks interactions with the remaining screen * @param box an element to hide */ - showCover(box?: HTMLElement); + showCover(box?: HTMLElement): void; + + /** + * scrolls the chart area to makes the specified date visible + * @param date the date to show in the chart + */ + showDate(date: Date): void; /** * opens the lightbox for the specified task - * @param id the task id + * @param id the task id */ - showLightbox(id : any); + showLightbox(id: string|number): void; /** * displays the pop-up task form for the specified task * @param id the task id */ - showQuickInfo(id: any); + showQuickInfo(id: string|number): void; /** * makes the specified task visible on the screen * @param id the task id */ - showTask(id: any); + showTask(id: string|number): void; /** * sorts the tasks in the grid * @param field the name of the column that the grid will be sorted by or a custom
sorting function * @param desc specifies the sorting direction: true - descending sort and false - ascending
sort. By default, false * @param parent the id of the parent task. Specify the parameter if you want to sort tasks only in
the branch of the specified parent. + * @param silent specifies whether rendering shall be invoked after reordering items */ - sort(field: any, desc?: boolean, parent?: any); + sort(field: string|GanttCallback, desc?: boolean, parent?: string|number, silent?: boolean): void; + + /** + * selects the specified task if it was unselected and vice versa + * @param task the task's id + */ + toggleTaskSelection(task: string|number): void; + + /** + * returns a unique id + */ + uid(): number; + + /** + * reverts the changes made in the gantt + */ + undo(): void; /** * removes selection from the selected task */ - unselectTask(); + unselectTask(): void; + + /** + * updates the specified collection with new options + * @param collection the name of the collection to update + * @param options the new values of the collection + */ + updateCollection(collection: string, options: any[]): boolean; /** * updates the specified dependency link * @param id the task id */ - updateLink(id: string); + updateLink(id: string): void; + + /** + * updates the specified marker + * @param markerId the marker's id + */ + updateMarker(markerId: string): void; /** * updates the specified task * @param id the task id */ - updateTask(id: string); + updateTask(id: string): void; + } -declare var gantt: GanttStatic; \ No newline at end of file +declare var gantt: GanttStatic; +declare var Gantt: GanttEnterprise; \ No newline at end of file diff --git a/dhtmlxscheduler/dhtmlxscheduler-tests.ts b/dhtmlxscheduler/dhtmlxscheduler-tests.ts index 2f1f2d9ce8..f3e864ffca 100644 --- a/dhtmlxscheduler/dhtmlxscheduler-tests.ts +++ b/dhtmlxscheduler/dhtmlxscheduler-tests.ts @@ -30,4 +30,11 @@ scheduler.load("/data/events"); //events scheduler.attachEvent("onEmptyClick", function (ev?: Event) { var date: Date = scheduler.getActionData(ev).date; -}); \ No newline at end of file +}); + +//filters +scheduler.filter_week = (id: string, e: Event) => true; + +//enterprise version +var scheduler2 = Scheduler.getSchedulerInstance(); +scheduler2.addEvent({ some: 1 }); \ No newline at end of file diff --git a/dhtmlxscheduler/dhtmlxscheduler.d.ts b/dhtmlxscheduler/dhtmlxscheduler.d.ts index 42bd819e4c..40123827ca 100644 --- a/dhtmlxscheduler/dhtmlxscheduler.d.ts +++ b/dhtmlxscheduler/dhtmlxscheduler.d.ts @@ -1,16 +1,20 @@ -// Type definitions for dhtmlxScheduler 4.0 +// Type definitions for dhtmlxScheduler 4.3.0 // Project: http://dhtmlx.com/docs/products/dhtmlxScheduler // Definitions by: Maksim Kozhukh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +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'; interface SchedulerTemplates{ /** * specifies the date in the header of the view - * @param start the start date of the view - * @param end the end date of the view + * @param start the start date of the view + * @param end the end date of the view */ - agenda_date(start : Date, end : Date): string; + agenda_date(start: Date, end: Date): string; /** * specifies the text in the second column of the Agenda view @@ -29,14 +33,14 @@ interface SchedulerTemplates{ agenda_time(start: Date, end: Date, event: any): string; /** - * specifies the format for dates that are set by means of API methods. Used to parse incoming dates + * specifies the format of dates that are set by means of API methods. Used to parse incoming dates * @param date the date which needs formatting */ api_date(date: Date): string; /** - * specifies the format of the day in a cell - * @param date the cell date + * specifies the format of the date in a cell + * @param date the cell's date */ calendar_date(date: Date): string; @@ -53,7 +57,7 @@ interface SchedulerTemplates{ calendar_scale_date(date: Date): string; /** - * specifies the date format of the lightbox start and end date inputs + * specifies the date format of the lightbox's start and end date inputs * @param date the date which needs formatting */ calendar_time(date: Date): string; @@ -70,6 +74,22 @@ interface SchedulerTemplates{ */ day_scale_date(date: Date): string; + /** + * specifies the CSS class that will be applied to the highlighted event's duration on the time scale + * @param start the date when an event is scheduled to begin + * @param end the date when an event is scheduled to be completed + * @param ev the event's object + */ + drag_marker_class(start: Date, end: Date, ev: any): void; + + /** + * specifies the content of the highlighted block on the time scale + * @param start the date when an event is scheduled to begin + * @param end the date when an event is scheduled to be completed + * @param ev the event's object + */ + drag_marker_content(start: Date, end: Date, ev: any): void; + /** * specifies the date of an event. Applied to one-day events only * @param start the date when an event is scheduled to begin @@ -79,20 +99,20 @@ interface SchedulerTemplates{ event_bar_date(start: Date, end: Date, event: any): string; /** - * specifies the event text. Applied to all events + * specifies the event's text. Applied to multi-day events only * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed - * @param event the event object + * @param event the event's object */ event_bar_text(start: Date, end: Date, event: any): string; /** - * specifies the css style for the event container + * specifies the CSS class that will be applied to the event's container * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed - * @param event the event object + * @param ev the event's object */ - event_class(start: Date, end: Date, event: any): string; + event_class(start: Date, end: Date, ev: any): string; /** * specifies the time part of the start and end dates of the event. Mostly used by other templates for presenting time periods @@ -101,15 +121,15 @@ interface SchedulerTemplates{ event_date(date: Date): string; /** - * specifies the event header + * specifies the event's header * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed - * @param event the event object + * @param event the event's object */ event_header(start: Date, end: Date, event: any): string; /** - * specifies the event text + * specifies the event's text * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed * @param event the event object @@ -129,11 +149,11 @@ interface SchedulerTemplates{ load_format(date: Date): string; /** - * specified the date in the header of the view - * @param start the start date of the view - * @param end the end date of the view + * specifies the date in the header of the view + * @param start the start date of the view + * @param end the end date of the view */ - map_date(start : Date, end : Date): string; + map_date(start: Date, end: Date): string; /** * specifies the text in the second column of the view @@ -174,12 +194,10 @@ interface SchedulerTemplates{ month_date(date: Date): string; /** - * specifies the css class that will be applied to a day cell - * @param start the date when an event is scheduled to begin - * @param end the date when an event is scheduled to be completed - * @param event the event object + * specifies the CSS class that will be applied to a day cell + * @param date the date which needs formatting */ - month_date_class(start: Date, end: Date, event: any): string; + month_date_class(date: Date): string; /** * specifies the format of the day in a cell @@ -244,12 +262,12 @@ interface SchedulerTemplates{ tooltip_text(start: Date, end: Date, event: any): string; /** - * specifies the event text + * specifies the event's text * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed * @param event the event object - * @param cellDate the date of a day cell that an one-day event or a single occurrence of the recurring event displayes in - * @param pos the position a single occurrence in the recurring event: 'start' - the first occurrence, 'end' - the last occurrence, 'middle' - for remaining occurrences + * @param cellDate the date of a day cell that a one-day event or a single occurrence of
the recurring event displays in + * @param pos the position of a single occurrence in the recurring event: 'start' - the first occurrence, 'end' - the last occurrence, 'middle' - for remaining occurrences */ week_agenda_event_text(start: Date, end: Date, event: any, cellDate: Date, pos: string): string; @@ -260,14 +278,14 @@ interface SchedulerTemplates{ week_agenda_scale_date(date: Date): string; /** - * specified the date in the header of the view - * @param start the start date of the view - * @param end the end date of the view + * specifies the date in the header of the view + * @param start the start date of the view + * @param end the end date of the view */ - week_date(start : Date, end : Date): string; + week_date(start: Date, end: Date): string; /** - * specifies the css class that will be applied to a day cell + * specifies the CSS class that will be applied to a day cell * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed * @param event the event object @@ -299,13 +317,13 @@ interface SchedulerTemplates{ year_date(date: Date): string; /** - * specifies the month name in the header of a month block of the view. + * specifies the month's name in the header of a month block of the view. * @param date the date which needs formatting */ year_month(date: Date): string; /** - * specifies the day name in the sub-header of a month block of the view + * specifies the day's name in the sub-header of a month block of the view * @param date the date which needs formatting */ year_scale_date(date: Date): string; @@ -319,7 +337,7 @@ interface SchedulerTemplates{ year_tooltip(start: Date, end: Date, event: any): string; /** - * specifies the lightbox header + * specifies the lightbox's header * @param start the date when an event is scheduled to begin * @param end the date when an event is scheduled to be completed * @param event the event object @@ -328,10 +346,10 @@ interface SchedulerTemplates{ /** * specifies the date in the header of the view - * @param start the start date of the view - * @param end the end date of the view + * @param start the start date of the view + * @param end the end date of the view */ - grid_date(start : Date, end : Date): string; + grid_date(start: Date, end: Date): string; /** * specifies the format of dates in columns with id='date' @@ -349,7 +367,7 @@ interface SchedulerTemplates{ /** * specifies the text in the columns - * @param field_name the column id + * @param field_name the column's id * @param event the event object */ grid_field(field_name: string, event: any): string; @@ -357,16 +375,17 @@ interface SchedulerTemplates{ /** * specifies the number of scheduled events in a cell of the view * @param evs an array of objects of events contained in a cell + * @param date the date of a cell */ - timeline_cell_value(evs: any): string; + timeline_cell_value(evs: any[], date: Date): string; /** - * specifies the css style for a cell of the view + * specifies the CSS class that will be applied to a cell of the view * @param evs an array of objects of events contained in a cell (defined only in the 'cell' mode) - * @param date the date of a column + * @param date the date of a column * @param section the section object */ - timeline_cell_class(evs: any, date : Date, section: any): string; + timeline_cell_class(evs: any[], date: Date, section: any): string; /** * specifies the name of a CSS class that will be applied to items of the X-Axis @@ -382,19 +401,19 @@ interface SchedulerTemplates{ /** * specifies the name of a CSS class that will be applied to items of the Y-Axis - * @param key the section id - * @param label the section label - * @param section the section object that contains the key and label properties + * @param key the section's id + * @param label the section's label + * @param section the section object that contains the 'key' and 'label' properties */ - timeline_scaley_class(key: string, label : string, section: any): string; + timeline_scaley_class(key: string, label: string, section: any): string; /** * specifies items of the Y-Axis - * @param key the section id (key) - * @param label the section label - * @param section the section object containing the key and label properties + * @param key the section's id (key) + * @param label the section's label + * @param section the section object containing the 'key' and 'label' properties */ - timeline_scale_label(key : string, label : string, section : any): string; + timeline_scale_label(key: string, label: string, section: any): string; /** * specifies the tooltip over a day cell containing some scheduled event(s) @@ -406,10 +425,10 @@ interface SchedulerTemplates{ /** * specifies the date in the header of the view - * @param date1 the date when an event is scheduled to begin - * @param date2 the date when an event is scheduled to be completed + * @param date1 the date when an event is scheduled to begin + * @param date2 the date when an event is scheduled to be completed */ - timeline_date(date1 : Date, date2 : Date): string; + timeline_date(date1: Date, date2: Date): string; /** * specifies items of the X-Axis @@ -431,11 +450,12 @@ interface SchedulerTemplates{ /** * specifies items of the X-Axis - * @param key the unit id (key) - * @param label the unit label - * @param unit the unit object containing the key and label properties + * @param key the unit's id (key) + * @param label the unit's label + * @param unit the unit object containing the 'key' and 'label' properties */ - units_scale_text(key : string, label : string, unit : any): string; + units_scale_text(key: string, label: string, unit: any): string; + } interface SchedulerConfigOptions{ @@ -454,10 +474,15 @@ interface SchedulerConfigOptions{ */ agenda_start: Date; + /** + * specifies how to display the default error notification in case the XML data loading failed + */ + ajax_error: string|boolean; + /** * 'says' to show multi-day events in the regular way (as one-day events are displayed) */ - all_timed: any; + 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 @@ -472,12 +497,12 @@ interface SchedulerConfigOptions{ /** * stores a collection of buttons resided in the left bottom corner of the lightbox */ - buttons_left: any; + buttons_left: any[]; /** * stores a collection of buttons resided in the right bottom corner of the lightbox */ - buttons_right: any; + buttons_right: any[]; /** * sets the maximum number of events in a cascade @@ -510,7 +535,7 @@ interface SchedulerConfigOptions{ container_autoresize: boolean; /** - * sets the format for the date in the header of the Week and Units views + * sets the date format for the X-Axis of the Week and Units views */ day_date: string; @@ -524,13 +549,18 @@ interface SchedulerConfigOptions{ */ default_date: string; + /** + * sets a timeout (in milliseconds) that wraps the api/scheduler_updateview.md and api/scheduler_setcurrentview.md calls ( that cause re-drawing of the scheduler ) + */ + delay_render: number; + /** * 'says' to use the extended form while creating new events by drag or double click */ details_on_create: boolean; /** - * 'says' to open the extended form after double clicking on an event + * 'says' to open the lightbox after double clicking on an event */ details_on_dblclick: boolean; @@ -554,6 +584,16 @@ interface SchedulerConfigOptions{ */ drag_create: boolean; + /** + * highlights the event's duration on the time scale when you drags an event over the scheduler + */ + drag_highlight: boolean; + + /** + * restrict dragging events to the calling scheduler from any other scheduler(s) + */ + drag_in: boolean; + /** * enables the possibility to drag the lightbox by the header */ @@ -564,6 +604,11 @@ interface SchedulerConfigOptions{ */ drag_move: boolean; + /** + * restrict dragging events from the calling scheduler to any other scheduler(s) + */ + drag_out: boolean; + /** * enables the possibility to resize events by drag-and-drop */ @@ -590,7 +635,7 @@ interface SchedulerConfigOptions{ fix_tab_position: boolean; /** - * enables setting of the event duration to the full day + * enables setting of the event's duration to the full day */ full_day: boolean; @@ -600,7 +645,7 @@ interface SchedulerConfigOptions{ highlight_displayed_event: boolean; /** - * sets the format of Y-Axis items + * sets the time format of Y-Axis. Also used in the default event and lighbox templates for setting the time part. */ hour_date: string; @@ -610,20 +655,25 @@ interface SchedulerConfigOptions{ hour_size_px: number; /** - * stores a collection of icons visible in the side edit menu of the event box + * stores a collection of icons visible in the side edit menu of the event's box */ - icons_edit: any; + icons_edit: any[]; /** - * stores a collection of icons visible in the side selection menu of the event box + * stores a collection of icons visible in the side selection menu of the event's box */ - icons_select: any; + icons_select: any[]; /** * defines whether the date specified in the 'End by' field should be exclusive or inclusive */ include_end_by: boolean; + /** + * disables the keyboard navigation in the scheduler + */ + key_nav: boolean; + /** * sets the maximum value of the hour scale (Y-Axis) */ @@ -640,10 +690,15 @@ interface SchedulerConfigOptions{ lightbox: any; /** - * defines the lightbox behavior while opening in the edit mode + * defines the lightbox's behavior, when the user opens the lightbox to edit a recurring event */ lightbox_recurring: string; + /** + * denies to drag events out of the visible area of the scheduler + */ + limit_drag_out: boolean; + /** * sets the right border of the allowable date range */ @@ -660,7 +715,7 @@ interface SchedulerConfigOptions{ limit_time_select: boolean; /** - * limits viewing events + * limits the date period during which the user can view the events */ limit_view: boolean; @@ -675,7 +730,7 @@ interface SchedulerConfigOptions{ map_end: Date; /** - * sets the position that will be displayed on the map in case the event location can't be identified + * sets the position that will be displayed on the map in case the event's location can't be identified */ map_error_position: any; @@ -695,7 +750,7 @@ interface SchedulerConfigOptions{ map_initial_zoom: number; /** - * activates attempts to resolve the event location if the database doesn't have the event's coordinates stored + * activates attempts to resolve the event's location, if the database doesn't have the event's coordinates stored */ map_resolve_event_location: boolean; @@ -715,7 +770,7 @@ interface SchedulerConfigOptions{ map_type: any; /** - * sets the zoom that will be used to show the user's location if he agrees to the browser offer to show it + * sets the zoom that will be used to show the user's location, if the user agrees to the browser's offer to show it */ map_zoom_after_resolve: number; @@ -725,12 +780,12 @@ interface SchedulerConfigOptions{ mark_now: boolean; /** - * sets the maximum number of displayable in a cell events + * sets the maximum number of events displayable in a cell */ max_month_events: number; /** - * specifies the minicalendar object + * specifies the mini calendar object */ minicalendar: any; @@ -740,7 +795,7 @@ interface SchedulerConfigOptions{ month_date: string; /** - * sets the format for the day in a cell of the Month and Year views + * sets the format for the day in the cells of the Month and Year views */ month_day: string; @@ -757,7 +812,22 @@ interface SchedulerConfigOptions{ /** * sets the height of the area that displays multi-day events */ - multi_day_height_limit: any; + multi_day_height_limit: number|boolean; + + /** + * enables the possibility to render the same events in several sections of the Timeline or Units view + */ + multisection: boolean; + + /** + * specifies whether while dragging events that assigned to several sections of the Timeline or Units view, all instances should be dragged at once ('true') or just the selected one ('false') + */ + multisection_shift_all: boolean; + + /** + * sets the date for the current-time marker in the Limit extension (enabled by the configuration - mark_now) + */ + now_date: Date; /** * allows working with recurring events independently of time zones @@ -765,12 +835,12 @@ interface SchedulerConfigOptions{ occurrence_timestamp_in_utc: boolean; /** - * defines the 'saving' behaviour for the case when the user edits the event text directly in the event box + * defines the 'saving' behaviour for the case, when the user edits the event's text directly in the event's box */ positive_closing: boolean; /** - * fixes dnd in case of non-linear time scale + * preserves the visible length of an event while dragging along a non-linear time scale */ preserve_length: boolean; @@ -800,7 +870,12 @@ interface SchedulerConfigOptions{ readonly_form: boolean; /** - * sets the date format of the 'End by' field in the 'recurring' lighbox + * specifies working days that will affect the recurring event when the user selects the ""Every workday" option in the lightbox + */ + recurring_workdays: any[]; + + /** + * sets the date format of the 'End by' field in the 'recurring' lightbox */ repeat_date: string; @@ -810,12 +885,27 @@ interface SchedulerConfigOptions{ repeat_precise: boolean; /** - * sets the initial position of the vertical scroll in the scheduler (an hour in the 24h format) + * enables the possibility to resize multi-day events in the Month view by drag-and-drop + */ + resize_month_events: boolean; + + /** + * enables the possibility to resize single-day events in the Month view by drag-n-drop + */ + resize_month_timed: boolean; + + /** + * sets the initial position of the vertical scroll in the scheduler (an hour in the 24-hour clock format) */ scroll_hour: number; /** - * shows/hides the select bar in the event box + * specifies the delimeter that will be used to separate several sections/units in the related data property of the event + */ + section_delemiter: string; + + /** + * shows/hides the select bar in the event's box */ select: boolean; @@ -825,7 +915,7 @@ interface SchedulerConfigOptions{ separate_short_events: boolean; /** - * enables converting server-side dates from UTC to a local time zone (and backward) during sending data to the server + * enables converting server-side dates from UTC to a local time zone (and backward) while sending data to the server */ server_utc: boolean; @@ -834,6 +924,11 @@ interface SchedulerConfigOptions{ */ show_loading: boolean; + /** + * activates/disables the 'quick_info' extension (pop-up task's details form) + */ + show_quick_info: boolean; + /** * sets the start day of weeks */ @@ -847,25 +942,35 @@ interface SchedulerConfigOptions{ /** * enables/disables the touch support in the scheduler */ - touch: any; + touch: boolean|string; /** * defines the time period in milliseconds that is used to differ the long touch gesture from the scroll gesture */ - touch_drag: any; + touch_drag: number|boolean; /** - * enables/disables prompting messages in the right up corner of the screen + * enables/disables prompting messages in the right top corner of the screen */ touch_tip: boolean; + /** + * disables dhtmxlScheduler's tooltips on the touch devices + */ + touch_tooltip: boolean; + + /** + * updates the mode when the scheduler fully repaints itself on any action + */ + update_render: boolean; + /** * 'says' events to occupy the whole width of the cell */ use_select_menu_space: boolean; /** - * sets the format for the date in the sub-header of the Month view + * sets the format of the date in the sub-header of the Month view */ week_date: string; @@ -887,9 +992,9 @@ interface SchedulerConfigOptions{ /** * sets the number of columns in the Year view */ - year_y: number; -} + year_y: number; +} interface SchedulerDateHelpers{ add(origin: Date, count: number, unit: string): Date; @@ -917,8 +1022,6 @@ interface SchedulerHotkeys{ edit_cancel: number; } -//scheduler.locale - interface SchedulerLocaleDate{ month_full: string[]; month_short: string[]; @@ -948,6 +1051,7 @@ interface SchedulerLocale{ labels: SchedulerLocaleLabels; } + interface SchedulerSizes{ /** * the height of day cells in the month view @@ -1020,6 +1124,13 @@ interface SchedulerSizes{ scroll_width: number; } +interface SchedulerEnterprise{ + /** + * Creates a new instance of Scheduler + */ + getSchedulerInstance(): SchedulerStatic; +} + interface SchedulerStatic{ templates: SchedulerTemplates; config: SchedulerConfigOptions; @@ -1030,6 +1141,59 @@ interface SchedulerStatic{ xy: SchedulerSizes; locale: SchedulerLocale; + /** + * filter events that will be displayed on the day view + */ + filter_day: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the week view + */ + filter_week: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the month view + */ + filter_month: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the year view + */ + filter_year: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the agenda view + */ + filter_agenda: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the timeline view + */ + filter_timeline: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the units view + */ + filter_units: SchedulerFilterCallback; + + /** + * filter events that will be displayed on the grid view + */ + filter_grid: SchedulerFilterCallback; + + + /** + * removes all blocking sets from the scheduler + */ + deleteMarkedTimespan(); + + /** + * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods + * @param configuration for deleting + */ + deleteMarkedTimespan(config: any); + + /** * adds a new event * @param event the event object @@ -1043,10 +1207,10 @@ interface SchedulerStatic{ addEventNow(event: any): string; /** - * marks dates but with certain settings makes blocking (unlike blockTime() allows setting custom styling for the limit) + * marks dates, but with certain settings makes blocking (unlike blockTime() allows setting custom styling for the limit) * @param config the configuration object of the timespan to mark/block */ - addMarkedTimespan(config: any); + addMarkedTimespan(config: any): number; /** * adds a section to the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) @@ -1057,55 +1221,55 @@ interface SchedulerStatic{ /** * attaches the handler to an inner event of dhtmlxScheduler - * @param name the event name, case-insensitive + * @param name the event's name, case-insensitive * @param handler the handler function */ - attachEvent(name: string, handler: (...args: any[])=>any): string; + attachEvent(name: SchedulerEventName, handler: SchedulerCallback): string; /** * makes the scheduler reflect all data changes in the Backbone model and vice versa * @param events the Backbone data collection */ - backbone(events: any); + backbone(events: any): void; /** * blocks the specified date and applies the default 'dimmed' style to it. - * @param date a date to block ( if a number is provided, the parameter will be treated as a week day: '0' index refers to Sunday, '6' - to Saturday) - * @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 date a date to block ( if a number is provided, the parameter will be treated as a week
day: '0' index refers to Sunday,'6' - to Saturday ) + * @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: any, time_points: any, items?: any); + blockTime(date: Date|number, time_points: any[], items?: any): void; /** * calls an inner event - * @param name the event name, case-insensitive - * @param params an array of the event related data + * @param name the event's name, case-insensitive + * @param params an array of the event-related data */ - callEvent(name: string, params: any): boolean; + callEvent(name: string, params: any[]): boolean; /** - * changes the event id - * @param id the current event id - * @param new_id the new event id + * changes the event's id + * @param id the current event's id + * @param new_id the new event's id */ - changeEventId(id: string, new_id: string); + changeEventId(id: string, new_id: string): void; /** - * checks whether the specified event occurs at the time that has been already occupied with another event(s) + * checks whether the specified event occurs at the time that has already been occupied by another event(s) * @param event the event object */ checkCollision(event: any): boolean; /** * checks whether an event has some handler(s) specified - * @param name the event name + * @param name the event's name */ - checkEvent(name: string): boolean; + checkEvent(name: SchedulerEventName): boolean; /** - * checks whether an event resides in a specific timespan + * checks whether an event resides in a timespan of a specific type * @param event the event object - * @param timespan the timespan type + * @param timespan the timespan's type */ checkInMarkedTimespan(event: any, timespan: string): boolean; @@ -1118,118 +1282,100 @@ interface SchedulerStatic{ /** * removes all events from the scheduler */ - clearAll(); + clearAll(): void; /** * closes all sections in the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) */ - closeAllSections(); + closeAllSections(): void; /** * closes the specified section in the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) - * @param section_id the section id + * @param section_id the section's id */ - closeSection(section_id: string); + closeSection(section_id: string): void; /** * collapses the expanded scheduler back to the normal size */ - collapse(); + collapse(): void; /** * creates the Grid view in the scheduler * @param config the configuration object of the Grid view */ - createGridView(config: any); + createGridView(config: any): void; /** * creates the Timeline view in the scheduler * @param config the configuration object of the Timeline view */ - createTimelineView(config: any); + createTimelineView(config: any): void; /** * creates the Units view in the scheduler * @param config the configuration object of the Units view */ - createUnitsView(config: any); + createUnitsView(config: any): void; /** * deletes all sections from the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) */ - deleteAllSections(); + deleteAllSections(): void; /** * deletes the specified event - * @param id the event id + * @param id the event's id */ - deleteEvent(id: any); - - /** - * removes all blocking sets from the scheduler - */ - deleteMarkedTimespan(); + deleteEvent(id: string|number): void; /** * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods - * @param id the timespan id + * @param id the timespan's id */ - deleteMarkedTimespan(id: string); - - /** - * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods - * @param configuration for deleting - */ - deleteMarkedTimespan(config: any); + deleteMarkedTimespan(id: string): void; /** * deletes a section from the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) - * @param section_id the section id + * @param section_id the section's id */ deleteSection(section_id: string): boolean; /** * destroys previously created mini-calendar - * @param name the mini-calendar's object (if not specified, the scheduler attempts to destroy the last created mini calendar) + * @param name the mini-calendar's object (if not specified, the scheduler attempts
to destroy the last created mini calendar) */ - destroyCalendar(name?: any); + destroyCalendar(name?: any): void; /** * detaches a handler from an event (which was attached before by the attachEvent method) - * @param id the event id + * @param id the event's id */ - detachEvent(id: string); + detachEvent(id: string): void; /** - * opens the inline editor to alter the event text (the editor in the event box) - * @param id the event id + * opens the inline editor to alter the event's text (the editor in the event's box) + * @param id the event's id */ - edit(id: string); + edit(id: string): void; /** - * closes the inline event edotor if it's currently open - * @param id the event id + * closes the inline event editor, if it's currently open + * @param id the event's id */ - editStop(id: string); + editStop(id: string): void; /** * closes the lightbox - * @param mode if set to true, the changes made in the lightbox will be saved before closing. If - false, the changes will be cancelled. + * @param mode if set to true, the changes, made in the lightbox, will be saved before closing.
If - false, the changes will be cancelled. * @param box the HTML container for the lightbox */ - endLightbox(mode: boolean, box: HTMLElement); + endLightbox(mode: boolean, box?: HTMLElement): void; /** * expands the scheduler to the full screen view */ - expand(); - - /** - * filter events that will be displayed on the week view - * @param id event-id - * @param event event-object - */ - filter_week(id: any, event: any); + expand(): void; /** * gives access to the objects of lightbox's sections @@ -1244,26 +1390,26 @@ interface SchedulerStatic{ getActionData(e: Event): any; /** - * return the event object by its id - * @param event_id event_id + * returns the event object by its id + * @param event_id the event's id */ - getEvent(event_id: any): T; + getEvent(event_id: string|number): void; /** * gets the event's end date - * @param id the event id + * @param id the event's id */ getEventEndDate(id: string): Date; /** * gets the event's start date - * @param id the event id + * @param id the event's id */ getEventStartDate(id: string): Date; /** * gets the event's text - * @param id the event id + * @param id the event's id */ getEventText(id: string): string; @@ -1272,14 +1418,14 @@ interface SchedulerStatic{ * @param from the start date of the period * @param to the end date of the period */ - getEvents(from?: Date, to?: Date); + getEvents(from?: Date, to?: Date): void; /** - * gets the label of a select control in the lighbox + * 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 id. This parameter is compared with the event data property to assign the select's option to an event + * @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: any); + getLabel(property: string, key: string|number): void; /** * gets the lightbox's HTML object element @@ -1294,14 +1440,14 @@ interface SchedulerStatic{ getRecDates(id: string, number: number): any; /** - * gets the object of the currently displayable event - * @param id the event id + * gets the object of the currently displayed event + * @param id the event's id */ getRenderedEvent(id: string): HTMLElement; /** * gets the object of the specified section in the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) - * @param section_id the section id + * @param section_id the section's id */ getSection(section_id: string): any; @@ -1312,7 +1458,7 @@ interface SchedulerStatic{ /** * gets the user data associated with the specified event - * @param id the event id + * @param id the event's id * @param name the user data name */ getUserData(id: string, name: string): any; @@ -1321,31 +1467,37 @@ interface SchedulerStatic{ * hides the lightbox modal overlay that blocks interactions with the remaining screen * @param box an element to hide */ - hideCover(box?: HTMLElement); + hideCover(box?: HTMLElement): void; /** * hides the pop-up event form (if it's currently active) */ - hideQuickInfo(); + hideQuickInfo(): void; /** - * initializes an instance of dhtmlxScheduler - * @param container the id or object of the HTML container that the scheduler will be created inside + * highlights the event's duration on the time scale + * @param event the event object + */ + highlightEventPosition(event: any): void; + + /** + * constructor. Initializes a dhtmlxScheduler object + * @param container an HTML container ( or its id) where a dhtmlxScheduler object will be initialized * @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: any, date?: Date, view?: string); + init(container: string|HTMLElement, date?: Date, view?: string): void; /** * inverts the specified time zones - * @param zones an array [start_minute,end_minute,..,start_minute_N,end_minute_N] where each pair sets a certain limit range (in minutes). The array can have any number of such pairs + * @param zones an array **[start_minute,end_minute,..,start_minute_N,end_minute_N]**
where each pair sets a certain limit range (in minutes). The array can have any
number of such pairs */ - invertZones(zones: any); + invertZones(zones: any[]): void; /** - * checks whether the calendar is currently open in the scheduler + * checks whether the calendar is currently opened in the scheduler */ - isCalendarVisible(): any; + isCalendarVisible(): boolean|HTMLElement; /** * checks whether the specified event one-day or multi-day @@ -1354,19 +1506,25 @@ interface SchedulerStatic{ isOneDayEvent(event: any): boolean; /** - * 'says' to change the active date in the mini calendar each time the active date in the scheduler is changed - * @param calendar the mini calendar object - * @param shift a function that defines the difference between active dates in the mini-calendar and the scheduler. The function takes the scheduler's date as a parameter and returns the date that should be displayed in the mini calendar + * checks whether a view with the specified name exists + * @param name the view name */ - linkCalendar(calendar: any, shift: (...args: any[])=>any); + isViewExists(name: string): boolean; + + /** + * 'says' to change the active date in the mini calendar each time, the active date in the scheduler is changed + * @param calendar the mini calendar object + * @param shift a function that defines the difference between active dates in the mini-calendar
and the scheduler. The function takes the scheduler's date as a parameter and
returns the date that should be displayed in the mini calendar + */ + linkCalendar(calendar: any, shift: SchedulerCallback): void; /** * loads data to the scheduler from an external data source - * @param url the server side url (may be a static file or a server side script which outputs data as XML) + * @param url the server side url (may be a static file or a server side script which outputs data
as XML) * @param type ('json', 'xml', 'ical') the data type. The default value - 'xml' * @param callback the callback function */ - load(url: string, type?: string, callback?: (...args: any[])=>any); + load(url: string, type?: string, callback?: SchedulerCallback): void; /** * applies a css class to the specified date @@ -1374,40 +1532,40 @@ interface SchedulerStatic{ * @param date the date to mark * @param css the name of a css class */ - markCalendar(calendar: any, date: Date, css: string); + markCalendar(calendar: any, date: Date, css: string): void; /** * marks and/or blocks date(s) by applying the default or a custom style to them. Marking is cancelled right after any internal update in the app. Can be used for highlighting * @param config the configuration object of the timespan to mark/block */ - markTimespan(config: any); + markTimespan(config: any): void; /** * opens all sections in the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) */ - openAllSections(); + openAllSections(): void; /** * opens the specified section in the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) - * @param section_id the section id + * @param section_id the section's id */ - openSection(section_id: string); + openSection(section_id: string): void; /** * loads data from a client-side resource * @param data a string or object which represents data * @param type ('json', 'xml', 'ical') the data type. The default value - 'xml' */ - parse(data: any, type?: string); + parse(data: any, type?: string): void; /** * creates a mini calendar * @param config the calendar configuration object */ - renderCalendar(config: any); + renderCalendar(config: any): void; /** - * generates the HTML content for a custom event box + * generates HTML content for a custom event's box * @param container the event container * @param event the event object */ @@ -1416,116 +1574,116 @@ interface SchedulerStatic{ /** * removes the current lightbox's HTML object element */ - resetLightbox(); + resetLightbox(): void; /** * scrolls the specified number of units in the Units view - * @param step the number of units to scroll (set the positive value to scroll units in the right direction, the negative value - in the left direction). + * @param step the number of units to scroll (set the positive value to scroll units to the right
side, the negative value - to the left side
). */ - scrollUnit(step: number); + scrollUnit(step: number): void; /** * selects the specified event - * @param id the event id + * @param id the event's id */ - select(id: string); + select(id: string): void; /** * returns a list of options * @param list_name the name of a list * @param options an array of options */ - serverList(list_name: string, options?: any); + serverList(list_name: string, options?: any[]): void; /** * displays the specified view and date * @param date the date to display * @param view the name of a view to display */ - setCurrentView(date?: Date, view?: string); + setCurrentView(date?: Date, view?: string): void; /** * adds a new event to the scheduler's data pool - * @param id the event id + * @param id the event's id * @param event the event object */ - setEvent(id: any, event: any); + setEvent(id: string|number, event: any): void; /** * sets the event's end date - * @param id the event id + * @param id the event's id * @param date the new end date of the event */ - setEventEndDate(id: string, date: Date); + setEventEndDate(id: string, date: Date): void; /** - * set the event's start date - * @param id the event id + * sets the event's start date + * @param id the event's id * @param date the new start date of the event */ - setEventStartDate(id: string, date: Date); + setEventStartDate(id: string, date: Date): void; /** - * set the event's text - * @param id the event id + * sets the event's text + * @param id the event's id * @param text the new text of the event */ - setEventText(id: string, text: string); + setEventText(id: string, text: string): void; /** * forces the lightbox to resize */ - setLightboxSize(); + setLightboxSize(): void; /** * sets the mode that allows loading data by parts (enables the dynamic loading) * @param mode the loading mode */ - setLoadMode(mode: string); + setLoadMode(mode: string): void; /** * sets the user data associated with the specified event - * @param id the event id + * @param id the event's id * @param name the user data name * @param value the user data value */ - setUserData(id: string, name: string, value: any); + setUserData(id: string, name: string, value: any): void; /** * shows the lightbox modal overlay that blocks interactions with the remaining screen * @param box an element to hide */ - showCover(box?: HTMLElement); + showCover(box?: HTMLElement): void; /** * shows and highlights the specified event in the current or specified view - * @param id the event id + * @param id the event's id * @param view the view name */ - showEvent(id: string, view?: string); + showEvent(id: string, view?: string): void; /** * opens the lightbox for the specified event - * @param id the event id + * @param id the event's id */ - showLightbox(id: string); + showLightbox(id: string): void; /** * displays the pop-up event form for the specified event - * @param id the event id + * @param id the event's id */ - showQuickInfo(id: string); + showQuickInfo(id: string): void; /** * shows a custom lightbox in the specified HTML container centered on the screen - * @param id the event id + * @param id the event's id * @param box the lightbox's HTML container */ - startLightbox(id : string, box: HTMLElement); + startLightbox(id: string, box: HTMLElement): void; /** - * convers scheduler's data to the ICal format - * @param header sets the value for the content header field + * converts scheduler's data to the ICal format + * @param header sets the value for the content's header field */ toICal(header?: string): string; @@ -1539,7 +1697,7 @@ interface SchedulerStatic{ * @param url the path to the server-side PDF converter * @param mode the color map of the resulting PDF document */ - toPDF(url: string, mode?: string); + toPDF(url: string, mode?: string): void; /** * exports several scheduler's views to a PDF document (can be used for printing) @@ -1549,7 +1707,7 @@ interface SchedulerStatic{ * @param path the path to the php file which generates a PDF file (details) * @param color the color map in use */ - toPDFRange(from: Date, to: Date, view: string, path: string, color: string); + toPDFRange(from: Date, to: Date, view: string, path: string, color: string): void; /** * converts scheduler's data into the XML format @@ -1557,17 +1715,17 @@ interface SchedulerStatic{ toXML(): string; /** - * generates an unique ID (unique inside the current scheduler, not GUID) + * generates a unique ID (unique inside the current scheduler, not GUID) */ - uid(); + uid(): void; /** * removes blocking set by the blockTime() method * @param days (Date, number,array, string) days that should be limited - * @param zones the period in minutes that should be limited. Can be set to 'fullday' value to limit the entire day + * @param zones the period in minutes that should be limited. Can be set to 'fullday' value
to limit the entire day * @param sections allows blocking date(s) just for specific items of specific views. BTW, the specified date(s) will be blocked just in the related view(s) */ - unblockTime(days: any, zones?: any, sections?: any); + unblockTime(days: any, zones?: any[], sections?: any): void; /** * removes a css class from the specified date @@ -1575,48 +1733,50 @@ interface SchedulerStatic{ * @param date the date to unmark * @param css the name of a css class to remove */ - unmarkCalendar(calendar: any, date: Date, css: string); + unmarkCalendar(calendar: any, date: Date, css: string): void; /** * removes marking/blocking set by the markTimespan() method * @param divs a timespan to remove marking/blocking from (or an array of timespans) */ - unmarkTimespan(divs: any); + unmarkTimespan(divs: HTMLElement|any[]): void; /** * unselects the specified event - * @param id the event id (if not specified, the currently selected event will be unselected) + * @param id the event's id (if not specified, the currently selected event will be unselected) */ - unselect(id?: string); + unselect(id?: string): void; /** * displays the specified date in the mini calendar * @param calendar the mini calendar object * @param new_date a new date to display in the mini calendar */ - updateCalendar(calendar: any, new_date: Date); + updateCalendar(calendar: any, new_date: Date): void; /** - * updates tht specified collection with new options + * updates the specified collection with new options * @param collection the name of the collection to update * @param options the new values of the collection */ - updateCollection(collection: string, options: any): boolean; + updateCollection(collection: string, options: any[]): boolean; /** * updates the specified event - * @param id the event id + * @param id the event's id */ - updateEvent(id: string); + updateEvent(id: string): void; /** - * displays the specified view and date (doesn't invokes any events) + * displays the specified view and date (doesn't invoke any events) * @param date the date to set * @param view the view name */ - updateView(date: Date, view: string); + updateView(date: Date, view: string): void; + } declare var scheduler: SchedulerStatic; +declare var Scheduler: SchedulerEnterprise; \ No newline at end of file diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index 455ffc8fe3..bf3258a14a 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -649,7 +649,7 @@ declare namespace dojo { * @param url URL to request * @param options OptionalOptions for the request. */ - interface xhr { (url: String, options?: dojo.request.xhr.__Options): void } + interface xhr { (url: String, options?: dojo.request.xhr.__Options): dojo.request.__Promise } interface xhr { /** * Send an HTTP DELETE request using XMLHttpRequest with the given URL and options. diff --git a/dotdotdot/dotdotdot-tests.ts b/dotdotdot/dotdotdot-tests.ts index 95fe346745..6920d3c2c0 100644 --- a/dotdotdot/dotdotdot-tests.ts +++ b/dotdotdot/dotdotdot-tests.ts @@ -4,6 +4,7 @@ $("span").dotdotdot({ ellipsis: ":::" }); $("span").dotdotdot({ wrap: "letter" }); $("span").dotdotdot({ fallbackToLetter: false }); +$("span").dotdotdot({ after: "a.after" }); $("span").dotdotdot({ after: $("#after") }); $("span").dotdotdot({ watch: true }); $("span").dotdotdot({ height: 42 }); diff --git a/dotdotdot/dotdotdot.d.ts b/dotdotdot/dotdotdot.d.ts index 6219340ba6..bedd6cecac 100644 --- a/dotdotdot/dotdotdot.d.ts +++ b/dotdotdot/dotdotdot.d.ts @@ -31,7 +31,7 @@ declare namespace JQueryDotDotDot { /** jQuery-selector for the element to keep and put after the ellipsis. * Default: null */ - after?: JQuery; + after?: string | JQuery; /** Whether to update the ellipsis: true/'window' * Default: false diff --git a/email-templates/email-templates-tests.ts b/email-templates/email-templates-tests.ts index 9b70728106..f48dedef40 100644 --- a/email-templates/email-templates-tests.ts +++ b/email-templates/email-templates-tests.ts @@ -4,6 +4,7 @@ import EmailTemplates = require('email-templates'); var EmailTemplate = EmailTemplates.EmailTemplate; var template = new EmailTemplate("./"); +var templateWithOptions = new EmailTemplate('./', {sassOptions: {}, juiceOptions: {}}); var users = [ { email: 'pappa.pizza@spaghetti.com', diff --git a/email-templates/email-templates.d.ts b/email-templates/email-templates.d.ts index c117980877..a836fdfadc 100644 --- a/email-templates/email-templates.d.ts +++ b/email-templates/email-templates.d.ts @@ -19,6 +19,12 @@ interface EmailTemplateResults { * @type {string} */ text: string; + + /** + * @summary Subject result. + * @type {string} + */ + subject: string; } /** @@ -32,6 +38,15 @@ interface EmailTemplateCallback { (err: Object, results: EmailTemplateResults): void; } +/** + * @summary Interface for email-template options + * @interface + */ +interface EmailTemplateOptions { + sassOptions?: any; + juiceOptions?: any; +} + declare module "email-templates" { /** * @summary Email template class. @@ -42,7 +57,7 @@ declare module "email-templates" { * @summary Constructor. * @param {string} templateDir The template directory. */ - constructor(templateDir: string); + constructor(templateDir: string, options?: EmailTemplateOptions); /** * @summary Render a single template. diff --git a/enzyme/enzyme-1.2.0-tests.tsx b/enzyme/enzyme-1.2.0-tests.tsx new file mode 100644 index 0000000000..44db5705bc --- /dev/null +++ b/enzyme/enzyme-1.2.0-tests.tsx @@ -0,0 +1,605 @@ +/// +/// + +import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme"; +import * as React from "react"; +import {Component, ReactElement, HTMLAttributes} from "react"; +import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme"; + + +// Help classes/interfaces +interface MyComponentProps { + propsProperty: any; + numberProp?: number; +} + +interface StatelessProps { + stateless: any; +} + +interface MyComponentState { + stateProperty: any; +} + +class MyComponent extends Component { + setState(...args: any[]) { + } +} + +const MyStatelessComponent = (props: StatelessProps) => ; + +// API +namespace SpyLifecycleTest { + spyLifecycle(MyComponent); +} + +// ShallowWrapper +namespace ShallowWrapperTest { + var shallowWrapper: ShallowWrapper = + shallow(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: ShallowWrapper + + function test_find() { + elementWrapper = shallowWrapper.find('.selector'); + shallowWrapper = shallowWrapper.find(MyComponent); + shallowWrapper.find(MyStatelessComponent).props().stateless; + shallowWrapper.find(MyStatelessComponent).shallow(); + } + + function test_findWhere() { + shallowWrapper = + shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper) => true); + } + + function test_filter() { + elementWrapper = shallowWrapper.filter('.selector'); + shallowWrapper = shallowWrapper.filter(MyComponent).shallow(); + } + + function test_filterWhere() { + shallowWrapper = + shallowWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = shallowWrapper.contains(
); + } + + function test_hasClass() { + boolVal = shallowWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = shallowWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = shallowWrapper.find('.foo').not('.bar'); + } + + function test_children() { + shallowWrapper = shallowWrapper.children(); + shallowWrapper.children(MyStatelessComponent).props().stateless; + } + + function test_parents() { + shallowWrapper = shallowWrapper.parents(); + } + + function test_parent() { + shallowWrapper = shallowWrapper.parent(); + } + + function test_closest() { + elementWrapper = shallowWrapper.closest('.selector'); + shallowWrapper = shallowWrapper.closest(MyComponent); + } + + function test_shallow() { + shallowWrapper = shallowWrapper.shallow(); + } + + function test_unmount() { + shallowWrapper = shallowWrapper.unmount(); + } + + function test_render() { + var cheerioWrapper: CheerioWrapper = shallowWrapper.render(); + } + + function test_text() { + stringVal = shallowWrapper.text(); + } + + + function test_html() { + stringVal = shallowWrapper.html(); + } + + function test_get() { + reactElement = shallowWrapper.get(1); + } + + function test_at() { + shallowWrapper = shallowWrapper.at(1); + } + + function test_first() { + shallowWrapper = shallowWrapper.first(); + } + + function test_last() { + shallowWrapper = shallowWrapper.last(); + } + + function test_state() { + shallowWrapper.state(); + shallowWrapper.state('key'); + } + + function test_props() { + objectVal = shallowWrapper.props(); + } + + function test_prop() { + shallowWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + shallowWrapper.simulate('click'); + shallowWrapper.simulate('click', args); + } + + function test_setState() { + shallowWrapper = shallowWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + shallowWrapper = shallowWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = shallowWrapper.instance(); + } + + function test_update() { + shallowWrapper = shallowWrapper.update(); + } + + function test_debug() { + stringVal = shallowWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = shallowWrapper.type(); + } + + function test_forEach() { + shallowWrapper = + shallowWrapper.forEach(wrapper => wrapper.shallow().props().propsProperty); + } + + function test_map() { + var arrayNumbers: Array = + shallowWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + shallowWrapper.reduce( + (amount: number, n: ShallowWrapper) => amount + n.props().numberProp + ); + } + + function test_reduceRight() { + const total: number[] = + shallowWrapper.reduceRight( + (amount: number, n: ShallowWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = shallowWrapper.some('.selector'); + boolVal = shallowWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = shallowWrapper.someWhere((aShallowWrapper: ShallowWrapper) => true); + } + + function test_every() { + boolVal = shallowWrapper.every('.selector'); + boolVal = shallowWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper) => true); + } +} + + +// ReactWrapper +namespace ReactWrapperTest { + var reactWrapper: ReactWrapper = + mount(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: ReactWrapper + + function test_unmount() { + reactWrapper = reactWrapper.unmount(); + } + + function test_mount() { + reactWrapper = reactWrapper.mount(); + } + + function test_find() { + elementWrapper = reactWrapper.find('.selector'); + reactWrapper = reactWrapper.find(MyComponent); + reactWrapper.find(MyStatelessComponent).props().stateless; + } + + function test_findWhere() { + reactWrapper = + reactWrapper.findWhere((aReactWrapper: ReactWrapper) => true); + } + + function test_filter() { + elementWrapper = reactWrapper.filter('.selector'); + reactWrapper = reactWrapper.filter(MyComponent); + } + + function test_filterWhere() { + reactWrapper = + reactWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = reactWrapper.contains(
); + } + + function test_hasClass() { + boolVal = reactWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = reactWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = reactWrapper.find('.foo').not('.bar'); + } + + function test_children() { + reactWrapper = reactWrapper.children(); + } + + function test_parents() { + reactWrapper = reactWrapper.parents(); + } + + function test_parent() { + reactWrapper = reactWrapper.parent(); + } + + function test_closest() { + elementWrapper = reactWrapper.closest('.selector'); + reactWrapper = reactWrapper.closest(MyComponent); + } + + function test_text() { + stringVal = reactWrapper.text(); + } + + function test_html() { + stringVal = reactWrapper.html(); + } + + function test_get() { + reactElement = reactWrapper.get(1); + } + + function test_at() { + reactWrapper = reactWrapper.at(1); + } + + function test_first() { + reactWrapper = reactWrapper.first(); + } + + function test_last() { + reactWrapper = reactWrapper.last(); + } + + function test_state() { + reactWrapper.state(); + reactWrapper.state('key'); + } + + function test_props() { + objectVal = reactWrapper.props(); + } + + function test_prop() { + reactWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + reactWrapper.simulate('click'); + reactWrapper.simulate('click', args); + } + + function test_setState() { + reactWrapper = reactWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + reactWrapper = reactWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + reactWrapper = reactWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = reactWrapper.instance(); + } + + function test_update() { + reactWrapper = reactWrapper.update(); + } + + function test_debug() { + stringVal = reactWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = reactWrapper.type(); + } + + function test_forEach() { + reactWrapper = + reactWrapper.forEach(wrapper => wrapper.props().propsProperty); + } + + function test_map() { + var arrayNumbers: Array = + reactWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + reactWrapper.reduce( + (amount: number, n: ReactWrapper) => amount + n.prop('amount') + ); + } + + function test_reduceRight() { + const total: number[] = + reactWrapper.reduceRight( + (amount: number, n: ReactWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = reactWrapper.some('.selector'); + boolVal = reactWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = reactWrapper.someWhere((aReactWrapper: ReactWrapper) => true); + } + + function test_every() { + boolVal = reactWrapper.every('.selector'); + boolVal = reactWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper) => true); + } +} + +// CheerioWrapper +namespace CheerioWrapperTest { + var cheerioWrapper: CheerioWrapper = + render(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String, + elementWrapper: CheerioWrapper + + function test_find() { + elementWrapper = cheerioWrapper.find('.selector'); + cheerioWrapper = cheerioWrapper.find(MyComponent); + cheerioWrapper.find(MyStatelessComponent).props().stateless; + } + + function test_findWhere() { + cheerioWrapper = + cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper) => true); + } + + function test_filter() { + elementWrapper = cheerioWrapper.filter('.selector'); + cheerioWrapper = cheerioWrapper.filter(MyComponent); + } + + function test_filterWhere() { + cheerioWrapper = + cheerioWrapper.filterWhere(wrapper => { + wrapper.props().propsProperty; + return true; + }); + } + + function test_contains() { + boolVal = cheerioWrapper.contains(
); + } + + function test_hasClass() { + boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); + } + + function test_is() { + boolVal = cheerioWrapper.is('.some-class'); + } + + function test_not() { + elementWrapper = cheerioWrapper.find('.foo').not('.bar'); + } + + function test_children() { + cheerioWrapper = cheerioWrapper.children(); + } + + function test_parents() { + cheerioWrapper = cheerioWrapper.parents(); + } + + function test_parent() { + cheerioWrapper = cheerioWrapper.parent(); + } + + function test_closest() { + elementWrapper = cheerioWrapper.closest('.selector'); + cheerioWrapper = cheerioWrapper.closest(MyComponent); + } + + function test_text() { + stringVal = cheerioWrapper.text(); + } + + function test_html() { + stringVal = cheerioWrapper.html(); + } + + function test_get() { + reactElement = cheerioWrapper.get(1); + } + + function test_at() { + cheerioWrapper = cheerioWrapper.at(1); + } + + function test_first() { + cheerioWrapper = cheerioWrapper.first(); + } + + function test_last() { + cheerioWrapper = cheerioWrapper.last(); + } + + function test_state() { + cheerioWrapper.state(); + cheerioWrapper.state('key'); + } + + function test_props() { + objectVal = cheerioWrapper.props(); + } + + function test_prop() { + cheerioWrapper.prop('key'); + } + + + function test_simulate(...args: any[]) { + cheerioWrapper.simulate('click'); + cheerioWrapper.simulate('click', args); + } + + function test_setState() { + cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'}); + } + + function test_setProps() { + cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'}); + } + + function test_setContext() { + cheerioWrapper = cheerioWrapper.setContext({name: 'baz'}); + } + + function test_instance() { + var myComponent: MyComponent = cheerioWrapper.instance(); + } + + function test_update() { + cheerioWrapper = cheerioWrapper.update(); + } + + function test_debug() { + stringVal = cheerioWrapper.debug(); + } + + function test_type() { + var stringOrFunction: String|Function = cheerioWrapper.type(); + } + + function test_forEach() { + cheerioWrapper = + cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper)=> { + }); + } + + function test_map() { + var arrayNumbers: Array = + cheerioWrapper.map(wrapper => wrapper.props().numberProp); + } + + function test_reduce() { + const total: number[] = + cheerioWrapper.reduce( + (amount: number, n: CheerioWrapper) => amount + n.prop('amount') + ); + } + + function test_reduceRight() { + const total: number[] = + cheerioWrapper.reduceRight( + (amount: number, n: CheerioWrapper) => amount + n.prop('amount') + ); + } + + function test_some() { + boolVal = cheerioWrapper.some('.selector'); + boolVal = cheerioWrapper.some(MyComponent); + } + + function test_someWhere() { + boolVal = cheerioWrapper.someWhere((aCheerioWrapper: CheerioWrapper) => true); + } + + function test_every() { + boolVal = cheerioWrapper.every('.selector'); + boolVal = cheerioWrapper.every(MyComponent); + } + + function test_everyWhere() { + boolVal = cheerioWrapper.everyWhere((aCheerioWrapper: CheerioWrapper) => true); + } +} diff --git a/enzyme/enzyme-1.2.0.d.ts b/enzyme/enzyme-1.2.0.d.ts new file mode 100644 index 0000000000..13c00041a5 --- /dev/null +++ b/enzyme/enzyme-1.2.0.d.ts @@ -0,0 +1,473 @@ +// Type definitions for Enzyme v1.2.0 +// Project: https://github.com/airbnb/enzyme +// Definitions by: Marian Palkus , Cap3 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "enzyme" { + + import {ReactElement, Component, StatelessComponent, ComponentClass, HTMLAttributes} from "react"; + + export class ElementClass extends Component { + } + + /** + * Many methods in Enzyme's API accept a selector as an argument. Selectors in Enzyme can fall into one of the + * following three categories: + * + * 1. A Valid CSS Selector + * 2. A React Component Constructor + * 3. A React Component's displayName + */ + export type EnzymeSelector = String | typeof ElementClass; + + interface CommonWrapper { + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): CommonWrapper; + find(statelessComponent: StatelessComponent): CommonWrapper; + find(selector: string): CommonWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): CommonWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): CommonWrapper; + filter(statelessComponent: StatelessComponent): CommonWrapper; + filter(selector: string): CommonWrapper; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. + * @param predicate + */ + filterWhere(predicate: (wrapper: this) => Boolean): this; + + /** + * Returns whether or not the current wrapper has a node anywhere in it's render tree that looks like the one passed in. + * @param node + */ + contains(node: ReactElement): Boolean; + + /** + * Returns whether or not the current node has a className prop including the passed in class name. + * @param className + */ + hasClass(className: String): Boolean; + + /** + * Returns whether or not the current node matches a provided selector. + * @param selector + */ + is(selector: EnzymeSelector): Boolean; + + /** + * Returns a new wrapper with only the nodes of the current wrapper that don't match the provided selector. + * This method is effectively the negation or inverse of filter. + * @param selector + */ + not(selector: EnzymeSelector): this; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): CommonWrapper; + children(statelessComponent: StatelessComponent): CommonWrapper; + children(selector: string): CommonWrapper; + children(): CommonWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): CommonWrapper; + parents(statelessComponent: StatelessComponent): CommonWrapper; + parents(selector: string): CommonWrapper; + parents(): CommonWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): CommonWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): CommonWrapper; + closest(statelessComponent: StatelessComponent): CommonWrapper; + closest(selector: string): CommonWrapper; + + /** + * Returns a string of the rendered text of the current render tree. This function should be looked at with + * skepticism if being used to test what the actual HTML output of the component will be. If that is what you + * would like to test, use enzyme's render function instead. + * + * Note: can only be called on a wrapper of a single node. + */ + text(): String; + + /** + * Returns a string of the rendered HTML markup of the current render tree. + * + * Note: can only be called on a wrapper of a single node. + */ + html(): String; + + /** + * Returns the node at a given index of the current wrapper. + * @param index + */ + get(index: number): ReactElement; + + /** + * Returns a wrapper around the node at a given index of the current wrapper. + * @param index + */ + at(index: number): this; + + /** + * Reduce the set of matched nodes to the first in the set. + */ + first(): this; + + /** + * Reduce the set of matched nodes to the last in the set. + */ + last(): this; + + /** + * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + * @param [key] + */ + state(key?: String): any; + + /** + * Returns the props hash for the current node of the wrapper. + * + * NOTE: can only be called on a wrapper of a single node. + */ + props(): P; + + /** + * Returns the prop value for the node of the current wrapper with the provided key. + * + * NOTE: can only be called on a wrapper of a single node. + * @param key + */ + prop(key: String): any; + + /** + * Simulate events. + * Returns itself. + * @param event + * @param args? + */ + simulate(event: string, ...args: any[]): this; + + /** + * A method to invoke setState() on the root component instance similar to how you might in the definition of + * the component, and re-renders. This method is useful for testing your component in hard to achieve states, + * however should be used sparingly. If possible, you should utilize your component's external API in order to + * get it into whatever state you want to test, in order to be as accurate of a test as possible. This is not + * always practical, however. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setState(state: S): this; + + /** + * A method that sets the props of the root component, and re-renders. Useful for when you are wanting to test + * how the component behaves over time with changing props. Calling this, for instance, will call the + * componentWillReceiveProps lifecycle method. + * + * Similar to setState, this method accepts a props object and will merge it in with the already existing props. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setProps(props: P): this; + + /** + * A method that sets the context of the root component, and re-renders. Useful for when you are wanting to + * test how the component behaves over time with changing contexts. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + * @param state + */ + setContext(context: Object): this; + + /** + * Gets the instance of the component being rendered as the root node passed into shallow(). + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + instance(): Component; + + /** + * Forces a re-render. Useful to run before checking the render output if something external may be updating + * the state of the component somewhere. + * Returns itself. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + update(): this; + + /** + * Returns an html-like string of the wrapper for debugging purposes. Useful to print out to the console when + * tests are not passing when you expect them to. + */ + debug(): String; + + /** + * Returns the type of the current node of this wrapper. If it's a composite component, this will be the + * component constructor. If it's native DOM node, it will be a string of the tag name. + * + * Note: can only be called on a wrapper of a single node. + */ + type(): String | Function; + + /** + * Iterates through each node of the current wrapper and executes the provided function with a wrapper around + * the corresponding node passed in as the first argument. + * + * Returns itself. + * @param fn A callback to be run for every node in the collection. Should expect a ShallowWrapper as the first + * argument, and will be run with a context of the original instance. + */ + forEach(fn: (wrapper: this) => any): this; + + /** + * Maps the current array of nodes to another array. Each node is passed in as a ShallowWrapper to the map + * function. + * Returns an array of the returned values from the mapping function.. + * @param fn A mapping function to be run for every node in the collection, the results of which will be mapped + * to the returned array. Should expect a ShallowWrapper as the first argument, and will be run + * with a context of the original instance. + */ + map(fn: (wrapper: this) => V): V[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. Each node + * is passed in as a ShallowWrapper, and is processed from left to right. + * @param fn + * @param initialValue + */ + reduce(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Applies the provided reducing function to every node in the wrapper to reduce to a single value. + * Each node is passed in as a ShallowWrapper, and is processed from right to left. + * @param fn + * @param initialValue + */ + reduceRight(fn: (prevVal: R, wrapper: this, index: number) => R, initialValue?: R): R[]; + + /** + * Returns whether or not any of the nodes in the wrapper match the provided selector. + * @param selector + */ + some(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + someWhere(fn: (wrapper: this) => Boolean): Boolean; + + /** + * Returns whether or not all of the nodes in the wrapper match the provided selector. + * @param selector + */ + every(selector: EnzymeSelector): Boolean; + + /** + * Returns whether or not any of the nodes in the wrapper pass the provided predicate function. + * @param fn + */ + everyWhere(fn: (wrapper: this) => Boolean): Boolean; + + length: number; + } + + export interface ShallowWrapper extends CommonWrapper { + shallow(): ShallowWrapper; + render(): CheerioWrapper; + unmount(): ShallowWrapper; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ShallowWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ShallowWrapper; + find(selector: string): ShallowWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ShallowWrapper; + filter(statelessComponent: StatelessComponent): ShallowWrapper; + filter(selector: string): ShallowWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ShallowWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ShallowWrapper; + children(statelessComponent: StatelessComponent): ShallowWrapper; + children(selector: string): ShallowWrapper; + children(): ShallowWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ShallowWrapper; + parents(statelessComponent: StatelessComponent): ShallowWrapper; + parents(selector: string): ShallowWrapper; + parents(): ShallowWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ShallowWrapper; + closest(statelessComponent: StatelessComponent): ShallowWrapper; + closest(selector: string): ShallowWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ShallowWrapper; + } + + export interface ReactWrapper extends CommonWrapper { + unmount(): ReactWrapper; + mount(): ReactWrapper; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ReactWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(selector: string): ReactWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(selector: string): ReactWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; + children(selector: string): ReactWrapper; + children(): ReactWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(selector: string): ReactWrapper; + parents(): ReactWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(selector: string): ReactWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ReactWrapper; + } + + export interface CheerioWrapper extends CommonWrapper { + + } + + /** + * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that + * your tests aren't indirectly asserting on behavior of child components. + * @param node + * @param [options] + */ + export function shallow(node: ReactElement

, options?: any): ShallowWrapper; + + /** + * Mounts and renders a react component into the document and provides a testing wrapper around it. + * @param node + * @param [options] + */ + export function mount(node: ReactElement

, options?: any): ReactWrapper; + + /** + * Render react components to static HTML and analyze the resulting HTML structure. + * @param node + * @param [options] + */ + export function render(node: ReactElement

, options?: any): CheerioWrapper; + + export function describeWithDOM(description: String, fn: Function): void; + + export function spyLifecycle(component: typeof Component): void; +} \ No newline at end of file diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 56767b4ab3..805201e53a 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -73,6 +73,26 @@ namespace ShallowWrapperTest { boolVal = shallowWrapper.contains(

); } + function test_containsMatchingElement() { + boolVal = shallowWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = shallowWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = shallowWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = shallowWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = shallowWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = shallowWrapper.find('.my-button').hasClass('disabled'); } @@ -90,6 +110,20 @@ namespace ShallowWrapperTest { shallowWrapper.children(MyStatelessComponent).props().stateless; } + function test_childAt() { + const childWrapper: ShallowWrapper = shallowWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: ShallowWrapper = shallowWrapper.childAt(0); + } + function test_parents() { shallowWrapper = shallowWrapper.parents(); } @@ -107,6 +141,10 @@ namespace ShallowWrapperTest { shallowWrapper = shallowWrapper.shallow(); } + function test_unmount() { + shallowWrapper = shallowWrapper.unmount(); + } + function test_render() { var cheerioWrapper: CheerioWrapper = shallowWrapper.render(); } @@ -139,6 +177,13 @@ namespace ShallowWrapperTest { function test_state() { shallowWrapper.state(); shallowWrapper.state('key'); + const tmp: String = shallowWrapper.state('key'); + } + + function test_context() { + shallowWrapper.context(); + shallowWrapper.context('key'); + const tmp: String = shallowWrapper.context('key'); } function test_props() { @@ -147,8 +192,12 @@ namespace ShallowWrapperTest { function test_prop() { shallowWrapper.prop('key'); + const tmp: String = shallowWrapper.prop('key'); } + function test_key() { + stringVal = shallowWrapper.key(); + } function test_simulate(...args: any[]) { shallowWrapper.simulate('click'); @@ -156,15 +205,15 @@ namespace ShallowWrapperTest { } function test_setState() { - shallowWrapper = shallowWrapper.setState({stateProperty: 'state'}); + shallowWrapper = shallowWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - shallowWrapper = shallowWrapper.setProps({propsProperty: 'foo'}); + shallowWrapper = shallowWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - shallowWrapper = shallowWrapper.setContext({name: 'baz'}); + shallowWrapper = shallowWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -180,7 +229,11 @@ namespace ShallowWrapperTest { } function test_type() { - var stringOrFunction: String|Function = shallowWrapper.type(); + var stringOrFunction: String | Function = shallowWrapper.type(); + } + + function test_name() { + var str: String = shallowWrapper.name(); } function test_forEach() { @@ -238,6 +291,32 @@ namespace ReactWrapperTest { stringVal: String, elementWrapper: ReactWrapper + function test_unmount() { + reactWrapper = reactWrapper.unmount(); + } + + function test_mount() { + reactWrapper = reactWrapper.mount(); + } + + function test_ref() { + reactWrapper = reactWrapper.ref('refName'); + + interface TmpType1 { + foo: string + } + + interface TmpType2 { + bar: string + } + + const tmp: ReactWrapper = reactWrapper.ref('refName'); + } + + function test_detach() { + reactWrapper.detach(); + } + function test_find() { elementWrapper = reactWrapper.find('.selector'); reactWrapper = reactWrapper.find(MyComponent); @@ -266,6 +345,26 @@ namespace ReactWrapperTest { boolVal = reactWrapper.contains(
); } + function test_containsMatchingElement() { + boolVal = reactWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = reactWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = reactWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = reactWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = reactWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = reactWrapper.find('.my-button').hasClass('disabled'); } @@ -282,6 +381,20 @@ namespace ReactWrapperTest { reactWrapper = reactWrapper.children(); } + function test_childAt() { + const childWrapper: ReactWrapper = reactWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: ReactWrapper = reactWrapper.childAt(0); + } + function test_parents() { reactWrapper = reactWrapper.parents(); } @@ -322,6 +435,13 @@ namespace ReactWrapperTest { function test_state() { reactWrapper.state(); reactWrapper.state('key'); + const tmp: String = reactWrapper.state('key'); + } + + function test_context() { + reactWrapper.context(); + reactWrapper.context('key'); + const tmp: String = reactWrapper.context('key'); } function test_props() { @@ -330,8 +450,12 @@ namespace ReactWrapperTest { function test_prop() { reactWrapper.prop('key'); + const tmp: String = reactWrapper.prop('key'); } + function test_key() { + stringVal = reactWrapper.key(); + } function test_simulate(...args: any[]) { reactWrapper.simulate('click'); @@ -339,15 +463,15 @@ namespace ReactWrapperTest { } function test_setState() { - reactWrapper = reactWrapper.setState({stateProperty: 'state'}); + reactWrapper = reactWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - reactWrapper = reactWrapper.setProps({propsProperty: 'foo'}); + reactWrapper = reactWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - reactWrapper = reactWrapper.setContext({name: 'baz'}); + reactWrapper = reactWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -363,7 +487,11 @@ namespace ReactWrapperTest { } function test_type() { - var stringOrFunction: String|Function = reactWrapper.type(); + var stringOrFunction: String | Function = reactWrapper.type(); + } + + function test_name() { + var str: String = reactWrapper.name(); } function test_forEach() { @@ -418,7 +546,7 @@ namespace CheerioWrapperTest { objectVal: Object, boolVal: Boolean, stringVal: String, - elementWrapper: ReactWrapper + elementWrapper: CheerioWrapper function test_find() { elementWrapper = cheerioWrapper.find('.selector'); @@ -448,6 +576,26 @@ namespace CheerioWrapperTest { boolVal = cheerioWrapper.contains(
); } + function test_containsMatchingElement() { + boolVal = cheerioWrapper.contains(
); + } + + function test_containsAllMatchingElements() { + boolVal = cheerioWrapper.containsAllMatchingElements([
]); + } + + function test_containsAnyMatchingElement() { + boolVal = cheerioWrapper.containsAnyMatchingElements([
]); + } + + function test_equals() { + boolVal = cheerioWrapper.equals(
); + } + + function test_matchesElement() { + boolVal = cheerioWrapper.matchesElement(
); + } + function test_hasClass() { boolVal = cheerioWrapper.find('.my-button').hasClass('disabled'); } @@ -464,6 +612,20 @@ namespace CheerioWrapperTest { cheerioWrapper = cheerioWrapper.children(); } + function test_childAt() { + const childWrapper: CheerioWrapper = cheerioWrapper.childAt(0); + + interface TmpType1 { + foo: any + } + + interface TmpType2 { + bar: any + } + + const childWrapper2: CheerioWrapper = cheerioWrapper.childAt(0); + } + function test_parents() { cheerioWrapper = cheerioWrapper.parents(); } @@ -504,6 +666,13 @@ namespace CheerioWrapperTest { function test_state() { cheerioWrapper.state(); cheerioWrapper.state('key'); + const tmp: String = cheerioWrapper.state('key'); + } + + function test_context() { + cheerioWrapper.context(); + cheerioWrapper.context('key'); + const tmp: String = cheerioWrapper.context('key'); } function test_props() { @@ -512,8 +681,12 @@ namespace CheerioWrapperTest { function test_prop() { cheerioWrapper.prop('key'); + const tmp: String = cheerioWrapper.prop('key'); } + function test_key() { + stringVal = cheerioWrapper.key(); + } function test_simulate(...args: any[]) { cheerioWrapper.simulate('click'); @@ -521,15 +694,15 @@ namespace CheerioWrapperTest { } function test_setState() { - cheerioWrapper = cheerioWrapper.setState({stateProperty: 'state'}); + cheerioWrapper = cheerioWrapper.setState({ stateProperty: 'state' }); } function test_setProps() { - cheerioWrapper = cheerioWrapper.setProps({propsProperty: 'foo'}); + cheerioWrapper = cheerioWrapper.setProps({ propsProperty: 'foo' }); } function test_setContext() { - cheerioWrapper = cheerioWrapper.setContext({name: 'baz'}); + cheerioWrapper = cheerioWrapper.setContext({ name: 'baz' }); } function test_instance() { @@ -545,12 +718,16 @@ namespace CheerioWrapperTest { } function test_type() { - var stringOrFunction: String|Function = cheerioWrapper.type(); + var stringOrFunction: String | Function = cheerioWrapper.type(); + } + + function test_name() { + var str: String = cheerioWrapper.name(); } function test_forEach() { cheerioWrapper = - cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper)=> { + cheerioWrapper.forEach((aCheerioWrapper: CheerioWrapper) => { }); } diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 9047fbf728..2698fd366b 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme v1.2.0 +// Type definitions for Enzyme v2.3.0 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -57,6 +57,34 @@ declare module "enzyme" { */ contains(node: ReactElement): Boolean; + /** + * Returns whether or not a given react element exists in the shallow render tree. + * @param node + */ + containsMatchingElement(node: ReactElement): Boolean; + + /** + * Returns whether or not all the given react elements exists in the shallow render tree + * @param nodes + */ + containsAllMatchingElements(nodes: ReactElement[]): Boolean; + + /** + * Returns whether or not one of the given react elements exists in the shallow render tree. + * @param nodes + */ + containsAnyMatchingElements(nodes: ReactElement[]): Boolean; + + /** + * Returns whether or not the current render tree is equal to the given node, based on the expected value. + */ + equals(node: ReactElement): Boolean; + + /** + * Returns whether or not a given react element matches the shallow render tree. + */ + matchesElement(node: ReactElement): Boolean; + /** * Returns whether or not the current node has a className prop including the passed in class name. * @param className @@ -86,6 +114,13 @@ declare module "enzyme" { children(selector: string): CommonWrapper; children(): CommonWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): CommonWrapper; + childAt(index: Number): CommonWrapper; + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. @@ -157,6 +192,13 @@ declare module "enzyme" { * @param [key] */ state(key?: String): any; + state(key?: String): T; + + /** + * Returns the context hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. + */ + context(key?: String): any; + context(key?: String): T; /** * Returns the props hash for the current node of the wrapper. @@ -172,6 +214,13 @@ declare module "enzyme" { * @param key */ prop(key: String): any; + prop(key: String): T; + + /** + * Returns the key value for the node of the current wrapper. + * NOTE: can only be called on a wrapper of a single node. + */ + key(): String; /** * Simulate events. @@ -247,6 +296,11 @@ declare module "enzyme" { */ type(): String | Function; + /** + * Returns the name of the current node of the wrapper. + */ + name(): String; + /** * Iterates through each node of the current wrapper and executes the provided function with a wrapper around * the corresponding node passed in as the first argument. @@ -313,6 +367,7 @@ declare module "enzyme" { export interface ShallowWrapper extends CommonWrapper { shallow(): ShallowWrapper; render(): CheerioWrapper; + unmount(): ShallowWrapper; /** * Find every node in the render tree that matches the provided selector. @@ -346,6 +401,13 @@ declare module "enzyme" { children(selector: string): ShallowWrapper; children(): ShallowWrapper; + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): ShallowWrapper; + childAt(index: Number): ShallowWrapper; + /** * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. @@ -376,7 +438,94 @@ declare module "enzyme" { } export interface ReactWrapper extends CommonWrapper { + unmount(): ReactWrapper; + mount(): ReactWrapper; + /** + * Returns a wrapper of the node that matches the provided reference name. + * + * NOTE: can only be called on a wrapper instance that is also the root instance. + */ + ref(refName: String): ReactWrapper; + ref(refName: String): ReactWrapper; + + /** + * Detaches the react tree from the DOM. Runs ReactDOM.unmountComponentAtNode() under the hood. + * + * This method will most commonly be used as a "cleanup" method if you decide to use the attachTo option in mount(node, options). + * + * The method is intentionally not "fluent" (in that it doesn't return this) because you should not be doing anything with this wrapper after this method is called. + * + * Using the attachTo is not generally recommended unless it is absolutely necessary to test something. It is your responsibility to clean up after yourself at the end of the test if you do decide to use it, though. + */ + detach() : void; + + /** + * Find every node in the render tree that matches the provided selector. + * @param selector The selector to match. + */ + find(component: ComponentClass): ReactWrapper; + find(statelessComponent: (props: P2) => JSX.Element): ReactWrapper; + find(selector: string): ReactWrapper; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (wrapper: CommonWrapper) => Boolean): ReactWrapper; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(component: ComponentClass): ReactWrapper; + filter(statelessComponent: StatelessComponent): ReactWrapper; + filter(selector: string): ReactWrapper; + + /** + * Returns a new wrapper with all of the children of the node(s) in the current wrapper. Optionally, a selector + * can be provided and it will filter the children by this selector. + * @param [selector] + */ + children(component: ComponentClass): ReactWrapper; + children(statelessComponent: StatelessComponent): ReactWrapper; + children(selector: string): ReactWrapper; + children(): ReactWrapper; + + /** + * Returns a new wrapper with child at the specified index. + * @param index + */ + childAt(index: Number): ReactWrapper; + childAt(index: Number): ReactWrapper; + + /** + * Returns a wrapper around all of the parents/ancestors of the wrapper. Does not include the node in the + * current wrapper. Optionally, a selector can be provided and it will filter the parents by this selector. + * + * Note: can only be called on a wrapper of a single node. + * @param [selector] + */ + parents(component: ComponentClass): ReactWrapper; + parents(statelessComponent: StatelessComponent): ReactWrapper; + parents(selector: string): ReactWrapper; + parents(): ReactWrapper; + + /** + * Returns a wrapper of the first element that matches the selector by traversing up through the current node's + * ancestors in the tree, starting with itself. + * + * Note: can only be called on a wrapper of a single node. + * @param selector + */ + closest(component: ComponentClass): ReactWrapper; + closest(statelessComponent: StatelessComponent): ReactWrapper; + closest(selector: string): ReactWrapper; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): ReactWrapper; } export interface CheerioWrapper extends CommonWrapper { diff --git a/es6-promise/es6-promise-commonjs-tests.ts b/es6-promise/es6-promise-commonjs-tests.ts index b5a2fcbe49..308a042ec6 100644 --- a/es6-promise/es6-promise-commonjs-tests.ts +++ b/es6-promise/es6-promise-commonjs-tests.ts @@ -1,6 +1,7 @@ /// import rsvp = require('es6-promise'); +rsvp.polyfill(); // Test for polyfill method existence var Promise = rsvp.Promise; var promiseString: Promise, diff --git a/es6-promise/es6-promise.d.ts b/es6-promise/es6-promise.d.ts index 001330fd24..4af46edfa6 100644 --- a/es6-promise/es6-promise.d.ts +++ b/es6-promise/es6-promise.d.ts @@ -6,7 +6,6 @@ interface Thenable { then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable; then(onFulfilled?: (value: T) => U | Thenable, onRejected?: (error: any) => void): Thenable; - catch(onRejected?: (error: any) => U | Thenable): Thenable; } declare class Promise implements Thenable { @@ -79,6 +78,7 @@ declare module 'es6-promise' { var foo: typeof Promise; // Temp variable to reference Promise in local context namespace rsvp { export var Promise: typeof foo; + export function polyfill(): void; } export = rsvp; } diff --git a/es6-shim/es6-shim.d.ts b/es6-shim/es6-shim.d.ts index 1c3df0ed7f..b2cad2f4ce 100644 --- a/es6-shim/es6-shim.d.ts +++ b/es6-shim/es6-shim.d.ts @@ -582,6 +582,7 @@ interface Set { entries(): IterableIteratorShim<[T, T]>; keys(): IterableIteratorShim; values(): IterableIteratorShim; + '_es6-shim iterator_'(): IterableIteratorShim; } interface SetConstructor { diff --git a/escodegen/escodegen-tests.ts b/escodegen/escodegen-tests.ts new file mode 100644 index 0000000000..f6c18cf5cd --- /dev/null +++ b/escodegen/escodegen-tests.ts @@ -0,0 +1,56 @@ +/// + +import * as escodegen from 'escodegen'; + +let emptyIndentOptions: escodegen.IndentOptions = {}; +let indentOptions: escodegen.IndentOptions = { + style: ' ', + base: 0, + adjustMultilineComment: true +}; + +let emptyFormatOptions: escodegen.FormatOptions = {}; +let formatOptions: escodegen.FormatOptions = { + indent: indentOptions, + newline: '\n', + space: ' ', + json: true, + renumber: true, + hexadecimal: true, + quotes: 'single', + escapeless: true, + compact: true, + parentheses: true, + semicolons: true, + safeConcatenation: true, + preserveBlankLines: true + } + +let emptyMozillaOptions: escodegen.MozillaOptions = {}; +let mozillaOptions: escodegen.MozillaOptions = { + starlessGenerator: true, + parenthesizedComprehensionBlock: true, + comprehensionExpressionStartsWithAssignment: true +} + +let emptyGenerateOptions: escodegen.GenerateOptions = {}; +let generateOptions: escodegen.GenerateOptions = { + format: formatOptions, + moz: mozillaOptions, + parse: () => {}, + comment: true, + sourceMap: " ", + sourceMapWithCode: true, + sourceContent: " ", + sourceCode: " ", + sourceMapRoot: " ", + directive: true, + file: " ", + verbatim: " " +}; + +let precedence: escodegen.Precedence = escodegen.Precedence.Primary; + +let myCode: string = escodegen.generate({}, generateOptions); + +let ast: any = escodegen.attachComments({}, {}, {}); diff --git a/escodegen/escodegen.d.ts b/escodegen/escodegen.d.ts new file mode 100644 index 0000000000..b72cfdedc6 --- /dev/null +++ b/escodegen/escodegen.d.ts @@ -0,0 +1,178 @@ +// Type definitions for escodegen +// Project: https://github.com/estools/escodegen +// Definitions by: Simon de Lang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'escodegen' { + + export interface FormatOptions { + /** + * The indent options + */ + indent?: IndentOptions; + /** + * New line string. Default is '\n'. + */ + newline?: string; + /** + * White space string. Default is standard ' ' (\x20). + */ + space?: string; + /** + * Enforce JSON format of numeric and string literals. This option takes precedence over option.format.hexadecimal and option.format.quotes. Default is false. + */ + json?: boolean; + /** + * Try to generate shorter numeric literals than toString() (9.8.1). Default is false. + */ + renumber?: boolean; + /** + * Generate hexadecimal a numeric literal if it is shorter than its equivalents. Requires option.format.renumber. Default is false. + */ + hexadecimal?: boolean; + /** + * Delimiter to use for string literals. Accepted values are: 'single', 'double', and 'auto'. When 'auto' is specified, escodegen selects a delimiter that results in a shorter literal. Default is 'single'. + */ + quotes?: string; + /** + * Escape as few characters in string literals as necessary. Default is false. + */ + escapeless?: boolean; + /** + * Do not include superfluous whitespace characters and line terminators. Default is false. + */ + compact?: boolean; + /** + * Preserve parentheses in new expressions that have no arguments. Default is true. + */ + parentheses?: boolean; + /** + * Preserve semicolons at the end of blocks and programs. Default is true. + */ + semicolons?: boolean; + safeConcatenation?: boolean; + preserveBlankLines?: boolean; + } + + export interface IndentOptions { + /** + * Indent string. Default is 4 spaces (' '). + */ + style?: string; + /** + * Base indent level. Default is 0. + */ + base?: number; + /** + * Adjust the indentation of multiline comments to keep asterisks vertically aligned. Default is false. + */ + adjustMultilineComment?: boolean; + } + + export interface MozillaOptions { + /** + * Default: false + */ + starlessGenerator?: boolean; + /** + * Default: false + */ + parenthesizedComprehensionBlock?: boolean; + /** + * Default: false + */ + comprehensionExpressionStartsWithAssignment?: boolean; + } + + export interface GenerateOptions { + /** + * The format options + */ + format?: FormatOptions; + moz?: MozillaOptions; + /** + * Mozilla Parser API compatible parse function, e.g., the parse function exported by esprima. If it is provided, generator tries to use the 'raw' representation. See esprima raw information. Default is null. + */ + parse?: Function; + /** + * If comments are attached to AST, escodegen is going to emit comments to output code. Default is false. + */ + comment?: boolean; + /** + * sourceMap is the source maps's source filename, that's a name that will show up in the browser debugger for the generated source (if source-maps is enabled). + * If a non-empty string value is provided, generate a source map. + */ + sourceMap?: string; + /** + * . If sourceMapWithCode is true generator returns output hash, where output.map is a source-map representation, which can be serialized as output.map.toString(). output.code is a string with generated JS code (note that it's not going to have //@ sourceMappingURL comment in it). + */ + sourceMapWithCode?: boolean; + /** + * Optionally option.sourceContent string can be passed (which represents original source of the file, for example it could be a source of coffeescript from which JS is being generated), if provided generated source map will have original source embedded in it. + */ + sourceContent?: string; + sourceCode?: string; + /** + * Optionally option.sourceMapRoot can be provided, in which case option.sourceMap will be treated as relative to it. For more information about source map itself, see source map library document, V3 draft and HTML5Rocks introduction. Default is undefined + * sourceMapRoot is the source root for the source map (see the Mozilla documentation). If sourceMapWithCode is truthy, an object is returned from generate() of the form: { code: .. , map: .. }. If file is provided, it will be used as file property of generated source map. + */ + sourceMapRoot?: string; + /** + * Recognize DirectiveStatement and distinguish it from ExpressionStatement. Default: false + */ + directive?: boolean; + /** + * If file is provided, it will be used as file property of generated source map. + */ + file?: string; + /** + * Providing verbatim code generation option to Expression nodes. + * verbatim option is provided by user as string. When generating Expression code, + * looking up node[option.verbatim] value and dump it instead of normal code generation. + * + * @example + * + */ + verbatim?: string; + } + + /** + * https://github.com/estools/escodegen/commit/adf113333cd4888cf59bfc4f957df98bf7db82b6 + */ + export enum Precedence { + Sequence, + Yield, + Await, + Assignment, + Conditional, + ArrowFunction, + LogicalOR, + LogicalAND, + BitwiseOR, + BitwiseXOR, + BitwiseAND, + Equality, + Relational, + BitwiseSHIFT, + Additive, + Multiplicative, + Unary, + Postfix, + Call, + New, + TaggedTemplate, + Member, + Primary + } + + /** + * Produces given Abstract Syntax Tree as javascript code + * @param ast The Abstract Syntax Tree to generate code from + * @param options The generation options + */ + export function generate(ast: any, options?: GenerateOptions): string; + /** + * Attaching the comments is needed to keep the comments and to allow blank lines to be preserved. + */ + export function attachComments(ast: any, comments: any, tokens: any): any; +} diff --git a/estraverse/estraverse-tests.ts b/estraverse/estraverse-tests.ts new file mode 100644 index 0000000000..0650aa99e2 --- /dev/null +++ b/estraverse/estraverse-tests.ts @@ -0,0 +1,59 @@ +/// + +import * as estraverse from 'estraverse'; + +let ast: any = { + "type": "Program", + "body": [ + { + "type": "VariableDeclaration", + "declarations": [ + { + "type": "VariableDeclarator", + "id": { + "type": "Identifier", + "name": "answer" + }, + "init": { + "type": "BinaryExpression", + "operator": "*", + "left": { + "type": "Literal", + "value": 6, + "raw": "6" + }, + "right": { + "type": "Literal", + "value": 7, + "raw": "7" + } + } + } + ], + "kind": "var" + } + ], + "sourceType": "script" +}; + +estraverse.traverse(ast, { + enter: (node: any, parentNode: any) => { + if (node.type === 'Identifier') { + return estraverse.VisitorOption.Skip; + } + }, + leave: (node: any, parentNode: any) => {}, + fallback: 'iteration', + keys: { + TestExpression: ['argument'] + } +}); + +estraverse.replace(ast, { + enter: (node: any, parentNode: any) => { + return node; + }, + leave: (node: any, parentNode: any) => { + return node; + } +}); \ No newline at end of file diff --git a/estraverse/estraverse.d.ts b/estraverse/estraverse.d.ts new file mode 100644 index 0000000000..69b4d5d311 --- /dev/null +++ b/estraverse/estraverse.d.ts @@ -0,0 +1,22 @@ +// Type definitions for estraverse +// Project: https://github.com/estools/estraverse +// Definitions by: Sanex3339 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'estraverse' { + export interface Visitor { + enter?: (node: any, parentNode: any) => any; + leave?: (node: any, parentNode: any) => any; + + fallback?: string; + + keys?: {}; + } + + export enum VisitorOption { + Skip, Break, Remove + } + + export function traverse (ast: any, visitor: Visitor): any; + export function replace (ast: any, visitor: Visitor): any; +} \ No newline at end of file diff --git a/exorcist/exorcist-tests.ts b/exorcist/exorcist-tests.ts new file mode 100644 index 0000000000..26a1be0e07 --- /dev/null +++ b/exorcist/exorcist-tests.ts @@ -0,0 +1,15 @@ +/// + +import exorcist = require("exorcist"); + +module ExorcistTest { + + function pullSourceMaps(srcPath: string, projRoot: string) { + exorcist(srcPath, undefined, projRoot); + exorcist(srcPath, null, projRoot, null, true); + exorcist(srcPath, null, projRoot, "./"); + } + +} + +export = ExorcistTest; \ No newline at end of file diff --git a/exorcist/exorcist.d.ts b/exorcist/exorcist.d.ts new file mode 100644 index 0000000000..a60908915b --- /dev/null +++ b/exorcist/exorcist.d.ts @@ -0,0 +1,21 @@ +// Type definitions for exorcist v0.4.0 +// Project: https://github.com/thlorenz/exorcist +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'exorcist' { + import through = require("through"); + + /** Externalizes the source map found inside a stream to an external .map file. + * Works with both JavaScript and CSS input streams + * @param file full path to the map file to which to write the extracted source map + * @param [url] full URL to the map file, set as sourceMappingURL in the streaming output (default: file) + * @param [root] root URL for loading relative source paths, set as sourceRoot in the source map (default: "") + * @param [base] base path for calculating relative source paths (default: use absolute paths) + * @param [errorOnMissing] when truthy, causes 'error' to be emitted instead of 'missing-map' if no map was found in the stream (default: falsey) + */ + function exorcist(file: string, url?: string, root?: string, base?: string, errorOnMissing?: boolean): through.ThroughStream; + export = exorcist; +} \ No newline at end of file diff --git a/express-domain-middleware/express-domain-middleware-tests.ts b/express-domain-middleware/express-domain-middleware-tests.ts new file mode 100644 index 0000000000..446b732353 --- /dev/null +++ b/express-domain-middleware/express-domain-middleware-tests.ts @@ -0,0 +1,2 @@ +/// +import fn = require('express-domain-middleware'); diff --git a/express-domain-middleware/express-domain-middleware.d.ts b/express-domain-middleware/express-domain-middleware.d.ts new file mode 100644 index 0000000000..1710d548e0 --- /dev/null +++ b/express-domain-middleware/express-domain-middleware.d.ts @@ -0,0 +1,12 @@ +// Type definitions for express-domain-middleware +// Project: https://www.npmjs.com/package/express-domain-middleware +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "express-domain-middleware" { + import express = require('express'); + function e(req: express.Request, res: express.Response, next: express.NextFunction): any; + export = e; +} 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 70817018a9..e15dbcb5b6 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -17,21 +17,23 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; + type RequestHandlerParams = RequestHandler | RequestHandler[]; + interface IRoute { path: string; stack: any; - all(...handler: RequestHandler[]): IRoute; - get(...handler: RequestHandler[]): IRoute; - post(...handler: RequestHandler[]): IRoute; - put(...handler: RequestHandler[]): IRoute; - delete(...handler: RequestHandler[]): IRoute; - patch(...handler: RequestHandler[]): IRoute; - options(...handler: RequestHandler[]): IRoute; - head(...handler: RequestHandler[]): IRoute; + all(...handler: RequestHandlerParams[]): IRoute; + get(...handler: RequestHandlerParams[]): IRoute; + post(...handler: RequestHandlerParams[]): IRoute; + put(...handler: RequestHandlerParams[]): IRoute; + delete(...handler: RequestHandlerParams[]): IRoute; + patch(...handler: RequestHandlerParams[]): IRoute; + options(...handler: RequestHandlerParams[]): IRoute; + head(...handler: RequestHandlerParams[]): IRoute; } interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandler[]): T; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; } interface IRouter extends RequestHandler { @@ -88,13 +90,13 @@ declare module "express-serve-static-core" { route(path: string): IRoute; - use(...handler: RequestHandler[]): T; - use(handler: ErrorRequestHandler | RequestHandler): T; - use(path: string, ...handler: RequestHandler[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandler): T; - use(path: string[], ...handler: RequestHandler[]): T; + use(...handler: RequestHandlerParams[]): T; + use(handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string, ...handler: RequestHandlerParams[]): T; + use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; + use(path: string[], ...handler: RequestHandlerParams[]): T; use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandler[]): T; + use(path: RegExp, ...handler: RequestHandlerParams[]): T; use(path: RegExp, handler: ErrorRequestHandler): T; use(path: string, router: Router): T; } @@ -408,7 +410,7 @@ declare module "express-serve-static-core" { interface Send { (status: number, body?: any): Response; - (body: any): Response; + (body?: any): Response; } interface Response extends http.ServerResponse, Express.Response { @@ -860,7 +862,7 @@ declare module "express-serve-static-core" { set(setting: string, val: any): Application; get: { (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandler[]): Application; + (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; }; /** diff --git a/fast-simplex-noise/fast-simplex-noise-tests.ts b/fast-simplex-noise/fast-simplex-noise-tests.ts new file mode 100644 index 0000000000..94bac2f9b8 --- /dev/null +++ b/fast-simplex-noise/fast-simplex-noise-tests.ts @@ -0,0 +1,29 @@ +/// + +import FastSimplexNoise = require('fast-simplex-noise') + +var defaultNoiseGen: FastSimplexNoise = new FastSimplexNoise() +var emptyOptionsNoiseGen: FastSimplexNoise = new FastSimplexNoise({}) + +var noiseGen: FastSimplexNoise = new FastSimplexNoise({ + amplitude: 1, + frequency: 0.01, + max: 255, + min: 0, + octaves: 8, + persistence: 0.5, + random: Math.random +}) + +var values: number[] = [] + +values.push(noiseGen.cylindrical2D(5, 1, 1)) +values.push(noiseGen.cylindrical3D(5, 1, 1, 1)) +values.push(noiseGen.in2D(1, 1)) +values.push(noiseGen.in3D(1, 1, 1)) +values.push(noiseGen.in4D(1, 1, 1, 1)) +values.push(noiseGen.raw2D(1, 1)) +values.push(noiseGen.raw3D(1, 1, 1)) +values.push(noiseGen.raw4D(1, 1, 1, 1)) +values.push(noiseGen.spherical2D(5, 1, 1)) +values.push(noiseGen.spherical3D(5, 1, 1, 1)) diff --git a/fast-simplex-noise/fast-simplex-noise.d.ts b/fast-simplex-noise/fast-simplex-noise.d.ts new file mode 100644 index 0000000000..14df3351ef --- /dev/null +++ b/fast-simplex-noise/fast-simplex-noise.d.ts @@ -0,0 +1,94 @@ +// Type definitions for FastSimplexNoise v2.1.1 +// Project: https://www.npmjs.com/package/fast-simplex-noise +// Definitions by: Tobias Cohen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * A JavaScript implementation of the improved, faster Simplex algorithm outlined in Stefan Gustavson's Simplex noise demystified. + * + * Convenience functions have been added as well, in order to avoid needing to scale and handle the raw noise data directly. + */ +declare class FastSimplexNoise { + amplitude: number; + frequency: number; + max: number; + min: number; + octaves: number; + persistence: number; + random: ()=>number; + + /** + * Options is an optional object that can contain: + * + * amplitude: float - The base amplitude (default: 1.0) + * frequency: float - The base frequency (default: 1.0) + * max: float - The maximum scaled value to return (effective default: 1.0) + * min: float - The minimum scaled value to return (effective default: -1.0) + * octaves: integer - The number of octaves to sum for noise generation (default: 1) + * persistence: float - The persistence of amplitude per octave (default: 0.5) + * random: function - A function that generates random values between 0 and 1 (default: Math.random) + */ + constructor(options?: { + amplitude?: number; + frequency?: number; + max?: number; + min?: number; + octaves?: number; + persistence?: number; + random?: ()=>number; + }); + + /** + * Get a noise value between min and max for a point (x,y) on the surface of a cylinder with circumference c. + */ + cylindrical2D(c: number, x: number, y: number): number; + + /** + * Get a noise value between min and max for a point (x, y, z) on the surface of a cylinder with circumference c. + */ + cylindrical3D(c: number, x: number, y: number, z: number): number; + + /** + * Get a noise value between min and max at the 2D coordinate (x,y) in summed octaves, using amplitude, frequency, and persistence values. + */ + in2D(x: number, y: number): number; + + /** + * Get a noise value between min and max at the 3D coordinate (x,y,z) in summed octaves, using amplitude, frequency, and persistence values. + */ + in3D(x: number, y: number, z: number): number; + + /** + * Get a noise value between min and max at the 4D coordinate (x,y,z,w) in summed octaves, using amplitude, frequency, and persistence values. + */ + in4D(x: number, y: number, z: number, w: number): number; + + /** + * Get a noise value [-1, 1] at the 2D coordinate (x,y). + */ + raw2D(x: number, y: number): number; + + /** + * Get a noise value [-1, 1] at the 3D coordinate (x,y,z). + */ + raw3D(x: number, y: number, z: number): number; + + /** + * Get a noise value [-1, 1] at the 4D coordinate (x,y,z,w). + */ + raw4D(x: number, y: number, z: number, w: number): number; + + /** + * Get a noise value between min and max for a point (x, y) on the surface of a sphere with circumference c. + */ + spherical2D(c: number, x: number, y: number): number; + + /** + * Get a noise value between min and max for a point (x, y, z) on the surface of a sphere with circumference c. + */ + spherical3D(c: number, x: number, y: number, z: number): number; +} + +declare module "fast-simplex-noise" { + export = FastSimplexNoise; +} diff --git a/fbemitter/fbemitter.d.ts b/fbemitter/fbemitter.d.ts index b26b1a3162..0f5f6af528 100644 --- a/fbemitter/fbemitter.d.ts +++ b/fbemitter/fbemitter.d.ts @@ -3,7 +3,7 @@ // Definitions by: kmxz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'fbemitter' { +declare namespace FBEmitter { export class EventSubscription { @@ -64,4 +64,8 @@ declare module 'fbemitter' { } -} \ No newline at end of file +} + +declare module 'fbemitter' { + export = FBEmitter; +} diff --git a/flux/flux-tests.ts b/flux/flux-tests.ts index 24369ef2dd..6bb4350dc6 100644 --- a/flux/flux-tests.ts +++ b/flux/flux-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import flux = require('flux') import FluxUtils = require('flux/utils') @@ -88,7 +88,7 @@ export = customDispatcher // Sample Reduce Store -class CounterStore extends FluxUtils.ReduceStore { +class CounterStore extends FluxUtils.ReduceStore { getInitialState(): number { return 0; } @@ -126,4 +126,4 @@ class CounterContainer extends Component { } } -const container = Container.create(CounterContainer); +const container = Container.create(CounterContainer); diff --git a/flux/flux.d.ts b/flux/flux.d.ts index c3e9e3c10a..944aa54f3a 100644 --- a/flux/flux.d.ts +++ b/flux/flux.d.ts @@ -1,9 +1,11 @@ // Type definitions for Flux // Project: http://facebook.github.io/flux/ -// Definitions by: Steve Baker , Giedrius Grabauskas +// Definitions by: Steve Baker , Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// +/// declare namespace Flux { @@ -71,6 +73,29 @@ declare module "flux" { declare namespace FluxUtils { import React = __React; + import fbEmitter = FBEmitter; + import immutable = Immutable; + + /** + * Default options to create a Container with + * + * @interface RealOptions + */ + interface RealOptions { + /** + * Default value: true + * + * @type {boolean} + */ + pure?: boolean; + /** + * Default value: false + * + * @type {boolean} + */ + withProps?: boolean; + } + export class Container { constructor(); /** @@ -78,14 +103,13 @@ declare namespace FluxUtils { * that updates its state when relevant stores change. * The provided base class must have static methods getStores() and calculateState(). */ - static create(base: React.ComponentClass, options?: any): React.ComponentClass; + static create(base: React.ComponentClass, options?: RealOptions): React.ComponentClass; } /** * This class extends ReduceStore and defines the state as an immutable map. */ - // TODO: Change to > - export class MapStore extends ReduceStore { + export class MapStore extends ReduceStore, TPayload> { /** * Access the value at the given key. * Throws an error if the key does not exist in the cache. @@ -108,12 +132,10 @@ declare namespace FluxUtils { * it allows providing a previous result to update instead of generating a new map. * Providing a previous result allows the possibility of keeping the same reference if the keys did not change. */ - // TODO: Update with Immutable interface. - // getAll(keys: Immutable.IndexedIterable, prev?: Immutable.Map): Immutable.Map; - getAll(keys: any, prev?: any): any; + getAll(keys: immutable.Iterable.Indexed, prev?: immutable.Map): immutable.Map; } - export class ReduceStore extends Store { + export class ReduceStore extends Store { /** * Getter that exposes the entire state of this store. * If your state is not immutable you should override this and not expose state directly. @@ -131,7 +153,7 @@ declare namespace FluxUtils { * All subclasses must implement this method. * This method should be pure and have no side-effects. */ - reduce(state: T, action: any): T; + reduce(state: T, action: TPayload): T; /** * Checks if two versions of state are the same. @@ -141,24 +163,24 @@ declare namespace FluxUtils { } - export class Store { + export class Store { /** * Constructs and registers an instance of this store with the given dispatcher. */ - constructor(dispatcher: Flux.Dispatcher); + constructor(dispatcher: Flux.Dispatcher); /** * Adds a listener to the store, when the store changes the given callback will be called. * A token is returned that can be used to remove the listener. * Calling the remove() function on the returned token will remove the listener. */ - addListener(callback: Function): { remove: Function }; + addListener(callback: Function): fbEmitter.EventSubscription; /** * Returns the dispatcher this store is registered with. */ - getDispatcher(): Flux.Dispatcher; + getDispatcher(): Flux.Dispatcher; /** * Returns the dispatch token that the dispatcher recognizes this store by. @@ -185,7 +207,7 @@ declare namespace FluxUtils { * This is how the store receives actions from the dispatcher. * All state mutation logic must be done during this method. */ - __onDispatch(payload: any): void; + __onDispatch(payload: TPayload): void; } } diff --git a/fontfaceobserver/fontfaceobserver-tests.ts b/fontfaceobserver/fontfaceobserver-tests.ts new file mode 100644 index 0000000000..1ea9a7a222 --- /dev/null +++ b/fontfaceobserver/fontfaceobserver-tests.ts @@ -0,0 +1,46 @@ +/// + +function test1() { + var font = new FontFaceObserver('My Family', { + weight: 400 + }); + + font.load().then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available'); + }); +} + +function test2() { + var font = new FontFaceObserver('My Family'); + + font.load('中国').then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available'); + }); +} + +function test3() { + var font = new FontFaceObserver('My Family'); + + font.load(null, 5000).then(function () { + console.log('Font is available'); + }, function () { + console.log('Font is not available after waiting 5 seconds'); + }); +} + +function test4() { + var fontA = new FontFaceObserver('Family A'); + var fontB = new FontFaceObserver('Family B'); + + fontA.load().then(function () { + console.log('Family A is available'); + }); + + fontB.load().then(function () { + console.log('Family B is available'); + }); +} diff --git a/fontfaceobserver/fontfaceobserver-tests.ts.tscparams b/fontfaceobserver/fontfaceobserver-tests.ts.tscparams new file mode 100644 index 0000000000..14fce22a5c --- /dev/null +++ b/fontfaceobserver/fontfaceobserver-tests.ts.tscparams @@ -0,0 +1 @@ +--target ES6 diff --git a/fontfaceobserver/fontfaceobserver.d.ts b/fontfaceobserver/fontfaceobserver.d.ts new file mode 100644 index 0000000000..8f461dbd4f --- /dev/null +++ b/fontfaceobserver/fontfaceobserver.d.ts @@ -0,0 +1,33 @@ +// Type definitions for fontfaceobserver +// Project: https://github.com/bramstein/fontfaceobserver +// Definitions by: Rand Scullard +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare namespace FontFaceObserver { + interface FontVariant { + weight?: number | string; + style?: string; + stretch?: string; + } +} + +declare class FontFaceObserver { + /** + * Creates a new FontFaceObserver. + * @param fontFamilyName Name of the font family to observe. + * @param variant Description of the font variant to observe. If a property is not present it will default to normal. + */ + constructor(fontFamilyName: string, variant?: FontFaceObserver.FontVariant); + + /** + * Starts observing the loading of the specified font. Immediately returns a new Promise that resolves when the font is available and rejected when the font is not available. + * @param testString If your font doesn't contain latin characters you can pass a custom test string. + * @param timeout The default timeout for giving up on font loading is 3 seconds. You can increase or decrease this by passing a number of milliseconds. + */ + load(testString?: string, timeout?: number): Promise; +} + +declare module "fontfaceobserver" { + export = FontFaceObserver; +} diff --git a/fullpage.js/fullpage.js-tests.ts b/fullpage.js/fullpage.js-tests.ts new file mode 100644 index 0000000000..31e66fdd60 --- /dev/null +++ b/fullpage.js/fullpage.js-tests.ts @@ -0,0 +1,64 @@ +/// + +function test_public_methods() { + $(() => { + $('#fullpage').fullpage({ + // Navigation + menu: '#menu', + lockAnchors: false, + anchors:['firstPage', 'secondPage'], + navigation: false, + navigationPosition: 'right', + navigationTooltips: ['firstSlide', 'secondSlide'], + showActiveTooltip: false, + slidesNavigation: true, + slidesNavPosition: 'bottom', + + // Scrolling + css3: true, + scrollingSpeed: 700, + autoScrolling: true, + fitToSection: true, + fitToSectionDelay: 1000, + scrollBar: false, + easing: 'easeInOutCubic', + easingcss3: 'ease', + loopBottom: false, + loopTop: false, + loopHorizontal: true, + continuousVertical: false, + normalScrollElements: '#element1, .element2', + scrollOverflow: false, + scrollOverflowOptions: null, + touchSensitivity: 15, + normalScrollElementTouchThreshold: 5, + + // Accessibility + keyboardScrolling: true, + animateAnchor: true, + recordHistory: true, + + // Design + controlArrows: true, + verticalCentered: true, + sectionsColor : ['#ccc', '#fff'], + paddingTop: '3em', + paddingBottom: '10px', + fixedElements: '#header, .footer', + responsiveWidth: 0, + responsiveHeight: 0, + + // Custom selectors + sectionSelector: '.section', + slideSelector: '.slide', + + // Events + onLeave: (index, nextIndex, direction) => {}, + afterLoad: (anchorLink, index) => {}, + afterRender: () => {}, + afterResize: () => {}, + afterSlideLoad: (anchorLink, index, slideAnchor, slideIndex) => {}, + onSlideLeave: (anchorLink, index, slideIndex, direction, nextSlideIndex) => {} + }); + }); +} diff --git a/fullpage.js/fullpage.js.d.ts b/fullpage.js/fullpage.js.d.ts new file mode 100644 index 0000000000..b2bedc62d9 --- /dev/null +++ b/fullpage.js/fullpage.js.d.ts @@ -0,0 +1,267 @@ +// Type definitions for fullpage.js v2.8.0 +// Project: http://alvarotrigo.com/fullPage/ +// Definitions by: Andrew Roberts +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface FullPageJsOptions { + /** + * (default false) A selector can be used to specify the menu to link with the sections. This way the scrolling of the sections will activate the corresponding element in the menu using the class active. This won't generate a menu but will just add the active class to the element in the given menu with the corresponding anchor links. In order to link the elements of the menu with the sections, an HTML 5 data-tag (data-menuanchor) will be needed to use with the same anchor links as used within the sections. + */ + menu?: string; + + /** + * (default false). Determines whether anchors in the URL will have any effect at all in the plugin. You can still using anchors internally for your own functions and callbacks, but they won't have any effect in the scrolling of the site. Useful if you want to combine fullPage.js with other plugins using anchor in the URL. + */ + lockAnchors?: boolean; + + /** + * (default []) Defines the anchor links (#example) to be shown on the URL for each section. Anchors value should be unique. The position of the anchors in the array will define to which sections the anchor is applied. (second position for second section and so on). Using anchors forward and backward navigation will also be possible through the browser. This option also allows users to bookmark a specific section or slide. Be careful! anchors can not have the same value as any ID element on the site (or NAME element for IE). Now anchors can be defined directly in the HTML structure by using the attribute data-anchor as explained here. + */ + anchors?: string[]; + + /** + * (default false) If set to true, it will show a navigation bar made up of small circles. + */ + navigation?: boolean; + + /** + * (default none) It can be set to left or right and defines which position the navigation bar will be shown (if using one). + */ + navigationPosition?: string; + + /** + * (default []) Defines the tooltips to show for the navigation circles in case they are being used. Example: navigationTooltips: ['firstSlide', 'secondSlide']. + */ + navigationTooltips?: string[]; + + /** + * (default false) Shows a persistent tooltip for the actively viewed section in the vertical navigation. + */ + showActiveTooltip?: boolean; + + /** + * (default false) If set to true it will show a navigation bar made up of small circles for each landscape slider on the site. + */ + slidesNavigation?: boolean; + + /** + * (default bottom) Defines the position for the landscape navigation bar for sliders. Admits top and bottom as values. You may want to modify the CSS styles to determine the distance from the top or bottom as well as any other style such as color. + */ + slidesNavPosition?: string; + + // Scrolling + + /** + * (default true). Defines whether to use JavaScript or CSS3 transforms to scroll within sections and slides. Useful to speed up the movement in tablet and mobile devices with browsers supporting CSS3. If this option is set to true and the browser doesn't support CSS3, a jQuery fallback will be used instead. + */ + css3?: boolean; + + /** + * (default 700) Speed in milliseconds for the scrolling transitions. + */ + scrollingSpeed?: number; + + /** + * (default true) Defines whether to use the "automatic" scrolling or the "normal" one. It also has affects the way the sections fit in the browser/device window in tablets and mobile phones. + */ + autoScrolling?: boolean; + + /** + * (default true). Determines whether or not to fit sections to the viewport or not. When set to true the current active section will always fill the whole viewport. Otherwise the user will be free to stop in the middle of a section (when ) + */ + fitToSection?: boolean; + + /** + * (default 1000). If fitToSection is set to true, this delays the fitting by the configured milliseconds. + */ + fitToSectionDelay?: number; + + /** + * (default false). Determines whether to use scrollbar for the site or not. In case of using scroll bar, the autoScrolling functionality will still working as expected. The user will also be free to scroll the site with the scroll bar and fullPage.js will fit the section in the screen when scrolling finishes. + */ + scrollBar?: boolean; + + /** + * (default easeInOutCubic) Defines the transition effect to use for the vertical and horizontal scrolling. It requires the file vendors/jquery.easings.min.js or jQuery UI for using some of its transitions. Other libraries could be used instead. + */ + easing?: string; + + /** + * (default ease) Defines the transition effect to use in case of using css3:true. You can use the pre-defined ones (such as linear, ease-out...) or create your own ones using the cubic-bezier function. You might want to use Matthew Lein CSS Easing Animation Tool for it. + */ + easingcss3?: string; + + /** + * (default false) Defines whether scrolling down in the last section should scroll to the first one or not. + */ + loopBottom?: boolean; + + /** + * (default false) Defines whether scrolling up in the first section should scroll to the last one or not. + */ + loopTop?: boolean; + + /** + * (default true) Defines whether horizontal sliders will loop after reaching the last or previous slide or not. + */ + loopHorizontal?: boolean; + + /** + * (default false) Defines whether scrolling down in the last section should scroll down to the first one or not, and if scrolling up in the first section should scroll up to the last one or not. Not compatible with loopTop or loopBottom. + */ + continuousVertical?: boolean; + + /** + * (default null) If you want to avoid the auto scroll when scrolling over some elements, this is the option you need to use. (useful for maps, scrolling divs etc.) It requires a string with the jQuery selectors for those elements. (For example: normalScrollElements: '#element1, .element2') + */ + normalScrollElements?: string; + + /** + * (default false) defines whether or not to create a scroll for the section/slide in case its content is bigger than the height of it. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. In case of setting it to true, it requires the vendor library scrolloverflow.min.js and it should be loaded before the fullPage.js plugin. + */ + scrollOverflow?: boolean; + + /** + * when using scrollOverflow:true fullpage.js will make use of a forked and modified version of iScroll.js libary. You can customize the scrolling behaviour by providing fullpage.js with the iScroll.js options you want to use. Check its documentation for more info. + */ + scrollOverflowOptions?: any; + + /** + * (default 5) Defines a percentage of the browsers window width/height, and how far a swipe must measure for navigating to the next section / slide + */ + touchSensitivity?: number; + + /** + * (default 5) Defines the threshold for the number of hops up the html node tree Fullpage will test to see if normalScrollElements is a match to allow scrolling functionality on divs on a touch device. (For example: normalScrollElementTouchThreshold: 3) + */ + normalScrollElementTouchThreshold?: number; + + // Accessibility + + /** + * (default true) Defines if the content can be navigated using the keyboard + */ + keyboardScrolling?: boolean; + + /** + * (default true) Defines whether the load of the site when given an anchor (#) will scroll with animation to its destination or will directly load on the given section. + */ + animateAnchor?: boolean; + + /** + * (default true) Defines whether to push the state of the site to the browser's history. When set to true each section/slide of the site will act as a new page and the back and forward buttons of the browser will scroll the sections/slides to reach the previous or next state of the site. When set to false, the URL will keep changing but will have no effect ont he browser's history. This option is automatically turned off when using autoScrolling:false. + */ + recordHistory?: boolean; + + // Design + /** + * (default: true) Determines whether to use control arrows for the slides to move right or left. + */ + controlArrows?: boolean; + + /** + * (default true) Vertically centering of the content within sections. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. + */ + verticalCentered?: boolean; + + + resize ?: boolean; + + /** + * (default none) Define the CSS background-color property for each section + */ + sectionsColor ?: string[]; + + /** + * (default 0) Defines the top padding for each section with a numerical value and its measure (paddingTop: '10px', paddingTop: '10em'...) Useful in case of using a fixed header. + */ + paddingTop?: string; + + /** + * (default 0) Defines the bottom padding for each section with a numerical value and its measure (paddingBottom: '10px', paddingBottom: '10em'...). Useful in case of using a fixed footer. + */ + paddingBottom?: string; + + /** + * (default null) Defines which elements will be taken off the scrolling structure of the plugin which is necessary when using the css3 option to keep them fixed. It requires a string with the jQuery selectors for those elements. (For example: fixedElements: '#element1, .element2') + */ + fixedElements?: string; + + /** + * (default 0) A normal scroll (autoScrolling:false) will be used under the defined width in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for his own responsive CSS. For example, if set to 900, whenever the browser's width is less than 900 the plugin will scroll like a normal site. + */ + responsiveWidth?: number; + + /** + * (default 0) A normal scroll (autoScrolling:false) will be used under the defined height in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for his own responsive CSS. For example, if set to 900, whenever the browser's height is less than 900 the plugin will scroll like a normal site. + */ + responsiveHeight?: number; + + // Custom selectors + + /** + * (default .section) Defines the jQuery selector used for the plugin sections. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. + */ + sectionSelector?: string; + + /** + * (default .slide) Defines the jQuery selector used for the plugin slides. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. + */ + slideSelector?: string; + + // Events + /** + * This callback is fired once the user leaves a section, in the transition to the new section. Returning false will cancel the move before it takes place. + * @param index index of the leaving section. Starting from 1. + * @param nextIndex index of the destination section. Starting from 1. + * @param direction it will take the values up or down depending on the scrolling direction. + */ + onLeave?: (index: number, nextIndex: number, direction: string) => void; + + /** + * Callback fired once the sections have been loaded, after the scrolling has ended. + * @param anchorLink anchorLink corresponding to the section. + * @param index index of the section. Starting from 1. + */ + afterLoad?: (anchorLink: string, index: number) => void; + + /** + * This callback is fired just after the structure of the page is generated. This is the callback you want to use to initialize other plugins or fire any code which requires the document to be ready (as this plugin modifies the DOM to create the resulting structure). + */ + afterRender?: () => void; + + /** + * This callback is fired after resizing the browser's window. Just after the sections are resized. + */ + afterResize?: () => void; + + /** + * Callback fired once the slide of a section have been loaded, after the scrolling has ended. + * + * In case of not having anchorLinks defined for the slide or slides the slideIndex parameter would be the only one to use. + * + * Parameters: + * + * @param anchorLink anchorLink corresponding to the section. + * @param index index of the section. Starting from 1. + * @param slideAnchor anchor corresponding to the slide (in case there is) + * @param slideIndex index of the slide. Starting from 1. (the default slide doesn't count as slide, but as a section) + */ + afterSlideLoad?: (anchorLink: string, index: number, slideAnchor: string, slideIndex: number) => void; + + /** + * This callback is fired once the user leaves an slide to go to another, in the transition to the new slide. Returning false will cancel the move before it takes place. + * @param anchorLink: anchorLink corresponding to the section. + * @param index index of the section. Starting from 1. + * @param slideIndex index of the slide. Starting from 0. + * @param direction takes the values right or left depending on the scrolling direction. + * @param nextSlideIndex index of the destination slide. Starting from 0. + */ + onSlideLeave?: (anchorLink: string, index: number, slideIndex: number, direction: string, nextSlideIndex: number) => void; +} + +interface JQuery { + fullpage(options?: FullPageJsOptions): JQuery; +} diff --git a/gapi.auth2/gapi.auth2.d.ts b/gapi.auth2/gapi.auth2.d.ts index 9b23a34874..c94ed8c1a9 100644 --- a/gapi.auth2/gapi.auth2.d.ts +++ b/gapi.auth2/gapi.auth2.d.ts @@ -64,7 +64,7 @@ declare namespace gapi.auth2 { fetch_basic_profile?: boolean; prompt?: boolean; scope?: string; - }, onsuccess: () => any, onfailure: (reason: string) => any): any; + }, onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } export interface IsSignedIn{ diff --git a/generic-functions/generic-functions.d.ts b/generic-functions/generic-functions.d.ts new file mode 100644 index 0000000000..d25ebde7cc --- /dev/null +++ b/generic-functions/generic-functions.d.ts @@ -0,0 +1,15 @@ +// Type definitions for generic-functions +// Project: https://github.com/stpettersens/generic-functions +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/definitelytyped/DefinitelyTyped + +declare module "generic-functions" { + function strcmp(str1: string, str2: string): boolean; + function icstrcmp(str1: string, str2: string): boolean; + function strendswith(str: string, suffix: string): boolean; + function icstrendswith(str: string, suffix: string): boolean; + function endswithdot(str: string): string; + function println(message: string): void; + function printlns(message: string[]): void; + function objGetKeyByValue(object: Object, value: any): string; +} diff --git a/generic-functions/genetic-functions-tests.ts b/generic-functions/genetic-functions-tests.ts new file mode 100644 index 0000000000..d3dc53665a --- /dev/null +++ b/generic-functions/genetic-functions-tests.ts @@ -0,0 +1,16 @@ +/// + +import g = require('generic-functions'); + +var tvShow: Object = { + seasons: 2, + show: "Better Call Saul" +}; + +console.log(g.strcmp("foo", "foo")); // => true +console.log(g.icstrcmp("BAR", "bar")); // => true +console.log(g.strendswith("file.pdf", "pdf")); // => true +console.log(g.icstrendswith("file.PDF", "pdf")); // => true +console.log(g.endswithdot("file.pdf")); // => ".pdf" +console.log(g.objGetKeyByValue(tvShow, 2)); // => "seasons" +console.log(g.objGetKeyByValue(tvShow, "Better Call Saul")); // => "show" diff --git a/geojson/geojson-tests.ts b/geojson/geojson-tests.ts index ce38b654b2..75cf6ffd54 100644 --- a/geojson/geojson-tests.ts +++ b/geojson/geojson-tests.ts @@ -72,6 +72,11 @@ var point: GeoJSON.Point = { coordinates: [100.0, 0.0] }; + +// This type is commonly used in the turf package +var pointCoordinates: number[] = point.coordinates + + var lineString: GeoJSON.LineString = { type: "LineString", coordinates: [ [100.0, 0.0], [101.0, 1.0] ] @@ -126,4 +131,4 @@ var geometryCollection: GeoJSON.GeometryCollection = { coordinates: [ [101.0, 0.0], [102.0, 1.0] ] } ] -} \ No newline at end of file +} diff --git a/geojson/geojson.d.ts b/geojson/geojson.d.ts index d77de1fe86..38715a9a27 100644 --- a/geojson/geojson.d.ts +++ b/geojson/geojson.d.ts @@ -18,10 +18,7 @@ declare namespace GeoJSON { /*** * http://geojson.org/geojson-spec.html#positions */ - export interface Position - { - [index: number]: number; - } + export type Position = number[] /*** * http://geojson.org/geojson-spec.html#geometry-objects @@ -36,6 +33,7 @@ declare namespace GeoJSON { */ export interface Point extends GeometryObject { + type: 'Point' coordinates: Position } @@ -44,6 +42,7 @@ declare namespace GeoJSON { */ export interface MultiPoint extends GeometryObject { + type: 'MultiPoint' coordinates: Position[] } @@ -52,6 +51,7 @@ declare namespace GeoJSON { */ export interface LineString extends GeometryObject { + type: 'LineString' coordinates: Position[] } @@ -60,6 +60,7 @@ declare namespace GeoJSON { */ export interface MultiLineString extends GeometryObject { + type: 'MultiLineString' coordinates: Position[][] } @@ -68,6 +69,7 @@ declare namespace GeoJSON { */ export interface Polygon extends GeometryObject { + type: 'Polygon' coordinates: Position[][] } @@ -76,6 +78,7 @@ declare namespace GeoJSON { */ export interface MultiPolygon extends GeometryObject { + type: 'MultiPolygon' coordinates: Position[][][] } @@ -84,6 +87,7 @@ declare namespace GeoJSON { */ export interface GeometryCollection extends GeoJsonObject { + type: 'GeometryCollection' geometries: GeometryObject[]; } @@ -92,6 +96,7 @@ declare namespace GeoJSON { */ export interface Feature extends GeoJsonObject { + type: 'Feature' geometry: T; properties: any; id?: string; @@ -102,6 +107,7 @@ declare namespace GeoJSON { */ export interface FeatureCollection extends GeoJsonObject { + type: 'FeatureCollection' features: Feature[]; } diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index a2c40c1d68..9a75f9699e 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -45,7 +45,6 @@ var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } - return true; }); if (shouldQuit) { @@ -80,19 +79,9 @@ app.on('ready', () => { mainWindow = null; }); - mainWindow.print({silent: true, printBackground: false}); mainWindow.webContents.print({silent: true, printBackground: false}); - mainWindow.print(); mainWindow.webContents.print(); - mainWindow.printToPDF({ - marginsType: 1, - pageSize: 'A3', - printBackground: true, - printSelectionOnly: true, - landscape: true, - }, (error: Error, data: Buffer) => {}); - mainWindow.webContents.printToPDF({ marginsType: 1, pageSize: 'A3', @@ -101,7 +90,6 @@ app.on('ready', () => { landscape: true, }, (error: Error, data: Buffer) => {}); - mainWindow.printToPDF({}, (err, data) => {}); mainWindow.webContents.printToPDF({}, (err, data) => {}); mainWindow.webContents.executeJavaScript('return true;'); @@ -147,6 +135,29 @@ app.on('ready', () => { mainWindow.webContents.debugger.sendCommand("Network.enable"); }); +app.commandLine.appendSwitch('enable-web-bluetooth'); + +app.on('ready', () => { + mainWindow.webContents.on('select-bluetooth-device', (event, deviceList, callback) => { + event.preventDefault(); + + let result = (() => { + for (let device of deviceList) { + if (device.deviceName === 'test') { + return device; + } + } + return null; + })(); + + if (!result) { + callback(''); + } else { + callback(result.deviceId); + } + }); +}); + // Locale app.getLocale(); @@ -288,10 +299,6 @@ if (browserOptions.transparent) { win.loadURL('file://' + __dirname + '/fallback.html'); } -app.on('platform-theme-changed', () => { - console.log(systemPreferences.isDarkMode()); -}); - // app // https://github.com/atom/electron/blob/master/docs/api/app.md @@ -315,6 +322,14 @@ app.on('login', function(event, webContents, request, authInfo, callback) { callback('username', 'secret'); }); +var win = new BrowserWindow({show: false}) +win.once('ready-to-show', () => { + win.show(); +}); + +app.relaunch({args: process.argv.slice(1).concat(['--relaunch'])}); +app.exit(0); + // auto-updater // https://github.com/atom/electron/blob/master/docs/api/auto-updater.md @@ -344,6 +359,8 @@ win.show(); var toolbarRect = document.getElementById('toolbar').getBoundingClientRect(); win.setSheetOffset(toolbarRect.height); +var installed = BrowserWindow.getDevToolsExtensions().hasOwnProperty('devtron'); + // content-tracing // https://github.com/atom/electron/blob/master/docs/api/content-tracing.md @@ -718,6 +735,8 @@ var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); +let image2 = nativeImage.createFromPath('/Users/somebody/images/icon.png'); + // process // https://github.com/electron/electron/blob/master/docs/api/process.md @@ -818,15 +837,23 @@ session.defaultSession.on('will-download', (event, item, webContents) => { console.log(item.getFilename()); console.log(item.getTotalBytes()); - item.on('updated', function() { - console.log('Received bytes: ' + item.getReceivedBytes()); + item.on('updated', (event, state) => { + if (state === 'interrupted') { + console.log('Download is interrupted but can be resumed'); + } else if (state === 'progressing') { + if (item.isPaused()) { + console.log('Download is paused'); + } else { + console.log(`Received bytes: ${item.getReceivedBytes()}`); + } + } }); item.on('done', function(e, state) { if (state == "completed") { console.log("Download successfully"); } else { - console.log("Download is cancelled or interrupted that can't be resumed"); + console.log(`Download failed: ${state}`) } }); }); @@ -858,6 +885,13 @@ session.defaultSession.setPermissionRequestHandler(function(webContents, permiss callback(true); }); +// consider any url ending with `example.com`, `foobar.com`, `baz` +// for integrated authentication. +session.defaultSession.allowNTLMCredentialsForDomains('*example.com, *foobar.com, *baz') + +// consider all urls for integrated authentication. +session.defaultSession.allowNTLMCredentialsForDomains('*') + // Modify the user agent for all requests to the following urls. var filter = { urls: ["https://*.github.com/*", "*://electron.github.io"] @@ -867,3 +901,15 @@ session.defaultSession.webRequest.onBeforeSendHeaders(filter, function(details, details.requestHeaders['User-Agent'] = "MyAgent"; callback({cancel: false, requestHeaders: details.requestHeaders}); }); + +app.on('ready', function () { + const protocol = session.defaultSession.protocol + protocol.registerFileProtocol('atom', function (request, callback) { + var url = request.url.substr(7); + callback({path: path.normalize(__dirname + '/' + url)}); + }, function (error) { + if (error) { + console.error('Failed to register protocol'); + } + }) +}); diff --git a/github-electron/github-electron-renderer-tests.ts b/github-electron/github-electron-renderer-tests.ts index 42d034c5c7..eecec65752 100644 --- a/github-electron/github-electron-renderer-tests.ts +++ b/github-electron/github-electron-renderer-tests.ts @@ -75,6 +75,9 @@ webFrame.executeJavaScript('JSON.stringify({})', false, (result) => { console.log(result); }); +console.log(webFrame.getResourceUsage()); +webFrame.clearCache(); + // clipboard // https://github.com/atom/electron/blob/master/docs/api/clipboard.md @@ -232,7 +235,7 @@ webview.addEventListener('found-in-page', function(e) { } }); -var rquestId = webview.findInPage("test"); +var requestId = webview.findInPage("test"); webview.addEventListener('new-window', function(e) { require('electron').shell.openExternal(e.url); diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index dfcff3d83c..f7dd206708 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v0.37.8 +// Type definitions for Electron v1.2.3 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -49,7 +49,9 @@ declare namespace Electron { /** * Emitted when all windows have been closed. * - * This event is only emitted when the application is not going to quit. + * If you do not subscribe to this event and all windows are closed, + * the default behavior is to quit the app; however, if you subscribe, + * you control whether the app quits or not. * If the user pressed Cmd + Q, or the developer called app.quit(), * Electron will first try to close all the windows and then emit the will-quit event, * and in this case the window-all-closed event would not be emitted. @@ -96,6 +98,11 @@ declare namespace Electron { * Note: This is only implemented on OS X. */ on(event: 'activate', listener: Function): this; + /** + * Emitted during Handoff when an activity from a different device wants to be resumed. + * You should call event.preventDefault() if you want to handle this event. + */ + on(event: 'continue-activity', listener: (event: Event, type: string, userInfo: Object) => void): this; /** * Emitted when a browserWindow gets blurred. */ @@ -108,6 +115,10 @@ declare namespace Electron { * Emitted when a new browserWindow is created. */ on(event: 'browser-window-created', listener: (event: Event, browserWindow: BrowserWindow) => void): this; + /** + * Emitted when a new webContents is created. + */ + on(event: 'web-contents-created', listener: (event: Event, webContents: WebContents) => void): this; /** * Emitted when failed to verify the certificate for url, to trust the certificate * you should prevent the default behavior with event.preventDefault() and call callback(true). @@ -166,6 +177,24 @@ declare namespace Electron { * and the before-quit and will-quit events will not be emitted. */ exit(exitCode: number): void; + /** + * Relaunches the app when current instance exits. + * + * By default the new instance will use the same working directory + * and command line arguments with current instance. + * When args is specified, the args will be passed as command line arguments instead. + * When execPath is specified, the execPath will be executed for relaunch instead of current app. + * + * Note that this method does not quit the app when executed, you have to call app.quit + * or app.exit after calling app.relaunch to make the app restart. + * + * When app.relaunch is called for multiple times, multiple instances + * will be started after current instance exited. + */ + relaunch(options?: { + args?: string[], + execPath?: string + }): void; /** * On Linux, focuses on the first visible window. * On OS X, makes the application the active app. @@ -251,8 +280,7 @@ declare namespace Electron { /** * Removes the current executable as the default handler for a protocol (aka URI scheme). * - * Note: This is only implemented on Windows. - * On OS X, removing the app will automatically remove the app as the default protocol handler. + * Note: This is only implemented on OS X and Windows. */ removeAsDefaultProtocolClient(protocol: string): void; /** @@ -267,20 +295,35 @@ declare namespace Electron { * Note: This API is only available on Windows. */ setUserTasks(tasks: Task[]): void; - /** - * Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. - * Normally, Electron will only send NTLM/Kerberos credentials for URLs that fall under - * "Local Intranet" sites (i.e. are in the same domain as you). - * However, this detection often fails when corporate networks are badly configured, - * so this lets you co-opt this behavior and enable it for all URLs. - */ - allowNTLMCredentialsForAllDomains(allow: boolean): void; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance * of your app is running, and other instances signal this instance and exit. */ - makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean; + makeSingleInstance(callback: (args: string[], workingDirectory: string) => void): boolean; + /** + * Releases all locks that were created by makeSingleInstance. This will allow + * multiple instances of the application to once again run side by side. + */ + releaseSingleInstance(): void; + /** + * Creates an NSUserActivity and sets it as the current activity. + * The activity is eligible for Handoff to another device afterward. + * + * @param type Uniquely identifies the activity. Maps to NSUserActivity.activityType. + * @param userInfo App-specific state to store for use by another device. + * @param webpageURL The webpage to load in a browser if no suitable app is + * installed on the resuming device. The scheme must be http or https. + * + * Note: This API is only available on Mac. + */ + setUserActivity(type: string, userInfo: Object, webpageURL?: string): void; + /** + * @returns The type of the currently running activity. + * + * Note: This API is only available on Mac. + */ + getCurrentActivityType(): string; /** * Changes the Application User Model ID to id. */ @@ -293,6 +336,11 @@ declare namespace Electron { * Note: This API is only available on Linux. */ importCertificate(options: ImportCertificateOptions, callback: (result: number) => void): void; + /** + * Disables hardware acceleration for current app. + * This method can only be called before app is ready. + */ + disableHardwareAcceleration(): void; commandLine: CommandLine; /** * Note: This API is only available on Mac. @@ -300,7 +348,7 @@ declare namespace Electron { dock: Dock; } - type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'; + type AppPathName = 'home'|'appData'|'userData'|'temp'|'exe'|'module'|'desktop'|'documents'|'downloads'|'music'|'pictures'|'videos'|'pepperFlashSystemPlugin'; interface ImportCertificateOptions { /** @@ -348,6 +396,12 @@ declare namespace Electron { * Note: This API is only available on Mac. */ cancelBounce(id: number): void; + /** + * Bounces the Downloads stack if the filePath is inside the Downloads folder. + * + * Note: This API is only available on Mac. + */ + downloadFinished(filePath: string): void; /** * Sets the string to be displayed in the dock’s badging area. * @@ -448,9 +502,8 @@ declare namespace Electron { on(event: string, listener: Function): this; /** * Set the url and initialize the auto updater. - * The url cannot be changed once it is set. */ - setFeedURL(url: string): void; + setFeedURL(url: string, requestHeaders?: Headers): void; /** * Ask the server whether there is an update, you have to call setFeedURL * before using this API @@ -509,6 +562,10 @@ declare namespace Electron { * Emitted when the window is hidden. */ on(event: 'hide', listener: Function): this; + /** + * Emitted when the web page has been rendered and window can be displayed without visual flash. + */ + on(event: 'ready-to-show', listener: Function): this; /** * Emitted when window is maximized. */ @@ -600,6 +657,10 @@ declare namespace Electron { * @param name The name of the devtools extension to remove. */ static removeDevToolsExtension(name: string): void; + /** + * @returns devtools extensions. + */ + static getDevToolsExtensions(): DevToolsExtensions; /** * The WebContents object this window owns, all web page related events and * operations would be done via it. @@ -825,7 +886,7 @@ declare namespace Electron { * Changes the attachment point for sheets on Mac OS X. * Note: This API is available only on OS X. */ - setSheetOffset(offset: number): void; + setSheetOffset(offsetY: number, offsetX?: number): void; /** * Starts or stops flashing the window to attract user's attention. */ @@ -899,19 +960,11 @@ declare namespace Electron { capturePage(rect: Rectangle, callback: (image: NativeImage) => void): void; capturePage(callback: (image: NativeImage) => void): void; /** - * Same with webContents.print([options]) - */ - print(options?: PrintOptions): void; - /** - * Same with webContents.printToPDF([options]) - */ - printToPDF(options: PrintToPDFOptions, callback: (error: Error, data: Buffer) => void): void; - /** - * Same with webContents.loadURL(url). + * Same as webContents.loadURL(url). */ loadURL(url: string, options?: LoadURLOptions): void; /** - * Same with webContents.reload. + * Same as webContents.reload. */ reload(): void; /** @@ -954,10 +1007,15 @@ declare namespace Electron { */ setThumbarButtons(buttons: ThumbarButton[]): boolean; /** - * Shows pop-up dictionary that searches the selected word on the page. + * Same as webContents.showDefinitionForSelection(). * Note: This API is available only on OS X. */ showDefinitionForSelection(): void; + /** + * Changes window icon. + * Note: This API is not available on OS X. + */ + setIcon(icon: NativeImage): void; /** * Sets whether the window menu bar should hide itself automatically. Once set * the menu bar will only show when users press the single Alt key. @@ -989,10 +1047,17 @@ declare namespace Electron { */ isVisibleOnAllWorkspaces(): boolean; /** - * Ignore all moused events that happened in the window. - * Note: This API is available only on OS X. + * Makes the window ignore all mouse events. + * + * All mouse events happened in this window will be passed to the window below this window, + * but if this window has focus, it will still receive keyboard events. */ setIgnoreMouseEvents(ignore: boolean): void; + /** + * Changes whether the window can be focused. + * Note: This API is available only on Windows. + */ + setFocusable(focusable: boolean): void; } type SwipeDirection = 'up' | 'right' | 'down' | 'left'; @@ -1006,6 +1071,13 @@ declare namespace Electron { flags?: ThumbarButtonFlags[]; } + interface DevToolsExtensions { + [name: string]: { + name: string; + value: string; + } + } + interface WebPreferences { /** * Whether node integration is enabled. @@ -1104,9 +1176,18 @@ declare namespace Electron { */ directWrite?: boolean; /** - * A list of feature strings separated by ",". + * Enables scroll bounce (rubber banding) effect on OS X. + * Default: false. + */ + scrollBounce?: boolean; + /** + * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to enable. */ blinkFeatures?: string; + /** + * A list of feature strings separated by ",", like CSSVariables,KeyboardEventKey to disable. + */ + disableBlinkFeatures?: string; /** * Sets the default font for the font-family. */ @@ -1232,6 +1313,14 @@ declare namespace Electron { * Default: true. */ closable?: boolean; + /** + * Whether the window can be focused. + * On Windows setting focusable: false also implies setting skipTaskbar: true. + * On Linux setting focusable: false makes the window stop interacting with wm, + * so the window will always stay on top in all workspaces. + * Default: true. + */ + focusable?: boolean; /** * Whether the window should always stay on top of other windows. * Default: false. @@ -1239,12 +1328,13 @@ declare namespace Electron { alwaysOnTop?: boolean; /** * Whether the window should show in fullscreen. - * When explicity set to false the fullscreen button will be hidden or disabled on OS X. + * When explicitly set to false the fullscreen button will be hidden or disabled on OS X. * Default: false. */ fullscreen?: boolean; /** - * Whether the maximize/zoom button on OS X should toggle full screen mode or maximize window. + * Whether the window can be put into fullscreen mode. + * On OS X, also whether the maximize/zoom button should toggle full screen mode or maximize window. * Default: true. */ fullscreenable?: boolean; @@ -1361,11 +1451,11 @@ declare namespace Electron { /** * @returns The contents of the clipboard as markup. */ - readHtml(type?: ClipboardType): string; + readHTML(type?: ClipboardType): string; /** * Writes markup to the clipboard. */ - writeHtml(markup: string, type?: ClipboardType): void; + writeHTML(markup: string, type?: ClipboardType): void; /** * @returns The contents of the clipboard as a NativeImage. */ @@ -1377,11 +1467,11 @@ declare namespace Electron { /** * @returns The contents of the clipboard as RTF. */ - readRtf(type?: ClipboardType): string; + readRTF(type?: ClipboardType): string; /** * Writes the text into the clipboard in RTF. */ - writeRtf(text: string, type?: ClipboardType): void; + writeRTF(text: string, type?: ClipboardType): void; /** * Clears everything in clipboard. */ @@ -1687,6 +1777,10 @@ declare namespace Electron { interface OpenDialogOptions { title?: string; defaultPath?: string; + /** + * Custom label for the confirmation button, when left empty the default label will be used. + */ + buttonLabel?: string; /** * File types that can be displayed or selected. */ @@ -1707,6 +1801,10 @@ declare namespace Electron { interface SaveDialogOptions { title?: string; defaultPath?: string; + /** + * Custom label for the confirmation button, when left empty the default label will be used. + */ + buttonLabel?: string; /** * File types that can be displayed, see dialog.showOpenDialog for an example. */ @@ -1722,7 +1820,7 @@ declare namespace Electron { */ type?: 'none' | 'info' | 'error' | 'question' | 'warning'; /** - * Texts for buttons. + * Texts for buttons. On Windows, an empty array will result in one button labeled "OK". */ buttons?: string[]; /** @@ -1765,9 +1863,9 @@ declare namespace Electron { */ interface DownloadItem extends NodeJS.EventEmitter { /** - * Emits when the downloadItem gets updated. + * Emitted when the download has been updated and is not done. */ - on(event: 'updated', listener: Function): this; + on(event: 'updated', listener: (event: Event, state: 'progressing' | 'interrupted') => void): this; /** * Emits when the download is in a terminal state. This includes a completed download, * a cancelled download (via downloadItem.cancel()), and interrupted download that can’t be resumed. @@ -1785,10 +1883,18 @@ declare namespace Electron { * Pauses the download. */ pause(): void; + /** + * @returns Whether the download is paused. + */ + isPaused(): boolean; /** * Resumes the download that has been paused. */ resume(): void; + /** + * @returns Whether the download can resume. + */ + canResume(): boolean; /** * Cancels the download operation. */ @@ -1824,6 +1930,10 @@ declare namespace Electron { * @returns The Content-Disposition field from the response header. */ getContentDisposition(): string; + /** + * @returns The current state. + */ + getState(): 'progressing' | 'completed' | 'cancelled' | 'interrupted'; } // https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md @@ -1974,8 +2084,8 @@ declare namespace Electron { } type MenuItemType = 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; - type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'selectall' | 'minimize' | 'close'; - type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'window' | 'help' | 'services'; + type MenuItemRole = 'undo' | 'redo' | 'cut' | 'copy' | 'paste' | 'pasteandmatchstyle' | 'selectall' | 'delete' | 'minimize' | 'close'; + type MenuItemRoleMac = 'about' | 'hide' | 'hideothers' | 'unhide' | 'front' | 'zoom' | 'window' | 'help' | 'services'; interface MenuItemOptions { /** @@ -2023,6 +2133,7 @@ declare namespace Electron { * Punctuations like ~, !, @, #, $, etc. * Plus * Space + * Tab * Backspace * Delete * Insert @@ -2558,10 +2669,19 @@ declare namespace Electron { * Clears the host resolver cache. */ clearHostResolverCache(callback: Function): void; + /** + * Dynamically sets whether to always send credentials for HTTP NTLM or Negotiate authentication. + * @param domains Comma-seperated list of servers for which integrated authentication is enabled. + */ + allowNTLMCredentialsForDomains(domains: string): void; /** * The webRequest API set allows to intercept and modify contents of a request at various stages of its lifetime. */ webRequest: WebRequest; + /** + * @returns An instance of protocol module for this session. + */ + protocol: Protocol; } type Permission = 'media' | 'geolocation' | 'notifications' | 'midiSysex' | 'pointerLock' | 'fullscreen' | 'openExternal'; @@ -2961,7 +3081,7 @@ declare namespace Electron { * * Note: This is only implemented on OS X. */ - subscribeNotification(event: string, callback: Function): number; + subscribeNotification(event: string, callback: (event: Event, userInfo: Object) => void): number; /** * Removes the subscriber with id. * @@ -2973,7 +3093,7 @@ declare namespace Electron { * * Note: This is only implemented on OS X. */ - getUserDefault(key: string, type: 'string' | 'boolean' | 'integer' | 'float' | 'double' | 'url'): any; + 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 @@ -3278,12 +3398,28 @@ declare namespace Electron { * */ on(event: 'did-change-theme-color', listener: Function): this; + /** + * Emitted when mouse moves over a link or the keyboard moves the focus to a link. + */ + on(event: 'update-target-url', listener: (event: Event, url: string) => void): this; /** * Emitted when the cursor’s type changes. * If the type parameter is custom, the image parameter will hold the custom cursor image * in a NativeImage, and the scale will hold scaling information for the image. */ on(event: 'cursor-changed', listener: (event: Event, type: CursorType, image?: NativeImage, scale?: number) => void): this; + /** + * Emitted when there is a new context menu that needs to be handled. + */ + on(event: 'context-menu', listener: (event: Event, params: ContextMenuParams) => void): this; + /** + * Emitted when bluetooth device needs to be selected on call to navigator.bluetooth.requestDevice. + * To use navigator.bluetooth api webBluetooth should be enabled. + * If event.preventDefault is not called, first available device will be selected. + * callback should be called with deviceId to be selected, + * passing empty string to callback will cancel the request. + */ + on(event: 'select-bluetooth-device', listener: (event: Event, deviceList: BluetoothDevice[], callback: (deviceId: string) => void) => void): this; on(event: string, listener: Function): this; /** * Loads the url in the window. @@ -3554,6 +3690,15 @@ declare namespace Electron { * @returns If the process of saving page has been initiated successfully. */ savePage(fullPath: string, saveType: 'HTMLOnly' | 'HTMLComplete' | 'MHTML', callback?: (eror: Error) => void): boolean; + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on OS X. + */ + showDefinitionForSelection(): void; + /** + * @returns The unique ID of this WebContents. + */ + id: number; /** * @returns The session object used by this webContents. */ @@ -3574,6 +3719,149 @@ declare namespace Electron { debugger: Debugger; } + interface ContextMenuParams { + /** + * x coodinate + */ + x: number; + /** + * y coodinate + */ + y: number; + /** + * URL of the link that encloses the node the context menu was invoked on. + */ + linkURL: string; + /** + * Text associated with the link. May be an empty string if the contents of the link are an image. + */ + linkText: string; + /** + * URL of the top level page that the context menu was invoked on. + */ + pageURL: string; + /** + * URL of the subframe that the context menu was invoked on. + */ + frameURL: string; + /** + * Source URL for the element that the context menu was invoked on. + * Elements with source URLs are images, audio and video. + */ + srcURL: string; + /** + * Type of the node the context menu was invoked on. + */ + mediaType: 'none' | 'image' | 'audio' | 'video' | 'canvas' | 'file' | 'plugin'; + /** + * Parameters for the media element the context menu was invoked on. + */ + mediaFlags: { + /** + * Wether the media element has crashed. + */ + inError: boolean; + /** + * Wether the media element is paused. + */ + isPaused: boolean; + /** + * Wether the media element is muted. + */ + isMuted: boolean; + /** + * Wether the media element has audio. + */ + hasAudio: boolean; + /** + * Wether the media element is looping. + */ + isLooping: boolean; + /** + * Wether the media element's controls are visible. + */ + isControlsVisible: boolean; + /** + * Wether the media element's controls are toggleable. + */ + canToggleControls: boolean; + /** + * Wether the media element can be rotated. + */ + canRotate: boolean; + } + /** + * Wether the context menu was invoked on an image which has non-empty contents. + */ + hasImageContents: boolean; + /** + * Wether the context is editable. + */ + isEditable: boolean; + /** + * These flags indicate wether the renderer believes it is able to perform the corresponding action. + */ + editFlags: { + /** + * Wether the renderer believes it can undo. + */ + canUndo: boolean; + /** + * Wether the renderer believes it can redo. + */ + canRedo: boolean; + /** + * Wether the renderer believes it can cut. + */ + canCut: boolean; + /** + * Wether the renderer believes it can copy + */ + canCopy: boolean; + /** + * Wether the renderer believes it can paste. + */ + canPaste: boolean; + /** + * Wether the renderer believes it can delete. + */ + canDelete: boolean; + /** + * Wether the renderer believes it can select all. + */ + canSelectAll: boolean; + } + /** + * Text of the selection that the context menu was invoked on. + */ + selectionText: string; + /** + * Title or alt text of the selection that the context was invoked on. + */ + titleText: string; + /** + * The misspelled word under the cursor, if any. + */ + misspelledWord: string; + /** + * The character encoding of the frame on which the menu was invoked. + */ + frameCharset: string; + /** + * If the context menu was invoked on an input field, the type of that field. + */ + inputFieldType: 'none' | 'plainText' | 'password' | 'other'; + /** + * Input source that invoked the context menu. + */ + menuSourceType: 'none' | 'mouse' | 'keyboard' | 'touch' | 'touchMenu'; + } + + interface BluetoothDevice { + deviceName: string; + deviceId: string; + } + interface Headers { [key: string]: string; } @@ -3582,8 +3870,8 @@ declare namespace Electron { /** * Specifies the action to take place when ending webContents.findInPage request. - * 'clearSelection' - Translate the selection into a normal selection. - * 'keepSelection' - Clear the selection. + * 'clearSelection' - Clear the selection. + * 'keepSelection' - Translate the selection into a normal selection. * 'activateSelection' - Focus and click the selection node. */ type StopFindInPageAtion = 'clearSelection' | 'keepSelection' | 'activateSelection'; @@ -3631,7 +3919,7 @@ declare namespace Electron { * Specify page size of the generated PDF. * Default: A4. */ - pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; + pageSize?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid' | Dimension; /** * Whether to print CSS backgrounds. * Default: false. @@ -3889,6 +4177,32 @@ declare namespace Electron { * this limitation. */ executeJavaScript(code: string, userGesture?: boolean, callback?: (result: any) => void): void; + /** + * @returns Object describing usage information of Blink’s internal memory caches. + */ + getResourceUsage(): ResourceUsages; + /** + * Attempts to free memory that is no longer being used (like images from a previous navigation). + */ + clearCache(): void; + } + + interface ResourceUsages { + fonts: ResourceUsage; + images: ResourceUsage; + cssStyleSheets: ResourceUsage; + xslStyleSheets: ResourceUsage; + scripts: ResourceUsage; + other: ResourceUsage; + } + + interface ResourceUsage { + count: number; + decodedSize: number; + liveSize: number; + purgeableSize: number; + purgedSize: number; + size: number; } // https://github.com/electron/electron/blob/master/docs/api/web-view-tag.md @@ -3968,6 +4282,10 @@ declare namespace Electron { * A list of strings which specifies the blink features to be enabled separated by ,. */ blinkfeatures: string; + /** + * A list of strings which specifies the blink features to be disabled separated by ,. + */ + disableblinkfeatures: string; /** * Loads the url in the webview, the url must contain the protocol prefix, e.g. the http:// or file://. */ @@ -4162,6 +4480,11 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Shows pop-up dictionary that searches the selected word on the page. + * Note: This API is available only on OS X. + */ + showDefinitionForSelection(): void; /** * @returns The WebContents associated with this webview. */ @@ -4297,6 +4620,10 @@ declare namespace Electron { * */ addEventListener(type: 'did-change-theme-color', listener: (event: WebViewElement.DidChangeThemeColorEvent) => void, useCapture?: boolean): void; + /** + * Emitted when mouse moves over a link or the keyboard moves the focus to a link. + */ + addEventListener(type: 'update-target-url', listener: (event: WebViewElement.UpdateTargetUrlEvent) => void, useCapture?: boolean): void; /** * Emitted when DevTools is opened. */ @@ -4396,6 +4723,10 @@ declare namespace Electron { interface DidChangeThemeColorEvent extends Event { themeColor: string; } + + interface UpdateTargetUrlEvent extends Event { + url: string; + } } /** @@ -4428,6 +4759,10 @@ declare namespace Electron { * properties and a single method. */ postMessage(message: string, targetOrigin: string): void; + /** + * Invokes the print dialog on the child window. + */ + print(): void; } // https://github.com/electron/electron/blob/master/docs/api/synopsis.md @@ -4495,6 +4830,10 @@ interface File { declare namespace NodeJS { interface Process { + /** + * Setting this to true can disable the support for asar archives in Node's built-in modules. + */ + noAsar?: boolean; /** * Process's type */ @@ -4511,16 +4850,17 @@ declare namespace NodeJS { * If the app is running as a Windows Store app (appx), this value is true, for other builds it is undefined. */ windowsStore?: boolean; + /** + * When app is started by being passed as parameter to the default app, + * this value is true in the main process, otherwise it is undefined. + */ + defaultApp?: boolean; /** * Emitted when Electron has loaded its internal initialization script * and is beginning to load the web page or the main script. */ on(event: 'loaded', listener: Function): this; on(event: string, listener: Function): this; - /** - * Setting this to true can disable the support for asar archives in Node's built-in modules. - */ - noAsar?: boolean; /** * Causes the main thread of the current process crash; */ @@ -4536,6 +4876,54 @@ declare namespace NodeJS { * Note: This API is only available on Mac and Linux. */ setFdLimit(maxDescriptors: number): void; + /** + * @returns Object giving memory usage statistics about the current process. + * Note: All statistics are reported in Kilobytes. + */ + getProcessMemoryInfo(): ProcessMemoryInfo; + /** + * @returns Object giving memory usage statistics about the entire system. + * Note: All statistics are reported in Kilobytes. + */ + getSystemMemoryInfo(): SystemMemoryInfo; + } + + interface ProcessMemoryInfo { + /** + * The amount of memory currently pinned to actual physical RAM. + */ + workingSetSize: number; + /** + * The maximum amount of memory that has ever been pinned to actual physical RAM. + */ + peakWorkingSetSize: number; + /** + * The amount of memory not shared by other processes, such as JS heap or HTML content. + */ + privateBytes: number; + /** + * The amount of memory shared between processes, typically memory consumed by the Electron code itself. + */ + sharedBytes: number; + } + + interface SystemMemoryInfo { + /** + * The total amount of physical memory available to the system. + */ + total: number; + /** + * The total amount of memory not being used by applications or disk cache. + */ + free: number; + /** + * The total amount of swap memory available to the system. + */ + swapTotal: number; + /** + * The free amount of swap memory available to the system. + */ + swapFree: number; } } diff --git a/globalize/globalize-0.1.3-tests.ts b/globalize/globalize-0.1.3-tests.ts new file mode 100644 index 0000000000..4e3e9056ed --- /dev/null +++ b/globalize/globalize-0.1.3-tests.ts @@ -0,0 +1,11 @@ +/// +module Tests { + Globalize.culture('en-US'); + Globalize.addCultureInfo('nb-NO', 'no', { messages: {Test: "Test"} }); + var cult = Globalize.findClosestCulture('nb-NO'); + var numberString = Globalize.format(1.245, 'n2'); + var testString = Globalize.localize('Test'); + var dateParsed = Globalize.parseDate('2016-02-03'); + var intParsed = Globalize.parseInt('123'); + var floatParsed = Globalize.parseFloat('12.3'); +} \ No newline at end of file diff --git a/globalize/globalize-0.1.3.d.ts b/globalize/globalize-0.1.3.d.ts new file mode 100644 index 0000000000..b31a1cc092 --- /dev/null +++ b/globalize/globalize-0.1.3.d.ts @@ -0,0 +1,25 @@ +// Type definitions for Globalize v0.1.3 (NuGet package version) +// Project: https://github.com/jquery/globalize +// Definitions by: Aram Taieb +// Definitions: https://github.com/afromogli/DefinitelyTyped + +interface GlobalizeStatic { + addCultureInfo(cultureName: string, baseCultureName: string, info: any): void; + findClosestCulture(name: string): any; + format(value: any, format: string): string; + format(value: any, format: string, cultureSelector: string): string; + localize(key: string): string; + localize(key: string, cultureSelector: string): string; + parseDate(value: any): Date; + parseDate(value: any, formats: any): Date; + parseDate(value: any, formats: any, culture: string): Date; + parseInt(value: any): number; + parseInt(value: any, radix: number): number; + parseInt(value: any, radix: number, cultureSelector: string): number; + parseFloat(value: any): number; + parseFloat(value: any, radix: number): number; + parseFloat(value: any, radix: number, cultureSelector: string): number; + culture(cultureSelector: string): any; +} + +declare var Globalize: GlobalizeStatic; diff --git a/globalize/globalize.d.ts b/globalize/globalize.d.ts index 8eeec964eb..d3bf7997d5 100644 --- a/globalize/globalize.d.ts +++ b/globalize/globalize.d.ts @@ -1,28 +1,330 @@ -// Type definitions for Globalize +// Type definitions for Globalize // Project: https://github.com/jquery/globalize -// Definitions by: Aram Taieb -// Definitions: https://github.com/afromogli/DefinitelyTyped +// Definitions by: Grégoire Castre , Aram Taieb +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Note: You'll need the cldr.js definition file to use the globalize (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/cldr.js) -interface NumberFormatterOptions { - minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; - minimumSignificantDigits?: number; - maximumSignificantDigits?: number; - round?: string; - useGrouping?: boolean; +/// + +interface DateFormatterOptions { + /** + * String value indicating a skeleton (see description above), eg. { skeleton: "GyMMMd" }. + * Skeleton provides a more flexible formatting mechanism than the predefined list full, long, medium, or short represented by date, time, or datetime. + * Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. + */ + skeleton?: string; + /** + * One of the following String values: full, long, medium, or short, eg. { date: "full" }. + */ + date?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { time: "full" }. + */ + time?: "full" | "long" | "medium" | "short"; + /** + * One of the following String values: full, long, medium, or short, eg. { datetime: "full" } + */ + datetime?: "full" | "long" | "medium" | "short"; + /** + * String value indicating a machine raw pattern (anything in the "Sym." column) eg. { raw: "dd/mm" }. + * Note this is NOT recommended for i18n in general. Use skeleton instead. + */ + raw?: string; } -interface Cldr { - /* TODO: add typings */ +interface CommonNumberFormatterOptions { + /** + * Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + */ + minimumIntegerDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + minimumFractionDigits?: number; + /** + * Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. + * Numbers will be rounded or padded with trailing zeroes if necessary. + * Either one or both of these properties must be present. + * If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + */ + maximumFractionDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + minimumSignificantDigits?: number; + /** + * Positive integer Number values indicating the minimum and maximum fraction digits to be shown. + * Either none or both of these properties are present. + * If they are, they override minimum and maximum integer and fraction digits. + * The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + */ + maximumSignificantDigits?: number; + /** + * String with rounding method ceil, floor, round (default), or truncate. + */ + round?: "ceil" | "floor" | "round" | "truncate"; + /** + * Boolean (default is true) value indicating whether a grouping separator should be used. + */ + useGrouping?: boolean; +} + +interface NumberFormatterOptions extends CommonNumberFormatterOptions { + /** + * decimal (default), or percent + */ + style?: "decimal" | "percent"; +} + +interface CurrencyFormatterOptions extends CommonNumberFormatterOptions { + /** + * symbol (default), accounting, code or name. + */ + style?: "symbol" | "accounting" | "code" | "name"; +} + +interface NumberParserOptions { + /** + * decimal (default), or percent. + */ + style?: "decimal" | "percent"; +} + +interface PluralGeneratorOptions { + /** + * cardinal (default), or ordinal. + */ + type?: "cardinal" | "ordinal"; +} + +interface RelativeTimeFormatterOptions { + /** + * eg. "short" or "narrow". Or falsy for default long form + */ + form?: "short" | "narrow"; +} + +interface UnitFormatterOptions { + /** + * form: [String] eg. "long", "short" or "narrow". + */ + form?: "long" | "short" | "narrow"; + + /** + * numberFormatter: [Function] a number formatter function. Defaults to Globalize .numberFormatter() for the current locale using the default options. + */ + numberFormatter?: NumberFormatterOptions; } interface GlobalizeStatic { - load(jsonData: any): void; - locale(locale: string): Cldr; - numberFormatter(options?: NumberFormatterOptions): (value: number) => string; - formatNumber(value:number, options?: NumberFormatterOptions): string; + cldr: cldr.CldrStatic; + + /** + * Globalize.load( json, ... ) + * @param {Object} [JSON] + * Load resolved or unresolved cldr data. + * Somewhat equivalent to previous Globalize.addCultureInfo(...). + */ + load(json: Object): void; + + /** + * Globalize.locale() + * Return the default Cldr instance. + */ + locale(): cldr.CldrStatic; + + /** + * Globalize.locale( [locale] ) + * @param {string} locale + * Set default Cldr instance + * Return the default Cldr instance. + */ + + locale(locale: string): cldr.CldrStatic; + /** + * Globalize.locale( cldr ) + * @param {Cldr} cldr [Cldr instance] + * Set default Cldr instance + * Return the default Cldr instance. + */ + locale(cldr: cldr.CldrStatic): cldr.CldrStatic; + + /** + * .dateFormatter( options ) + * @param {DateFormatterOptions} options see date/expand_pattern for more info. + * @returns {Function} Return a function that formats a date according to the given `options` and the default/instance locale. + */ + dateFormatter(options?: DateFormatterOptions): (value: Date) => string; + + //Return a function that parses a string representing a date into a JavaScript Date object according to the given options. The default parsing assumes numeric year, month, and day (i.e., { skeleton: "yMd" }). + dateParser(options?: DateFormatterOptions): (value: string) => Date; + + //Alias for .dateFormatter( [options] )( value ). + formatDate(value: Date, options?: DateFormatterOptions): string; + /** + * Alias for .dateParser( [options] )( value ). + * @param {string} value The object whose module id you wish to determine. + * @param {DateFormatterOptions} options The object whose module id you wish to determine. + * @returns {Date} Return the value as a Date. + */ + parseDate(value: string, options?: DateFormatterOptions): Date; + + /** + * Load messages data. + * @param {Object} json JSON object of messages data. Keys can use any character, except /, { and }. Values (i.e., the message content itself) can contain any character. + * @returns {void} + */ + loadMessages(json: Object): void; + /** + * Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @returns {Function} Return A function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections. + */ + messageFormatter(path: string | string[]): (variables?: string | string[] | Object) => string; + + /** + * Formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string + * @param path String or Array containing the path of the message content, eg. "greetings/bye", or [ "greetings", "bye" ]. + * @param variables Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such. + * @returns {string} Return a user-readable string. + */ + formatMessage(path: string | string[], variables?: string | string[] | Object): string + + /** + * Return a function that formats a number according to the given options or locale's defaults. + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {Function} Return a function that formats a number according to the given options. + */ + numberFormatter(options?: NumberFormatterOptions): (value: number) => string; + + /** + * Return a function that parses a string representing a number according to the given options or locale's defaults. + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {Function} Return a function that parses a String representing a number according to the given options. If value is invalid, NaN is returned. + */ + numberParser(options?: NumberParserOptions): (value: string) => number + + /** + * Return a number formatted according to the given options or locale's defaults. + * @param {number} value The number to format + * @param {NumberFormatterOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * minimumIntegerDigits Optional Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary. + * minimumFractionDigits and maximumFractionDigits Optional Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns. + * minimumSignificantDigits and maximumSignificantDigits Optional Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits. + * round Optional String with rounding method ceil, floor, round (default), or truncate. + * useGrouping Optional Boolean (default is true) value indicating whether a grouping separator should be used. + * @returns {string} Return the number formatted + */ + formatNumber(value: number, options?: NumberFormatterOptions): string; + + /** + * A function that parses a string representing a number according to the given options or locale's defaults. + * @param {string} value The number as string to parse + * @param {NumberParserOptions} options A JSON object including none or any of the following options. + * style Optional String decimal (default), or percent. + * @returns {number} Return a number according to the given options. If value is invalid, NaN is returned. + */ + parseNumber(value: string, options?: NumberParserOptions): number; + + /** + * Return a function that formats a currency according to the given options or locale's defaults. + * The returned function is invoked with one argument: the Number value to be formatted. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {Function} Return a function that formats a currency + */ + currencyFormatter(currency: string, options?: CurrencyFormatterOptions): (value: number) => string; + + /** + * Return a currency formatted according to the given options or locale's defaults. + * @param {number} value The value to format. + * @param {string} currency 3-letter currency code as defined by ISO 4217, eg. USD. + * @param {CurrencyFormatterOptions} options A JSON object including none or any of the following options. + * @returns {string} Return a string formatted in the currency according to the value and the options + */ + formatCurrency(value: number, currency: string, options?: CurrencyFormatterOptions): string; + + /** + * Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + * The returned function is invoked with one argument: the Number value for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {Function} Return a function that returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + pluralGenerator(options?: PluralGeneratorOptions): (value: number) => string; + + /** + * Returns the value's corresponding plural group: zero, one, two, few, many, or other. + * @param {number} value A Number for which to return the plural group. + * @param {PluralGeneratorOptions} options A JSON object including none or any of the following options. + * type Optional String cardinal (default), or ordinal. + * @returns {string} Returns the value's corresponding plural group: zero, one, two, few, many, or other. + */ + plural(value: number, options?: PluralGeneratorOptions): string; + + /** + * Returns a function that formats a relative time according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {Function} Returns a function that formats a relative time according to the given unit. + */ + relativeTimeFormatter(unit: string, options?: RelativeTimeFormatterOptions): (value: number) => string; + + /** + * Return a relative time according to the given unit + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. + * @param options form: [String] eg. "short" or "narrow". Or falsy for default long form. + * @returns {string} Return a relative time according to the given unit. + */ + formatRelativeTime(value: number, unit: string, options?: RelativeTimeFormatterOptions): string; + + /** + * Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + * The returned function is invoked with one argument: the number value to be formatted. + * @param unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param options form: [String] eg. "long", "short" or "narrow". + * @returns {Function} Returns a function that formats a unit according to the given unit, options, and the default/instance locale. + */ + unitFormatter(unit: string, options?: UnitFormatterOptions): (value: number) => string; + + /** + * Alias for .unitFormatter( unit, options )( value ). + * @param {number} value The number to be formatted. + * @param {string} unit String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour" + * @param {UnitFormatterOptions} options form: [String] eg. "long", "short" or "narrow". + * @returns {string} Returns the unit formatted. + */ + formatUnit(value: number, unit: string, options?: UnitFormatterOptions): string + + /** + * Create a Globalize instance. + * @param {string} Locale string of the instance. + * @returns {Globalize} A Globalize instance + */ + new (locale: string): GlobalizeStatic; + /** + * Create a Globalize instance. + * @param cldr Cldr instance of the instance. + * @returns {Globalize} A Globalize instance + */ + new (cldr: cldr.CldrStatic): GlobalizeStatic; } declare var Globalize: GlobalizeStatic; diff --git a/google-drive-realtime-api/google-drive-realtime-api.d.ts b/google-drive-realtime-api/google-drive-realtime-api.d.ts index 2964ee90b6..b263b30bb9 100644 --- a/google-drive-realtime-api/google-drive-realtime-api.d.ts +++ b/google-drive-realtime-api/google-drive-realtime-api.d.ts @@ -430,6 +430,38 @@ declare namespace gapi.drive.realtime { events : BaseModelEvent[]; } + // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ValuesAddedEvent + export interface ValuesAddedEvent extends BaseModelEvent { + new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[], + isLocal:boolean, isUndo:boolean, isRedo:boolean, index:number, + values:V[], movedFromList:CollaborativeList, movedFromIndex:number):ValuesAddedEvent; + + // The index of the first added value + index:number; + + // The index in the source collaborative list that the values were moved from, or null if this insert is not the result of a move operation. + movedFromIndex:number; + + // The collaborative list that the values were moved from, or null if this insertion is not the result of a move operation. + movedFromList:CollaborativeList; + } + + // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ValuesRemovedEvent + export interface ValuesRemovedEvent extends BaseModelEvent { + new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[], + isLocal:boolean, isUndo:boolean, isRedo:boolean, index:number, + values:V[], movedToList:CollaborativeList, movedToIndex:number):ValuesRemovedEvent; + + // The index of the first removed value. + index:number; + + // The index in the collaborative list that the values were moved to, or null if this delete is not the result of a move operation. + movedToIndex:number; + + // The collaborative list that the values were moved to, or null if this delete is not the result of a move operation. + movedToList:CollaborativeList; + } + // Complete // https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Document @@ -513,6 +545,30 @@ declare namespace gapi.drive.realtime { opt_initializerFn? : (m:Model) => void, opt_errorFn? : (e:gapi.drive.realtime.Error) => void ) : Document; + + /* Loads an existing file by id. + https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.load + + @Param fileId {string} Id of the file to load. + + @Param onLoaded {function(non-null gapi.drive.realtime.Document)} + A callback that will be called when the realtime document is ready. The created or opened realtime document + object will be passed to this function. + + @Param opt_initializerFn {function(non-null gapi.drive.realtime.Model)} + An optional initialization function that will be called before onLoaded only the first time that the document + is loaded. The document's gapi.drive.realtime.Model object will be passed to this function. + + @Param opt_errorFn {function(non-null gapi.drive.realtime.Error)} + An optional error handling function that will be called if an error occurs while the document is being + loaded or edited. A gapi.drive.realtime.Error object describing the error will be passed to this function. + */ + export function load( + fileId:string, + onLoaded? : (d:Document) => void, + opt_initializerFn? : (m:Model) => void, + opt_errorFn? : (e:gapi.drive.realtime.Error) => void + ):void; } @@ -540,6 +596,10 @@ declare namespace gapi.drive.realtime.EventType { export var TEXT_INSERTED: string export var TEXT_DELETED: string export var OBJECT_CHANGED: string + // List + export var VALUES_ADDED:string; + export var VALUES_REMOVED:string; + export var VALUES_SET:string; } diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 4d225779ce..f005582cb2 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -1585,6 +1585,10 @@ declare namespace google.maps { setZoom(zoom: number): void; } + export interface FullscreenControlOptions { + position?: ControlPosition; + } + export interface StreetViewPanoramaOptions { addressControl?: boolean; addressControlOptions?: StreetViewAddressControlOptions; @@ -1592,8 +1596,11 @@ declare namespace google.maps { disableDefaultUi?: boolean; disableDoubleClickZoom?: boolean; enableCloseButton?: boolean; + fullscreenControl?: boolean; + fullscreenControlOptions?: FullscreenControlOptions; imageDateControl?: boolean; linksControl?: boolean; + mode?: "html4" | "html5" |"webgl"; panControl?: boolean; panControlOptions?: PanControlOptions; pano?: string; diff --git a/gridstack/gridstack-tests.ts b/gridstack/gridstack-tests.ts index f084e4f46c..3414230a4a 100644 --- a/gridstack/gridstack-tests.ts +++ b/gridstack/gridstack-tests.ts @@ -12,9 +12,9 @@ var options = { }; var gridstack:GridStack = $(document).gridstack(options); -gridstack.add_widget("test", 1, 2, 3, 4, true); -gridstack.batch_update(); -gridstack.cell_height();; -gridstack.cell_height(2); -gridstack.cell_width(); -gridstack.get_cell_from_pixel({ left:20, top: 20 }); +gridstack.addWidget("test", 1, 2, 3, 4, true); +gridstack.batchUpdate(); +gridstack.cellHeight();; +gridstack.cellHeight(2); +gridstack.cellWidth(); +gridstack.getCellFromPixel({ left:20, top: 20 }); diff --git a/gridstack/gridstack.d.ts b/gridstack/gridstack.d.ts index c69770a1b6..399f25e04b 100644 --- a/gridstack/gridstack.d.ts +++ b/gridstack/gridstack.d.ts @@ -11,35 +11,35 @@ interface GridStack { /** * Creates new widget and returns it. * - * Widget will be always placed even if result height is more than actual grid height. You need to use will_it_fit method before calling add_widget for additional check. + * Widget will be always placed even if result height is more than actual grid height. You need to use willItFit method before calling addWidget for additional check. * * @param {string} el widget to add * @param {number} x widget position x * @param {number} y widget position y * @param {number} width widget dimension width * @param {number} height widget dimension height - * @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position + * @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position */ - add_widget(el: string, x: number, y: number, width: number, height: number, auto_position: boolean): JQuery + addWidget(el: string, x: number, y: number, width: number, height: number, autoPosition: boolean): JQuery /** * Initializes batch updates. You will see no changes until commit method is called. */ - batch_update():void + batchUpdate():void /** * Gets current cell height. */ - cell_height():number + cellHeight():number /** * Update current cell height. This method rebuilds an internal CSS style sheet. Note: You can expect performance issues if call this method too often. * @param {number} val the cell height */ - cell_height(val:number):void + cellHeight(val:number):void /** * Gets current cell width. */ - cell_width():number + cellWidth():number /** - * Finishes batch updates. Updates DOM nodes. You must call it after batch_update. + * Finishes batch updates. Updates DOM nodes. You must call it after batchUpdate. */ commit():void /** @@ -58,7 +58,7 @@ interface GridStack { * Get the position of the cell under a pixel on screen. * @param {MousePosition} position the position of the pixel to resolve in absolute coordinates, as an object with top and leftproperties */ - get_cell_from_pixel(position: MousePosition): CellPosition, + getCellFromPixel(position: MousePosition): CellPosition, /* * Checks if specified area is empty. * @param {number} x the position x. @@ -66,7 +66,7 @@ interface GridStack { * @param {number} width the width of to check * @param {number} height the height of to check */ - is_area_empty(x: number, y: number, width: number, height: number): void + isAreaEmpty(x: number, y: number, width: number, height: number): void /* * Locks/unlocks widget. * @param {HTMLElement} el widget to modify. @@ -78,13 +78,13 @@ interface GridStack { * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of columns */ - min_width(el: HTMLElement, val: number): void + minWidth(el: HTMLElement, val: number): void /* * Set the minHeight for a widget. * @param {HTMLElement} el widget to modify. * @param {number} val A numeric value of the number of rows */ - min_height(el: HTMLElement, val: number): void + minHeight(el: HTMLElement, val: number): void /* * Enables/Disables moving. * @param {HTMLElement} el widget to modify. @@ -102,13 +102,13 @@ interface GridStack { /** * Removes widget from the grid. * @param {HTMLElement} el widget to modify - * @param {boolean} detach_node if false DOM node won't be removed from the tree (Optional. Default true). + * @param {boolean} detachNode if false DOM node won't be removed from the tree (Optional. Default true). */ - remove_widget(el: HTMLElement, detach_node?: boolean): void + removeWidget(el: HTMLElement, detachNode?: boolean): void /** * Removes all widgets from the grid. */ - remove_all(): void + removeAll(): void /** * Changes widget size * @param {HTMLElement} el widget to modify @@ -124,9 +124,9 @@ interface GridStack { resizable(el: HTMLElement, val: boolean): void /** * Toggle the grid static state. Also toggle the grid-stack-static class. - * @param {boolean} static_value if true the grid become static. + * @param {boolean} staticValue if true the grid become static. */ - set_static(static_value: boolean): void + setStatic(staticValue: boolean): void /** * Updates widget position/size. * @param {HTMLElement} el widget to modify @@ -142,9 +142,9 @@ interface GridStack { * @param {number} y new position y. If value is null or undefined it will be ignored. * @param {number} width new dimensions width. If value is null or undefined it will be ignored. * @param {number} height new dimensions height. If value is null or undefined it will be ignored. - * @param {boolean} auto_position if true then x, y parameters will be ignored and widget will be places on the first available position + * @param {boolean} autoPosition if true then x, y parameters will be ignored and widget will be places on the first available position */ - will_it_fit(x: number, y: number, width: number, height: number, auto_position:boolean):boolean + willItFit(x: number, y: number, width: number, height: number, autoPosition:boolean):boolean } @@ -181,7 +181,7 @@ interface IGridstackOptions { /** * if true the resizing handles are shown even if the user is not hovering over the widget (default: false) */ - always_show_resize_handle: boolean; + alwaysShowResizeHandle: boolean; /** * turns animation on (default: true) */ @@ -193,7 +193,7 @@ interface IGridstackOptions { /** * one cell height (default: 60) */ - cell_height: number; + cellHeight: number; /** * allows to override jQuery UI draggable options. (default: { handle: '.grid-stack-item-content', scroll: true, appendTo: 'body' }) */ @@ -213,15 +213,15 @@ interface IGridstackOptions { /** * widget class (default: 'grid-stack-item') */ - item_class: string; + itemClass: string; /** * minimal width.If window width is less, grid will be shown in one - column mode (default: 768) */ - min_width: number; + minWidth: number; /** * class for placeholder (default: 'grid-stack-placeholder') */ - placeholder_class: string; + placeholderClass: string; /** * allows to override jQuery UI resizable options. (default: { autoHide: true, handles: 'se' }) */ @@ -229,11 +229,11 @@ interface IGridstackOptions { /** * makes grid static (default false).If true widgets are not movable/ resizable.You don't even need jQueryUI draggable/resizable. A CSS class grid-stack-static is also added to the container. */ - static_grid: boolean; + staticGrid: boolean; /** * vertical gap size (default: 20) */ - vertical_margin: number; + verticalMargin: number; /** * amount of columns (default: 12) */ diff --git a/gruntjs/gruntjs.d.ts b/gruntjs/gruntjs.d.ts index 410ed10ab0..0a8e4d9d5a 100644 --- a/gruntjs/gruntjs.d.ts +++ b/gruntjs/gruntjs.d.ts @@ -773,6 +773,7 @@ declare namespace grunt { * The taskList argument must be an array of tasks. */ registerTask(taskName: string, taskList: string[]): void + registerTask(taskName: string, description: string, taskList: string[]): void /** * If a description and taskFunction are passed, the specified function will be executed @@ -784,6 +785,7 @@ declare namespace grunt { * * @note taskFunction.apply(scope: grunt.task.ITask, args: any[]) */ + registerTask(taskName: string, taskFunction: Function): void registerTask(taskName: string, description: string, taskFunction: Function): void /** diff --git a/handsontable/handsontable-tests.ts b/handsontable/handsontable-tests.ts index 25ec4dee0f..318038967a 100644 --- a/handsontable/handsontable-tests.ts +++ b/handsontable/handsontable-tests.ts @@ -120,6 +120,88 @@ function test_HandsontableInit() { visibleRows: 123, width: 1232, wordWrap: true, + + // Hooks + afterAutofillApplyValues: function() {}, + afterCellMetaReset: function() {}, + afterChange: function() {}, + afterChangesObserved: function() {}, + afterColumnMove: function() {}, + afterColumnResize: function() {}, + afterColumnSort: function() {}, + afterContextMenuDefaultOptions: function() {}, + afterContextMenuHide: function() {}, + afterContextMenuShow: function() {}, + afterCopyLimit: function() {}, + afterCreateCol: function() {}, + afterCreateRow: function() {}, + afterDeselect: function() {}, + afterDestroy: function() {}, + afterDocumentKeyDown: function() {}, + afterFilter: function() {}, + afterGetCellMeta: function() {}, + afterGetColHeader: function() {}, + afterGetColumnHeaderRenderers: function() {}, + afterGetRowHeader: function() {}, + afterGetRowHeaderRenderers: function() {}, + afterInit: function() {}, + afterLoadData: function() {}, + afterMomentumScroll: function() {}, + afterOnCellCornerMouseDown: function() {}, + afterOnCellMouseDown: function() {}, + afterOnCellMouseOver: function() {}, + afterRemoveCol: function() {}, + afterRemoveRow: function() {}, + afterRender: function() {}, + afterRenderer: function() {}, + afterRowMove: function() {}, + afterRowResize: function() {}, + afterScrollHorizontally: function() {}, + afterScrollVertically: function() {}, + afterSelection: function() {}, + afterSelectionByProp: function() {}, + afterSelectionEnd: function() {}, + afterSelectionEndByProp: function() {}, + afterSetCellMeta: function() {}, + afterUpdateSettings: function() {}, + afterValidate: function() {}, + beforeAutofill: function() {}, + beforeCellAlignment: function() {}, + beforeChange: function() {}, + beforeChangeRender: function() {}, + beforeColumnMove: function() {}, + beforeColumnResize: function() {}, + beforeColumnSort: function() {}, + beforeDrawBorders: function() {}, + beforeFilter: function() {}, + beforeGetCellMeta: function() {}, + beforeInit: function() {}, + beforeInitWalkontable: function() {}, + beforeKeyDown: function() {}, + beforeOnCellMouseDown: function() {}, + beforeRemoveCol: function() {}, + beforeRemoveRow: function() {}, + beforeRender: function() {}, + beforeRenderer: function() {}, + beforeRowMove: function() {}, + beforeRowResize: function() {}, + beforeSetRangeEnd: function() {}, + beforeStretchingColumnWidth: function() {}, + beforeTouchScroll: function() {}, + beforeValidate: function() {}, + construct: function() {}, + init: function() {}, + modifyCol: function() {}, + modifyColHeader: function() {}, + modifyColWidth: function() {}, + modifyCopyableRange: function() {}, + modifyRow: function() {}, + modifyRowHeader: function() {}, + modifyRowHeight: function() {}, + persistentStateLoad: function() {}, + persistentStateReset: function() {}, + persistentStateSave: function() {}, + unmodifyCol: function() {} }); } diff --git a/handsontable/handsontable.d.ts b/handsontable/handsontable.d.ts index 9c7f87aaa3..790eb4b087 100644 --- a/handsontable/handsontable.d.ts +++ b/handsontable/handsontable.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Handsontable 0.24.1 +// Type definitions for Handsontable 0.24.3 // Project: https://handsontable.com/ // Definitions by: Handsoncode sp. z o.o. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\ @@ -124,6 +124,88 @@ declare namespace ht { wordWrap?: boolean; isEmptyCol?: (col: number) => boolean; isEmptyRow?: (row: number) => boolean; + + // hooks + afterAutofillApplyValues?: (startArea: any[], entireArea: any[]) => void; + afterCellMetaReset?: () => void; + afterChange?: (changes: any[], source: string) => void; + afterChangesObserved?: () => void; + afterColumnMove?: (startColumn: number, endColumn: number) => void; + afterColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void; + afterColumnSort?: (column: number, order: boolean) => void; + afterContextMenuDefaultOptions?: (predefinedItems: any[]) => void; + afterContextMenuHide?: (context: Object) => void; + afterContextMenuShow?: (context: Object) => void; + afterCopyLimit?: (selectedRows: number, selectedColumnds: number, copyRowsLimit: number, copyColumnsLimit: number) => void; + afterCreateCol?: (index: number, amount: number) => void; + afterCreateRow?: (index: number, amount: number) => void; + afterDeselect?: () => void; + afterDestroy?: () => void; + afterDocumentKeyDown?: (event: Event) => void; + afterFilter?: (formulasStack: any[]) => void; + afterGetCellMeta?: (row: number, col: number, cellProperties: Object) => void; + afterGetColHeader?: (col: number, TH: Element) => void; + afterGetColumnHeaderRenderers?: (array: any[]) => void; + afterGetRowHeader?: (row: number, TH: Element) => void; + afterGetRowHeaderRenderers?: (array: any[]) => void; + afterInit?: () => void; + afterLoadData?: (firstTime: boolean) => void; + afterMomentumScroll?: () => void; + afterOnCellCornerMouseDown?: (event: Object) => void; + afterOnCellMouseDown?: (event: Object, coords: Object, TD: Element) => void; + afterOnCellMouseOver?: (event: Object, coords: Object, TD: Element) => void; + afterRemoveCol?: (index: number, amount: number) => void; + afterRemoveRow?: (index: number, amount: number) => void; + afterRender?: (isForced: boolean) => void; + afterRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void; + afterRowMove?: (startRow: number, endRow: number) => void; + afterRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => void; + afterScrollHorizontally?: () => void; + afterScrollVertically?: () => void; + afterSelection?: (r: number, c: number, r2: number, c2: number) => void; + afterSelectionByProp?: (r: number, p: string, r2: number, p2: string) => void; + afterSelectionEnd?: (r: number, c: number, r2: number, c2: number) => void; + afterSelectionEndByProp?: (r: number, p: string, r2: number, p2: string) => void; + afterSetCellMeta?: (row: number, col: number, key: string, value: any) => void; + afterUpdateSettings?: () => void; + afterValidate?: (isValid: boolean, value: any, row: number, prop: string|number, source: string) => void|boolean; + beforeAutofill?: (start: Object, end: Object, data: any[]) => void; + beforeCellAlignment?: (stateBefore: any, range: any, type: string, alignmentClass: string) => void; + beforeChange?: (changes: any[], source: string) => void; + beforeChangeRender?: (changes: any[], source: string) => void; + beforeColumnMove?: (startColumn: number, endColumn: number) => void; + beforeColumnResize?: (currentColumn: number, newSize: number, isDoubleClick: boolean) => void; + beforeColumnSort?: (column: number, order: boolean) => void; + beforeDrawBorders?: (corners: any[], borderClassName: string) => void; + beforeFilter?: (formulasStack: any[]) => void; + beforeGetCellMeta?: (row: number, col: number, cellProperties: Object) => void; + beforeInit?: () => void; + beforeInitWalkontable?: (walkontableConfig: Object) => void; + beforeKeyDown?: (event: Event) => void; + beforeOnCellMouseDown?: (event: Event, coords: Object, TD: Element) => void; + beforeRemoveCol?: (index: number, amount: number, logicalCols?: any[]) => void; + beforeRemoveRow?: (index: number, amount: number, logicalRows?: any[]) => void; + beforeRender?: (isForced: boolean) => void; + beforeRenderer?: (TD: Element, row: number, col: number, prop: string|number, value: string, cellProperties: Object) => void; + beforeRowMove?: (startRow: number, endRow: number) => void; + beforeRowResize?: (currentRow: number, newSize: number, isDoubleClick: boolean) => any; + beforeSetRangeEnd?: (coords: any[]) => void; + beforeStretchingColumnWidth?: (stretchedWidth: number, column: number) => void; + beforeTouchScroll?: () => void; + beforeValidate?: (value: any, row: number, prop: string|number, source: string) => void; + construct?: () => void; + init?: () => void; + modifyCol?: (col: number) => void; + modifyColHeader?: (column: number) => void; + modifyColWidth?: (width: number, col: number) => void; + modifyCopyableRange?: (copyableRanges: any[]) => void; + modifyRow?: (row: number) => void; + modifyRowHeader?: (row: number) => void; + modifyRowHeight?: (height: number, row: number) => void; + persistentStateLoad?: (key: string, valuePlaceholder: Object) => void; + persistentStateReset?: (key: string) => void; + persistentStateSave?: (key: string, value: any) => void; + unmodifyCol?: (col: number) => void; } interface Methods { addHook(key: string, callback: Function|any[]): void; @@ -203,6 +285,8 @@ declare namespace ht { validateCells(callback: Function): void; } } + + declare var Handsontable: { new (element: Element, options: ht.Options): ht.Methods; }; diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index d45c03549a..743a4ad3ee 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -79,6 +79,7 @@ server.route({ method: 'GET', path: '/hello', handler: function (request: Hapi.Request, reply: Function) { + request.log('info', { route: '/hello' }, Date.now()); reply('hello world'); } }); diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 9962dd6c62..2867dd7de9 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -875,7 +875,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 | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } @@ -1301,7 +1301,7 @@ declare module "hapi" { log(/** a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events.*/ tags: string | string[], /** an optional message string or object with the application data being logged.*/ - data?: string, + data?: any, /** an optional timestamp expressed in milliseconds. Defaults to Date.now() (now).*/ timestamp?: number): void; diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 3a0bd2ba08..7cd14fc214 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -77,8 +77,9 @@ interface HeatmapConfiguration { /* * The property name of the value/weight in a datapoint + * Default value: 'value' */ - valueField: string; + valueField?: string; } /* diff --git a/helmet/helmet.d.ts b/helmet/helmet.d.ts index 7154d0b739..6feef0bad8 100644 --- a/helmet/helmet.d.ts +++ b/helmet/helmet.d.ts @@ -1,6 +1,6 @@ // Type definitions for helmet // Project: https://github.com/helmetjs/helmet -// Definitions by: Cyril Schumacher +// Definitions by: Cyril Schumacher , Evan Hahn // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index c7584f4e0d..45f69a0bda 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -4954,7 +4954,7 @@ interface HighchartsDataPoint { * The inner radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - innerRadius?: number; + innerRadius?: number|string; /** * When this property is true, the points acts as a summary column for the values added or substracted since the * last intermediate sum, or since the start of the series. The y value is ignored. @@ -5005,7 +5005,7 @@ interface HighchartsDataPoint { * The outer radius of an individual point in a solid gauge. Can be given as a number (pixels) or percentage string. * @since 4.1.6 */ - radius?: number; + radius?: number|string; /** * Whether the data point is selected initially. * @default false diff --git a/html2canvas/html2canvas.d.ts b/html2canvas/html2canvas.d.ts index 1d5fd82fe7..e1fcbc7a1b 100644 --- a/html2canvas/html2canvas.d.ts +++ b/html2canvas/html2canvas.d.ts @@ -1,6 +1,6 @@ -// Type definitions for html2canvas.js v0.4.1 +// Type definitions for html2canvas.js v0.5.0-bata.4 // Project: https://github.com/niklasvh/html2canvas -// Definitions by: Richard Hepburn +// Definitions by: Richard Hepburn , Pei-Tang Huang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -36,26 +36,14 @@ declare namespace Html2Canvas { /** Whether to attempt to load cross-origin images as CORS served, before reverting back to proxy. */ useCORS?: boolean; - + /** Use svg powered rendering where available (FF11+). */ svgRendering?: boolean; - - /** Callback providing the rendered canvas element after rendering */ - onrendered?(canvas: HTMLCanvasElement): void; } } interface Html2CanvasStatic { - /** - * Renders an HTML element to a canvas so that a screenshot can be generated. - * - * The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, - * but builds the screenshot based on the information available on the page. - * - * @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window. - */ - (element: HTMLElement): void; /** * Renders an HTML element to a canvas so that a screenshot can be generated. * @@ -65,7 +53,25 @@ interface Html2CanvasStatic { * @param {HTMLElement} element The HTML element which will be rendered to the canvas. Use the root element to render the entire window. * @param {Html2CanvasOptions} options The options object that controls how the element will be rendered. */ - (element: HTMLElement, options: Html2Canvas.Html2CanvasOptions): void; + (element: HTMLElement, options?: Html2Canvas.Html2CanvasOptions): Html2CanvasPromise; +} + +// FIXME: +// Find out a way to dependent on real Promise interface. +// And remove following custome Promise interface. +interface Html2CanvasThenable { + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasThenable; + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => void): Html2CanvasThenable; +} + +interface Html2CanvasPromise extends Html2CanvasThenable { + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasPromise; + then(onFulfilled?: (value: R) => U | Html2CanvasThenable, onRejected?: (error: any) => void): Html2CanvasPromise; + catch(onRejected?: (error: any) => U | Html2CanvasThenable): Html2CanvasPromise; +} + +declare module 'html2canvas' { + export = html2canvas; } declare var html2canvas: Html2CanvasStatic; diff --git a/i18n-node/i18n-node.d.ts b/i18n-node/i18n-node.d.ts index 568228df45..d5703a825d 100644 --- a/i18n-node/i18n-node.d.ts +++ b/i18n-node/i18n-node.d.ts @@ -50,6 +50,11 @@ declare namespace i18n { * json files prefix */ prefix?: string; + + /** + * object or [obj1, obj2] to bind the i18n api and current locale to - defaults to null + */ + register?: any; } export interface TranslateOptions { phrase: string; diff --git a/i18next/i18next-tests.ts b/i18next/i18next-tests.ts index e46a9ed5bf..373b7394b4 100644 --- a/i18next/i18next-tests.ts +++ b/i18next/i18next-tests.ts @@ -62,3 +62,5 @@ i18n.t('helloWorld', { defaultValue: 'default', count: 10 }); +const currentLanguage:string = i18n.language; +const userLanguageCodes:string[] = i18n.languages; diff --git a/i18next/i18next.d.ts b/i18next/i18next.d.ts index 9f976fd751..5e2f8dcd20 100644 --- a/i18next/i18next.d.ts +++ b/i18next/i18next.d.ts @@ -94,6 +94,10 @@ declare namespace I18next { loadResources(callback?:(err:any) => void):void; + language:string; + + languages:string[]; + use(module:any):I18n; changeLanguage(lng:string, callback?:(err:any, t:TranslationFunction) => void):void; diff --git a/imagemapster/imagemapster-tests.ts b/imagemapster/imagemapster-tests.ts new file mode 100644 index 0000000000..7f9ec9d761 --- /dev/null +++ b/imagemapster/imagemapster-tests.ts @@ -0,0 +1,88 @@ +/// +/// + +const areaOptions: ImageMapster.AreaRenderingOptions = { + key: "foo", + includeKeys: "foo", + isMask: true, + toolTip: "tooltip", +}; + +const onClickData: ImageMapster.OnClickData = { + listTarget: $(), + key: "foo", + e: $.Event("click"), + selected: true, +} + +const onMouseData: ImageMapster.OnMouseData = { + key: "foo", + selected: true, + e: $.Event("click"), + options: areaOptions, +}; + +const onGetListData: ImageMapster.OnGetListData = { + key: "foo", + value: "foo", + area: [{}], + options: areaOptions, +}; + +const onStateChangeData: ImageMapster.OnStateChangeData = { + key: "foo", + state: "highlight", + selected: true, +}; + +const onShowToolTipData: ImageMapster.OnShowToolTipData = { + toolTip: $(), + key: "foo", + selected: true, + areaOptions, +}; + +const bool = true; + +const options: ImageMapster.Options = { + mapKey: "foo", + mapValue: "foo", + clickNavigate: true, + listKey: "foo", + listSelectedAttribute: "foo", + listSelectedClass: "foo", + wrapClass: "foo", + wrapCss: "foo", + mouseoutDelay: 123, + sortList: "asc", + configTimeout: 123, + scaleMap: true, + noHrefIsMask: true, + boundList: $(), + showToolTip: true, + toolTipContainer: $(), + toolTipClose: ["area-mouseout", "area-click", "tooltip-click", "image-mouseout"], + onClick: onClickData => {}, + onMouseover: onMouseData => {}, + onMouseout: onMouseData => {}, + onGetList: onGetListData => $(), + onConfigured: bool => {}, + onStateChange: onStateChangeData => {}, + onShowToolTip: onShowToolTipData => {}, +}; + +$("img").mapster(options) +$("img").mapster("select") +$("img").mapster("deselect") +$("img").mapster("set", true, options) +$("img").mapster("get", "foo") +$("img").mapster("highlight", true) +$("img").mapster("unbind", true) +$("img").mapster("snapshot") +$("img").mapster("rebind", options) +$("img").mapster("resize", 123, 123, 123) +$("img").mapster("keys", "foo", true) +$("img").mapster("keys", true) +$("img").mapster("set_options", options) +$("img").mapster("get_options", "foo", true) +$("img").mapster("tooltip", "foo"); diff --git a/imagemapster/imagemapster.d.ts b/imagemapster/imagemapster.d.ts new file mode 100644 index 0000000000..ad9eed3066 --- /dev/null +++ b/imagemapster/imagemapster.d.ts @@ -0,0 +1,996 @@ +// Type definitions for imagemapster 1.2.10 +// Project: http://www.outsharked.com/imagemapster/ +// Definitions by: delphinus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ImageMapster { + + type Select = "select"; + type Deselect = "deselect"; + type Set = "set"; + type Get = "get"; + type Highlight = "highlight"; + type Unbind = "unbind"; + type Resize = "resize"; + type Snapshot = "snapshot"; + type Rebind = "rebind"; + type Keys = "keys"; + type SetOptions = "set_options"; + type GetOptions = "get_options"; + type Tooltip = "tooltip"; + type ToolTipCloseEvent = "area-mouseout" | "area-click" | "tooltip-click" | "image-mouseout"; + type State = "highlight" | "select"; + + interface RenderingOptions { + + /** + * fade effect - can only be applied to "render_highlight". + * + * Use a fade effect when highlighting areas on mouseover. + */ + fade?: boolean; + + /** + * The duration of the fade-in effect, in milliseconds. + */ + fadeDuration?: number; + + /** + * highlight areas on mouseover. When null (default), the behavior is + * disabled for mobile browsers. You can explicitly enable or disable + * it by setting this option to a boolean value. + */ + highlight?: boolean; + + /** + * the map or an area on the map can be selected (or deselected). + * + * When true, the image map will function like a multiple-select menu. + * Users can click any area to select or deselect it. When applied to + * the entire map, it determines whether or not the click-selection + * functionality is enabled. When applied to an area, it determines + * whether that individual area (or group) can be selected. By default, + * the map and all areas are selectable. + */ + isSelectable?: boolean; + + /** + * the map or area on the map can be deselected. + * + * Normally true, this option can be used to prevent users from + * unselecting items once they have been selected. When combined with + * singleSelect, the effect is that one and only one option can be + * selected at any given time. Users cannot deselect the active option. + * This provides a menu-like functionality. It is possible for zero + * items to be selected if this is the default state (or the only + * selected item is deselected programatically). + */ + isDeselectable?: boolean; + + /** + * only one area can be selected at a time + * + * When true, only one or zero areas can be selected at any given time. + * If an area is selected and the user selects another area, the + * previously selected area will become deselected. Unlike + * "staticState", this property cannot be overridden by setting areas + * programatically, only one (or zero) areas can ever be selected when + * this option is true. + */ + singleSelect?: boolean; + + /** + * the map or area is permanently in a selected or deselected state. + * + * When true or false, the map or area to which this option applies + * will be permanently selected or deselected. Typically this is more + * useful applied to individual areas that you want to exclude from the + * interactive part of the map. + * + * staticState forces an area to be always selected or deselected. If + * set, this will supercede isSelectable. Something with a staticState + * will always be in that state and it cannot be changed by the user. + * Note that when setting states programatically, this option will not + * be honored; it only affects user interaction. + */ + staticState?: boolean; + + /** + * initial selection state of an area. + * + * The area in question is selected. To set default selections when + * creating a new mapster, use this option for a specific area (see + * above). + */ + selected?: boolean; + + /** + * Use an alternate image of the same size as the imagemap as the + * source for highlight or select effects. + * + * When specified, the mapster will highlight areas using the image + * data obtained from the same area in an alternate image, instead of + * using a fill effect to highlight or select the area. This feature is + * currently available in browsers with HTML5 canvas support. In + * practical terms, this means it will work in all commonly used + * browsers except IE 8 or lower. + * + * If this feature is enabled when an unsupported browser is used, it + * will fall back to the normal highlight method. + * + * The fill, stroke and opacity effects can be specified independently + * from those used for the normal higlight effect. This ensures that + * when your page is viewed with a non-supported browser, you can still + * control the rendering as would be appropriate for a normal + * fill/stroke effect, which may be different from when you're using an + * alternate image. + */ + altImage?: string; + altImageFill?: boolean; + altImageStroke?: boolean; + altImageOpacity?: number; + + /** + * Areas should be flood-filled when moused over or highlighted. + */ + fill?: boolean; + + /** + * The color used for flood fill. + */ + fillColor?: string; + fillColorMask?: string; + + /** + * The opacity of the fill. This is a number from 0 to 1. + */ + fillOpacity?: number; + + /** + * Areas should be outlined when moused over or highlighted. + */ + stroke?: boolean; + + /** + * The color of the outline. + */ + strokeColor?: string; + + /** + * The opacity of the outline. + */ + strokeOpacity?: number; + + /** + * The width of the outline. + */ + strokeWidth?: number; + + /** + * The options below control the way highlighted areas are rendered. + * Each can be applied globally to the map, or to each element, using + * the areas option to pass area-specific options. These options apply + * to either highlighted or selected areas. Highlighting occurs when + * the mouse enters an area on the image map. Selection occurs when an + * area is clicked, and selection is enabled. These options will be + * applied to both situations if present in the root of the options + * object. They can also be applied to one or the other situations + * specifically using the render_highlight and render_select options. + */ + render_highlight?: string | RenderingOptions; + render_select?: string | RenderingOptions; + } + + interface AreaRenderingOptions extends RenderingOptions { + + key: string; + + /** + * when rendering an area or area group, also render the areas in the + * other group (or groups) specified + * + * This is an area-specific option that allows you to create + * supergroups. A supergroup is a collection of groups that will all be + * highlighted simultaneously, but only when the area that defines the + * supergroup is moused over or activated through code. + * + * When the area for which this option has been set is activated, all + * the areas specified in the includeKeys list will also be rendered. + * This is a one-way relationship. Defining a supergroup in an area + * causes all the other groups to be highlighted, but not the other way + * around. + * + * A typical use of this is to define areas that you want to be + * highlighted when the mouse enters some specific area, but that you + * do not want to be highlighted on their own if the target area is + * moused over. This could be a hidden menu, for example: you want the + * menu to display when the hotspot is moused over, but when it's + * hidden, mousing over the menu area itself should have no effect. + */ + includeKeys?: string; + + /** + * the area is a mask rather than a highlighted area. + * + * Normally, every area in an imagemap is an active area, and would be + * highlighted when moused over (unless its behavior was otherwise + * specified with staticState). The isMask option allows you to + * identify an area as being a mask. When a mask is part of an area + * group, the masked area will be specifically excluded from the + * rendering of a highlight or selected state. + * + * This is usually used in conjunction, or instead of, the nohref + * attribute of the area tag. When nohref is specified on an area tag, + * that area is specifically excluded from the hotspot of any area that + * encompasses it. It will not respond to mouse events, and will not be + * highlighted. This can be used to create "holes" in hotspots. By + * default, ImageMapster will treat any area with nohref or no href tag + * as masks, the same as if this option had been applied. + * + * Sometimes you won't be able to use nohref to identify something as a + * mask, for example, if you intend to re-use an area has both a mask, + * and an independent hotspot. This would be typical if you wanted to a + * selectable area that was completely included within another + * selectable area, but functioned independently, such as concentric + * circles. In this case, you would need to identify the inner circle + * as both a mask, and a hotspot. The nohref attribute would make it + * not act as a hotspot, and only function as a mask. You couldn't also + * select the inner area. You can solve this problem by including the + * inner circle in two different groups - one group which is a mask for + * the main area, and another which is an independent selectable area. + * You can specify different options for each group, so even though + * it's just one area, it can function as two completely independent + * ones. + * + * There may also be situations where you do not want an area marked + * with nohref to be treated as a mask. For example, given "area1" and + * "area2," you may want to create a configuration where mousing over + * "area1" causes both "area1" and "area2" to be highlighted, but + * "area2" should not be highlighted on its own when it is moused over. + * In this situation, you'll need to use "nohref" to prevent the hover + * behavior for the area, but you still want it to be treated normally + * when it's rendered as a result of mousing over "area1." You can + * accomplish this using the noHrefIsMask global option, below. + * + * Generally, masked areas will appear as a window to the underlying + * image. If stroke is in effect, the stroke will be rendered for the + * mask as well as the areas, to create both inner and outer borders. + * You can always specifically enable or disable this, or any other + * effect, for any area as desired. + * + */ + isMask?: boolean; + + /** + * tool tip data for an area + * + * When this area-specific option is present and showToolTips = true, a + * toolTipContainer will be created this will be inserted into it, + * either as inner text (if only text as passed) or as HTML if a jQuery + * object is passed. In order to pass anything other than plain text + * using this option you must use a jQuery object. Any string will be + * treated as plain text (and special characters rendered correctly). + */ + toolTip?: string; + } + + interface OnClickData { + + /** + * $(item) from boundList + */ + listTarget?: JQuery; + + /** + * mapKey for this area + */ + key: string; + + e: JQueryEventObject; + selected: boolean; + } + + interface OnStateChangeData { + + /** + * map key + */ + key: string; + + state: "highlight" | "select"; + + /** + * indicating the current state (following the event) + */ + selected: boolean; + } + + interface OnMouseData { + + /** + * area key + */ + key: string; + + /** + * true if area is currently selected + */ + selected: boolean; + + e: JQueryEventObject; + options: AreaRenderingOptions; + } + + interface OnGetListData { + + /** + * primary mapKey for this area or area group + */ + key: string; + + /** + * mapValue for this area or group + */ + value: string; + + /** + * array of areas that make up this group + */ + area: any[]; + + options: AreaRenderingOptions; + } + + interface OnShowToolTipData { + + /** + * jQuery object of the tooltip container + */ + toolTip: JQuery; + + /** + * map key for this area + */ + key: string; + + /** + * current state of the area + */ + selected: boolean; + + areaOptions: AreaRenderingOptions; + } + + interface Options extends RenderingOptions { + + /** + * an attribute identifying each imagemap area. + * + * If specified, this refers to an attribute on the area tags that will + * be used to group them logically. Any areas containing the same + * mapKey will be considered part of a group, and rendered together + * when any of these areas is activated. If you don't want this + * functionality, ensure each key is unique. When mapKey is omitted, + * then each area is considered to be independent from the other and no + * grouping is applied. + * + * When mapKey is present, any area tags that are missing this + * attribute will be excluded from the image map e ntirely. This is + * functionally identical to setting staticState=false for these areas, + * except they will be inaccessible through the API. + * + * ImageMapster will work with any attribute you identify as a key. If + * you wish to maintain HTML compliance, it's recommeded that you use + * attribute names starting with "data-", for example, data-mapkey. Any + * such names are legal for the HTML5 document type. If you are using + * older document types, the class attribute is part of the HTML spec + * for area and will not cause any visual effects, so this is also a + * good choice. It is not recommended to use id, since the values of + * this attribute must be unique. title and alt also will cause + * possibly undesired side effects. + * + * You can specify more than one value in the mapKey attribute, + * separated by commas. This will cause an area to be a member of more + * than one group. The area may have different options in the context + * of each group. When the area is physically moused over, the first + * key listed will identify the group that's effective for that action. + */ + mapKey?: string; + + /** + * an attribute on each area tag containing additional descriptive + * information about an area. + * + * This option is applicable only when using onGetList. When set, the + * data provided to the callback function will include the value of + * this attribute for each group. This can be used to simplify building + * a list with associated information, without having to match against + * another resource. It also ties this information to the image map + * itself. It is not required to use this option when using onGetList. + * + * For example, you could set mapValue: 'data-statename' to an imagemap + * of the united states, and add an attribute to your areas that + * provided the full name of each state, e.g. data-statename="Alaska". + * This text would be included in the onGetList callback, and so you + * could use it to construct an external list of states. + * + * If there are grouped areas (areas with the same key), then the value + * from the first area found with data in this attribute will be used. + */ + mapValue?: string; + + /** + * Clicking on a link should cause the browser to navigate to the href + * whenever it's not a hash sign (#). Version 1.2.4.050 and later + * + * By default, ImageMapster will prevent the default browser behavior + * in image maps, and "select" areas when they are clicked. If you want + * to navigate to the url for an area, use this option. When enabled, + * all areas that have an href attribute, and its value is not empty or + * "#" (just a hashtag). + * + * When area grouping is used, if an href is present for any area in + * the primary group, this will be used as the navigation target. This + * way you don't need to copy the url for every area in groups, rather, + * you can include it on just one, and clicking any area will cause the + * appropraite navigation. + */ + clickNavigate?: boolean; + + /** + * an attribute on items in a boundList that corresponds to the value + * of the mapKey attributes. + * + * This is used to synchronize the actions on the imagemap with the + * actions on a boundList. Each value should match a value from the + * imageMap mapKey tag. Any item in the boundList with missing or + * mismatched data will be ignored. + */ + listKey?: string; + + /** + * attribute to set or remove when an area is selected or deselected + * + * If boundList is present, when a map area is selected, set or remove + * this attribute on the list element that matches that area based on + * their respective keys. + */ + listSelectedAttribute?: string; + + /** + * a class to add or remove when an area is selected or deselected + * + * If a boundList is present, when a map area is selected, this class + * is added or removed from the corresponding list element. This can be + * used to easily create any kind of associated action when areas on + * the map are changed. + */ + listSelectedClass?: string; + + /** + * + * define area-specific options; each object in the array must contain + * a "key" property identifying a valid mapKey, and additional + * rendering options specific to that area or group + */ + areas?: AreaRenderingOptions[], + + /** + * add "classname" class to the wrapper created around the image, or + * copy classes from the image if "true" + */ + wrapClass?: string | boolean; + + /** + * add CSS to the wrapper created around the image + */ + wrapCss?: string | boolean; + + /** + * delay removing highlight when mouse exits an area (1.2.5b36) + * + * Normally, when the user's mouse pointer exits an area, the highlight + * effect is removed immediately. This behavior can be changed with + * this option. Setting it to a positive number causes a delay of n + * milliseconds before the effect is removed. Setting to -1 causes the + * effect to remain active until another hotspot is entered (e.g., it + * will only be removed when superceded by a different area being + * highlighted). + * + * When using mouseoutDelay, the onMouseover event will still be fired + * at the time the user's mouse pointer leaves the area. However, the + * onStateChange event will be delayed until the highlight is actually + * removed. + * + * Whether or not you are using mouseoutDelay, only one area can be + * highlighted at a time. That is, whenever the mouse pointer moves + * onto a new active area, any previously highlighted area will become + * un-highlighted, regardless of any delay in effect. Hovering over a + * new area will always supercede any delay and cause the new area (and + * only the new area) to be highlighted at that time. So, for dense + * imagemaps where most areas adjoin one another, this option may not + * have much effect within the boundaries of the imagemap. Rather, it + * is intended to help keep the higlights active for imagemaps that are + * sparse, or have very small areas. + */ + mouseoutDelay?: number; + + /** + * sort the values before calling onGetList + * + * If a non-false value or "asc" is passed, the list will be sorted in + * ascending order by the area value from mapValue. If "desc" is + * passed, the list will be sorted in descending order. + */ + sortList?: boolean | "asc" | "desc"; + + /** + * time (in milliseconds) to wait for images to load before giving up + * + * When first bound, ImageMapster has to wait for the source image,and + * any altImage images to load before it can finish binding. This is + * necessary because otherwise it's not alwasy possible to know the + * native size of the images. After this period of time, ImageMapster + * will give up. If you have particularly large pages or images, you + * may want to increase this to account for long load times. + */ + configTimeout?: number; + + /** + * Automatically scale imagemaps to match the size of a + * dynamically-scaled image. + * + * When you render an image, you can optionally define a size through + * CSS or using the "height" and "width" attributes. If omitted, the + * image will be displayed in its native size. If included, browsers + * will automatically resize the image to display in the dimensions you + * have provided. + * + * Starting with 1.1.3, ImageMapster will automatically recalculate all + * area data to match the effective size of the image. This means that + * you can set the size of your image to anything you want and + * ImageMapster will work with no changes at all needed to the "area" + * data. + * + * If this behavior is not desired for some reason, this can be + * disabled by setting this option to false. + */ + scaleMap?: boolean; + + /** + * Treat areas containing the onhref attribute (or missing the href + * attribute) as masks. This is true by default. + * + * Set this to "false" to disable automatic masking of these areas. You + * can control them explicitly by creating independent groups for areas + * you wish to mask and assigning the isMask area-specific option when + * using this option. + * + * There are some things to be aware of when using nohref and masking: + * + * * You must put the area that include the nohref attribute before + * other areas that overlap it, or it will be ignored. + * + * * You should also explicitly omit the href tag when using nohref. + * + * * Due to limitations in rendering with VML (e.g. Internet Explorer + * 6-8), it is not possible to create a true mask, which would allow + * the underlying image to show through the masked area. Instead, the + * "masked" areas are rendered on top of the highlighted area in a + * different color. This can be specified for each area (see the + * fillColorMask option below) to create the best possible effect. + */ + noHrefIsMask?: boolean; + + /** + * a jQuery object whose elements are bound to the map. + * + * boundList can be any list of objects. To be bound to the map, they + * must contain an attribute whose name is identified by the option + * listKey, and whose value matches the value in an area tag's mapKey + * attribute. If more than one element in the list has the same value, + * the action will affect all matching elements. + */ + boundList?: JQuery; + + /** + * enable tooltips + * + * When showToolTip is true, mapster will look for a property called + * toolTip in the areas option for a an area. If present, a tool tip + * dialog will be shown on mouseover for that area. It will + * automatically be closed according to the behavior specified by + * toolTipClose. This option does not apply at the item level, but + * rather enables tooltips for the entire map. At the item level, only + * the presence of tooltip data is necessary for a tooltip to appear. + */ + showToolTip?: boolean; + + /** + * HTML describing the popup that will be created for tooltips. + * + * A div with some simple styling is included as the default tooltip + * container. This can be replaced with anything using this option. + * + * When tooltips are rendered, the code attempts to determine the best + * place for it. It will try to position it in near the top-left part + * of the area, and continue to try other corners in order to render it + * within the confines of the container where the image map resides. If + * it can't be placed within the image, it will be placed in the + * lower-right corner and extend outside the image. + */ + toolTipContainer?: string | JQuery; + + /** + * specify the behavior that causes a toolTip to close. + * + * This option should be passed an array of strings that define the + * events that cause active tooltips to close. The array can include + * one or more of the following stings: + * + * 'area-mouseout' - tooltips close when the mouse pointer leaves the + * area that activated it. This is the default. + * + * 'area-click' - tooltips close when another area (or the same one) is + * clicked + * + * 'tooltip-click' - tooltips close when the tooltip itself is clicked + * anywhere + * + * 'image-mouseout' - tooltips close when the mouse pointer leaves the + * image itself. + * + * Under any circumstances, active tooltip will disappear when a new + * one is created. You don't have to define an automatic closing + * behavior; setting this option to an empty array will result in + * tooltips never closing, leaving it to you to close them manually + * though the tooltip method. + */ + toolTipClose?: ToolTipCloseEvent[]; + + /** + * callback when a hotspot area is clicked. Return false to cancel + * default select action, or true to navigate to the 'href' + */ + + /** + * a callback when an area is clicked.:silent doautocmd FocusLost % + * + * This event occurs when the usual click event happens, but includes + * data from the mapster about the area: + * + * This can be used to perform additional actions on a click without + * binding another event and having to obtain information manually. + */ + onClick?: (data: OnClickData) => void; + + /** + * callback when mouse enters a bound area. + * + * This function is called when the mouse enters a bound area. + */ + onMouseover?: (data: OnMouseData) => void; + + /** + * callback when mouse leavesd a bound area. + * + * Callback when the mouse leaves a bound area. The data structure + * passed to the callback is the same as onMouseover. + */ + onMouseout?: (data: OnMouseData) => void; + + /** + * a callback on mapster initialization that provides summary data + * about the image map, and expects a jQuery list to be returned. + * + * This callback allows you to dynamically provide a boundList based on + * summary data from the imagemap itself, rather than providing the + * list up front. The event passes an array of AreaData objects + * + * The client should return a jQuery object containing all the elements + * that make up the bound list, the same as if it was assigned + * manually. + */ + onGetList?: (data: OnGetListData) => JQuery; + + /** + * a callback when the mapster has finished initial configuration + * + * This event is fired when the mapster configuration completes. When + * control execution continues after a first-time bind operation, the + * mapster is not guaranteed to be configured, because images are + * loaded asynchronously by web browsers. If a mapster is bound to an + * image that is not yet loaded, it will attempt to rebind every 200 + * milliseconds. This event will be fired when it is eventually + * successful, or the length of time specified by configTimeout is + * exceeded (default of ten seconds). + * + * The altImage option will also increase the time needed to configure, + * because the alternate image is loaded by the client at configure + * time to ensure it is available immediately when needed. + */ + onConfigured?: (success: boolean) => void; + + /** + * callback when area state is changed (either highlight or select). + * + * onStateChange can be used to get more specific information than the + * mouseover or click events. + */ + onStateChange?: (data: OnStateChangeData) => void; + + /** + * callback when a toolTip is created + * + * This can be used to control tooltip closing behavior directly, if + * desired. + */ + onShowToolTip?: (data: OnShowToolTipData) => void; + } +} + +interface JQuery { + + /** + * + * All images in the jQuery object will be bound. The specific example + * above will attempt to bind to all images present on the page. Each image + * must be bound to an image map identified with the usemap attribute. If + * there is no usemap attribute, or it does not refer to a valid map, then + * the image will be ignored. Therefore you can use this syntax to activate + * all imagemaps on a page. Because pages often contain many images, + * though, it will be faster to select just the image you are targeting + * using a more specific selector. + * + * Images are often not completely loaded when script execution begins. + * ImageMapster will ensure that all images are loaded before it permits + * interaction from the client. If an alternate image is specified, this + * will also be preloaded. + * + * Because images are loaded asynchronously, code execution will often + * return to your script before the ImageMapster is available. If you apply + * other methods to it (such as selecting or deselecting areas), these + * commands will be queued until the image has been loaded, and then + * executed automatically. So you don't need to worry about using callbacks + * for initial configuration. You can assign a function to a callback when + * configuration is complete if needed to perform other setup activities on + * the page. + */ + mapster(options?: ImageMapster.Options): JQuery; + + /** + * select: Cause an area to become selected. This is similar to a user + * click, but will not cause a click event to be fired. + * + * Programatically select elements from the image map. The programmatic + * selection/deselection methods will not honor the staticState property. + */ + mapster(method: ImageMapster.Select): void; + + /** + * deselect: Cause an area to become deselected + * + * The opposite of select, this causes an area to become deselected. If it + * was not previously selected, nothing changes. + */ + mapster(method: ImageMapster.Deselect): void; + + /** + * set: select or deselect an area + * + * Select or deselect elements from jQuery objects wrapping "area" tags on + * the map based on truthiness of selected. If the area represents a bound + * area on the imagemap, it will be selected or deselected. The method can + * be called from an AREA, or from a bound image, passing a specific key as + * a 2nd parameter + * + * If the selected parameter is omitted (or anything other than "true" or + * "false") then the state of each area will be toggled. + * + * You can include an object containing rendering options as the last + * parameter. When present, these will supercede the default and + * area-specific rendering options. + */ + mapster(method: ImageMapster.Set, selected: boolean, options: ImageMapster.RenderingOptions): JQuery; + mapster(method: ImageMapster.Set, options: ImageMapster.RenderingOptions): JQuery; + + /** + * get: get keys for all selected areas + * + * When no "key" parameter is included, returns a comma-separated list of + * keys representing the areas currently selected. If specified, returns + * true or false indicating whether the area specified is selected. + */ + mapster(method: ImageMapster.Get, key?: string): string | boolean; + + /** + * highlight: highlight, clear, or return highlight state + * + * This method is used to control or obtain the current highlight state. + * Setting the highlight does not mimic a mouseover, rather, it only sets + * the highlight. Events and tooltips will not be activated. Even using + * these methods, it is not possible to highlight more than one area at a + * time. If another area is highlighted programatically, any existing + * highlight will be removed. + * + * Once set this way, the highlight will be removed when any user-event + * that would normally cause a highlight to be removed occurs (e.g. moving + * the mouse into any area), or it is removed programatically. + */ + mapster(method: ImageMapster.Highlight, flag?: string | boolean): void; + + /** + * unbind: unbind ImageMapster from an image + * + * Removes the ImageMapster binding from an image and restores it to its + * original state. All visible elements (selections, tooltips) will be + * removed. + * + * If the optional "preserveState" parameter is true, the selection overlay + * and any active tooltips will be preserved. Tooltips can still be + * dismissed by a user click, but once unbound, the selection states can no + * longer be controlled either by the user or programatically. To remove + * them, the actual DOM elements must be removed. + * + * Notes: When a mapster is first bound, several things happen. A div + * element is created which wraps the image. A copy is made of the original + * image, and the original image is set be transparent. This allows + * creating visible elements for the selections & highlights without + * interfering with the image map. Additionally, canvas elements are + * created (for HTML5 browsers), or a VML elements are created for Internet + * Explorer, to render the effects. Profile information about each bound + * image map is stored in memory, and finally, event handlers are bound to + * the image map. + * + * The "unbind" method cleans up these resources: it removes the wrapper, + * restores the image to its original visibility state, and releases + * internal resources. When using 'preserveState', the internal resources + * are cleaned up and event handling is disabled, but HTML elements are not + * removed. Each element created by ImageMapster is assigned a class of + * "mapster_el", which can be used to target them for later removal, though + * it is not easy to complete this process manually because of the wrapper + * and styles applied during configuration, which will be left intact when + * using "preserveState." + */ + mapster(method: ImageMapster.Unbind, preserveState?: boolean): JQuery; + + /** + * snapshot: take a "snapshot" of the current selection state, and reset + * ImageMapster + * + * This option is similar to unbind with preserveState. After a snapshot, + * any active selections will still appear as they did at the time of the + * snapshot, but they are no longer part of the ImageMapster. This is + * useful for configuring an initial state, or creating complex + * representations that may not be easily accomplished with area + * configuration options. + * + * For example, you could bind in image with a specific set of options; + * programatically select some areas; and take a snapshot; then set new + * options that cause a different rendering mode. This way you could have + * certain areas appear differently from the selection highlight, but be + * "highlighted again" using the new rendering options. Any effects in + * place at the time of the snapshot essentially become part of the image + * and are not affected by future operations. + */ + mapster(method: ImageMapster.Snapshot): JQuery; + + /** + * rebind: rebind ImageMapster with new options + * + * This method is similar to set_options, in that its purpose is to change + * options for an existing bound map. However, unlike set_options rebind + * will immediately apply all the new options to the existing map. This + * means that rendering options will change areas that are already selected + * to be rendered with the new options. If you pass area-specific options, + * these will also be applied, e.g. you could cause new areas to be + * selected by passing selected: true in an area specific options. + * + * set_options, in contrast only changes the options, and does not apply + * them to any existing data. When using set_options the new options only + * apply to future actions. + */ + mapster(method: ImageMapster.Rebind, options: ImageMapster.Options): JQuery; + + /** + * resize: change the size of the image and map + * + * This will resize the image map to the dimensions specified. Note that + * either width or height should be passed, and the other will be + * calculated in the same aspect ratio as the original image. If you pass + * both, only the width will be used to calculate the new dimensions: the + * proportions must remain the same as the original image. (Though I intend + * to allow scaling without constraining proportions, it will be difficult + * to make work for certain shapes -- e.g. circles, which would have to + * become ovals). + * + * This method will recalculate and re-render the entire imagemap, so it + * will work exactly the same under the new sizing scheme. When the image + * is unbound, the imagemap will be restored to its original condition. + * + * When using HTML5 canvases, any existing selections, etc. will be + * preserved during the animation. VML data cannot be resized dynamically, + * however, so in IE<9 the selections will be erased, then redrawn when the + * animation is complete. + */ + mapster(method: ImageMapster.Resize, width: number, height: number, duration?: number): JQuery; + + /** + * keys: get the primary mapKey (or comma-separated list of keys) for an + * area, set of areas, or key group. Version 1.2.4.050 + * + * This method allows you to obtain the primary mapKey (or keys) associated + * with another key, or one or more areas. If the all parameter is true, + * the method returns all keys or groups that include the area. + * + * When using area groups, it is possible for more than one key to be + * associated with a map area. It's also possible for an area to be + * highlighted from code as part of a group, but be inaccessible to the + * end-user. This is because area groups are separate physical entities + * from the areas defined by their primary key. They can have different + * options, and are highlighted independently. Note: the way area groups + * work is not well documented here yet. I am working on a more + * comprehensive tutorial for the site. In the meantime please see this + * example which describes area groups in detail, and shows how they work + * through an active demonstration. + * + * There are reasons you may want to be able to access the primary keys + * that make up an area group directly. Perhaps you want to select a group + * of areas using the options from a group - but not as a separate group. + * Perhaps you want to be able to compare the area clicked against a group + * you have defined to take some action if the area is a member of a + * certain group. This method provides access to that information. + * + * This method allows working with groups in a variety of ways by providing + * access to a complete list of primary keys in any group, or all keys + * which contain a given primary key. + */ + mapster(method: ImageMapster.Keys, key: string, all?: boolean): string | string[]; + mapster(method: ImageMapster.Keys, all: boolean): string | string[]; + + /** + * set_options: set active options + * + * When called without the "options" parameter, returns an object with all + * active options. When the parameter is included, the active options are + * updated for the imagemap, and any area options are merged with existing + * area options. Unlike "rebind", this will not rebind or reapply any + * options, but only update the state. This may affect future actions, but + * it will not change any existing state information. + */ + mapster(method: ImageMapster.SetOptions, options?: ImageMapster.Options): JQuery; + + /** + * get_options: get active options + * + * When called with no parameters, returns the options that the mapster was + * configured using. When called with a single key it returns the + * area-specific options assigned to that area. The final parameter + * effective determines whether the actual options in effect for this area, + * or the specific options assigned are returned. + * + * Areas inherit the global options assigned, but can be overridden by + * area-specific options. The "effective" options contain all options + * including those that are inherited, as well as any specifically assigned + * to the area. + */ + mapster(method: ImageMapster.GetOptions, key?: string, effective?: boolean): ImageMapster.Options | ImageMapster.AreaRenderingOptions; + + /** + * tooltip: show/hide tooltips from code + * + * See the tooltip options section below for options to control how + * tooltips appear and are dismissed. + * + * This method can be used to manipulate tooltips from code. If the global + * showToolTip option is false, these methods will still work, so you have + * the ability to control tooltips bound to areas completely using your own + * logic, if desired. These methods can also be used to have better control + * over events needed to close the tooltip, e.g. you could have no tooltip + * closing event, but add a "close" button to your contianer that will + * cause the tooltip to close when clicked. + */ + mapster(method: ImageMapster.Tooltip, key?: string): JQuery; +} diff --git a/immutable/immutable-tests.ts b/immutable/immutable-tests.ts new file mode 100644 index 0000000000..17240ebe9c --- /dev/null +++ b/immutable/immutable-tests.ts @@ -0,0 +1,329 @@ +/// + +import immutable = require('immutable') + +// List tests + +let list: immutable.List = immutable.List([0, 1, 2, 3, 4, 5]); +let list1: immutable.List = immutable.List(list); + +list = immutable.List.of(0, 1, 2, 3, 4); +let bool: boolean = immutable.List.isList(list); + +list = list.set(0, 1); +list = list.delete(0); +list = list.remove(0); +list = list.insert(0, 1); +list = list.clear(); +list = list.push(0, 1, 2, 3, 4, 5); +list = list.pop(); +list = list.unshift(1, 2, 3); +list = list.shift(); +list = list.update((value: immutable.List) => value); +list = list.update(1, (value: number) => value); +list = list.update(1, 1, (value: number) => value); +list = list.merge(list1, list); +list = list.merge([0, 1, 2], [3, 4, 5]); +list = list.mergeWith((prev: number, next: number, key: number) => prev, list, list1); +list = list.mergeWith((prev: number, next: number, key: number) => prev, [0, 1, 2], [3, 4, 5]); +list = list.mergeDeep(list1, list); +list = list.mergeDeep([0, 1, 2], [3, 4, 5]); +list = list.mergeDeepWith((prev: number, next: number, key: number) => prev, list, list1); +list = list.mergeDeepWith((prev: number, next: number, key: number) => prev, [0, 1, 2], [3, 4, 5]); +list = list.setSize(5); +list = list.setIn([0, 1, 2], 5); +list = list.deleteIn([0, 1, 2]); +list = list.removeIn([0, 1, 2]); +list = list.updateIn([0, 1, 2], value => value); +list = list.updateIn([0, 1, 2], 1, value => value); +list = list.mergeIn([0, 1, 2], list, list1); +list = list.mergeIn([0, 1, 2], [0, 1, 2], [3, 4, 5]); +list = list.mergeDeepIn([0, 1, 2], list, list1); +list = list.mergeDeepIn([0, 1, 2], [0, 1, 2], [3, 4, 5]); +list = list.withMutations((mutable: immutable.List) => mutable); +list = list.asMutable(); +list = list.asImmutable(); + +// Collection.Indexed +let indexedSeq: immutable.Seq.Indexed = list.toSeq(); + +// Iterable tests +let value: number = list.get(0); +value = list.get(0, 1); +list = list.interpose(0); +list = list.interleave(list, list1); +list = list.splice(0, 2, 4, 5, 6); +list = list.zip(list1); +let indexedIterable: immutable.Iterable.Indexed = list.zipWith( + (value: number, other: number) => value + other, + list1 +); +let indexedIterable1: immutable.Iterable.Indexed = list.zipWith( + (value: number, other: number, third: number) => value + other + third, + list1, + indexedIterable +); +indexedIterable = list.zipWith( + (value: number, other: number, third: number) => value + other + third, + list1, + indexedIterable1 +); +value = list.indexOf(1); +value = list.lastIndexOf(1); +value = list.findIndex((value: number, index: number, iter: immutable.List) => true); +value = list.findLastIndex((value: number, index: number, iter: immutable.List) => true); +value = list.size; + +bool = list.equals(list1); +value = list.hashCode(); +bool = list.has(1); +bool = list.includes(1); +bool = list.contains(1); +value = list.first(); +value = list.last(); +let toArr: number[] = list.toArray(); +let toMap: immutable.Map = list.toMap(); +let toOrderedMap: immutable.OrderedMap = list.toOrderedMap(); +let toSet: immutable.Set = list.toSet(); +let toOrderedSet: immutable.OrderedSet = list.toOrderedSet(); +list = list.toList(); +let toStack: immutable.Stack = list.toStack(); +let toKeyedSeq: immutable.Seq.Keyed = list.toKeyedSeq(); +indexedSeq = list.toIndexedSeq(); +let toSetSeq: immutable.Seq.Set = list.toSetSeq(); + +let iter: immutable.Iterator = list.keys(); +iter = list.values(); +let iter1: immutable.Iterator<[number, number]> = list.entries(); + +indexedSeq = list.keySeq(); +indexedSeq = list.valueSeq(); +let indexedSeq1: immutable.Seq.Indexed<[number, number]> = list.entrySeq(); + +let iter2: immutable.Iterable = list.map( + (value: number, key: number, iter: immutable.List) => "foo" +) + +list = list.filterNot((value: number, key: number, iter: immutable.List) => true); +list = list.reverse(); +list = list.sort((valA: number, valB: number) => 0); +list = list.sortBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); + +let keyedSeq2: immutable.Seq.Keyed> = list.groupBy( + (value: number, key: number, iter: immutable.List) => "" +); + +value = list.forEach((value: number, key: number, iter: immutable.List) => true); +list = list.slice(0, 1); +list = list.rest(); +list = list.butLast(); +list = list.skip(0); +list = list.skipLast(0); +list = list.skipWhile( + (value: number, key: number, iter: immutable.List) => true +); +list = list.take(2); +list = list.takeLast(2); +list = list.takeWhile( + (value: number, key: number, iter: immutable.List) => true +); +list = list.takeUntil( + (value: number, key: number, iter: immutable.List) => true +); +list = list.concat(list1, 2, 3); +list = list.flatten(1); +list = list.flatten(true); +let str: string = list.reduce( + (red: string, value: number, key: number, iter: immutable.List) => red + "bar", + "foo" +); +str = list.reduceRight( + (red: string, value: number, key: number, iter: immutable.List) => red + "bar", + "foo" +); +bool = list.every( + (value: number, key: number, iter: immutable.List) => true +); +bool = list.some( + (value: number, key: number, iter: immutable.List) => true +); +str = list.join(","); +bool = list.isEmpty(); +value = list.count(); +value = list.count( + (value: number, key: number, iter: immutable.List) => true +); +let keyedSeq3: immutable.Seq.Keyed = list.countBy( + (value: number, key: number, iter: immutable.List) => "foo" +); +value = list.find( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +value = list.findLast( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +let tuple: [number, number] = list.findEntry( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +tuple = list.findLastEntry( + (value: number, key: number, iter: immutable.List) => true, + null, + 0 +); +value = list.findKey( + (value: number, key: number, iter: immutable.List) => true, + null +); +value = list.findLastKey( + (value: number, key: number, iter: immutable.List) => true, + null +); +value = list.keyOf(0); +value = list.lastKeyOf(0); +value = list.max((valA: number, valB: number) => 0); +value = list.maxBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); +value = list.min((valA: number, valB: number) => 0); +value = list.minBy( + (value: number, key: number, iter: immutable.List) => "foo", + (valueA: string, valueB: string) => 0 +); +bool = list.isSubset(list1); +bool = list.isSubset([0, 1, 2]); +bool = list.isSuperset(list1); +bool = list.isSuperset([0, 1, 2]); + + +// Map tests + +let map: immutable.Map = immutable.Map(); +map = immutable.Map([["foo", 1], ["bar", 2]]); +let map1: immutable.Map = immutable.Map(map); +map = map.set("baz", 3); +map.delete("foo"); +map.remove("foo"); +map = map.clear(); +map = map.update((value: immutable.Map) => value); +map = map.update("foo", (value: number) => value); +map = map.update("bar", 1, (value: number) => value); +map = map.merge(map1, map); +map = map.merge({ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeWith((prev: number, next: number, key: string) => prev, map, map1); +map = map.mergeWith((prev: number, next: number, key: string) => prev,{ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeep(map1, map); +map = map.mergeDeep({ "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeepWith((prev: number, next: number, key: string) => prev, map, map1); +map = map.mergeDeepWith((prev: number, next: number, key: string) => prev, { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.setIn([0, 1, 2], 5); +map = map.deleteIn([0, 1, 2]); +map = map.removeIn([0, 1, 2]); +map = map.updateIn([0, 1, 2], value => value); +map = map.updateIn([0, 1, 2], 1, value => value); +map = map.mergeIn([0, 1, 2], map, map1); +map = map.mergeIn([0, 1, 2], { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.mergeDeepIn([0, 1, 2], map, map1); +map = map.mergeDeepIn([0, 1, 2], { "foo": 0, "bar": 1}, {"baz": 2}); +map = map.withMutations((mutable: immutable.Map) => mutable); +map = map.asMutable(); +map = map.asImmutable(); + +bool = immutable.Map.isMap(map); +map = immutable.Map.of("foo", 0, "bar", 1); + +// OrderedMap tests +bool = immutable.OrderedMap.isOrderedMap(toOrderedMap); +toOrderedMap = immutable.OrderedMap(toOrderedMap); + +// Set tests +let set: immutable.Set = immutable.Set.of(0, 1, 2, 3); +bool = immutable.Set.isSet(set); +set = immutable.Set.fromKeys(toMap); +let set1: immutable.Set = immutable.Set.fromKeys({ "foo": 1, "bar": 2}); +set = immutable.Set(); +set = immutable.Set(set); +set = set.add(3); +set.delete(1); +set.remove(2); +set = set.clear(); +set = set.union(map, list); +set = set.union([1, 2, 3], [4, 5, 6]); +set = set.merge(map1, list); +set = set.merge([1, 2, 3], [4, 5, 6]); +set = set.intersect(map1, list); +set = set.intersect([1, 2, 3], [4, 5, 6]); +set = set.subtract(map1, list); +set = set.subtract([1, 2, 3], [4, 5, 6]); +set = set.withMutations((mutable: immutable.Set) => mutable); +set = set.asMutable(); +set = set.asImmutable(); + + +// OrderedSet tests +bool = immutable.OrderedSet.isOrderedSet(set); +let orderedSet1: immutable.OrderedSet = immutable.OrderedSet.of(0, 1, 2, 3); +orderedSet1 = immutable.OrderedSet.fromKeys(toMap); +let orderedSet2: immutable.Set = immutable.Set.fromKeys({ "foo": 1, "bar": 2}); + +// Stack tests + +let stack: immutable.Stack = immutable.Stack(); +bool = immutable.Stack.isStack(stack); +stack = immutable.Stack.of(0, 1, 2, 3, 4, 5); +stack = immutable.Stack(list); +value = stack.peek(); +stack = stack.clear(); +stack = stack.unshift(0, 1, 2); +stack = stack.unshiftAll(list); +stack = stack.unshiftAll([1, 2, 3]); +stack = stack.shift(); +stack = stack.push(1, 2, 3); +stack = stack.pushAll(list); +stack = stack.pushAll([1, 2, 3]); +stack = stack.pop(); +stack = stack.withMutations((mutable: immutable.Stack) => mutable); +stack = stack.asMutable(); +stack = stack.asImmutable(); + + +// Range and Repeat function tests + +let funcSeqIndexed: immutable.Seq.Indexed = immutable.Range(0, 3, 1); +funcSeqIndexed = immutable.Repeat(2, 10); + + +// Seq tests +let seq: immutable.Seq = immutable.Seq(); +bool = immutable.Seq.isSeq(seq); +funcSeqIndexed = immutable.Seq.of(0, 1, 2, 3); +seq = immutable.Seq(map); +value = seq.size; +seq = seq.cacheResult(); + + +// keyed +let seqKeyed: immutable.Seq.Keyed = immutable.Seq.Keyed(); +seqKeyed = immutable.Seq.Keyed(map); +seqKeyed = seqKeyed.toSeq(); + +// indexed +let seqIndexed: immutable.Seq.Indexed = immutable.Seq.Indexed(); +seqIndexed = immutable.Seq.Indexed.of(0, 1, 2, 3); +seqIndexed = immutable.Seq.Indexed(list); +seqIndexed = seqIndexed.toSeq(); + +// indexed +let seqSet: immutable.Seq.Set = immutable.Seq.Set(); +seqSet = immutable.Seq.Set.of(0, 1, 2, 3); +seqSet = immutable.Seq.Set(list); +seqSet = seqSet.toSeq(); diff --git a/immutable/immutable.d.ts b/immutable/immutable.d.ts new file mode 100644 index 0000000000..86f23bc6e3 --- /dev/null +++ b/immutable/immutable.d.ts @@ -0,0 +1,2546 @@ +// Type definitions for Facebook's Immutable 3.8.1 +// Project: https://github.com/facebook/immutable-js +// Definitions by: tht13 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Core of typings are from repository itself + +/** + * Copyright (c) 2014-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +/** + * Immutable data encourages pure functions (data-in, data-out) and lends itself + * to much simpler application development and enabling techniques from + * functional programming such as lazy evaluation. + * + * While designed to bring these powerful functional concepts to JavaScript, it + * presents an Object-Oriented API familiar to Javascript engineers and closely + * mirroring that of Array, Map, and Set. It is easy and efficient to convert to + * and from plain Javascript types. + + * Note: all examples are presented in [ES6][]. To run in all browsers, they + * need to be translated to ES3. For example: + * + * // ES6 + * foo.map(x => x * x); + * // ES3 + * foo.map(function (x) { return x * x; }); + * + * [ES6]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla + */ + +declare namespace Immutable { + + /** + * Deeply converts plain JS objects and arrays to Immutable Maps and Lists. + * + * If a `reviver` is optionally provided, it will be called with every + * collection as a Seq (beginning with the most nested collections + * and proceeding to the top-level collection itself), along with the key + * refering to each collection and the parent JS object provided as `this`. + * For the top level, object, the key will be `""`. This `reviver` is expected + * to return a new Immutable Iterable, allowing for custom conversions from + * deep JS objects. + * + * This example converts JSON to List and OrderedMap: + * + * Immutable.fromJS({a: {b: [10, 20, 30]}, c: 40}, function (key, value) { + * var isIndexed = Immutable.Iterable.isIndexed(value); + * return isIndexed ? value.toList() : value.toOrderedMap(); + * }); + * + * // true, "b", {b: [10, 20, 30]} + * // false, "a", {a: {b: [10, 20, 30]}, c: 40} + * // false, "", {"": {a: {b: [10, 20, 30]}, c: 40}} + * + * If `reviver` is not provided, the default behavior will convert Arrays into + * Lists and Objects into Maps. + * + * `reviver` acts similarly to the [same parameter in `JSON.parse`][1]. + * + * `Immutable.fromJS` is conservative in its conversion. It will only convert + * arrays which pass `Array.isArray` to Lists, and only raw objects (no custom + * prototype) to Map. + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + * + * [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter + * "Using the reviver parameter" + */ + export function fromJS( + json: any, + reviver?: (k: any, v: Iterable) => any + ): any; + + + /** + * Value equality check with semantics similar to `Object.is`, but treats + * Immutable `Iterable`s as values, equal if the second `Iterable` includes + * equivalent values. + * + * It's used throughout Immutable when checking for equality, including `Map` + * key equality and `Set` membership. + * + * var map1 = Immutable.Map({a:1, b:1, c:1}); + * var map2 = Immutable.Map({a:1, b:1, c:1}); + * assert(map1 !== map2); + * assert(Object.is(map1, map2) === false); + * assert(Immutable.is(map1, map2) === true); + * + * Note: Unlike `Object.is`, `Immutable.is` assumes `0` and `-0` are the same + * value, matching the behavior of ES6 Map key equality. + */ + export function is(first: any, second: any): boolean; + + + /** + * Lists are ordered indexed dense collections, much like a JavaScript + * Array. + * + * Lists are immutable and fully persistent with O(log32 N) gets and sets, + * and O(1) push and pop. + * + * Lists implement Deque, with efficient addition and removal from both the + * end (`push`, `pop`) and beginning (`unshift`, `shift`). + * + * Unlike a JavaScript Array, there is no distinction between an + * "unset" index and an index set to `undefined`. `List#forEach` visits all + * indices from 0 to size, regardless of whether they were explicitly defined. + */ + export module List { + + /** + * True if the provided value is a List + */ + function isList(maybeList: any): boolean; + + /** + * Creates a new List containing `values`. + */ + function of(...values: T[]): List; + } + + /** + * Create a new immutable List containing the values of the provided + * iterable-like. + */ + export function List(): List; + export function List(iter: Iterable.Indexed): List; + export function List(iter: Iterable.Set): List; + export function List(iter: Iterable.Keyed): List<[K,V]>; + export function List(array: Array): List; + export function List(iterator: Iterator): List; + export function List(iterable: Iterable): List; + + + export interface List extends Collection.Indexed { + + // Persistent changes + + /** + * Returns a new List which includes `value` at `index`. If `index` already + * exists in this List, it will be replaced. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.set(-1, "value")` sets the last item in the List. + * + * If `index` larger than `size`, the returned List's `size` will be large + * enough to include the `index`. + */ + set(index: number, value: T): List; + + /** + * Returns a new List which excludes this `index` and with a size 1 less + * than this List. Values at indices above `index` are shifted down by 1 to + * fill the position. + * + * This is synonymous with `list.splice(index, 1)`. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.delete(-1)` deletes the last item in the List. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(index: number): List; + remove(index: number): List; + + /** + * Returns a new List with `value` at `index` with a size 1 more than this + * List. Values at indices above `index` are shifted over by 1. + * + * This is synonymous with `list.splice(index, 0, value) + */ + insert(index: number, value: T): List; + + /** + * Returns a new List with 0 size and no values. + */ + clear(): List; + + /** + * Returns a new List with the provided `values` appended, starting at this + * List's `size`. + */ + push(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the last index in this List. + * + * Note: this differs from `Array#pop` because it returns a new + * List rather than the removed value. Use `last()` to get the last value + * in this List. + */ + pop(): List; + + /** + * Returns a new List with the provided `values` prepended, shifting other + * values ahead to higher indices. + */ + unshift(...values: T[]): List; + + /** + * Returns a new List with a size ones less than this List, excluding + * the first index in this List, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * List rather than the removed value. Use `first()` to get the first + * value in this List. + */ + shift(): List; + + /** + * Returns a new List with an updated value at `index` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * `index` was not set. If called with a single argument, `updater` is + * called with the List itself. + * + * `index` may be a negative number, which indexes back from the end of the + * List. `v.update(-1)` updates the last item in the List. + * + * @see `Map#update` + */ + update(updater: (value: List) => List): List; + update(index: number, updater: (value: T) => T): List; + update(index: number, notSetValue: T, updater: (value: T) => T): List; + + /** + * @see `Map#merge` + */ + merge(...iterables: Iterable.Indexed[]): List; + merge(...iterables: Array[]): List; + + /** + * @see `Map#mergeWith` + */ + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeep` + */ + mergeDeep(...iterables: Iterable.Indexed[]): List; + mergeDeep(...iterables: Array[]): List; + + /** + * @see `Map#mergeDeepWith` + */ + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepWith( + merger: (previous?: T, next?: T, key?: number) => T, + ...iterables: Array[] + ): List; + + /** + * Returns a new List with size `size`. If `size` is less than this + * List's size, the new List will exclude values at the higher indices. + * If `size` is greater than this List's size, the new List will have + * undefined values for the newly available indices. + * + * When building a new List and the final size is known up front, `setSize` + * used in conjunction with `withMutations` may result in the more + * performant construction. + */ + setSize(size: number): List; + + + // Deep persistent changes + + /** + * Returns a new List having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + * + * Index numbers are used as keys to determine the path to follow in + * the List. + */ + setIn(keyPath: Array, value: any): List; + setIn(keyPath: Iterable, value: any): List; + + /** + * Returns a new List having removed the value at this `keyPath`. If any + * keys in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): List; + deleteIn(keyPath: Iterable): List; + removeIn(keyPath: Array): List; + removeIn(keyPath: Iterable): List; + + /** + * @see `Map#updateIn` + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): List; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): List; + + /** + * @see `Map#mergeIn` + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + /** + * @see `Map#mergeDeepIn` + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable.Indexed[] + ): List; + mergeDeepIn( + keyPath: Array, + ...iterables: Array[] + ): List; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, `pop`, `shift`, `unshift` and + * `merge` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: List) => any): List; + + /** + * @see `Map#asMutable` + */ + asMutable(): List; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): List; + } + + + /** + * Immutable Map is an unordered Iterable.Keyed of (key, value) pairs with + * `O(log32 N)` gets and `O(log32 N)` persistent sets. + * + * Iteration order of a Map is undefined, however is stable. Multiple + * iterations of the same Map will iterate in the same order. + * + * Map's keys can be of any type, and use `Immutable.is` to determine key + * equality. This allows the use of any value (including NaN) as a key. + * + * Because `Immutable.is` returns equality based on value semantics, and + * Immutable collections are treated as values, any Immutable collection may + * be used as a key. + * + * Map().set(List.of(1), 'listofone').get(List.of(1)); + * // 'listofone' + * + * Any JavaScript object may be used as a key, however strict identity is used + * to evaluate key equality. Two similar looking objects will represent two + * different keys. + * + * Implemented by a hash-array mapped trie. + */ + export module Map { + + /** + * True if the provided value is a Map + */ + function isMap(maybeMap: any): boolean; + + /** + * Creates a new Map from alternating keys and values + */ + function of(...keyValues: (K|V)[]): Map; + } + + /** + * Creates a new Immutable Map. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * var newMap = Map({key: "value"}); + * var newMap = Map([["key", "value"]]); + * + * Keep in mind, when using JS objects to construct Immutable Maps, that + * JavaScript Object properties are always strings, even if written in a + * quote-less shorthand, while Immutable Maps accept keys of any type. + * + * ```js + * var obj = { 1: "one" }; + * Object.keys(obj); // [ "1" ] + * obj["1"]; // "one" + * obj[1]; // "one" + * + * var map = Map(obj); + * map.get("1"); // "one" + * map.get(1); // undefined + * ``` + * + * Property access for JavaScript Objects first converts the key to a string, + * but since Immutable Map keys can be of any type the argument to `get()` is + * not altered. + */ + export function Map(): Map; + export function Map(iter: Iterable.Keyed): Map; + export function Map(iter: Iterable): Map; + export function Map(array: Array<[K,V]>): Map; + export function Map(obj: {[key: string]: V}): Map; + export function Map(iterator: Iterator<[K,V]>): Map; + export function Map(iterable: Iterable): Map; + + export interface Map extends Collection.Keyed { + + // Persistent changes + + /** + * Returns a new Map also containing the new key, value pair. If an equivalent + * key already exists in this Map, it will be replaced. + */ + set(key: K, value: V): Map; + + /** + * Returns a new Map which excludes this `key`. + * + * Note: `delete` cannot be safely used in IE8, but is provided to mirror + * the ES6 collection API. + * @alias remove + */ + delete(key: K): Map; + remove(key: K): Map; + + /** + * Returns a new Map containing no keys or values. + */ + clear(): Map; + + /** + * Returns a new Map having updated the value at this `key` with the return + * value of calling `updater` with the existing value, or `notSetValue` if + * the key was not set. If called with only a single argument, `updater` is + * called with the Map itself. + * + * Equivalent to: `map.set(key, updater(map.get(key, notSetValue)))`. + */ + update(updater: (value: Map) => Map): Map; + update(key: K, updater: (value: V) => V): Map; + update(key: K, notSetValue: V, updater: (value: V) => V): Map; + + /** + * Returns a new Map resulting from merging the provided Iterables + * (or JS objects) into this Map. In other words, this takes each entry of + * each iterable and sets it on this Map. + * + * If any of the values provided to `merge` are not Iterable (would return + * false for `Immutable.Iterable.isIterable`) then they are deeply converted + * via `Immutable.fromJS` before being merged. However, if the value is an + * Iterable but includes non-iterable JS objects or arrays, those nested + * values will be preserved. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.merge(y) // { a: 50, b: 40, c: 30, d: 60 } + * y.merge(x) // { b: 20, a: 10, d: 60, c: 30 } + * + */ + merge(...iterables: Iterable[]): Map; + merge(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `merge()`, `mergeWith()` returns a new Map resulting from merging + * the provided Iterables (or JS objects) into this Map, but uses the + * `merger` function for dealing with conflicts. + * + * var x = Immutable.Map({a: 10, b: 20, c: 30}); + * var y = Immutable.Map({b: 40, a: 50, d: 60}); + * x.mergeWith((prev, next) => prev / next, y) // { a: 0.2, b: 0.5, c: 30, d: 60 } + * y.mergeWith((prev, next) => prev / next, x) // { b: 2, a: 5, d: 60, c: 30 } + * + */ + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * Like `merge()`, but when two Iterables conflict, it merges them as well, + * recursing deeply through the nested data. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeep(y) // {a: { x: 2, y: 10 }, b: { x: 20, y: 5 }, c: { z: 3 } } + * + */ + mergeDeep(...iterables: Iterable[]): Map; + mergeDeep(...iterables: {[key: string]: V}[]): Map; + + /** + * Like `mergeDeep()`, but when two non-Iterables conflict, it uses the + * `merger` function to determine the resulting value. + * + * var x = Immutable.fromJS({a: { x: 10, y: 10 }, b: { x: 20, y: 50 } }); + * var y = Immutable.fromJS({a: { x: 2 }, b: { y: 5 }, c: { z: 3 } }); + * x.mergeDeepWith((prev, next) => prev / next, y) + * // {a: { x: 5, y: 10 }, b: { x: 20, y: 10 }, c: { z: 3 } } + * + */ + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: Iterable[] + ): Map; + mergeDeepWith( + merger: (previous?: V, next?: V, key?: K) => V, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Deep persistent changes + + /** + * Returns a new Map having set `value` at this `keyPath`. If any keys in + * `keyPath` do not exist, a new immutable Map will be created at that key. + */ + setIn(keyPath: Array, value: any): Map; + setIn(KeyPath: Iterable, value: any): Map; + + /** + * Returns a new Map having removed the value at this `keyPath`. If any keys + * in `keyPath` do not exist, no change will occur. + * + * @alias removeIn + */ + deleteIn(keyPath: Array): Map; + deleteIn(keyPath: Iterable): Map; + removeIn(keyPath: Array): Map; + removeIn(keyPath: Iterable): Map; + + /** + * Returns a new Map having applied the `updater` to the entry found at the + * keyPath. + * + * If any keys in `keyPath` do not exist, new Immutable `Map`s will + * be created at those keys. If the `keyPath` does not already contain a + * value, the `updater` function will be called with `notSetValue`, if + * provided, otherwise `undefined`. + * + * var data = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data = data.updateIn(['a', 'b', 'c'], val => val * 2); + * // { a: { b: { c: 20 } } } + * + * If the `updater` function returns the same value it was called with, then + * no change will occur. This is still true if `notSetValue` is provided. + * + * var data1 = Immutable.fromJS({ a: { b: { c: 10 } } }); + * data2 = data1.updateIn(['x', 'y', 'z'], 100, val => val); + * assert(data2 === data1); + * + */ + updateIn( + keyPath: Array, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Array, + notSetValue: any, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + updater: (value: any) => any + ): Map; + updateIn( + keyPath: Iterable, + notSetValue: any, + updater: (value: any) => any + ): Map; + + /** + * A combination of `updateIn` and `merge`, returning a new Map, but + * performing the merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.merge(y)); + * x.mergeIn(['a', 'b', 'c'], y); + * + */ + mergeIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + /** + * A combination of `updateIn` and `mergeDeep`, returning a new Map, but + * performing the deep merge at a point arrived at by following the keyPath. + * In other words, these two lines are equivalent: + * + * x.updateIn(['a', 'b', 'c'], abc => abc.mergeDeep(y)); + * x.mergeDeepIn(['a', 'b', 'c'], y); + * + */ + mergeDeepIn( + keyPath: Iterable, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: Iterable[] + ): Map; + mergeDeepIn( + keyPath: Array, + ...iterables: {[key: string]: V}[] + ): Map; + + + // Transient changes + + /** + * Every time you call one of the above functions, a new immutable Map is + * created. If a pure function calls a number of these to produce a final + * return value, then a penalty on performance and memory has been paid by + * creating all of the intermediate immutable Maps. + * + * If you need to apply a series of mutations to produce a new immutable + * Map, `withMutations()` creates a temporary mutable copy of the Map which + * can apply mutations in a highly performant manner. In fact, this is + * exactly how complex mutations like `merge` are done. + * + * As an example, this results in the creation of 2, not 4, new Maps: + * + * var map1 = Immutable.Map(); + * var map2 = map1.withMutations(map => { + * map.set('a', 1).set('b', 2).set('c', 3); + * }); + * assert(map1.size === 0); + * assert(map2.size === 3); + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + * + */ + withMutations(mutator: (mutable: Map) => any): Map; + + /** + * Another way to avoid creation of intermediate Immutable maps is to create + * a mutable copy of this collection. Mutable copies *always* return `this`, + * and thus shouldn't be used for equality. Your function should never return + * a mutable copy of a collection, only use it internally to create a new + * collection. If possible, use `withMutations` as it provides an easier to + * use API. + * + * Note: if the collection is already mutable, `asMutable` returns itself. + * + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set` and `merge` may be used mutatively. + */ + asMutable(): Map; + + /** + * The yin to `asMutable`'s yang. Because it applies to mutable collections, + * this operation is *mutable* and returns itself. Once performed, the mutable + * copy has become immutable and can be safely returned from a function. + */ + asImmutable(): Map; + } + + + /** + * A type of Map that has the additional guarantee that the iteration order of + * entries will be the order in which they were set(). + * + * The iteration behavior of OrderedMap is the same as native ES6 Map and + * JavaScript Object. + * + * Note that `OrderedMap` are more expensive than non-ordered `Map` and may + * consume more memory. `OrderedMap#set` is amortized O(log32 N), but not + * stable. + */ + + export module OrderedMap { + + /** + * True if the provided value is an OrderedMap. + */ + function isOrderedMap(maybeOrderedMap: any): boolean; + } + + /** + * Creates a new Immutable OrderedMap. + * + * Created with the same key value pairs as the provided Iterable.Keyed or + * JavaScript Object or expects an Iterable of [K, V] tuple entries. + * + * The iteration order of key-value pairs provided to this constructor will + * be preserved in the OrderedMap. + * + * var newOrderedMap = OrderedMap({key: "value"}); + * var newOrderedMap = OrderedMap([["key", "value"]]); + * + */ + export function OrderedMap(): OrderedMap; + export function OrderedMap(iter: Iterable.Keyed): OrderedMap; + export function OrderedMap(iter: Iterable): OrderedMap; + export function OrderedMap(array: Array<[K,V]>): OrderedMap; + export function OrderedMap(obj: {[key: string]: V}): OrderedMap; + export function OrderedMap(iterator: Iterator<[K,V]>): OrderedMap; + export function OrderedMap(iterable: Iterable): OrderedMap; + + export interface OrderedMap extends Map {} + + + /** + * A Collection of unique values with `O(log32 N)` adds and has. + * + * When iterating a Set, the entries will be (value, value) pairs. Iteration + * order of a Set is undefined, however is stable. Multiple iterations of the + * same Set will iterate in the same order. + * + * Set values, like Map keys, may be of any type. Equality is determined using + * `Immutable.is`, enabling Sets to uniquely include other Immutable + * collections, custom value types, and NaN. + */ + export module Set { + + /** + * True if the provided value is a Set + */ + function isSet(maybeSet: any): boolean; + + /** + * Creates a new Set containing `values`. + */ + function of(...values: T[]): Set; + + /** + * `Set.fromKeys()` creates a new immutable Set containing the keys from + * this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): Set; + function fromKeys(obj: {[key: string]: any}): Set; + } + + /** + * Create a new immutable Set containing the values of the provided + * iterable-like. + */ + export function Set(): Set; + export function Set(iter: Iterable.Set): Set; + export function Set(iter: Iterable.Indexed): Set; + export function Set(iter: Iterable.Keyed): Set<[K,V]>; + export function Set(array: Array): Set; + export function Set(iterator: Iterator): Set; + export function Set(iterable: Iterable): Set; + + export interface Set extends Collection.Set { + + // Persistent changes + + /** + * Returns a new Set which also includes this value. + */ + add(value: T): Set; + + /** + * Returns a new Set which excludes this value. + * + * Note: `delete` cannot be safely used in IE8 + * @alias remove + */ + delete(value: T): Set; + remove(value: T): Set; + + /** + * Returns a new Set containing no values. + */ + clear(): Set; + + /** + * Returns a Set including any value from `iterables` that does not already + * exist in this Set. + * @alias merge + */ + union(...iterables: Iterable[]): Set; + union(...iterables: Array[]): Set; + merge(...iterables: Iterable[]): Set; + merge(...iterables: Array[]): Set; + + + /** + * Returns a Set which has removed any values not also contained + * within `iterables`. + */ + intersect(...iterables: Iterable[]): Set; + intersect(...iterables: Array[]): Set; + + /** + * Returns a Set excluding any values contained within `iterables`. + */ + subtract(...iterables: Iterable[]): Set; + subtract(...iterables: Array[]): Set; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `add` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Set) => any): Set; + + /** + * @see `Map#asMutable` + */ + asMutable(): Set; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Set; + } + + + /** + * A type of Set that has the additional guarantee that the iteration order of + * values will be the order in which they were `add`ed. + * + * The iteration behavior of OrderedSet is the same as native ES6 Set. + * + * Note that `OrderedSet` are more expensive than non-ordered `Set` and may + * consume more memory. `OrderedSet#add` is amortized O(log32 N), but not + * stable. + */ + export module OrderedSet { + + /** + * True if the provided value is an OrderedSet. + */ + function isOrderedSet(maybeOrderedSet: any): boolean; + + /** + * Creates a new OrderedSet containing `values`. + */ + function of(...values: T[]): OrderedSet; + + /** + * `OrderedSet.fromKeys()` creates a new immutable OrderedSet containing + * the keys from this Iterable or JavaScript Object. + */ + function fromKeys(iter: Iterable): OrderedSet; + function fromKeys(obj: {[key: string]: any}): OrderedSet; + } + + /** + * Create a new immutable OrderedSet containing the values of the provided + * iterable-like. + */ + export function OrderedSet(): OrderedSet; + export function OrderedSet(iter: Iterable.Set): OrderedSet; + export function OrderedSet(iter: Iterable.Indexed): OrderedSet; + export function OrderedSet(iter: Iterable.Keyed): OrderedSet<[K,V]>; + export function OrderedSet(array: Array): OrderedSet; + export function OrderedSet(iterator: Iterator): OrderedSet; + export function OrderedSet(iterable: Iterable): OrderedSet; + + export interface OrderedSet extends Set {} + + + /** + * Stacks are indexed collections which support very efficient O(1) addition + * and removal from the front using `unshift(v)` and `shift()`. + * + * For familiarity, Stack also provides `push(v)`, `pop()`, and `peek()`, but + * be aware that they also operate on the front of the list, unlike List or + * a JavaScript Array. + * + * Note: `reverse()` or any inherent reverse traversal (`reduceRight`, + * `lastIndexOf`, etc.) is not efficient with a Stack. + * + * Stack is implemented with a Single-Linked List. + */ + export module Stack { + + /** + * True if the provided value is a Stack + */ + function isStack(maybeStack: any): boolean; + + /** + * Creates a new Stack containing `values`. + */ + function of(...values: T[]): Stack; + } + + /** + * Create a new immutable Stack containing the values of the provided + * iterable-like. + * + * The iteration order of the provided iterable is preserved in the + * resulting `Stack`. + */ + export function Stack(): Stack; + export function Stack(iter: Iterable.Indexed): Stack; + export function Stack(iter: Iterable.Set): Stack; + export function Stack(iter: Iterable.Keyed): Stack<[K,V]>; + export function Stack(array: Array): Stack; + export function Stack(iterator: Iterator): Stack; + export function Stack(iterable: Iterable): Stack; + + export interface Stack extends Collection.Indexed { + + // Reading values + + /** + * Alias for `Stack.first()`. + */ + peek(): T; + + + // Persistent changes + + /** + * Returns a new Stack with 0 size and no values. + */ + clear(): Stack; + + /** + * Returns a new Stack with the provided `values` prepended, shifting other + * values ahead to higher indices. + * + * This is very efficient for Stack. + */ + unshift(...values: T[]): Stack; + + /** + * Like `Stack#unshift`, but accepts a iterable rather than varargs. + */ + unshiftAll(iter: Iterable): Stack; + unshiftAll(iter: Array): Stack; + + /** + * Returns a new Stack with a size ones less than this Stack, excluding + * the first item in this Stack, shifting all other values to a lower index. + * + * Note: this differs from `Array#shift` because it returns a new + * Stack rather than the removed value. Use `first()` or `peek()` to get the + * first value in this Stack. + */ + shift(): Stack; + + /** + * Alias for `Stack#unshift` and is not equivalent to `List#push`. + */ + push(...values: T[]): Stack; + + /** + * Alias for `Stack#unshiftAll`. + */ + pushAll(iter: Iterable): Stack; + pushAll(iter: Array): Stack; + + /** + * Alias for `Stack#shift` and is not equivalent to `List#pop`. + */ + pop(): Stack; + + + // Transient changes + + /** + * Note: Not all methods can be used on a mutable collection or within + * `withMutations`! Only `set`, `push`, and `pop` may be used mutatively. + * + * @see `Map#withMutations` + */ + withMutations(mutator: (mutable: Stack) => any): Stack; + + /** + * @see `Map#asMutable` + */ + asMutable(): Stack; + + /** + * @see `Map#asImmutable` + */ + asImmutable(): Stack; + } + + + /** + * Returns a Seq.Indexed of numbers from `start` (inclusive) to `end` + * (exclusive), by `step`, where `start` defaults to 0, `step` to 1, and `end` to + * infinity. When `start` is equal to `end`, returns empty range. + * + * Range() // [0,1,2,3,...] + * Range(10) // [10,11,12,13,...] + * Range(10,15) // [10,11,12,13,14] + * Range(10,30,5) // [10,15,20,25] + * Range(30,10,5) // [30,25,20,15] + * Range(30,30,5) // [] + * + */ + export function Range(start?: number, end?: number, step?: number): Seq.Indexed; + + + /** + * Returns a Seq.Indexed of `value` repeated `times` times. When `times` is + * not defined, returns an infinite `Seq` of `value`. + * + * Repeat('foo') // ['foo','foo','foo',...] + * Repeat('bar',4) // ['bar','bar','bar','bar'] + * + */ + export function Repeat(value: T, times?: number): Seq.Indexed; + + + /** + * Creates a new Class which produces Record instances. A record is similar to + * a JS object, but enforce a specific set of allowed string keys, and have + * default values. + * + * var ABRecord = Record({a:1, b:2}) + * var myRecord = new ABRecord({b:3}) + * + * Records always have a value for the keys they define. `remove`ing a key + * from a record simply resets it to the default value for that key. + * + * myRecord.size // 2 + * myRecord.get('a') // 1 + * myRecord.get('b') // 3 + * myRecordWithoutB = myRecord.remove('b') + * myRecordWithoutB.get('b') // 2 + * myRecordWithoutB.size // 2 + * + * Values provided to the constructor not found in the Record type will + * be ignored. For example, in this case, ABRecord is provided a key "x" even + * though only "a" and "b" have been defined. The value for "x" will be + * ignored for this record. + * + * var myRecord = new ABRecord({b:3, x:10}) + * myRecord.get('x') // undefined + * + * Because Records have a known set of string keys, property get access works + * as expected, however property sets will throw an Error. + * + * Note: IE8 does not support property access. Only use `get()` when + * supporting IE8. + * + * myRecord.b // 3 + * myRecord.b = 5 // throws Error + * + * Record Classes can be extended as well, allowing for custom methods on your + * Record. This is not a common pattern in functional environments, but is in + * many JS programs. + * + * Note: TypeScript does not support this type of subclassing. + * + * class ABRecord extends Record({a:1,b:2}) { + * getAB() { + * return this.a + this.b; + * } + * } + * + * var myRecord = new ABRecord({b: 3}) + * myRecord.getAB() // 4 + * + */ + export module Record { + export interface Class { + new (): Map; + new (values: {[key: string]: any}): Map; + new (values: Iterable): Map; // deprecated + + (): Map; + (values: {[key: string]: any}): Map; + (values: Iterable): Map; // deprecated + } + } + + export function Record( + defaultValues: {[key: string]: any}, name?: string + ): Record.Class; + + + /** + * Represents a sequence of values, but may not be backed by a concrete data + * structure. + * + * **Seq is immutable** — Once a Seq is created, it cannot be + * changed, appended to, rearranged or otherwise modified. Instead, any + * mutative method called on a `Seq` will return a new `Seq`. + * + * **Seq is lazy** — Seq does as little work as necessary to respond to any + * method call. Values are often created during iteration, including implicit + * iteration when reducing or converting to a concrete data structure such as + * a `List` or JavaScript `Array`. + * + * For example, the following performs no work, because the resulting + * Seq's values are never iterated: + * + * var oddSquares = Immutable.Seq.of(1,2,3,4,5,6,7,8) + * .filter(x => x % 2).map(x => x * x); + * + * Once the Seq is used, it performs only the work necessary. In this + * example, no intermediate data structures are ever created, filter is only + * called three times, and map is only called once: + * + * console.log(oddSquares.get(1)); // 9 + * + * Seq allows for the efficient chaining of operations, + * allowing for the expression of logic that can otherwise be very tedious: + * + * Immutable.Seq({a:1, b:1, c:1}) + * .flip().map(key => key.toUpperCase()).flip().toObject(); + * // Map { A: 1, B: 1, C: 1 } + * + * As well as expressing logic that would otherwise be memory or time limited: + * + * Immutable.Range(1, Infinity) + * .skip(1000) + * .map(n => -n) + * .filter(n => n % 2 === 0) + * .take(2) + * .reduce((r, n) => r * n, 1); + * // 1006008 + * + * Seq is often used to provide a rich collection API to JavaScript Object. + * + * Immutable.Seq({ x: 0, y: 1, z: 2 }).map(v => v * 2).toObject(); + * // { x: 0, y: 2, z: 4 } + */ + + export module Seq { + /** + * True if `maybeSeq` is a Seq, it is not backed by a concrete + * structure such as Map, List, or Set. + */ + function isSeq(maybeSeq: any): boolean; + + /** + * Returns a Seq of the values provided. Alias for `Seq.Indexed.of()`. + */ + function of(...values: T[]): Seq.Indexed; + + + /** + * `Seq` which represents key-value pairs. + */ + export module Keyed {} + + /** + * Always returns a Seq.Keyed, if input is not keyed, expects an + * iterable of [K, V] tuples. + */ + export function Keyed(): Seq.Keyed; + export function Keyed(seq: Iterable.Keyed): Seq.Keyed; + export function Keyed(seq: Iterable): Seq.Keyed; + export function Keyed(array: Array<[K,V]>): Seq.Keyed; + export function Keyed(obj: {[key: string]: V}): Seq.Keyed; + export function Keyed(iterator: Iterator<[K,V]>): Seq.Keyed; + export function Keyed(iterable: Iterable): Seq.Keyed; + + export interface Keyed extends Seq, Iterable.Keyed { + + /** + * Returns itself + */ + toSeq(): this + } + + + /** + * `Seq` which represents an ordered indexed list of values. + */ + module Indexed { + + /** + * Provides an Seq.Indexed of the values provided. + */ + function of(...values: T[]): Seq.Indexed; + } + + /** + * Always returns Seq.Indexed, discarding associated keys and + * supplying incrementing indices. + */ + export function Indexed(): Seq.Indexed; + export function Indexed(seq: Iterable.Indexed): Seq.Indexed; + export function Indexed(seq: Iterable.Set): Seq.Indexed; + export function Indexed(seq: Iterable.Keyed): Seq.Indexed<[K,V]>; + export function Indexed(array: Array): Seq.Indexed; + export function Indexed(iterator: Iterator): Seq.Indexed; + export function Indexed(iterable: Iterable): Seq.Indexed; + + export interface Indexed extends Seq, Iterable.Indexed { + + /** + * Returns itself + */ + toSeq(): this + } + + + /** + * `Seq` which represents a set of values. + * + * Because `Seq` are often lazy, `Seq.Set` does not provide the same guarantee + * of value uniqueness as the concrete `Set`. + */ + export module Set { + + /** + * Returns a Seq.Set of the provided values + */ + function of(...values: T[]): Seq.Set; + } + + /** + * Always returns a Seq.Set, discarding associated indices or keys. + */ + export function Set(): Seq.Set; + export function Set(seq: Iterable.Set): Seq.Set; + export function Set(seq: Iterable.Indexed): Seq.Set; + export function Set(seq: Iterable.Keyed): Seq.Set<[K,V]>; + export function Set(array: Array): Seq.Set; + export function Set(iterator: Iterator): Seq.Set; + export function Set(iterable: Iterable): Seq.Set; + + export interface Set extends Seq, Iterable.Set { + + /** + * Returns itself + */ + toSeq(): this + } + + } + + /** + * Creates a Seq. + * + * Returns a particular kind of `Seq` based on the input. + * + * * If a `Seq`, that same `Seq`. + * * If an `Iterable`, a `Seq` of the same kind (Keyed, Indexed, or Set). + * * If an Array-like, an `Seq.Indexed`. + * * If an Object with an Iterator, an `Seq.Indexed`. + * * If an Iterator, an `Seq.Indexed`. + * * If an Object, a `Seq.Keyed`. + * + */ + export function Seq(): Seq; + export function Seq(seq: Seq): Seq; + export function Seq(iterable: Iterable): Seq; + export function Seq(array: Array): Seq.Indexed; + export function Seq(obj: {[key: string]: V}): Seq.Keyed; + export function Seq(iterator: Iterator): Seq.Indexed; + export function Seq(iterable: Iterable): Seq.Indexed; + + export interface Seq extends Iterable { + + /** + * Some Seqs can describe their size lazily. When this is the case, + * size will be an integer. Otherwise it will be undefined. + * + * For example, Seqs returned from `map()` or `reverse()` + * preserve the size of the original `Seq` while `filter()` does not. + * + * Note: `Range`, `Repeat` and `Seq`s made from `Array`s and `Object`s will + * always have a size. + */ + size: number/*?*/; + + + // Force evaluation + + /** + * Because Sequences are lazy and designed to be chained together, they do + * not cache their results. For example, this map function is called a total + * of 6 times, as each `join` iterates the Seq of three values. + * + * var squares = Seq.of(1,2,3).map(x => x * x); + * squares.join() + squares.join(); + * + * If you know a `Seq` will be used multiple times, it may be more + * efficient to first cache it in memory. Here, the map function is called + * only 3 times. + * + * var squares = Seq.of(1,2,3).map(x => x * x).cacheResult(); + * squares.join() + squares.join(); + * + * Use this method judiciously, as it must fully evaluate a Seq which can be + * a burden on memory and possibly performance. + * + * Note: after calling `cacheResult`, a Seq will always have a `size`. + */ + cacheResult(): this; + } + + /** + * The `Iterable` is a set of (key, value) entries which can be iterated, and + * is the base class for all collections in `immutable`, allowing them to + * make use of all the Iterable methods (such as `map` and `filter`). + * + * Note: An iterable is always iterated in the same order, however that order + * may not always be well defined, as is the case for the `Map` and `Set`. + */ + export module Iterable { + /** + * True if `maybeIterable` is an Iterable, or any of its subclasses. + */ + function isIterable(maybeIterable: any): boolean; + + /** + * True if `maybeKeyed` is an Iterable.Keyed, or any of its subclasses. + */ + function isKeyed(maybeKeyed: any): boolean; + + /** + * True if `maybeIndexed` is a Iterable.Indexed, or any of its subclasses. + */ + function isIndexed(maybeIndexed: any): boolean; + + /** + * True if `maybeAssociative` is either a keyed or indexed Iterable. + */ + function isAssociative(maybeAssociative: any): boolean; + + /** + * True if `maybeOrdered` is an Iterable where iteration order is well + * defined. True for Iterable.Indexed as well as OrderedMap and OrderedSet. + */ + function isOrdered(maybeOrdered: any): boolean; + + + /** + * Keyed Iterables have discrete keys tied to each value. + * + * When iterating `Iterable.Keyed`, each iteration will yield a `[K, V]` + * tuple, in other words, `Iterable#entries` is the default iterator for + * Keyed Iterables. + */ + export module Keyed {} + + /** + * Creates an Iterable.Keyed + * + * Similar to `Iterable()`, however it expects iterable-likes of [K, V] + * tuples if not constructed from a Iterable.Keyed or JS Object. + */ + export function Keyed(iter: Iterable.Keyed): Iterable.Keyed; + export function Keyed(iter: Iterable): Iterable.Keyed; + export function Keyed(array: Array<[K,V]>): Iterable.Keyed; + export function Keyed(obj: {[key: string]: V}): Iterable.Keyed; + export function Keyed(iterator: Iterator<[K,V]>): Iterable.Keyed; + export function Keyed(iterable: Iterable): Iterable.Keyed; + + export interface Keyed extends Iterable { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + + + // Sequence functions + + /** + * Returns a new Iterable.Keyed of the same type where the keys and values + * have been flipped. + * + * Seq({ a: 'z', b: 'y' }).flip() // { z: 'a', y: 'b' } + * + */ + flip(): this; + + /** + * Returns a new Iterable.Keyed of the same type with keys passed through + * a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapKeys(x => x.toUpperCase()) + * // Seq { A: 1, B: 2 } + * + */ + mapKeys( + mapper: (key?: K, value?: V, iter?: this) => M, + context?: any + ): /*this*/Iterable.Keyed; + + /** + * Returns a new Iterable.Keyed of the same type with entries + * ([key, value] tuples) passed through a `mapper` function. + * + * Seq({ a: 1, b: 2 }) + * .mapEntries(([k, v]) => [k.toUpperCase(), v * 2]) + * // Seq { A: 2, B: 4 } + * + */ + mapEntries( + mapper: ( + entry?: [K, V], + index?: number, + iter?: this + ) => [KM, VM], + context?: any + ): /*this*/Iterable.Keyed; + } + + + /** + * Indexed Iterables have incrementing numeric keys. They exhibit + * slightly different behavior than `Iterable.Keyed` for some methods in order + * to better mirror the behavior of JavaScript's `Array`, and add methods + * which do not make sense on non-indexed Iterables such as `indexOf`. + * + * Unlike JavaScript arrays, `Iterable.Indexed`s are always dense. "Unset" + * indices and `undefined` indices are indistinguishable, and all indices from + * 0 to `size` are visited when iterated. + * + * All Iterable.Indexed methods return re-indexed Iterables. In other words, + * indices always start at 0 and increment until size. If you wish to + * preserve indices, using them as keys, convert to a Iterable.Keyed by + * calling `toKeyedSeq`. + */ + export module Indexed {} + + /** + * Creates a new Iterable.Indexed. + */ + export function Indexed(iter: Iterable.Indexed): Iterable.Indexed; + export function Indexed(iter: Iterable.Set): Iterable.Indexed; + export function Indexed(iter: Iterable.Keyed): Iterable.Indexed<[K,V]>; + export function Indexed(array: Array): Iterable.Indexed; + export function Indexed(iterator: Iterator): Iterable.Indexed; + export function Indexed(iterable: Iterable): Iterable.Indexed; + + export interface Indexed extends Iterable { + + // Reading values + + /** + * Returns the value associated with the provided index, or notSetValue if + * the index is beyond the bounds of the Iterable. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.get(-1)` gets the last item in the Iterable. + */ + get(index: number, notSetValue?: T): T; + + + // Conversion to Seq + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + + /** + * If this is an iterable of [key, value] entry tuples, it will return a + * Seq.Keyed of those entries. + */ + fromEntrySeq(): Seq.Keyed; + + + // Combination + + /** + * Returns an Iterable of the same type with `separator` between each item + * in this Iterable. + */ + interpose(separator: T): this; + + /** + * Returns an Iterable of the same type with the provided `iterables` + * interleaved into this iterable. + * + * The resulting Iterable includes the first item from each, then the + * second from each, etc. + * + * I.Seq.of(1,2,3).interleave(I.Seq.of('A','B','C')) + * // Seq [ 1, 'A', 2, 'B', 3, 'C' ] + * + * The shortest Iterable stops interleave. + * + * I.Seq.of(1,2,3).interleave( + * I.Seq.of('A','B'), + * I.Seq.of('X','Y','Z') + * ) + * // Seq [ 1, 'A', 'X', 2, 'B', 'Y' ] + */ + interleave(...iterables: Array>): this; + + /** + * Splice returns a new indexed Iterable by replacing a region of this + * Iterable with new values. If values are not provided, it only skips the + * region to be removed. + * + * `index` may be a negative number, which indexes back from the end of the + * Iterable. `s.splice(-2)` splices after the second to last item. + * + * Seq(['a','b','c','d']).splice(1, 2, 'q', 'r', 's') + * // Seq ['a', 'q', 'r', 's', 'd'] + * + */ + splice( + index: number, + removeNum: number, + ...values: Array | T> + ): this; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables. + * + * Like `zipWith`, but using the default `zipper`: creating an `Array`. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zip(b); // Seq [ [ 1, 4 ], [ 2, 5 ], [ 3, 6 ] ] + * + */ + zip(...iterables: Array>): this; + + /** + * Returns an Iterable of the same type "zipped" with the provided + * iterables by using a custom `zipper` function. + * + * var a = Seq.of(1, 2, 3); + * var b = Seq.of(4, 5, 6); + * var c = a.zipWith((a, b) => a + b, b); // Seq [ 5, 7, 9 ] + * + */ + zipWith( + zipper: (value: T, otherValue: U) => Z, + otherIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (value: T, otherValue: U, thirdValue: V) => Z, + otherIterable: Iterable, + thirdIterable: Iterable + ): Iterable.Indexed; + zipWith( + zipper: (...any: Array) => Z, + ...iterables: Array> + ): Iterable.Indexed; + + + // Search for value + + /** + * Returns the first index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + indexOf(searchValue: T): number; + + /** + * Returns the last index at which a given value can be found in the + * Iterable, or -1 if it is not present. + */ + lastIndexOf(searchValue: T): number; + + /** + * Returns the first index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findIndex( + predicate: (value?: T, index?: number, iter?: this) => boolean, + context?: any + ): number; + + /** + * Returns the last index in the Iterable where a value satisfies the + * provided predicate function. Otherwise -1 is returned. + */ + findLastIndex( + predicate: (value?: T, index?: number, iter?: this) => boolean, + context?: any + ): number; + } + + + /** + * Set Iterables only represent values. They have no associated keys or + * indices. Duplicate values are possible in Seq.Sets, however the + * concrete `Set` does not allow duplicate values. + * + * Iterable methods on Iterable.Set such as `map` and `forEach` will provide + * the value as both the first and second arguments to the provided function. + * + * var seq = Seq.Set.of('A', 'B', 'C'); + * assert.equal(seq.every((v, k) => v === k), true); + * + */ + export module Set {} + + /** + * Similar to `Iterable()`, but always returns a Iterable.Set. + */ + export function Set(iter: Iterable.Set): Iterable.Set; + export function Set(iter: Iterable.Indexed): Iterable.Set; + export function Set(iter: Iterable.Keyed): Iterable.Set<[K,V]>; + export function Set(array: Array): Iterable.Set; + export function Set(iterator: Iterator): Iterable.Set; + export function Set(iterable: Iterable): Iterable.Set; + + export interface Set extends Iterable { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + /** + * Creates an Iterable. + * + * The type of Iterable created is based on the input. + * + * * If an `Iterable`, that same `Iterable`. + * * If an Array-like, an `Iterable.Indexed`. + * * If an Object with an Iterator, an `Iterable.Indexed`. + * * If an Iterator, an `Iterable.Indexed`. + * * If an Object, an `Iterable.Keyed`. + * + * This methods forces the conversion of Objects and Strings to Iterables. + * If you want to ensure that a Iterable of one item is returned, use + * `Seq.of`. + */ + export function Iterable(iterable: Iterable): Iterable; + export function Iterable(array: Array): Iterable.Indexed; + export function Iterable(obj: {[key: string]: V}): Iterable.Keyed; + export function Iterable(iterator: Iterator): Iterable.Indexed; + export function Iterable(iterable: Iterable): Iterable.Indexed; + export function Iterable(value: V): Iterable.Indexed; + + export interface Iterable { + + // Value equality + + /** + * True if this and the other Iterable have value equality, as defined + * by `Immutable.is()`. + * + * Note: This is equivalent to `Immutable.is(this, other)`, but provided to + * allow for chained expressions. + */ + equals(other: Iterable): boolean; + + /** + * Computes and returns the hashed identity for this Iterable. + * + * The `hashCode` of an Iterable is used to determine potential equality, + * and is used when adding this to a `Set` or as a key in a `Map`, enabling + * lookup via a different instance. + * + * var a = List.of(1, 2, 3); + * var b = List.of(1, 2, 3); + * assert(a !== b); // different instances + * var set = Set.of(a); + * assert(set.has(b) === true); + * + * If two values have the same `hashCode`, they are [not guaranteed + * to be equal][Hash Collision]. If two values have different `hashCode`s, + * they must not be equal. + * + * [Hash Collision]: http://en.wikipedia.org/wiki/Collision_(computer_science) + */ + hashCode(): number; + + + // Reading values + + /** + * Returns the value associated with the provided key, or notSetValue if + * the Iterable does not contain this key. + * + * Note: it is possible a key may be associated with an `undefined` value, + * so if `notSetValue` is not provided and this method returns `undefined`, + * that does not guarantee the key was not found. + */ + get(key: K, notSetValue?: V): V; + + /** + * True if a key exists within this `Iterable`, using `Immutable.is` to determine equality + */ + has(key: K): boolean; + + /** + * True if a value exists within this `Iterable`, using `Immutable.is` to determine equality + * @alias contains + */ + includes(value: V): boolean; + contains(value: V): boolean; + + /** + * The first value in the Iterable. + */ + first(): V; + + /** + * The last value in the Iterable. + */ + last(): V; + + + // Reading deep values + + /** + * Returns the value found by following a path of keys or indices through + * nested Iterables. + */ + getIn(searchKeyPath: Array, notSetValue?: any): any; + getIn(searchKeyPath: Iterable, notSetValue?: any): any; + + /** + * True if the result of following a path of keys or indices through nested + * Iterables results in a set value. + */ + hasIn(searchKeyPath: Array): boolean; + hasIn(searchKeyPath: Iterable): boolean; + + + // Conversion to JavaScript types + + /** + * Deeply converts this Iterable to equivalent JS. + * + * `Iterable.Indexeds`, and `Iterable.Sets` become Arrays, while + * `Iterable.Keyeds` become Objects. + * + * @alias toJSON + */ + toJS(): any; + + /** + * Shallowly converts this iterable to an Array, discarding keys. + */ + toArray(): Array; + + /** + * Shallowly converts this Iterable to an Object. + * + * Throws if keys are not strings. + */ + toObject(): { [key: string]: V }; + + + // Conversion to Collections + + /** + * Converts this Iterable to a Map, Throws if keys are not hashable. + * + * Note: This is equivalent to `Map(this.toKeyedSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toMap(): Map; + + /** + * Converts this Iterable to a Map, maintaining the order of iteration. + * + * Note: This is equivalent to `OrderedMap(this.toKeyedSeq())`, but + * provided for convenience and to allow for chained expressions. + */ + toOrderedMap(): OrderedMap; + + /** + * Converts this Iterable to a Set, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Set(this)`, but provided to allow for + * chained expressions. + */ + toSet(): Set; + + /** + * Converts this Iterable to a Set, maintaining the order of iteration and + * discarding keys. + * + * Note: This is equivalent to `OrderedSet(this.valueSeq())`, but provided + * for convenience and to allow for chained expressions. + */ + toOrderedSet(): OrderedSet; + + /** + * Converts this Iterable to a List, discarding keys. + * + * Note: This is equivalent to `List(this)`, but provided to allow + * for chained expressions. + */ + toList(): List; + + /** + * Converts this Iterable to a Stack, discarding keys. Throws if values + * are not hashable. + * + * Note: This is equivalent to `Stack(this)`, but provided to allow for + * chained expressions. + */ + toStack(): Stack; + + + // Conversion to Seq + + /** + * Converts this Iterable to a Seq of the same kind (indexed, + * keyed, or set). + */ + toSeq(): Seq; + + /** + * Returns a Seq.Keyed from this Iterable where indices are treated as keys. + * + * This is useful if you want to operate on an + * Iterable.Indexed and preserve the [index, value] pairs. + * + * The returned Seq will have identical iteration order as + * this Iterable. + * + * Example: + * + * var indexedSeq = Immutable.Seq.of('A', 'B', 'C'); + * indexedSeq.filter(v => v === 'B').toString() // Seq [ 'B' ] + * var keyedSeq = indexedSeq.toKeyedSeq(); + * keyedSeq.filter(v => v === 'B').toString() // Seq { 1: 'B' } + * + */ + toKeyedSeq(): Seq.Keyed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + toIndexedSeq(): Seq.Indexed; + + /** + * Returns a Seq.Set of the values of this Iterable, discarding keys. + */ + toSetSeq(): Seq.Set; + + + // Iterators + + /** + * An iterator of this `Iterable`'s keys. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `keySeq` instead, if this is what you want. + */ + keys(): Iterator; + + /** + * An iterator of this `Iterable`'s values. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `valueSeq` instead, if this is what you want. + */ + values(): Iterator; + + /** + * An iterator of this `Iterable`'s entries as `[key, value]` tuples. + * + * Note: this will return an ES6 iterator which does not support Immutable JS sequence algorithms. Use `entrySeq` instead, if this is what you want. + */ + entries(): Iterator<[K, V]>; + + + // Iterables (Seq) + + /** + * Returns a new Seq.Indexed of the keys of this Iterable, + * discarding values. + */ + keySeq(): Seq.Indexed; + + /** + * Returns an Seq.Indexed of the values of this Iterable, discarding keys. + */ + valueSeq(): Seq.Indexed; + + /** + * Returns a new Seq.Indexed of [key, value] tuples. + */ + entrySeq(): Seq.Indexed<[K, V]>; + + + // Sequence algorithms + + /** + * Returns a new Iterable of the same type with values passed through a + * `mapper` function. + * + * Seq({ a: 1, b: 2 }).map(x => 10 * x) + * // Seq { a: 10, b: 20 } + * + */ + map( + mapper: (value?: V, key?: K, iter?: this) => M, + context?: any + ): /*this*/Iterable; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns true. + * + * Seq({a:1,b:2,c:3,d:4}).filter(x => x % 2 === 0) + * // Seq { b: 2, d: 4 } + * + */ + filter( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type with only the entries for which + * the `predicate` function returns false. + * + * Seq({a:1,b:2,c:3,d:4}).filterNot(x => x % 2 === 0) + * // Seq { a: 1, c: 3 } + * + */ + filterNot( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type in reverse order. + */ + reverse(): this; + + /** + * Returns a new Iterable of the same type which includes the same entries, + * stably sorted by using a `comparator`. + * + * If a `comparator` is not provided, a default comparator uses `<` and `>`. + * + * `comparator(valueA, valueB)`: + * + * * Returns `0` if the elements should not be swapped. + * * Returns `-1` (or any negative number) if `valueA` comes before `valueB` + * * Returns `1` (or any positive number) if `valueA` comes after `valueB` + * * Is pure, i.e. it must always return the same value for the same pair + * of values. + * + * When sorting collections which have no defined order, their ordered + * equivalents will be returned. e.g. `map.sort()` returns OrderedMap. + */ + sort(comparator?: (valueA: V, valueB: V) => number): this; + + /** + * Like `sort`, but also accepts a `comparatorValueMapper` which allows for + * sorting by more sophisticated means: + * + * hitters.sortBy(hitter => hitter.avgHits); + * + */ + sortBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): this; + + /** + * Returns a `Iterable.Keyed` of `Iterable.Keyeds`, grouped by the return + * value of the `grouper` function. + * + * Note: This is always an eager operation. + */ + groupBy( + grouper: (value?: V, key?: K, iter?: this) => G, + context?: any + ): Seq.Keyed; + + + // Side effects + + /** + * The `sideEffect` is executed for every entry in the Iterable. + * + * Unlike `Array#forEach`, if any call of `sideEffect` returns + * `false`, the iteration will stop. Returns the number of entries iterated + * (including the last iteration which returned false). + */ + forEach( + sideEffect: (value?: V, key?: K, iter?: this) => any, + context?: any + ): number; + + + // Creating subsets + + /** + * Returns a new Iterable of the same type representing a portion of this + * Iterable from start up to but not including end. + * + * If begin is negative, it is offset from the end of the Iterable. e.g. + * `slice(-2)` returns a Iterable of the last two entries. If it is not + * provided the new Iterable will begin at the beginning of this Iterable. + * + * If end is negative, it is offset from the end of the Iterable. e.g. + * `slice(0, -1)` returns an Iterable of everything but the last entry. If + * it is not provided, the new Iterable will continue through the end of + * this Iterable. + * + * If the requested slice is equivalent to the current Iterable, then it + * will return itself. + */ + slice(begin?: number, end?: number): this; + + /** + * Returns a new Iterable of the same type containing all entries except + * the first. + */ + rest(): this; + + /** + * Returns a new Iterable of the same type containing all entries except + * the last. + */ + butLast(): this; + + /** + * Returns a new Iterable of the same type which excludes the first `amount` + * entries from this Iterable. + */ + skip(amount: number): this; + + /** + * Returns a new Iterable of the same type which excludes the last `amount` + * entries from this Iterable. + */ + skipLast(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns false. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipWhile(x => x.match(/g/)) + * // Seq [ 'cat', 'hat', 'god' ] + * + */ + skipWhile( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes entries starting + * from when `predicate` first returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .skipUntil(x => x.match(/hat/)) + * // Seq [ 'hat', 'god' ] + * + */ + skipUntil( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes the first `amount` + * entries from this Iterable. + */ + take(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes the last `amount` + * entries from this Iterable. + */ + takeLast(amount: number): this; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns true. + * + * Seq.of('dog','frog','cat','hat','god') + * .takeWhile(x => x.match(/o/)) + * // Seq [ 'dog', 'frog' ] + * + */ + takeWhile( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + /** + * Returns a new Iterable of the same type which includes entries from this + * Iterable as long as the `predicate` returns false. + * + * Seq.of('dog','frog','cat','hat','god').takeUntil(x => x.match(/at/)) + * // ['dog', 'frog'] + * + */ + takeUntil( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): this; + + + // Combination + + /** + * Returns a new Iterable of the same type with other values and + * iterable-like concatenated to this one. + * + * For Seqs, all entries will be present in + * the resulting iterable, even if they have the same key. + */ + concat(...valuesOrIterables: Array|V>): this; + + /** + * Flattens nested Iterables. + * + * Will deeply flatten the Iterable by default, returning an Iterable of the + * same type, but a `depth` can be provided in the form of a number or + * boolean (where true means to shallowly flatten one level). A depth of 0 + * (or shallow: false) will deeply flatten. + * + * Flattens only others Iterable, not Arrays or Objects. + * + * Note: `flatten(true)` operates on Iterable> and + * returns Iterable + */ + flatten(depth?: number): this; + flatten(shallow?: boolean): this; + + /** + * Flat-maps the Iterable, returning an Iterable of the same type. + * + * Similar to `iter.map(...).flatten(true)`. + */ + flatMap( + mapper: (value?: V, key?: K, iter?: this) => Iterable, + context?: any + ): /*this*/Iterable; + flatMap( + mapper: (value?: V, key?: K, iter?: this) => /*iterable-like*/any, + context?: any + ): /*this*/Iterable; + + + // Reducing a value + + /** + * Reduces the Iterable to a value by calling the `reducer` for every entry + * in the Iterable and passing along the reduced value. + * + * If `initialReduction` is not provided, or is null, the first item in the + * Iterable will be used. + * + * @see `Array#reduce`. + */ + reduce( + reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * Reduces the Iterable in reverse (from the right side). + * + * Note: Similar to this.reverse().reduce(), and provided for parity + * with `Array#reduceRight`. + */ + reduceRight( + reducer: (reduction?: R, value?: V, key?: K, iter?: this) => R, + initialReduction?: R, + context?: any + ): R; + + /** + * True if `predicate` returns true for all entries in the Iterable. + */ + every( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): boolean; + + /** + * True if `predicate` returns true for any entry in the Iterable. + */ + some( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): boolean; + + /** + * Joins values together as a string, inserting a separator between each. + * The default separator is `","`. + */ + join(separator?: string): string; + + /** + * Returns true if this Iterable includes no values. + * + * For some lazy `Seq`, `isEmpty` might need to iterate to determine + * emptiness. At most one iteration will occur. + */ + isEmpty(): boolean; + + /** + * Returns the size of this Iterable. + * + * Regardless of if this Iterable can describe its size lazily (some Seqs + * cannot), this method will always return the correct size. E.g. it + * evaluates a lazy `Seq` if necessary. + * + * If `predicate` is provided, then this returns the count of entries in the + * Iterable for which the `predicate` returns true. + */ + count(): number; + count( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): number; + + /** + * Returns a `Seq.Keyed` of counts, grouped by the return value of + * the `grouper` function. + * + * Note: This is not a lazy operation. + */ + countBy( + grouper: (value?: V, key?: K, iter?: this) => G, + context?: any + ): Seq.Keyed; + + + // Search for value + + /** + * Returns the first value for which the `predicate` returns true. + */ + find( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the last value for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLast( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): V; + + /** + * Returns the first [key, value] entry for which the `predicate` returns true. + */ + findEntry( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): [K, V]; + + /** + * Returns the last [key, value] entry for which the `predicate` + * returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastEntry( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any, + notSetValue?: V + ): [K, V]; + + /** + * Returns the key for which the `predicate` returns true. + */ + findKey( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): K; + + /** + * Returns the last key for which the `predicate` returns true. + * + * Note: `predicate` will be called for each entry in reverse. + */ + findLastKey( + predicate: (value?: V, key?: K, iter?: this) => boolean, + context?: any + ): K; + + /** + * Returns the key associated with the search value, or undefined. + */ + keyOf(searchValue: V): K; + + /** + * Returns the last key associated with the search value, or undefined. + */ + lastKeyOf(searchValue: V): K; + + /** + * Returns the maximum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `>`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `max` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `>` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + max(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `max`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.maxBy(hitter => hitter.avgHits); + * + */ + maxBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + /** + * Returns the minimum value in this collection. If any values are + * comparatively equivalent, the first one found will be returned. + * + * The `comparator` is used in the same way as `Iterable#sort`. If it is not + * provided, the default comparator is `<`. + * + * When two values are considered equivalent, the first encountered will be + * returned. Otherwise, `min` will operate independent of the order of input + * as long as the comparator is commutative. The default comparator `<` is + * commutative *only* when types do not differ. + * + * If `comparator` returns 0 and either value is NaN, undefined, or null, + * that value will be returned. + */ + min(comparator?: (valueA: V, valueB: V) => number): V; + + /** + * Like `min`, but also accepts a `comparatorValueMapper` which allows for + * comparing by more sophisticated means: + * + * hitters.minBy(hitter => hitter.avgHits); + * + */ + minBy( + comparatorValueMapper: (value?: V, key?: K, iter?: this) => C, + comparator?: (valueA: C, valueB: C) => number + ): V; + + + // Comparison + + /** + * True if `iter` includes every value in this Iterable. + */ + isSubset(iter: Iterable): boolean; + isSubset(iter: Array): boolean; + + /** + * True if this Iterable includes every value in `iter`. + */ + isSuperset(iter: Iterable): boolean; + isSuperset(iter: Array): boolean; + + + /** + * Note: this is here as a convenience to work around an issue with + * TypeScript https://github.com/Microsoft/TypeScript/issues/285, but + * Iterable does not define `size`, instead `Seq` defines `size` as + * nullable number, and `Collection` defines `size` as always a number. + * + * @ignore + */ + size: number; + } + + + /** + * Collection is the abstract base class for concrete data structures. It + * cannot be constructed directly. + * + * Implementations should extend one of the subclasses, `Collection.Keyed`, + * `Collection.Indexed`, or `Collection.Set`. + */ + export module Collection { + + + /** + * `Collection` which represents key-value pairs. + */ + export module Keyed {} + + export interface Keyed extends Collection, Iterable.Keyed { + + /** + * Returns Seq.Keyed. + * @override + */ + toSeq(): Seq.Keyed; + } + + + /** + * `Collection` which represents ordered indexed values. + */ + export module Indexed {} + + export interface Indexed extends Collection, Iterable.Indexed { + + /** + * Returns Seq.Indexed. + * @override + */ + toSeq(): Seq.Indexed; + } + + + /** + * `Collection` which represents values, unassociated with keys or indices. + * + * `Collection.Set` implementations should guarantee value uniqueness. + */ + export module Set {} + + export interface Set extends Collection, Iterable.Set { + + /** + * Returns Seq.Set. + * @override + */ + toSeq(): Seq.Set; + } + + } + + export interface Collection extends Iterable { + + /** + * All collections maintain their current `size` as an integer. + */ + size: number; + } + + + /** + * ES6 Iterator. + * + * This is not part of the Immutable library, but a common interface used by + * many types in ES6 JavaScript. + * + * @ignore + */ + export interface Iterator { + next(): { value: T; done: boolean; } + } + +} + +declare module "immutable" { + export = Immutable; +} diff --git a/interactjs/interact-tests.ts b/interactjs/interact-tests.ts index 90f43a9668..c7df68f3a4 100644 --- a/interactjs/interact-tests.ts +++ b/interactjs/interact-tests.ts @@ -1,6 +1,6 @@ /// -import interact = require("interact"); +import interact = require("interact.js"); var button: HTMLElement = document.createElement("BUTTON"); var rectangle: ClientRect = { @@ -11,7 +11,9 @@ var rectangle: ClientRect = { bottom: 100, height: 100 }; -var interactable = interact(button); +let context = document.createElement("a"); +let interactable = interact(".foo", {context: context}); +interactable = interact(button); interactable.draggable(); interactable.draggable(true); diff --git a/interactjs/interact.d.ts b/interactjs/interact.d.ts index 5283e73fe9..2a547450d5 100644 --- a/interactjs/interact.d.ts +++ b/interactjs/interact.d.ts @@ -200,6 +200,7 @@ declare namespace Interact { (element: HTMLElement): Interactable; (element: SVGElement): Interactable; (element: string): Interactable; + (element: string, {context: Element}): Interactable; // returns boolean or {[key: string]: any} autoScroll(): any; autoScroll(options: boolean): InteractStatic; @@ -242,6 +243,6 @@ declare namespace Interact { declare var interact: Interact.InteractStatic; -declare module "interact" { +declare module "interact.js" { export = interact; } diff --git a/intl-tel-input/intl-tel-input-tests.ts b/intl-tel-input/intl-tel-input-tests.ts new file mode 100644 index 0000000000..739fcc854b --- /dev/null +++ b/intl-tel-input/intl-tel-input-tests.ts @@ -0,0 +1,69 @@ +/// +/// + +$('#phone').intlTelInput(); + +$('#phone').intlTelInput({ + customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) { + return 'e.g. ' + selectedCountryPlaceholder; + } +}); + +$('#phone').intlTelInput({ + geoIpLookup: function(callback) { + $.get('http://ipinfo.io', function() {}, 'jsonp').always(function(resp) { + let countryCode = (resp && resp.country) ? resp.country : ''; + callback(countryCode); + }); + } +}); + +$('#phone').intlTelInput('destroy'); + +let extension = $('#phone').intlTelInput('getExtension'); + +let intlNumber = $('#phone').intlTelInput('getNumber'); +let ntlNumber = $('#phone').intlTelInput('getNumber', intlTelInputUtils.numberFormat.NATIONAL); + +let numberType = $('#phone').intlTelInput('getNumberType'); +if (numberType === intlTelInputUtils.numberType.MOBILE) {} + +let countryData = $('#phone').intlTelInput('getSelectedCountryData'); + +let error = $('#phone').intlTelInput('getValidationError'); +if (error === intlTelInputUtils.validationError.TOO_SHORT) {} + +let isValid = $('#phone').intlTelInput('isValidNumber'); + +$('#phone').intlTelInput('setCountry', 'gb'); + +$('#phone').intlTelInput('setNumber', '+447733123456'); + +let countryData3 = $.intlTelInput.getCountryData(); + +$.intlTelInput.loadUtils('build/js/utils.js'); + +$('#phone').intlTelInput({ + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + initialCountry: 'auto', + geoIpLookup: function(callback) { + $.get('http://ipinfo.io', function() {}, 'jsonp').always(function(resp) { + let countryCode = (resp && resp.country) ? resp.country : ''; + callback(countryCode); + }); + }, + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + nationalMode: true, + utilsScript: '../../build/js/utils.js' +}); + +$('#phone').intlTelInput({ + onlyCountries: ['al'], + utilsScript: '../../build/js/utils.js' +}); diff --git a/intl-tel-input/intl-tel-input.d.ts b/intl-tel-input/intl-tel-input.d.ts new file mode 100644 index 0000000000..7779f34bd4 --- /dev/null +++ b/intl-tel-input/intl-tel-input.d.ts @@ -0,0 +1,252 @@ +// Type definitions for intl-tel-input +// Project: https://github.com/jackocnr/intl-tel-input +// Definitions by: Fidan Hakaj +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace IntlTelInput { + + interface Options { + /** + * Whether or not to allow the dropdown. If disabled, there is no dropdown + * arrow, and the selected flag is not clickable. Also we display the + * selected flag on the right instead because it is just a marker of state. + */ + allowDropdown?: boolean; + /** + * If there is just a dial code in the input: remove it on blur or submit, + * and re-add it on focus. This is to prevent just a dial code getting + * submitted with the form. Requires nationalMode to be set to false. + */ + autoHideDialCode?: boolean; + /** + * Set the input's placeholder to an example number for the selected country. + * You can specify the number type using the numberType option. + * If there is already a placeholder attribute set on the input then that + * will take precedence. Requires the utilsScript option. + */ + autoPlaceholder?: boolean; + /** + * Change the placeholder generated by autoPlaceholder. Must return a string. + */ + customPlaceholder?: (selectedCountryPlaceholder: string, selectedCountryData: CountryData) => string; + /** + * Specify the container for the country dropdown (use a jQuery selector + * e.g. "body"). This is useful when the input is within a scrolling element, + * or an element with overflow: hidden. Wherever you put the dropdown it + * will automatically close on the window scroll event to prevent positioning + * issues. If you want it to close when a different element is scrolled + * (such as the input's parent), simply listen for the that scroll event, + * and trigger $(window).scroll() e.g. + */ + dropdownContainer?: string; + /** + * Don't display the countries you specify. + */ + excludeCountries?: Array; + /** + * Format the input value during initialisation. + */ + formatOnInit?: boolean; + /** + * When setting initialCountry to "auto", you must use this option to + * specify a custom function that looks up the user's location. Also note + * that when instantiating the plugin, we now return a deferred object, so + * you can use .done(callback) to know when initialisation requests like + * this have completed. + * Note that the callback must still be called in the event of an error. + */ + geoIpLookup?: (callback: (countryCode: string) => void) => void; + /** + * Set the initial country selection by specifying it's country code. + * You can also set it to "auto", which will lookup the user's country based + * on their IP address (requires the geoIpLookup option). + * Note that the "auto" option will not update the country selection if the + * input already contains a number. If you leave initialCountry blank, + * it will default to the first country in the list. + */ + initialCountry?: string; + /** + * Allow users to enter national numbers (and not have to think about + * international dial codes). Formatting, validation and placeholders still + * work. Then you can use getNumber to extract a full international number. + * This option now defaults to true, and it is recommended that you leave it + * that way as it provides a better experience for the user. + */ + nationalMode?: boolean; + /** + * Specify one of the keys from the global enum intlTelInputUtils.numberType + * e.g. "FIXED_LINE" to tell the plugin you're expecting that type of number. + * Currently this is only used to set the placeholder to the right type of number. + */ + numberType?: string; + /** + * Display only the countries you specify. + */ + onlyCountries?: Array; + /** + * Specify the countries to appear at the top of the list. + */ + preferredCountries?: Array; + /** + * Display the country dial code next to the selected flag so it's not part + * of the typed number. Note that this will disable nationalMode because + * technically we are dealing with international numbers, but with the + * dial code separated. + */ + separateDialCode?: boolean; + /** + * Enable formatting/validation etc. by specifying the path to the included + * utils.js script, which is fetched only when the page has finished loading + * (on window.load) to prevent blocking. When instantiating the plugin, + * we return a deferred object, so you can use .done(callback) to know when + * initialisation requests like this have finished. Note that if you're + * lazy loading the plugin script itself (intlTelInput.js) this will not + * work and you will need to use the loadUtils method instead. + */ + utilsScript?: string; + } + + interface CountryData { + name: string; + iso2: string; + dialCode: string; + } + + interface Static { + /** + * Get all of the plugin's country data. + * Note that any modifications must be done before initialising the plugin. + */ + getCountryData: () => Array; + /** + * Note: this is only needed if you're lazy loading the plugin script itself (intlTelInput.js). + * If not then just use the utilsScript option. Load the utils.js script + * (included in the lib directory) to enable formatting/validation etc. + * @param path path to the utils.js script. + */ + loadUtils: (path: string) => void; + } +} + +declare namespace intlTelInputUtils { + + const enum numberFormat { + E164 = 0, + INTERNATIONAL = 1, + NATIONAL = 2, + RFC3966 = 3 + } + + const enum numberType { + FIXED_LINE = 0, + MOBILE = 1, + FIXED_LINE_OR_MOBILE = 2, + TOLL_FREE = 3, + PREMIUM_RATE = 4, + SHARED_COST = 5, + VOIP = 6, + PERSONAL_NUMBER = 7, + PAGER = 8, + UAN = 9, + VOICEMAIL = 10, + UNKNOWN = -1 + } + + const enum validationError { + IS_POSSIBLE = 0, + INVALID_COUNTRY_CODE = 1, + TOO_SHORT = 2, + TOO_LONG = 3, + NOT_A_NUMBER = 4 + } +} + +interface JQueryStatic { + intlTelInput: IntlTelInput.Static; +} + +interface JQuery { + /** + * Remove the plugin from the input, and unbind any event listeners. + */ + intlTelInput(method: 'destroy'): void; + /** + * Get the extension from the current number. + * Requires the utilsScript option. + * e.g. if the input value was "(702) 555-5555 ext. 1234", this would + * return "1234". + */ + intlTelInput(method: 'getExtension'): string; + /** + * Get the current number in the given format (defaults to E.164 standard). + * The different formats are available in the enum + * intlTelInputUtils.numberFormat - taken from here. + * Requires the utilsScript option. + * Note that even if nationalMode is enabled, this can still return a full + * international number. + */ + intlTelInput(method: 'getNumber'): string; + /** + * Get the type (fixed-line/mobile/toll-free etc) of the current number. + * Requires the utilsScript option. + * Returns an integer, which you can match against the various options in the + * global enum intlTelInputUtils.numberType. + * Note that in the US there's no way to differentiate between fixed-line and + * mobile numbers, so instead it will return FIXED_LINE_OR_MOBILE. + */ + intlTelInput(method: 'getNumberType'): intlTelInputUtils.numberType; + /** + * Get the country data for the currently selected flag. + */ + intlTelInput(method: 'getSelectedCountryData'): IntlTelInput.CountryData; + /** + * Get more information about a validation error. + * Requires the utilsScript option. + * Returns an integer, which you can match against the various options in the + * global enum intlTelInputUtils.validationError + */ + intlTelInput(method: 'getValidationError'): intlTelInputUtils.validationError; + /** + * Validate the current number. Expects an internationally formatted number + * (unless nationalMode is enabled). If validation fails, you can use + * getValidationError to get more information. + * Requires the utilsScript option. + * Also see getNumberType if you want to make sure the user enters a certain + * type of number e.g. a mobile number. + */ + intlTelInput(method: 'isValidNumber'): boolean; + intlTelInput(method: string): void; + /** + * Change the country selection (e.g. when the user is entering their address). + * @param countryCode country code of the country to be set. + */ + intlTelInput(method: 'setCountry', countryCode: string): void; + /** + * Insert a number, and update the selected flag accordingly. + * Note that by default, if nationalMode is enabled it will try to use + * national formatting. + * @param aNumber number to be set. + */ + intlTelInput(method: 'setNumber', aNumber: string): void; + intlTelInput(method: string, value: string): void; + + /** + * Get the current number in the given format (defaults to E.164 standard). + * The different formats are available in the enum + * intlTelInputUtils.numberFormat - taken from here. + * Requires the utilsScript option. + * Note that even if nationalMode is enabled, this can still return a full + * international number. + * @param numberFormat the format in which the number will be returned. + */ + intlTelInput(method: 'getNumber', numberFormat: intlTelInputUtils.numberFormat): string; + intlTelInput(method: string, numberFormat: intlTelInputUtils.numberFormat): string; + + /** + * initialise the plugin with optional options. + * @param options options that can be provided during initialization. + */ + intlTelInput(options?: IntlTelInput.Options): JQueryDeferred; +} diff --git a/ioredis/ioredis.d.ts b/ioredis/ioredis.d.ts index d8cd4b3c70..42a498addc 100644 --- a/ioredis/ioredis.d.ts +++ b/ioredis/ioredis.d.ts @@ -678,6 +678,10 @@ declare module IORedis { * default: false. */ readOnly?: boolean; + /** + * If you are using the hiredis parser, it's highly recommended to enable this option. Create another instance with dropBufferSupport disabled for other commands that you want to return binary instead of string: + */ + dropBufferSupport?: boolean; } interface ScanStreamOption { diff --git a/irc/irc-tests.ts b/irc/irc-tests.ts index edda5e14fd..9e098f923c 100644 --- a/irc/irc-tests.ts +++ b/irc/irc-tests.ts @@ -3,52 +3,82 @@ import irc = require('irc'); -var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', { - debug: true, - channels: ['#blah', '#test'] -}); +function test_bot() { + var bot = new irc.Client('irc.dollyfish.net.nz', 'nodebot', { + debug: true, + channels: ['#blah', '#test'] + }); -bot.addListener('error', ((message: irc.IMessage) => { - console.error('ERROR: %s: %s', message.command, message.args.join(' ')); -})); + bot.connect(function() { + console.log("Connected"); + }); -bot.addListener('message#blah', ((from: string, message: string) => { - console.log('<%s> %s', from, message); -})); + bot.addListener('error', ((message: irc.IMessage) => { + console.error('ERROR: %s: %s', message.command, message.args.join(' ')); + })); -bot.addListener('message', ((from: string, to: string, message: string) => { - console.log('%s => %s: %s', from, to, message); + bot.addListener('message#blah', ((from: string, message: string) => { + console.log('<%s> %s', from, message); + })); - if (to.match(/^[#&]/)) { - // channel message - if (message.match(/hello/i)) { - bot.say(to, 'Hello there ' + from); + bot.addListener('message', ((from: string, to: string, message: string) => { + console.log('%s => %s: %s', from, to, message); + + if (to.match(/^[#&]/)) { + // channel message + if (message.match(/hello/i)) { + bot.say(to, 'Hello there ' + from); + } + if (message.match(/dance/)) { + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000); + setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000); + } } - if (message.match(/dance/)) { - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D\\-<\u0001'); }, 1000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 2000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D/-<\u0001'); }, 3000); - setTimeout(() => { bot.say(to, '\u0001ACTION dances: :D|-<\u0001'); }, 4000); + else { + // private message + console.log('private message'); } - } - else { - // private message - console.log('private message'); - } -})); + })); -bot.addListener('pm', ((nick: string, message: string) => { - console.log('Got private message from %s: %s', nick, message); -})); + bot.addListener('pm', ((nick: string, message: string) => { + console.log('Got private message from %s: %s', nick, message); + })); -bot.addListener('join', ((channel: string, who: string) => { - console.log('%s has joined %s', who, channel); -})); + bot.addListener('join', ((channel: string, who: string) => { + console.log('%s has joined %s', who, channel); + })); -bot.addListener('part', ((channel: string, who: string, reason: string) => { - console.log('%s has left %s: %s', who, channel, reason); -})); + bot.addListener('part', ((channel: string, who: string, reason: string) => { + console.log('%s has left %s: %s', who, channel, reason); + })); -bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { - console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); -})); + bot.addListener('kick', ((channel: string, who: string, by: string, reason: string) => { + console.log('%s was kicked from %s by %s: %s', who, channel, by, reason); + })); +} + +function test_secure() { + var options = true; + + var bot = new irc.Client('chat.us.freenode.net', 'nodebot', { + port: 6697, + debug: true, + secure: options, + channels: ['#botwar'] + }); +} + +function test_connect() { + var bot = new irc.Client('chat.us.freenode.net', 'nodebot', { + port: 6697, + autoConnect: false + }); + + bot.connect(5); + + bot.connect(5, function() {}); + + bot.connect(function() {}); +} diff --git a/irc/irc.d.ts b/irc/irc.d.ts index 00dd3220e1..546ca7c3c0 100644 --- a/irc/irc.d.ts +++ b/irc/irc.d.ts @@ -194,7 +194,7 @@ declare module 'irc' { * @param callback */ public connect( - retryCount?: number, + retryCount?: number | handlers.IRaw, callback?: handlers.IRaw ): void; @@ -228,6 +228,12 @@ declare module 'irc' { */ userName?: string; + /** + * IRC username + * @default '' + */ + password?: string; + /** * IRC "real name" * @default 'nodeJS IRC client' diff --git a/isomorphic-fetch/isomorphic-fetch.d.ts b/isomorphic-fetch/isomorphic-fetch.d.ts index 0edbe24afb..19754db0f1 100644 --- a/isomorphic-fetch/isomorphic-fetch.d.ts +++ b/isomorphic-fetch/isomorphic-fetch.d.ts @@ -4,23 +4,23 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare enum RequestContext { - "audio", "beacon", "cspreport", "download", "embed", "eventsource", - "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", - "image", "imageset", "import", "internal", "location", "manifest", - "object", "ping", "plugin", "prefetch", "script", "serviceworker", + "audio", "beacon", "cspreport", "download", "embed", "eventsource", + "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", + "image", "imageset", "import", "internal", "location", "manifest", + "object", "ping", "plugin", "prefetch", "script", "serviceworker", "sharedworker", "subresource", "style", "track", "video", "worker", "xmlhttprequest", "xslt" } declare enum RequestMode { "same-origin", "no-cors", "cors" } declare enum RequestCredentials { "omit", "same-origin", "include" } -declare enum RequestCache { - "default", "no-store", "reload", "no-cache", "force-cache", +declare enum RequestCache { + "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" } declare enum ResponseType { "basic", "cors", "default", "error", "opaque" } declare type HeaderInit = Headers | Array; -declare type BodyInit = Blob | FormData | string; +declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; declare type RequestInfo = Request | string; interface RequestInit { diff --git a/istanbul-middleware/istanbul-middleware-tests.ts b/istanbul-middleware/istanbul-middleware-tests.ts new file mode 100644 index 0000000000..01afa92082 --- /dev/null +++ b/istanbul-middleware/istanbul-middleware-tests.ts @@ -0,0 +1,2 @@ +/// +import i = require('istanbul-middleware'); diff --git a/istanbul-middleware/istanbul-middleware.d.ts b/istanbul-middleware/istanbul-middleware.d.ts new file mode 100644 index 0000000000..054e32931e --- /dev/null +++ b/istanbul-middleware/istanbul-middleware.d.ts @@ -0,0 +1,33 @@ +// Type definitions for istanbul-middleware +// Project: https://www.npmjs.com/package/istanbul-middleware +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "istanbul-middleware" { + import * as express from "express"; + + type Matcher = (file:string)=> boolean; + type PostLoadHookFn = (file:any)=> {}; + type PostLoadHook = (matcherfn:Matcher,transformer:any,verbose:boolean)=>PostLoadHookFn; + + export function hookLoader(matcherOrRoot:Matcher|string, opts?:{ + postLoadHook?:PostLoadHook, + verbose?:boolean + //and istanbul.Instrumenter(...opts) + }): void; + + export function createHandler(opts?:{ + resetOnGet?:boolean + }): any; + + type ClientMatcher = (req:express.Request)=> boolean; + type PathTransformer = (req:express.Request)=> string; + + export function createClientHandler(root:string,opts?:{ + matcher?:ClientMatcher, + pathTransformer?:PathTransformer, + verbose?:boolean + }): any; +} diff --git a/jasmine-ajax/jasmine-ajax.d.ts b/jasmine-ajax/jasmine-ajax.d.ts index db25ab73e6..143b3b1a5c 100644 --- a/jasmine-ajax/jasmine-ajax.d.ts +++ b/jasmine-ajax/jasmine-ajax.d.ts @@ -15,6 +15,7 @@ interface JasmineAjaxResponse { interface JasmineAjaxRequest extends XMLHttpRequest { url: string; method: string; + params: any; username: string; password: string; requestHeaders: { [key: string]: string }; diff --git a/javascript-obfuscator/javascript-obfuscator-tests.ts b/javascript-obfuscator/javascript-obfuscator-tests.ts new file mode 100644 index 0000000000..1c0753c3bf --- /dev/null +++ b/javascript-obfuscator/javascript-obfuscator-tests.ts @@ -0,0 +1,18 @@ +/// + +import { JavaScriptObfuscator } from 'javascript-obfuscator'; + +let sourceCode1: string = JavaScriptObfuscator.obfuscate('var foo = 1;'); +let sourceCode2: string = JavaScriptObfuscator.obfuscate('var foo = 1;', { + compact: true, + debugProtection: false, + debugProtectionInterval: false, + disableConsoleOutput: true, + encodeUnicodeLiterals: false, + reservedNames: ['^foo$'], + rotateUnicodeArray: true, + selfDefending: true, + unicodeArray: true, + unicodeArrayThreshold: 0.8, + wrapUnicodeArrayCalls: true +}); diff --git a/javascript-obfuscator/javascript-obfuscator.d.ts b/javascript-obfuscator/javascript-obfuscator.d.ts new file mode 100644 index 0000000000..17a91c4925 --- /dev/null +++ b/javascript-obfuscator/javascript-obfuscator.d.ts @@ -0,0 +1,25 @@ +// Type definitions for javascript-obfuscator +// Project: https://github.com/sanex3339/javascript-obfuscator +// Definitions by: sanex3339 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'javascript-obfuscator' { + export interface IOptions { + compact?: boolean; + debugProtection?: boolean; + debugProtectionInterval?: boolean; + disableConsoleOutput?: boolean; + encodeUnicodeLiterals?: boolean; + reservedNames?: string[]; + rotateUnicodeArray?: boolean; + selfDefending?: boolean; + unicodeArray?: boolean; + unicodeArrayThreshold?: number; + wrapUnicodeArrayCalls?: boolean; + [id: string]: any; + } + + export class JavaScriptObfuscator { + public static obfuscate (sourceCode: string, customOptions?: IOptions): string; + } +} diff --git a/joi/joi-6.5.0-tests.ts b/joi/joi-6.5.0-tests.ts new file mode 100644 index 0000000000..a00543fe4e --- /dev/null +++ b/joi/joi-6.5.0-tests.ts @@ -0,0 +1,774 @@ +/// +/// + +import Joi = require('joi'); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var x: any = null; +var value: any = null; +var num: number = 0; +var str: string = ''; +var bool: boolean = false; +var exp: RegExp = null; +var obj: Object = null; +var date: Date = null; +var bin: NodeBuffer = null; +var err: Error = null; +var func: Function = null; + +var anyArr: any[] = []; +var numArr: number[] = []; +var strArr: string[] = []; +var boolArr: boolean[] = []; +var expArr: RegExp[] = []; +var objArr: Object[] = []; +var bufArr: NodeBuffer[] = []; +var errArr: Error[] = []; +var funcArr: Function[] = []; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schema: Joi.Schema = null; + +var anySchema: Joi.AnySchema = null; +var numSchema: Joi.NumberSchema = null; +var strSchema: Joi.StringSchema = null; +var arrSchema: Joi.ArraySchema = null; +var boolSchema: Joi.BooleanSchema = null; +var binSchema: Joi.BinarySchema = null; +var dateSchema: Joi.DateSchema = null; +var funcSchema: Joi.FunctionSchema = null; +var objSchema: Joi.ObjectSchema = null; +var altSchema: Joi.AlternativesSchema = null; + +var schemaArr: Joi.Schema[] = []; + +var ref: Joi.Reference = null; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validOpts: Joi.ValidationOptions = null; + +validOpts = {abortEarly: bool}; +validOpts = {convert: bool}; +validOpts = {allowUnknown: bool}; +validOpts = {skipFunctions: bool}; +validOpts = {stripUnknown: bool}; +validOpts = {language: bool}; +validOpts = {presence: str}; +validOpts = {context: obj}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var renOpts: Joi.RenameOptions = null; + +renOpts = {alias: bool}; +renOpts = {multiple: bool}; +renOpts = {override: bool}; +renOpts = {ignoreUndefined: bool}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var emailOpts: Joi.EmailOptions = null; + +emailOpts = {errorLevel: num}; +emailOpts = {errorLevel: bool}; +emailOpts = {tldWhitelist: strArr}; +emailOpts = {tldWhitelist: obj}; +emailOpts = {minDomainAtoms: num}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var ipOpts: Joi.IpOptions = null; + +ipOpts = {version: str}; +ipOpts = {version: strArr}; +ipOpts = {cidr: str}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var uriOpts: Joi.UriOptions = null; + +uriOpts = {scheme: str}; +uriOpts = {scheme: exp}; +uriOpts = {scheme: strArr}; +uriOpts = {scheme: expArr}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var whenOpts: Joi.WhenOptions = null; + +whenOpts = {is: x}; +whenOpts = {is: schema, then: schema}; +whenOpts = {is: schema, otherwise: schema}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var refOpts: Joi.ReferenceOptions = null; + +refOpts = {separator: str}; +refOpts = {contextPrefix: str}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var validErr: Joi.ValidationError = null; +var validErrItem: Joi.ValidationErrorItem; + +validErrItem= { + message: str, + type: str, + path: str +}; + +validErrItem = { + message: str, + type: str, + path: str, + options: validOpts +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = anySchema; +schema = numSchema; +schema = strSchema; +schema = arrSchema; +schema = boolSchema; +schema = binSchema; +schema = dateSchema; +schema = funcSchema; +schema = objSchema; + +schema = ref; + +anySchema = anySchema; +anySchema = numSchema; +anySchema = strSchema; +anySchema = arrSchema; +anySchema = boolSchema; +anySchema = binSchema; +anySchema = dateSchema; +anySchema = funcSchema; +anySchema = objSchema; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var schemaMap: Joi.SchemaMap = null; + +schemaMap = { + a: numSchema, + b: strSchema +}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +anySchema = Joi.any(); + +namespace common { + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); + + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); + + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); + + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); + + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); + + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +arrSchema = Joi.array(); + +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.min(num); +arrSchema = arrSchema.max(num); +arrSchema = arrSchema.length(num); +arrSchema = arrSchema.unique(); + +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema); +arrSchema = arrSchema.items([numSchema, strSchema]); + + +// - - - - - - - - + +namespace common_copy_paste { + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); + + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); + + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); + + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); + + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); + + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +boolSchema = Joi.bool(); +boolSchema = Joi.boolean(); + +namespace common_copy_paste { + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + + boolSchema = boolSchema.default(x); + + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); + + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); + + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); + + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); + + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +binSchema = Joi.binary(); + +binSchema = binSchema.encoding(str); +binSchema = binSchema.min(num); +binSchema = binSchema.max(num); +binSchema = binSchema.length(num); + +namespace common { + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + + binSchema = binSchema.default(x); + + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); + + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); + + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); + + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); + + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +dateSchema = Joi.date(); + +dateSchema = dateSchema.min(date); +dateSchema = dateSchema.max(date); + +dateSchema = dateSchema.min(str); +dateSchema = dateSchema.max(str); + +dateSchema = dateSchema.min(num); +dateSchema = dateSchema.max(num); + +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + +namespace common { + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + + dateSchema = dateSchema.default(x); + + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); + + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); + + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); + + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); + + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +funcSchema = Joi.func(); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +numSchema = Joi.number(); + +numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); +numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); +numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); + +namespace common { + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + + numSchema = numSchema.default(x); + + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); + + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); + + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); + + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); + + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +objSchema = Joi.object(); +objSchema = Joi.object(schemaMap); + +objSchema = objSchema.keys(); +objSchema = objSchema.keys(schemaMap); + +objSchema = objSchema.min(num); +objSchema = objSchema.max(num); +objSchema = objSchema.length(num); + +objSchema = objSchema.pattern(exp, schema); + +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); +objSchema = objSchema.and(str, str, str); +objSchema = objSchema.and(strArr); + +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); +objSchema = objSchema.or(str, str, str); +objSchema = objSchema.or(strArr); + +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); +objSchema = objSchema.xor(str, str, str); +objSchema = objSchema.xor(strArr); + +objSchema = objSchema.with(str, str); +objSchema = objSchema.with(str, strArr); + +objSchema = objSchema.without(str, str); +objSchema = objSchema.without(str, strArr); + +objSchema = objSchema.rename(str, str); +objSchema = objSchema.rename(str, str, renOpts); + +objSchema = objSchema.assert(str, schema); +objSchema = objSchema.assert(str, schema, str); +objSchema = objSchema.assert(ref, schema); +objSchema = objSchema.assert(ref, schema, str); + +objSchema = objSchema.unknown(); +objSchema = objSchema.unknown(bool); + +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + +namespace common { + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + + objSchema = objSchema.default(x); + + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); + + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); + + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); + + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); + + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +strSchema = Joi.string(); + +strSchema = strSchema.insensitive(); +strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); +strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); +strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); +strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); +strSchema = strSchema.alphanum(); +strSchema = strSchema.token(); +strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); +strSchema = strSchema.guid(); +strSchema = strSchema.hex(); +strSchema = strSchema.hostname(); +strSchema = strSchema.isoDate(); +strSchema = strSchema.lowercase(); +strSchema = strSchema.uppercase(); +strSchema = strSchema.trim(); + +namespace common { + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + + strSchema = strSchema.default(x); + + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); + + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); + + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); + + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); + + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); +} + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.alternatives(schemaArr); +schema = Joi.alternatives(schema, anySchema, boolSchema); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +Joi.validate(value, obj); +Joi.validate(value, schema); +Joi.validate(value, schema, validOpts); +Joi.validate(value, schema, validOpts, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +Joi.validate(value, schema, (err, value) => { + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; +}); +// variant +Joi.validate(num, schema, validOpts, (err, value) => { + num = value; +}); + +// plain opts +Joi.validate(value, {}); + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +schema = Joi.compile(obj); + +Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); + +ref = Joi.ref(str, refOpts); +ref = Joi.ref(str); diff --git a/joi/joi-6.5.0.d.ts b/joi/joi-6.5.0.d.ts new file mode 100644 index 0000000000..d9ee7c20d1 --- /dev/null +++ b/joi/joi-6.5.0.d.ts @@ -0,0 +1,778 @@ +// Type definitions for joi v6.5.0 +// Project: https://github.com/spumko/joi +// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TODO express type of Schema in a type-parameter (.default, .valid, .example etc) + +declare module 'joi' { + + export interface ValidationOptions { + /** + * when true, stops validation on the first error, otherwise returns all the errors found. Defaults to true. + */ + abortEarly?: boolean; + /** + * when true, attempts to cast values to the required types (e.g. a string to a number). Defaults to true. + */ + convert?: boolean; + /** + * when true, allows object to contain unknown keys which are ignored. Defaults to false. + */ + allowUnknown?: boolean; + /** + * when true, ignores unknown keys with a function value. Defaults to false. + */ + skipFunctions?: boolean; + /** + * when true, unknown keys are deleted (only when value is an object). Defaults to false. + */ + stripUnknown?: boolean; + /** + * overrides individual error messages. Defaults to no override ({}). + */ + language?: Object; + /** + * sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + */ + presence?: string; + /** + * provides an external data set to be used in references + */ + context?: Object; + } + + export interface RenameOptions { + /** + * if true, does not delete the old key name, keeping both the new and old keys in place. Defaults to false. + */ + alias?: boolean; + /** + * if true, allows renaming multiple keys to the same destination where the last rename wins. Defaults to false. + */ + multiple?: boolean; + /** + * if true, allows renaming a key over an existing key. Defaults to false. + */ + override?: boolean; + /** + * if true, skip renaming of a key if it's undefined. Defaults to false. + */ + ignoreUndefined?: boolean; + } + + export interface EmailOptions { + /** + * Numerical threshold at which an email address is considered invalid + */ + errorLevel?: number | boolean; + /** + * Specifies a list of acceptable TLDs. + */ + tldWhitelist?: string[] | Object; + /** + * Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + */ + minDomainAtoms?: number; + } + + export interface IpOptions { + /** + * One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + */ + version ?: string | string[]; + /** + * Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + */ + cidr?: string; + } + + export interface UriOptions { + /** + * Specifies one or more acceptable Schemes, should only include the scheme name. + * Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + */ + scheme ?: string | RegExp | Array; + } + + export interface WhenOptions { + /** + * the required condition joi type. + */ + is: T; + /** + * the alternative schema type if the condition is true. Required if otherwise is missing. + */ + then?: Schema; + /** + * the alternative schema type if the condition is false. Required if then is missing + */ + otherwise?: Schema; + } + + export interface ReferenceOptions { + separator?: string; + contextPrefix?: string; + } + + export interface IPOptions { + version?: Array; + cidr?: string + } + + export interface ValidationError extends Error { + message: string; + details: ValidationErrorItem[]; + simple(): string; + annotated(): string; + } + + export interface ValidationErrorItem { + message: string; + type: string; + path: string; + options?: ValidationOptions; + } + + export interface ValidationResult { + error: ValidationError; + value: T; + } + + export interface SchemaMap { + [key: string]: Schema; + } + + export interface Schema extends AnySchema { + + } + + export interface Reference extends Schema { + + } + + export interface AnySchema> { + /** + * Whitelists a value + */ + allow(value: any, ...values: any[]): T; + allow(values: any[]): T; + + /** + * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. + */ + valid(value: any, ...values: any[]): T; + valid(values: any[]): T; + only(value: any, ...values : any[]): T; + only(values: any[]): T; + equal(value: any, ...values : any[]): T; + equal(values: any[]): T; + + /** + * Blacklists a value + */ + invalid(value: any, ...values: any[]): T; + invalid(values: any[]): T; + disallow(value: any, ...values : any[]): T; + disallow(values: any[]): T; + not(value: any, ...values : any[]): T; + not(values: any[]): T; + + /** + * Marks a key as required which will not allow undefined as value. All keys are optional by default. + */ + required(): T; + + /** + * Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. + */ + optional(): T; + + /** + * Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. + */ + forbidden(): T; + + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): T; + + /** + * Annotates the key + */ + description(desc: string): T; + + /** + * Annotates the key + */ + notes(notes: string): T; + notes(notes: string[]): T; + + /** + * Annotates the key + */ + tags(notes: string): T; + tags(notes: string[]): T; + + /** + * Attaches metadata to the key. + */ + meta(meta: Object): T; + + /** + * Annotates the key with an example value, must be valid. + */ + example(value: any): T; + + /** + * Annotates the key with an unit name. + */ + unit(name: string): T; + + /** + * Overrides the global validate() options for the current key and any sub-key. + */ + options(options: ValidationOptions): T; + + /** + * Sets the options.convert options to false which prevent type casting for the current key and any child keys. + */ + strict(isStrict?: boolean): T; + + /** + * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. + */ + default(value: any, description?: string): T; + default(): T; + + /** + * Returns a new type that is the result of adding the rules of one type to another. + */ + concat(schema: T): T; + + /** + * Converts the type into an alternatives type where the conditions are merged into the type definition where: + */ + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): T; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): T; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: any) : T; + } + + export interface BooleanSchema extends AnySchema { + + } + + export interface NumberSchema extends AnySchema { + /** + * Specifies the minimum value. + * It can also be a reference to another field. + */ + min(limit: number): NumberSchema; + min(limit: Reference): NumberSchema; + + /** + * Specifies the maximum value. + * It can also be a reference to another field. + */ + max(limit: number): NumberSchema; + max(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): NumberSchema; + greater(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): NumberSchema; + less(limit: Reference): NumberSchema; + + /** + * Requires the number to be an integer (no floating point). + */ + integer(): NumberSchema; + + /** + * Specifies the maximum number of decimal places where: + * limit - the maximum number of decimal places allowed. + */ + precision(limit: number): NumberSchema; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): NumberSchema; + + /** + * Requires the number to be positive. + */ + positive(): NumberSchema; + + /** + * Requires the number to be negative. + */ + negative(): NumberSchema; + } + + export interface StringSchema extends AnySchema { + /** + * Allows the value to match any whitelist of blacklist item in a case insensitive comparison. + */ + insensitive(): StringSchema; + + /** + * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + min(limit: number, encoding?: string): StringSchema; + min(limit: Reference, encoding?: string): StringSchema; + + /** + * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + max(limit: number, encoding?: string): StringSchema; + max(limit: Reference, encoding?: string): StringSchema; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): StringSchema; + + /** + * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. + */ + length(limit: number, encoding?: string): StringSchema; + length(limit: Reference, encoding?: string): StringSchema; + + /** + * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. + */ + regex(pattern: RegExp, name?: string): StringSchema; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): StringSchema; + replace(pattern: string, replacement: string): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, and 0-9. + */ + alphanum(): StringSchema; + + /** + * Requires the string value to only contain a-z, A-Z, 0-9, and underscore _. + */ + token(): StringSchema; + + /** + * Requires the string value to be a valid email address. + */ + email(options?: EmailOptions): StringSchema; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): StringSchema; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): StringSchema; + + /** + * Requires the string value to be a valid GUID. + */ + guid(): StringSchema; + + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(): StringSchema; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): StringSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + isoDate(): StringSchema; + + /** + * Requires the string value to be all lowercase. If the validation convert option is on (enabled by default), the string will be forced to lowercase. + */ + lowercase(): StringSchema; + + /** + * Requires the string value to be all uppercase. If the validation convert option is on (enabled by default), the string will be forced to uppercase. + */ + uppercase(): StringSchema; + + /** + * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. + */ + trim(): StringSchema; + } + + export interface ArraySchema extends AnySchema { + /** + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. + */ + sparse(enabled?: any): ArraySchema; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): ArraySchema; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(type: Schema, ...types: Schema[]): ArraySchema; + items(types: Schema[]): ArraySchema; + + /** + * Specifies the minimum number of items in the array. + */ + min(limit: number): ArraySchema; + + /** + * Specifies the maximum number of items in the array. + */ + max(limit: number): ArraySchema; + + /** + * Specifies the exact number of items in the array. + */ + length(limit: number): ArraySchema; + + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(): ArraySchema; + } + + export interface ObjectSchema extends AnySchema { + /** + * Sets the allowed object keys. + */ + keys(schema?: SchemaMap): ObjectSchema; + + /** + * Specifies the minimum number of keys in the object. + */ + min(limit: number): ObjectSchema; + + /** + * Specifies the maximum number of keys in the object. + */ + max(limit: number): ObjectSchema; + + /** + * Specifies the exact number of keys in the object. + */ + length(limit: number): ObjectSchema; + + /** + * Specify validation rules for unknown keys matching a pattern. + */ + pattern(regex: RegExp, schema: Schema): ObjectSchema; + + /** + * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. + */ + and(peer1: string, ...peers: string[]): ObjectSchema; + and(peers: string[]): ObjectSchema; + + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(peer1: string, ...peers: string[]): ObjectSchema; + nand(peers: string[]): ObjectSchema; + + /** + * Defines a relationship between keys where one of the peers is required (and more than one is allowed). + */ + or(peer1: string, ...peers: string[]): ObjectSchema; + or(peers: string[]): ObjectSchema; + + /** + * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: + */ + xor(peer1: string, ...peers: string[]): ObjectSchema; + xor(peers: string[]): ObjectSchema; + + /** + * Requires the presence of other keys whenever the specified key is present. + */ + with(key: string, peers: string): ObjectSchema; + with(key: string, peers: string[]): ObjectSchema; + + /** + * Forbids the presence of other keys whenever the specified is present. + */ + without(key: string, peers: string): ObjectSchema; + without(key: string, peers: string[]): ObjectSchema; + + /** + * Renames a key to another name (deletes the renamed key). + */ + rename(from: string, to: string, options?: RenameOptions): ObjectSchema; + + /** + * Verifies an assertion where. + */ + assert(ref: string, schema: Schema, message?: string): ObjectSchema; + assert(ref: Reference, schema: Schema, message?: string): ObjectSchema; + + /** + * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). + */ + unknown(allow?: boolean): ObjectSchema; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): ObjectSchema; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string): ObjectSchema; + requiredKeys(children: string[]): ObjectSchema; + requiredKeys(child:string, ...children: string[]): ObjectSchema; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string): ObjectSchema; + optionalKeys(children: string[]): ObjectSchema; + optionalKeys(child:string, ...children: string[]): ObjectSchema; + } + + export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): BinarySchema; + + /** + * Specifies the minimum length of the buffer. + */ + min(limit: number): BinarySchema; + + /** + * Specifies the maximum length of the buffer. + */ + max(limit: number): BinarySchema; + + /** + * Specifies the exact length of the buffer: + */ + length(limit: number): BinarySchema; + } + + export interface DateSchema extends AnySchema { + + /** + * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + min(date: Date): DateSchema; + min(date: number): DateSchema; + min(date: string): DateSchema; + min(date: Reference): DateSchema; + + /** + * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. + */ + max(date: Date): DateSchema; + max(date: number): DateSchema; + max(date: string): DateSchema; + max(date: Reference): DateSchema; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): DateSchema; + format(format: string[]): DateSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): DateSchema; + } + + export interface FunctionSchema extends AnySchema { + + } + + export interface AlternativesSchema extends AnySchema { + try(schemas: Schema[]): AlternativesSchema; + when(ref: string, options: WhenOptions): AlternativesSchema; + when(ref: Reference, options: WhenOptions): AlternativesSchema; + } + + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + + /** + * Generates a schema object that matches any data type. + */ + export function any(): Schema; + + /** + * Generates a schema object that matches an array data type. + */ + export function array(): ArraySchema; + + /** + * Generates a schema object that matches a boolean data type (as well as the strings 'true', 'false', 'yes', and 'no'). Can also be called via bool(). + */ + export function bool(): BooleanSchema; + + export function boolean(): BooleanSchema; + + /** + * Generates a schema object that matches a Buffer data type (as well as the strings which will be converted to Buffers). + */ + export function binary(): BinarySchema; + + /** + * Generates a schema object that matches a date type (as well as a JavaScript date string or number of milliseconds). + */ + export function date(): DateSchema; + + /** + * Generates a schema object that matches a function type. + */ + export function func(): FunctionSchema; + + /** + * Generates a schema object that matches a number data type (as well as strings that can be converted to numbers). + */ + export function number(): NumberSchema; + + /** + * Generates a schema object that matches an object data type (as well as JSON strings that parsed into objects). + */ + export function object(schema?: SchemaMap): ObjectSchema; + + /** + * Generates a schema object that matches a string data type. Note that empty strings are not allowed by default and must be enabled with allow(''). + */ + export function string(): StringSchema; + + /** + * Generates a type that will match one of the provided alternative schemas + */ + export function alternatives(types: Schema[]): Schema; + export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): Schema; + + /** + * Validates a value using the given schema and options. + */ + export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult; + + /** + * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). + */ + export function compile(schema: Object): Schema; + + /** + * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ + export function assert(value: any, schema: Schema, message?: string | Error): void; + + /** + * Generates a reference to the value of the named key. + */ + export function ref(key: string, options?: ReferenceOptions): Reference; +} diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index a00543fe4e..e5bda7874c 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -231,16 +231,18 @@ arrSchema = arrSchema.sparse(); arrSchema = arrSchema.sparse(bool); arrSchema = arrSchema.single(); arrSchema = arrSchema.single(bool); +arrSchema = arrSchema.ordered(anySchema); +arrSchema = arrSchema.ordered(anySchema, numSchema, strSchema, arrSchema, boolSchema, binSchema, dateSchema, funcSchema, objSchema); arrSchema = arrSchema.min(num); arrSchema = arrSchema.max(num); arrSchema = arrSchema.length(num); arrSchema = arrSchema.unique(); + arrSchema = arrSchema.items(numSchema); arrSchema = arrSchema.items(numSchema, strSchema); arrSchema = arrSchema.items([numSchema, strSchema]); - // - - - - - - - - namespace common_copy_paste { @@ -420,6 +422,10 @@ dateSchema = dateSchema.format(strArr); dateSchema = dateSchema.iso(); +dateSchema = dateSchema.timestamp(); +dateSchema = dateSchema.timestamp('javascript'); +dateSchema = dateSchema.timestamp('unix'); + namespace common { dateSchema = dateSchema.allow(x); dateSchema = dateSchema.allow(x, x); @@ -471,6 +477,11 @@ namespace common { funcSchema = Joi.func(); +funcSchema = funcSchema.arity(num); +funcSchema = funcSchema.minArity(num); +funcSchema = funcSchema.maxArity(num); +funcSchema = funcSchema.ref(); + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- numSchema = Joi.number(); @@ -770,5 +781,15 @@ Joi.assert(obj, schema); Joi.assert(obj, schema, str); Joi.assert(obj, schema, err); +Joi.attempt(obj, schema); +Joi.attempt(obj, schema, str); +Joi.attempt(obj, schema, err); + ref = Joi.ref(str, refOpts); ref = Joi.ref(str); + +Joi.isRef(ref); + +schema = Joi.reach(schema, ''); + +const Joi2 = Joi.extend({ name: '', base: schema }); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index d9ee7c20d1..72a1af9425 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -1,6 +1,6 @@ -// Type definitions for joi v6.5.0 -// Project: https://github.com/spumko/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers +// Type definitions for joi v9.0.0 +// Project: https://github.com/hapijs/joi +// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers , Gael Magnan de Bornier // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TODO express type of Schema in a type-parameter (.default, .valid, .example etc) @@ -487,6 +487,13 @@ declare module 'joi' { items(type: Schema, ...types: Schema[]): ArraySchema; items(types: Schema[]): ArraySchema; + /** + * Lists the types in sequence order for the array values where: + * @param type - a joi schema object to validate against each array item in sequence order. type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item with the same index position in the array. Errors will contain the number of items that didn't match. Any unmatched item having a label will be mentioned explicitly. + */ + ordered(type: Schema, ...types: Schema[]): ArraySchema; + /** * Specifies the minimum number of items in the array. */ @@ -683,10 +690,41 @@ declare module 'joi' { * Requires the string value to be in valid ISO 8601 date format. */ iso(): DateSchema; + + + /** + * Requires the value to be a timestamp interval from Unix Time. + * @param type - the type of timestamp (allowed values are unix or javascript [default]) + */ + timestamp(type?: 'javascript' | 'unix'): DateSchema; } export interface FunctionSchema extends AnySchema { + /** + * Specifies the arity of the function where: + * @param n - the arity expected. + */ + arity(n: number): FunctionSchema; + + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + minArity(n: number): FunctionSchema; + + + /** + * Specifies the minimal arity of the function where: + * @param n - the minimal arity expected. + */ + maxArity(n: number): FunctionSchema; + + /** + * Requires the function to be a Joi reference. + */ + ref(): FunctionSchema; } export interface AlternativesSchema extends AnySchema { @@ -695,6 +733,33 @@ declare module 'joi' { when(ref: Reference, options: WhenOptions): AlternativesSchema; } + export interface Terms { + value: any; + state: { + key: string, + path: string, + parent: any + }; + options: ValidationOptions; + } + + export interface Rules { + name: string; + params?: ObjectSchema | { [key: string]: Schema }; + setup?: Function; + validate?: Function; + description: string | Function; + } + + export interface Extension { + name: string; + base?: Schema; + pre?: Function; + language?: {}; + describe?: Function; + rules?: Rules[]; + } + // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- /** @@ -771,8 +836,38 @@ declare module 'joi' { */ export function assert(value: any, schema: Schema, message?: string | Error): void; + + /** + * Validates a value against a schema, returns valid object, and throws if validation fails where: + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. + */ + export function attempt(value: T, schema: Schema, message?: string | Error): T; + + /** * Generates a reference to the value of the named key. */ export function ref(key: string, options?: ReferenceOptions): Reference; + + + /** + * Checks whether or not the provided argument is a reference. It's especially useful if you want to post-process error messages. + */ + export function isRef(ref: any): boolean; + + + /** + * Get a sub-schema of an existing schema based on a path. Path separator is a dot (.). + */ + export function reach(schema: Schema, path: string): Schema; + + + /** + * Creates a new Joi instance customized with the extension(s) you provide included. + */ + export function extend(extention: Extension): any; + } diff --git a/jquery-steps/jquery-steps-tests.ts b/jquery-steps/jquery-steps-tests.ts new file mode 100644 index 0000000000..e0125a3c0f --- /dev/null +++ b/jquery-steps/jquery-steps-tests.ts @@ -0,0 +1,101 @@ +/// +/// + +var labels: JQuerySteps.LabelSettings = { + cancel: 'Cancel', + current: 'Current:', + pagination: 'Paging', + finish: 'Done', + next: 'Next >', + previous: '< Previous', + loading: 'Loading...' +} + +var onStepChangingFunc: JQuerySteps.FunctionOnStepChanging = (event, currentIndex, newIndex): boolean => true; + +var onStepChangedFunc: JQuerySteps.FunctionOnStepChanged = (event, currentIndex, priorIndex) => {}; + +var onCancelledFunc: JQuerySteps.FunctionOnCancelled = (event) => {}; + +var onFinishingFunc: JQuerySteps.FunctionOnFinishing= (event, currentIndex): boolean => true; + +var onFinishedFunc: JQuerySteps.FunctionOnFinished = (event, currentIndex) => {}; + +var onInitFunc: JQuerySteps.FunctionOnInit = (event, currentIndex) => {}; + +var onContentLoadedFunc: JQuerySteps.FunctionOnContentLoaded = (event, currentIndex) => {}; + +var settings: JQuerySteps.Settings = { + headerTag: 'h3', + bodyTag: 'section', + contentContainerTag: 'div', + actionContainerTag: 'div', + stepsContainerTag: 'div', + cssClass: 'wizard', + stepsOrientation: 'vertical', + titleTemplate: '#title#', + loadingTemplate: ' #text#', + autoFocus: true, + enableAllSteps: true, + enableKeyNavigation: false, + enablePagination: false, + suppressPaginationOnFocus: false, + enableContentCache: false, + enableCancelButton: true, + enableFinishButton: false, + showFinishButtonAlways: true, + forceMoveForward: true, + saveState: true, + startIndex: 1, + transitionEffect: 'slideLeft', + transitionEffectSpeed: 400, + labels: labels, + onCanceled: onCancelledFunc, + onContentLoaded: onContentLoadedFunc, + onFinished: onFinishedFunc, + onFinishing: onFinishingFunc, + onInit: onInitFunc, + onStepChanged: onStepChangedFunc, + onStepChanging: onStepChangingFunc +} + +var wizard = $('.wizard').JQuerySteps(settings); + +var newStep1: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 1' +} + +var test1 = wizard.add(newStep1); + +var newStep2: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 2', + contentMode: 'async', + contentUrl: 'data.xml' +} + +var test2 = wizard.insert(0, newStep2); + +var test3 = wizard.remove(1); + +var test4 = wizard.getCurrentStep(); + +var test5 = wizard.getCurrentIndex(); + +var test6 = wizard.getStep(0); + +var newStep3: JQuerySteps.Step = { + content: '
Content
', + title: 'Step 1' +} + +var test7 = wizard.insert(0, newStep3); + +var test8 = wizard.next(); + +var test9 = wizard.previous(); + +wizard.finish(); + +wizard.destroy(); diff --git a/jquery-steps/jquery-steps.d.ts b/jquery-steps/jquery-steps.d.ts new file mode 100644 index 0000000000..4b250e6708 --- /dev/null +++ b/jquery-steps/jquery-steps.d.ts @@ -0,0 +1,357 @@ +// Type definitions for jQuery Steps v1.1.0 +// Project: http://www.jquery-steps.com/ +// Definitions by: Joseph Blank +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface JQuery { + JQuerySteps(param?: JQuerySteps.Settings): JQuerySteps.JQuerySteps; +} + +declare module JQuerySteps { + + //#region "JQuerySteps" + + export interface JQuerySteps { + /** + * Adds a new step. (chainable) + */ + add(step: Step): JQuerySteps; + + /** + * Inserts a new step to a specific position. (chainable) + */ + insert(index: number, step: Step): JQuerySteps; + + /** + * Removes a specific step by an given index. + */ + remove(index: number): boolean; + + /** + * Gets the current step object. + */ + getCurrentStep(): Step; + + /** + * Gets the current step index. + */ + getCurrentIndex(): number; + + /** + * Gets a specific step object by index. + */ + getStep(index: number): Step; + + /** + * Routes to the previous step. + */ + next(): boolean; + + /** + * Routes to the next step. + */ + previous(): boolean; + + /** + * Triggers the onFinishing and onFinished event. + */ + finish(): void; + + /** + * Removes the control functionality completely and transforms the current state to the initial HTML structure. + */ + destroy(): void; + + /** + * Skips a certain amount of steps. Not yet implemented! + */ + skip(count: number): boolean; + } + + //#endregion "JQuerySteps" + + //#region "Settings" + export interface Settings { + //#region "Appearance" + + /** + * The header tag is used to find the step button text within the declared wizard area. Default value is h1. + */ + headerTag?: string; + + /** + * The body tag is used to find the step content within the declared wizard area. Default value is div. + */ + bodyTag?: string; + + /** + * The content container tag which will be used to wrap all step contents. Default value is div. + */ + contentContainerTag?: string; + + /** + * The action container tag which will be used to wrap the pagination navigation. Default value is div. + */ + actionContainerTag?: string; + + /** + * The steps container tag which will be used to wrap the steps navigation. Default value is div. + */ + stepsContainerTag?: string; + + /** + * The css class which will be added to the outer component wrapper. Default value is wizard. + */ + cssClass?: string; + + /** + * Determines whether the steps are vertically or horizontally oriented. Default value is horizontal or 0. + * This can be horizontal (0) or vertical (1). + */ + stepsOrientation?: string|number; + + //#endregion "Appearance" + + //#region "Templates" + + /** + * The title template which will be used to create a step button. Default value is span class="number">#index#. #title#. + */ + titleTemplate?: string; + + /** + * The loading template which will be used to create the loading animation. Default value is #text#. + */ + loadingTemplate?: string; + + //#endregion "Templates" + + //#region "Behavior" + + /** + * Sets the focus to the first wizard instance in order to enable the key navigation from the begining if true. Default value is false. + */ + autoFocus?: boolean; + + /** + * Enables all steps from the begining if true (all steps are clickable). Default value is false. + */ + enableAllSteps?: boolean; + + /** + * Enables keyboard navigation if true (arrow left and arrow right). Default value is true. + */ + enableKeyNavigation?: boolean; + + /** + * Enables pagination (next, previous and finish button) if true. Default value is true. + */ + enablePagination?: boolean; + + /** + * Suppresses pagination if a form field is focused. Default value is true. + */ + suppressPaginationOnFocus?: boolean; + + /** + * Enables cache for async loaded or iframe embedded content. Default value is true. + */ + enableContentCache?: boolean; + + /** + * Shows the cancel button if enabled. Default value is false. + */ + enableCancelButton?: boolean; + + /** + * Shows the finish button if enabled. Default value is true. + */ + enableFinishButton?: boolean; + + /** + * Shows the finish button always (on each step; right beside the next button) if true. Otherwise the next button will be replaced by the finish button if the last step becomes active. Default value is false. + */ + showFinishButtonAlways?: boolean; + + /** + * Prevents jumping to a previous step. Default value is false. + */ + forceMoveForward?: boolean; + + /** + * Saves the current state (step position) to a cookie. By coming next time the last active step becomes activated. Default value is false. + */ + saveState?: boolean; + + /** + * The position to start on (zero-based). Default value is 0. + */ + startIndex?: number; + + //#endregion "Behavior" + + //#region "Transition Effects" + + /** + * The animation effect which will be used for step transitions. Default value is none or 0. + * This can be none (0), fade (1), slide (2) or slideLeft (3). + */ + transitionEffect?: string|number; + + /** + * Animation speed for step transitions (in milliseconds). Default value is 200. + */ + transitionEffectSpeed?: number; + + //#endregion "Transition Effects" + + //#region "Events" + + /** + * Fires before the step changes and can be used to prevent step changing by returning false. + */ + onStepChanging?: FunctionOnStepChanging; + + /** + * Fires after the step has changed. + */ + onStepChanged?: FunctionOnStepChanged; + + /** + * Fires after cancellation. + */ + onCanceled?: FunctionOnCancelled; + + /** + * Fires before finishing and can be used to prevent completion by returning false. Very useful for form validation. + */ + onFinishing?: FunctionOnFinishing; + + /** + * Fires after completion. + */ + onFinished?: FunctionOnFinished; + + /** + * Fires when the wizard is initialized. + */ + onInit?: FunctionOnInit; + + /** + * Fires after async content is loaded. + */ + onContentLoaded?: FunctionOnContentLoaded; + + //#endregion "Events" + + //#region "Labels" + + labels?: LabelSettings; + + //#endregion "Labels" + } + //#endregion "Settings" + + //#region "Label Settings" + + interface LabelSettings { + + /** + * Label for the cancel button. Default value is Cancel. + */ + cancel?: string; + + /** + * This label is important for accessability reasons. Indicates which step is activated. Default value is current step:. + */ + current?: string; + + /** + * This label is important for accessability reasons and describes the kind of navigation. Default value is Pagination. + */ + pagination?: string; + + /** + * Label for the finish button. Default value is Finish. + */ + finish?: string; + + /** + * Label for the next button. Default value is Next. + */ + next?: string; + + /** + * Label for the previous button. Default value is Previous. + */ + previous?: string; + + /** + * Label for the loading animation. Default value is Loading ... . + */ + loading?: string; + + } + + //#endregion "Label Settings" + + //#region "Callback Functions" + + interface FunctionOnStepChanging { + (event: string, currentIndex: number, newIndex: number): boolean; + } + + interface FunctionOnStepChanged { + (event: string, currentIndex: number, priorIndex: number): void; + } + + interface FunctionOnCancelled { + (event: string): void; + } + + interface FunctionOnFinishing { + (event: string, currentIndex: number): boolean; + } + + interface FunctionOnFinished { + (event: string, currentIndex: number): void; + } + + interface FunctionOnInit { + (event: string, currentIndex: number): void; + } + + interface FunctionOnContentLoaded { + (event: string, currentIndex: number): void; + } + + //#endregion "Callback Functions" + + //#region "Step Object" + + interface Step { + + /** + * The step title (HTML). + */ + title?: string; + + /** + * The step content (HTML). + */ + content?: string; + + /** + * Indicates how the content will be loaded. + * This can be html (0), iframe (1), or async (2). + */ + contentMode?: string|number; + + /** + * The URI that refers to the content. + */ + contentUrl?: string; + } + + //#endregion "Step Object" +} diff --git a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts index fcc3bac9da..9c13b5a28f 100644 --- a/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts +++ b/jquery-validation-unobtrusive/jquery-validation-unobtrusive.d.ts @@ -1,5 +1,5 @@ // Type definitions for Microsoft jQuery Unobtrusive Validation v3.2.3 -// Project: http://aspnetwebstack.codeplex.com/ +// Project: https://github.com/aspnet/jquery-validation-unobtrusive // Definitions by: Matt Brooks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/jquery.pnotify/jquery.pnotify.d.ts b/jquery.pnotify/jquery.pnotify.d.ts index edb7e2468c..8daee5da1e 100644 --- a/jquery.pnotify/jquery.pnotify.d.ts +++ b/jquery.pnotify/jquery.pnotify.d.ts @@ -1,10 +1,15 @@ -// Type definitions for jquery.pnotify 2.x +// Type definitions for jquery.pnotify 3.x // Project: https://github.com/sciactive/pnotify // Definitions by: David Sichau // 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"; + interface PNotifyStack { dir1?: string; dir2?: string; @@ -13,7 +18,8 @@ interface PNotifyStack { spacing2?: number; firstpos1?: number; firstpos2?: number; - context?: JQuery + context?: JQuery; + modal?: boolean; } interface PNotifyLabel { @@ -24,11 +30,98 @@ interface PNotifyLabel { stick?: string; } + +interface PNotifyconfirmButton { + text?: string; + addClass?: string; + /** + * Whether to trigger this button when the user hits enter in a single line prompt. + */ + promptTrigger?: boolean; + click: (notice: PNotify, value: any) => void +} + +interface PNotifyconfirm { + /** + * Make a confirmation box. + */ + confirm?: boolean; + + /** + * Make a prompt. + */ + prompt?: boolean; + /** + * Classes to add to the input element of the prompt. + */ + prompt_class?: string + + /** + * The default value of the prompt. + */ + prompt_default?: string + + /** + * Whether the prompt should accept multiple lines of text. + */ + prompt_multi_line?: boolean; + + /** + * Where to align the buttons. (right, center, left, justify) + */ + align?: string; + + /** + * The buttons to display, and their callbacks. + */ + buttons?: PNotifyconfirmButton[]; + +} + +interface PNotifyButtons { + /** + * Provide a button for the user to manually close the notice. + */ + closer?: boolean; + /** + * Only show the closer button on hover. + */ + closer_hover?: boolean; + /** + * Provide a button for the user to manually stick the notice. + */ + sticker?: boolean; + /** + * Only show the sticker button on hover. + */ + sticker_hover?: boolean; + /** + * Show the buttons even when the nonblock module is in use. + */ + show_on_nonblock?: boolean; + /** + * The various displayed text, helps facilitating internationalization. + */ + labels?: { + close?: string; + stick?: string; + unstick?: string; + }; + /** + * The classes to use for button icons. Leave them null to use the classes from the styling you're using. + */ + classes?: { + closer?: string; + pin_up?: string; + pin_down?: string; + }; +} + interface PNotifyOptions { /** * The notice's title. Either boolean false or string */ - title?: any; + title?: string | boolean; /** * Whether to escape the content of the title. (Not allow HTML.) */ @@ -36,13 +129,13 @@ interface PNotifyOptions { /** * The notice's text. Either boolean false or string */ - text?: any; + text?: string | boolean; /** * Whether to escape the content of the text. (Not allow HTML.) */ text_escape?: boolean; /** - * What styling classes to use. (Can be either jqueryui or bootstrap.) + * What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", or "fontawesome".) */ styling?: string; /** @@ -58,7 +151,7 @@ interface PNotifyOptions { /** * Create a non-blocking notice. It lets the user click elements underneath it. */ - nonblock: boolean; + nonblock?: boolean; /** * The opacity of the notice (if it's non-blocking) when the mouse is over it. @@ -136,7 +229,7 @@ interface PNotifyOptions { } /** - * After a delay, remove the notice. + * After a delay, remove the notice, set to false for sticky note. */ hide?: boolean; /** @@ -166,17 +259,38 @@ interface PNotifyOptions { } interface PNotify { - elem: JQuery; - - update(options?: PNotifyOptions): void; + + /** + * The state can be "initializing", "opening", "open", "closing", and "closed" + */ + state?: string; + + /** + * This function is for updating the notice. + */ + update(options?: PNotifyOptions): PNotify; + + /** + * Remove the notice. + */ remove(): void; + + /** + * Display the notice. + */ + open(): void; + + /** + * Get the DOM element. + */ + get(): JQuery; + } interface PNotifyConstructor { new (options?: PNotifyOptions): PNotify; - + removeAll(): void; } declare var PNotify: PNotifyConstructor; - diff --git a/jquery.slimScroll/jquery.SlimScroll-tests.ts b/jquery.slimScroll/jquery.SlimScroll-tests.ts index deb4f2406d..046eda840f 100644 --- a/jquery.slimScroll/jquery.SlimScroll-tests.ts +++ b/jquery.slimScroll/jquery.SlimScroll-tests.ts @@ -41,6 +41,21 @@ $('#slimtest3').slimScroll({ alwaysVisible: true }); +$('#slimtest3').slimScroll({ + color: '#00f', + size: '10px', + height: '180px', + alwaysVisible: true, + destroy: true +}); + $("div").slimScroll().bind('slimscroll', function(e){ console.log("Reached " + e); -}); \ No newline at end of file +}); + +var options : IJQuerySlimScrollOptions = { + destroy: true, + position: 'left' +}; + +$('#slimtest3').slimScroll(options); diff --git a/jquery.slimScroll/jquery.slimScroll.d.ts b/jquery.slimScroll/jquery.slimScroll.d.ts index 4d77d28817..b5d3dab17f 100644 --- a/jquery.slimScroll/jquery.slimScroll.d.ts +++ b/jquery.slimScroll/jquery.slimScroll.d.ts @@ -1,58 +1,110 @@ -// Type definitions for jQuery.slimScroll v1.3.3 +// Type definitions for jQuery.slimScroll v1.3.8 // Project: https://github.com/rochal/jQuery-slimScroll // Definitions by: Chintan Shah // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// interface IJQuerySlimScrollOptions { - // width in pixels of the visible scroll area + /** + * width in pixels of the visible scroll area + */ width? :string; - // height in pixels of the visible scroll area + /** + * height in pixels of the visible scroll area + */ height? :string; - // width in pixels of the scrollbar and rail + /** + * width in pixels of the scrollbar and rail + */ size? :string; - // scrollbar color, accepts any hex/color value + /** + * scrollbar color, accepts any hex/color value + */ color?:string; - // scrollbar position - left/right + /** + * scrollbar position - left/right + */ position?:string; - // distance in pixels between the side edge and the scrollbar + /** + * distance in pixels between the side edge and the scrollbar + */ distance?:string; - // default scroll position on load - top / bottom / $('selector') + /** + * default scroll position on load - top / bottom / $('selector') + */ start?:any; - // sets scrollbar opacity + /** + * sets scrollbar opacity + */ opacity? :number; - // enables always-on mode for the scrollbar + /** + * enables always-on mode for the scrollbar + */ alwaysVisible?: boolean; - // check if we should hide the scrollbar when user is hovering over + /** + * check if we should hide the scrollbar when user is hovering over + */ disableFadeOut?: boolean; - // sets visibility of the rail + /** + * sets visibility of the rail + */ railVisible?: boolean; - // sets rail color + /** + * sets rail color + */ railColor?: string; - // sets rail opacity + /** + * sets rail opacity + */ railOpacity?:number; - // whether we should use jQuery UI Draggable to enable bar dragging + /** + * whether we should use jQuery UI Draggable to enable bar dragging + */ railDraggable?: boolean; - // defautlt CSS class of the slimscroll rail + /** + * default CSS class of the slimscroll rail + */ railClass?: string; - // defautlt CSS class of the slimscroll bar + /** + * default CSS class of the slimscroll bar + */ barClass?: string; - // defautlt CSS class of the slimscroll wrapper + /** + * default CSS class of the slimscroll wrapper + */ wrapperClass?: string; - // check if mousewheel should scroll the window if we reach top/bottom + /** + * check if mousewheel should scroll the window if we reach top/bottom + */ allowPageScroll?: boolean; - // scroll amount applied to each mouse wheel step + /** + * scroll amount applied to each mouse wheel step + */ wheelStep?: number; - // scroll amount applied when user is using gestures + /** + * scroll amount applied when user is using gestures + */ touchScrollStep?: number; - // sets border radius + /** + * sets border radius + */ borderRadius?: string; - // sets border radius of the rail + /** + * sets border radius of the rail + */ railBorderRadius?: string; - // jumps to the specified scroll value + /** + * jumps to the specified scroll value + */ scrollTo?: string; - // increases/decreases current scroll value by specified amount + /** + * increases/decreases current scroll value by specified amount + */ scrollBy?: string; + /** + * release resources held by the plugin + */ + destroy?:boolean; } interface JQuery { diff --git a/jquery.tooltipster/jquery.tooltipster-tests.ts b/jquery.tooltipster/jquery.tooltipster-tests.ts index 8a8f29acae..2542f4c0a8 100644 --- a/jquery.tooltipster/jquery.tooltipster-tests.ts +++ b/jquery.tooltipster/jquery.tooltipster-tests.ts @@ -1,8 +1,8 @@ /// -// Type definition tests for jQuery Tooltipster 3.0.5 +// Type definition tests for jQuery Tooltipster 3.3.0 // Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee +// Definitions by: Patrick Magee , Dmitry Pesterev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Tests taken from the getting started section of the Tooltipster website @@ -13,6 +13,10 @@ $(document).ready(function () { $('#my-tooltip').tooltipster({ content: $(' This text is in bold case !') }); + + $('#my-tooltip').tooltipster({ + content: 'string test' + }); }); @@ -59,6 +63,9 @@ $('.tooltip').tooltipster('content'); // update tooltip content $('.tooltip').tooltipster('content', myNewContent); +//update option +$('.tooltip').tooltipster('option', 'delay', '200'); + // reposition and resize the tooltip $('.tooltip').tooltipster('reposition'); @@ -163,6 +170,14 @@ $(document).ready(function () { // first on page load, initiate the Tooltipster plugin $('.tooltip').tooltipster(); + $('.tooltip').tooltipster({ + contentAsHTML: true + }); + + $('.tooltip').tooltipster({ + content: $(' This text is in bold case !') + }); + // then immediately show the tooltip $('#example').tooltipster('show'); @@ -170,11 +185,6 @@ $(document).ready(function () { $(window).keypress(function () { $('#example').tooltipster('hide'); }); -}); - -$(document).ready(function () { - - $('.tooltip').tooltipster(); $('#example').tooltipster('show', function () { alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); @@ -190,5 +200,3 @@ $(document).ready(function () { }); }); }); - -$('#my-special-tooltip').tooltipster('content', 'My new content'); \ No newline at end of file diff --git a/jquery.tooltipster/jquery.tooltipster.d.ts b/jquery.tooltipster/jquery.tooltipster.d.ts index a4df0a36e3..7197c6583e 100644 --- a/jquery.tooltipster/jquery.tooltipster.d.ts +++ b/jquery.tooltipster/jquery.tooltipster.d.ts @@ -1,6 +1,6 @@ -// Type definitions for jQuery Tooltipster 3.0.5 +// Type definitions for jQuery Tooltipster 3.3.0 // Project: https://github.com/iamceege/tooltipster -// Definitions by: Patrick Magee +// Definitions by: Patrick Magee , Dmitry Pesterev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -19,7 +19,7 @@ interface JQueryTooltipsterOptions { * Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color * hex code / rgb */ - arrowColor?: any; + arrowColor?: string; /** * If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true */ @@ -28,7 +28,7 @@ interface JQueryTooltipsterOptions { * If set, this will override the content of the tooltip. Default: null * @type string, jQuery object */ - content?: any; + content?: string | JQuery; /** * If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false */ @@ -37,14 +37,18 @@ interface JQueryTooltipsterOptions { * If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true */ contentCloning?: boolean; + /** + * Tooltipster logs notices into the console when you're doing something you ideally shouldn't be doing. Set to false to disable logging. Default: true + */ + debug?: boolean; /** * Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200 */ delay?: number; /** - * Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width) - */ - fixedWidth?: number; + * Set a minimum width for the tooltip. Default: 0 (auto width) + */ + minWidth?: number; /** * Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width) */ @@ -52,24 +56,28 @@ interface JQueryTooltipsterOptions { /** * Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {} */ - functionInit?: (origin, content) => any; + functionInit?: (origin: JQuery, content: string) => void | string; /** * Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); } */ - functionBefore?: (origin, continueTooltip) => void; + functionBefore?: (origin: JQuery, continueTooltip: Function) => void; /** * Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {} */ - functionReady?: (origin, tooltip) => void; + functionReady?: (origin: JQuery, tooltip: JQuery) => void; /** * Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {} */ - functionAfter?: (origin) => void; + functionAfter?: (origin: JQuery) => void; + /** + * If true, the tooltip will close if its origin is clicked. This option only applies when 'trigger' is 'hover' and 'autoClose' is false. Default: false + */ + hideOnClick?: boolean; /** * If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)' * @type string, jQuery object */ - icon?: any; + icon?: string | JQuery; /** * If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true */ @@ -94,6 +102,10 @@ interface JQueryTooltipsterOptions { * If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350 */ interactiveTolerance?: number; + /** + * Allows you to put multiple tooltips on a single element. Read further instructions down this page. Default: false + */ + multiple?: boolean; /** * Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0 */ @@ -115,6 +127,14 @@ interface JQueryTooltipsterOptions { * Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false */ positionTracker?: boolean; + /** + * Called after the tooltip has been repositioned by the position tracker (if enabled). Default: A function that will close the tooltip if the trigger is 'hover' and autoClose is false. + */ + positionTrackerCallback?: (origin: JQuery) => void; + /** + * Specify if a TITLE attribute should be restored on the HTML element after a call to the 'destroy' method. This attribute may be omitted, or be restored with the value that existed before Tooltipster was initialized, or be restored with the stringified value of the current content. Note: in case of multiple tooltips on a single element, only the last destroyed tooltip may trigger a restoration. Default: 'current' + */ + restoration?: string; /** * Set the speed of the animation. Default: 350 */ @@ -143,10 +163,12 @@ interface JQueryTooltipsterOptions { } interface JQuery { + /** * Initiate the Tooltipster plugin */ - tooltipster(): void; + tooltipster(): JQuery; + /** * Creates a new tooltip with the specified, or default, options. * @param options The options @@ -160,27 +182,91 @@ interface JQuery { * }); */ tooltipster(options?: JQueryTooltipsterOptions): JQuery; - /** - * Updates an existing tinyscrollbar with the specified, or default, options. - * @param options The options - * @param callback optional argument callback - * @example - * $(window).keypress(function() { - * $('#example').tooltipster('hide', function() { - * alert('The tooltip is now fully closed'); - * }); - * }); - */ - tooltipster(method: string, callback?: Function): JQuery; - /** - * Call a method trigger with optional paramter - * @example $('#my-special-tooltip').tooltipster('content', 'My new content'); - * @example - * $('#example').tooltipster('show', function() { - * alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content')); - * }); - */ - tooltipster(method: string, param?: string): any; + /** + * Show a tooltip (the 'callback' argument is optional) + * @param methodName show + * @param callback Function for call back + */ + tooltipster(methodName: "show", callback?: Function): JQuery; + + /** + * Hide a tooltip (the 'callback' argument is optional) + * @param methodName hide + * @param callback Function for call back + */ + tooltipster(methodName: "hide", callback?: Function): JQuery; + + /** + * Update tooltip content + * @param methodName content + * @param newContent New content + */ + tooltipster(methodName: "content", newContent: string): JQuery; + + /** + * Update tooltip content + * @param methodName option + * @param optionName Option name + */ + tooltipster(methodName: "option", optionName: string): JQuery; + + /** + * Set the value of an option (use at your own risk, we do not provide support for issues you may encounter when using this method) + * @param methodName option + * @param optionName Option name + * @param optionValue New vale for option + */ + tooltipster(methodName: "option", optionName: string, optionValue: string): JQuery; + + + /** + * Temporarily disable a tooltip from being able to open + * @param methodName disable + */ + tooltipster(methodName: "disable"): JQuery; + + /** + * Temporarily disable a tooltip from being able to open + * @param methodName enable + */ + tooltipster(methodName: "enable"): JQuery; + + /** + * Hide and destroy tooltip functionality + * @param methodName destroy + */ + tooltipster(methodName: "destroy"): JQuery; + + /** + * Return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned) + * @param methodName content + */ + tooltipster(methodName: "content"): string; + + /** + * Reposition and resize the tooltip + * @param methodName reposition + */ + tooltipster(methodName: "reposition"): JQuery; + + /** + * Return the HTML root element of the tooltip + * @param methodName elementTooltip + */ + tooltipster(methodName: "elementTooltip"): JQuery; + + /** + * Return the HTML root element of the icon if there is one, 'undefined' otherwise + * @param methodName elementIcon + */ + tooltipster(methodName: "elementIcon"): JQuery; + + /** + * Generics + */ + tooltipster(methodName: string, optionName: string, optionValue: string): JQuery; + tooltipster(methodName: string, param: string): JQuery; + tooltipster(methodName: string): JQuery; + tooltipster(methodName: string): string; } - diff --git a/jquery.validation/jquery.validation.d.ts b/jquery.validation/jquery.validation.d.ts index 7527652e80..e3d35bb0d1 100644 --- a/jquery.validation/jquery.validation.d.ts +++ b/jquery.validation/jquery.validation.d.ts @@ -188,6 +188,14 @@ declare namespace JQueryValidation * @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters. */ addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: string): void; + /** + * Add a custom validation method. It must consist of a name (must be a legal javascript identifier), a predicate function and a message generating function. + * + * @param name The name of the method used to identify it and referencing it; this must be a valid JavaScript identifier + * @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters. + * @param message Message generator. First argument: Parameters. Second argument: Validated element. + */ + addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => boolean, message?: (params: any, element: HTMLElement) => string): void; /** * Replaces {n} placeholders with arguments. * diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 6478529dad..40ebf2ee6c 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -1987,6 +1987,24 @@ interface JQuery { */ click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Trigger the "contextmenu" event on an element. + */ + contextmenu(): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + contextmenu(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + contextmenu(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** * Trigger the "dblclick" event on an element. */ diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 63a1591a21..c8167956ea 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -1794,7 +1794,7 @@ interface JQuery { uniqueId(): JQuery; removeUniqueId(): JQuery; scrollParent(): JQuery; - zIndex(): JQuery; + zIndex(): number; zIndex(zIndex: number): JQuery; widget: JQueryUI.Widget; diff --git a/js-quantities/js-quantities-tests.ts b/js-quantities/js-quantities-tests.ts new file mode 100644 index 0000000000..c8d00eef53 --- /dev/null +++ b/js-quantities/js-quantities-tests.ts @@ -0,0 +1,9 @@ +/// + +var Val1 = Qty('1 m') + +var Val2 = Qty(1); + +var Val3 = Qty(1, 'm'); + +var Val4 = Qty(Val1); \ No newline at end of file diff --git a/js-quantities/js-quantities.d.ts b/js-quantities/js-quantities.d.ts new file mode 100644 index 0000000000..a2e3c2d96c --- /dev/null +++ b/js-quantities/js-quantities.d.ts @@ -0,0 +1,79 @@ +// Type definitions for JS-quantities +// Project: http://gentooboontoo.github.io/js-quantities/ +// Definitions by: William Comartin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var Qty: QtyModule.QtyStatic; + +declare namespace QtyModule { + interface QtyStatic { + (value: string): Qty; + (value: number): Qty; + (value: number, unit: string): Qty; + (value: Qty): Qty; + } + + interface Qty { + version: string; + + scalar: number; + baseScalar: number; + + parse(value: string): Qty; + + swiftConverter(srcUnits:string, dstUnits:string): (value:number) => number; + + getkinds(): string[]; + + getUnits(kind:string): string[]; + + getAliases(unitName:string): string[]; + + formatter(scalar:number, units:string):string; + + toFloat(): number; + + isUnitless(): boolean; + + isCompatible(other:string|Qty): boolean; + + isInverse(other:string|Qty): boolean + + kind(): string; + + isBase(): boolean; + + toBase(): Qty; + + units(): string; + + eq(other:Qty): boolean; + lt(other:Qty): boolean; + lte(other:Qty): boolean; + gt(other:Qty): boolean; + gte(other:Qty): boolean; + + toPrec(precQuantity: Qty|string|number): Qty; + + toString(targetUnitsOrMaxDecimalsOrPrec?:number|string|Qty, maxDecimals?: number): string; + + format(targetUnits?:string, formatter?:(scalar:number, units:string) => string): string; + + compareTo(other:Qty|string): number; + + same(other: Qty): boolean; + + inverse(): Qty; + + isDegrees(): boolean; + + isTemperature(): boolean; + + to(other:string|Qty): Qty; + + add(other:string|Qty): Qty; + sub(other:string|Qty): Qty; + mul(other:number|string|Qty): Qty; + div(other:number|string|Qty): Qty; + } +} \ No newline at end of file diff --git a/jsnlog/jsnlog-tests.ts b/jsnlog/jsnlog-tests.ts index dfb32a6c85..d37a7370dc 100644 --- a/jsnlog/jsnlog-tests.ts +++ b/jsnlog/jsnlog-tests.ts @@ -3,12 +3,14 @@ // ---------------------------------------------------------- // JL +var offLevel: number = JL.getOffLevel(); var traceLevel: number = JL.getTraceLevel(); var debugLevel: number = JL.getDebugLevel(); var infoLevel: number = JL.getInfoLevel(); var warnLevel: number = JL.getWarnLevel(); var errorLevel: number = JL.getErrorLevel(); var fatalLevel: number = JL.getFatalLevel(); +var allLevel: number = JL.getAllLevel(); JL.setOptions({ enabled: true, @@ -19,10 +21,15 @@ JL.setOptions({ defaultBeforeSend: null }); +// ---------------------------------------------------------- +// Exception + +var e = new JL.Exception("i is too small!"); + // ---------------------------------------------------------- // Ajax Appender -var ajaxAppender1: JSNLog.JSNLogAjaxAppender = JL.createAjaxAppender('ajaxAppender'); +var ajaxAppender1: JL.JSNLogAjaxAppender = JL.createAjaxAppender('ajaxAppender'); ajaxAppender1.setOptions({ level: 5000, @@ -40,7 +47,7 @@ ajaxAppender1.setOptions({ // ---------------------------------------------------------- // Console Appender -var consoleAppender1: JSNLog.JSNLogConsoleAppender = JL.createConsoleAppender('consoleAppender'); +var consoleAppender1: JL.JSNLogConsoleAppender = JL.createConsoleAppender('consoleAppender'); consoleAppender1.setOptions({ level: 5000, @@ -57,7 +64,7 @@ consoleAppender1.setOptions({ // ---------------------------------------------------------- // Loggers -var logger1: JSNLog.JSNLogLogger = JL('mylogger'); +var logger1: JL.JSNLogLogger = JL('mylogger'); var exception = {}; diff --git a/jsnlog/jsnlog.d.ts b/jsnlog/jsnlog.d.ts index 07d8aebe25..40daf96b24 100644 --- a/jsnlog/jsnlog.d.ts +++ b/jsnlog/jsnlog.d.ts @@ -1,30 +1,30 @@ -// Type definitions for JSNLog v2.11.0+ +// Type definitions for JSNLog v2.17.3+ // Project: https://github.com/mperdeck/jsnlog.js // Definitions by: Mattijs Perdeck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // ------------------------------- -// Full documentation is at +// Full documentation is at // http://jsnlog.com // ------------------------------- /** -* Copyright 2015 Mattijs Perdeck. +* Copyright 2016 Mattijs Perdeck. * * This project is licensed under the MIT license. -* +* * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -* +* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Declarations of all interfaces and ambient objects, except for JL itself. -// Provides strong typing in both jsnlog.ts itself and in TypeScript programs that use -// JSNLog. +// Provides strong typing in both jsnlog.ts itself and in TypeScript programs that use +// JSNLog. -declare namespace JSNLog { +declare namespace JL { interface JSNLogOptions { enabled?: boolean; @@ -83,30 +83,33 @@ declare namespace JSNLog { interface JSNLogConsoleAppender extends JSNLogAppender { } - - interface JSNLogStatic { - (loggerName?: string): JSNLogLogger; - - setOptions(options: JSNLogOptions): JSNLogStatic; - createAjaxAppender(appenderName: string): JSNLogAjaxAppender; - createConsoleAppender(appenderName: string): JSNLogConsoleAppender; - - getTraceLevel(): number; - getDebugLevel(): number; - getInfoLevel(): number; - getWarnLevel(): number; - getErrorLevel(): number; - getFatalLevel(): number; - } } -declare function __jsnlog_configure(jsnlog: JSNLog.JSNLogStatic): void; +declare function __jsnlog_configure(jsnlog: any): void;  -// Ambient declaration of the JL object itself - -declare var JL: JSNLog.JSNLogStatic; - +// Ambient declaration of the JL function itself +declare function JL(loggerName?: string): JL.JSNLogLogger; +// Definitions that need to be kept out of the main namespace definition, +// because otherwise during compilation of jsnlog.ts it complains that you can't +// overload ambient declarations with non-ambient declarations. +declare namespace JL { + export function setOptions(options: JSNLogOptions): void; + export function createAjaxAppender(appenderName: string): JSNLogAjaxAppender; + export function createConsoleAppender(appenderName: string): JSNLogConsoleAppender; + export class Exception { + constructor(data: any, inner?: any); + } + + export function getOffLevel(): number; + export function getTraceLevel(): number; + export function getDebugLevel(): number; + export function getInfoLevel(): number; + export function getWarnLevel(): number; + export function getErrorLevel(): number; + export function getFatalLevel(): number; + export function getAllLevel(): number; +} diff --git a/jsonnet/jsonnet-tests.ts b/jsonnet/jsonnet-tests.ts new file mode 100644 index 0000000000..88b3c82bed --- /dev/null +++ b/jsonnet/jsonnet-tests.ts @@ -0,0 +1,6 @@ +/// +import Jsonnet = require('jsonnet'); +var jsonnet = new Jsonnet(); +var code = '{a:1}'; +var result = jsonnet.eval(code); +console.log(result); diff --git a/jsonnet/jsonnet.d.ts b/jsonnet/jsonnet.d.ts new file mode 100644 index 0000000000..5a5aa5b619 --- /dev/null +++ b/jsonnet/jsonnet.d.ts @@ -0,0 +1,13 @@ +// Type definitions for jsonnet +// Project: https://github.com/yosuke-furukawa/node-jsonnet +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "jsonnet" { + class Jsonnet { + constructor(); + eval(code: string): any; + evalFile(): any; + destroy(): void; + } + export = Jsonnet; +} diff --git a/jsonwebtoken/jsonwebtoken.d.ts b/jsonwebtoken/jsonwebtoken.d.ts index 888ac75d6f..da2fb3b99a 100644 --- a/jsonwebtoken/jsonwebtoken.d.ts +++ b/jsonwebtoken/jsonwebtoken.d.ts @@ -23,7 +23,7 @@ declare module "jsonwebtoken" { */ algorithm?: string; /** @member {string} - Lifetime for the token expressed in a string describing a time span [rauchg/ms](https://github.com/rauchg/ms.js). Eg: `60`, `"2 days"`, `"10h"`, `"7d"` */ - expiresIn?: string; + expiresIn?: string | number; notBefore?: string; audience?: string; subject?: string; diff --git a/jstree/jstree.d.ts b/jstree/jstree.d.ts index db60de893d..f3961f7e3e 100644 --- a/jstree/jstree.d.ts +++ b/jstree/jstree.d.ts @@ -1,8 +1,8 @@ -// Type definitions for jsTree v3.0.9 +// Type definitions for jsTree v3.3.1 // Project: http://www.jstree.com/ // Definitions by: Adam Pluciński // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// 45 commit df38535 2015-03-02 13:23 +2:00 +// 1 commit 3b8f55d3797cd299eb36695b62d75c2313a3e3b3 2016-05-10 /// @@ -65,10 +65,12 @@ interface JSTreeStatic { /** * stores all loaded jstree plugins (used internally) + * @name $.jstree.plugins */ plugins: any[]; path: string; idregex: any; + root: string; /** * creates a jstree instance @@ -77,7 +79,7 @@ interface JSTreeStatic { * @param {Object} options options for this instance (extends `$.jstree.defaults`) * @return {jsTree} the new instance */ - create(el: any, options?: JSTreeStaticDefaults): JSTree; + create(el: HTMLElement|JQuery|string, options?: JSTreeStaticDefaults): JSTree; /** * remove all traces of jstree from the DOM and destroy all instances @@ -98,41 +100,22 @@ interface JSTreeStatic { * * __Examples__ * - * $.jstree.reference('tree'); - * $.jstree.reference('#tree'); - * $.jstree.reference('branch'); - * $.jstree.reference('#branch'); - * - * @param {String} selector - * @returns {JSTree|null} the instance or `null` if not found - */ - reference(selector: string): JSTree; - - /** - * get a reference to an existing instance - * - * __Examples__ - * - * $.jstree.reference(document.getElementByID('tree')); - * $.jstree.reference(document.getElementByID('branch')); - * - * @param {HTMLElement} element - * @returns {JSTree|null} the instance or `null` if not found - */ - reference(element: HTMLElement): JSTree; - - /** - * get a reference to an existing instance - * - * __Examples__ - * - * $.jstree.reference($('#tree')); - * $.jstree.reference($('#branch')); - * - * @param {JQuery} object - * @returns {JSTree|null} the instance or `null` if not found - */ - reference(object: JQuery): JSTree; + * // provided a container with an ID of "tree", and a nested node with an ID of "branch" + * // all of there will return the same instance + * $.jstree.reference('tree'); + * $.jstree.reference('#tree'); + * $.jstree.reference($('#tree')); + * $.jstree.reference(document.getElementByID('tree')); + * $.jstree.reference('branch'); + * $.jstree.reference('#branch'); + * $.jstree.reference($('#branch')); + * $.jstree.reference(document.getElementByID('branch')); + * + * @name $.jstree.reference(needle) + * @param {DOMElement|jQuery|String} needle + * @return {jsTree|null} the instance or `null` if not found + */ + reference(needle: HTMLElement|JQuery|string): JSTree; } interface JSTreeStaticDefaults { @@ -475,18 +458,19 @@ interface JSTreeStaticDefaultsContextMenu { /** * an object of actions, or a function that accepts a node and a callback function and calls the callback function with an object of actions available for that node (you can also return the items too). - * - * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required): - * + * + * Each action consists of a key (a unique name) and a value which is an object with the following properties (only label and action are required). Once a menu item is activated the `action` function will be invoked with an object containing the following keys: item - the contextmenu item definition as seen below, reference - the DOM node that was used (the tree node), element - the contextmenu DOM element, position - an object with x/y properties indicating the position of the menu. + * * * `separator_before` - a boolean indicating if there should be a separator before this item * * `separator_after` - a boolean indicating if there should be a separator after this item * * `_disabled` - a boolean indicating if this action should be disabled * * `label` - a string - the name of the action (could be a function returning a string) - * * `action` - a function to be executed if this item is chosen + * * `action` - a function to be executed if this item is chosen, the function will receive * * `icon` - a string, can be a path to an icon or a className, if using an image that is in the current directory use a `./` prefix, otherwise it will be detected as a class * * `shortcut` - keyCode which will trigger the action if the menu is open (for example `113` for rename, which equals F2) * * `shortcut_label` - shortcut label (like for example `F2` for rename) - * + * * `submenu` - an object with the same structure as $.jstree.defaults.contextmenu.items which can be used to create a submenu - each key will be rendered as a separate option in a submenu that will appear once the current item is hovered + * * @name $.jstree.defaults.contextmenu.items * @plugin contextmenu */ @@ -563,6 +547,14 @@ interface JSTreeStaticDefaultsDragNDrop { * @plugin dnd */ large_drag_target: boolean; + + /** + * controls whether use HTML5 dnd api instead of classical. That will allow better integration of dnd events with other HTML5 controls. + * @reference http://caniuse.com/#feat=dragndrop + * @name $.jstree.defaults.dnd.use_html5 + * @plugin dnd + */ + use_html5: boolean; } interface JSTreeStaticDefaultsMassload { @@ -627,6 +619,14 @@ interface JSTreeStaticDefaultsSearch { * @plugin search */ show_only_matches: boolean; + + /** + * Indicates if the children of matched element are shown (when show_only_matches is true) + * This setting can be changed at runtime when calling the search method. Default is `false`. + * @name $.jstree.defaults.search.show_only_matches_children + * @plugin search + */ + show_only_matches_children: boolean; /** * Indicates if all nodes opened to reveal the search result, @@ -720,7 +720,7 @@ interface JSTree extends JQuery { * @param {Object} options options for this instance * @trigger init.jstree, loading.jstree, loaded.jstree, ready.jstree, changed.jstree */ - init: (el:any, options:any) => void; + init: (el: HTMLElement|JQuery|string, options:any) => void; /** * destroy an instance @@ -932,8 +932,9 @@ interface JSTree extends JQuery { * @param {array} nodes * @param {function} callback a function to be executed once loading is complete, the function is executed in the instance's scope and receives one argument - the array passed to _load_nodes * @param {Boolean} is_callback - if false reloads node (AP - original comment missing in source code) + * @param {Boolean} force_reload - if true force reloads node (AP - original comment missing in source code) */ - _load_nodes: (nodes: any[], callback?: (nodes: any[]) => void, is_callback?: boolean) => void; + _load_nodes: (nodes: any[], callback?: (nodes: any[]) => void, is_callback?: boolean, force_reload?: boolean) => void; /** * loads all unloaded nodes @@ -1130,6 +1131,45 @@ interface JSTree extends JQuery { * @trigger disable_node.jstree */ disable_node: (obj: any) => boolean; + + /** + * determines if a node is hidden + * @name is_hidden(obj) + * @param {mixed} obj the node + */ + is_hidden: (obj: any) => boolean; + + /** + * hides a node - it is still in the structure but will not be visible + * @name hide_node(obj) + * @param {mixed} obj the node to hide + * @param {Boolean} skip_redraw internal parameter controlling if redraw is called + * @trigger hide_node.jstree + */ + hide_node: (obj: any, skip_redraw: boolean) => boolean; + + /** + * shows a node + * @name show_node(obj) + * @param {mixed} obj the node to show + * @param {Boolean} skip_redraw internal parameter controlling if redraw is called + * @trigger show_node.jstree + */ + show_node: (obj: any, skip_redraw: boolean) => boolean; + + /** + * hides all nodes + * @name hide_all() + * @trigger hide_all.jstree + */ + hide_all: (skip_redraw: boolean) => boolean; + + /** + * shows all nodes + * @name show_all() + * @trigger show_all.jstree + */ + show_all: (skip_redraw: boolean) => boolean; /** * called when a node is selected by the user. Used internally. @@ -1432,11 +1472,12 @@ interface JSTree extends JQuery { /** * put a node in edit mode (input field to rename the node) - * @name edit(obj [, default_text]) + * @name edit(obj [, default_text, callback]) * @param {mixed} obj - * @param {String} default_text the text to populate the input with (if omitted the node text value is used) - */ - edit: (obj: any, default_text?: string) => void; + * @param {String} default_text the text to populate the input with (if omitted or set to a non-string value the node's text value is used) + * @param {Function} callback a function to be called once the text box is blurred, it is called in the instance's scope and receives the node, a status parameter (true if the rename is successful, false otherwise) and a boolean indicating if the user cancelled the edit. You can access the node's title using .text + */ + edit: (obj: any, default_text?: string, callback?: (node: any, status: boolean, canceled: boolean) => void) => void; /** * changes the theme @@ -1553,6 +1594,10 @@ interface JSTree extends JQuery { * @param {mixed} obj */ show_icon: (obj: any) => void; + + /** + * checkbox plugin + */ /** * set the undetermined state where and if necessary. Used internally. @@ -1590,6 +1635,24 @@ interface JSTree extends JQuery { * @return {Boolean} */ is_undetermined: (obj: any) => boolean; + + /** + * disable a node's checkbox + * @name disable_checkbox(obj) + * @param {mixed} obj an array can be used too + * @trigger disable_checkbox.jstree + * @plugin checkbox + */ + disable_checkbox: (obj: any) => boolean; + + /** + * enable a node's checkbox + * @name disable_checkbox(obj) + * @param {mixed} obj an array can be used too + * @trigger enable_checkbox.jstree + * @plugin checkbox + */ + enable_checkbox: (obj: any) => boolean; /** * check a node (only if tie_selection in checkbox settings is false, otherwise select_node will be called internally) @@ -1689,6 +1752,10 @@ interface JSTree extends JQuery { * @private */ _show_contextmenu: (obj: any, x: number, y: number, i: number) => void; + + /** + * search plugin + */ /** * used to search the tree nodes for a given string @@ -1698,10 +1765,11 @@ interface JSTree extends JQuery { * @param {Boolean} show_only_matches if set to true only matching nodes will be shown (keep in mind this can be very slow on large trees or old browsers) * @param {mixed} inside an optional node to whose children to limit the search * @param {Boolean} append if set to true the results of this search are appended to the previous search + * @param {Boolean} show_only_matches_children show only matched children * @plugin search * @trigger search.jstree */ - search: (str: string, skip_async?: boolean, show_only_matches?: boolean, inside?: any, append?: boolean) => void; + search: (str: string, skip_async?: boolean, show_only_matches?: boolean, inside?: any, append?: boolean, show_only_matches_children?: boolean) => void; /** * used to clear the last search (removes classes and shows all nodes if filtering is on) @@ -1719,6 +1787,10 @@ interface JSTree extends JQuery { * @plugin search */ _search_open: (d: string[]) => void; + + /** + * sort plugin + */ /** * used to sort a node's children @@ -1730,6 +1802,10 @@ interface JSTree extends JQuery { * @trigger search.jstree */ sort: (obj: any, deep?: boolean) => void; + + /** + * state plugin + */ /** * save the state @@ -1751,6 +1827,10 @@ interface JSTree extends JQuery { * @plugin state */ clear_state: () => void; + + /** + * types plugin + */ /** * used to retrieve the type settings object for a node diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 20b6bf16a2..934a8cd8b1 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -262,7 +262,7 @@ declare namespace kendo { static fn: Observable; static extend(prototype: Object): Observable; - init(...args: any[]): void + init(...args: any[]): void; bind(eventName: string, handler: Function): Observable; one(eventName: string, handler: Function): Observable; first(eventName: string, handler: Function): Observable; @@ -843,6 +843,7 @@ declare namespace kendo.data { axes?: any; catalogs?: any; cubes?: any; + cube?: any; data?: any; dimensions?: any; hierarchies?: any; @@ -1281,6 +1282,7 @@ declare namespace kendo.data { interface DataSourceRequestStartEvent extends DataSourceEvent { type?: string; + preventDefault(): void; } interface DataSourceRequestEndEvent extends DataSourceEvent { @@ -1456,14 +1458,20 @@ declare namespace kendo.mobile { } interface ApplicationOptions { + browserHistory?: boolean; hideAddressBar?: boolean; updateDocumentTitle?: boolean; initial?: string; layout?: string; loading?: string; + modelScope?: Object; platform?: string; + retina?: boolean; serverNavigation?: boolean; + skin?: string; + statusBarStyle?: string; transition?: string; + useNativeScrolling?: boolean; } interface ApplicationEvent { @@ -1682,7 +1690,7 @@ declare namespace kendo.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point, size: kendo.geometry.Size); + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -1792,6 +1800,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Arc; geometry(value: kendo.geometry.Arc): void; fill(color: string, opacity?: number): kendo.drawing.Arc; @@ -1812,6 +1821,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -1835,6 +1845,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Circle; geometry(value: kendo.geometry.Circle): void; fill(color: string, opacity?: number): kendo.drawing.Circle; @@ -1855,6 +1866,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -1870,6 +1882,7 @@ declare namespace kendo.drawing { options: ElementOptions; + parent: kendo.drawing.Group; constructor(options?: ElementOptions); @@ -1878,6 +1891,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; transform(): kendo.geometry.Transformation; @@ -1982,6 +1996,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; insert(position: number, element: kendo.drawing.Element): void; opacity(): number; opacity(opacity: number): void; @@ -1998,6 +2013,7 @@ declare namespace kendo.drawing { cursor?: string; opacity?: number; pdf?: kendo.drawing.PDFOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2021,6 +2037,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; src(): string; @@ -2039,6 +2056,7 @@ declare namespace kendo.drawing { clip?: kendo.drawing.Path; cursor?: string; opacity?: number; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2128,6 +2146,7 @@ declare namespace kendo.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.MultiPath; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath; @@ -2160,6 +2179,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2233,6 +2253,7 @@ declare namespace kendo.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.Path; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path; @@ -2265,6 +2286,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2321,6 +2343,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Rect; geometry(value: kendo.geometry.Rect): void; fill(color: string, opacity?: number): kendo.drawing.Rect; @@ -2341,6 +2364,7 @@ declare namespace kendo.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2411,18 +2435,43 @@ declare namespace kendo.drawing { clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; + hideTooltip(): void; resize(force?: boolean): void; + showTooltip(element: kendo.drawing.Element, options?: any): void; } + interface SurfaceTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimation { + close?: SurfaceTooltipAnimationClose; + open?: SurfaceTooltipAnimationOpen; + } + + interface SurfaceTooltip { + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; + } + interface SurfaceOptions { name?: string; type?: string; height?: string; width?: string; + tooltip?: SurfaceTooltip; click?(e: SurfaceClickEvent): void; mouseenter?(e: SurfaceMouseenterEvent): void; mouseleave?(e: SurfaceMouseleaveEvent): void; + tooltipClose?(e: SurfaceTooltipCloseEvent): void; + tooltipOpen?(e: SurfaceTooltipOpenEvent): void; } interface SurfaceEvent { sender: Surface; @@ -2445,6 +2494,16 @@ declare namespace kendo.drawing { originalEvent?: any; } + interface SurfaceTooltipCloseEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + + interface SurfaceTooltipOpenEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + class Text extends kendo.drawing.Element { @@ -2459,6 +2518,7 @@ declare namespace kendo.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; content(): string; content(value: string): void; fill(color: string, opacity?: number): kendo.drawing.Text; @@ -2482,6 +2542,7 @@ declare namespace kendo.drawing { font?: string; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -2492,6 +2553,28 @@ declare namespace kendo.drawing { } + interface TooltipOptions { + + + + autoHide?: boolean; + content?: string|Function; + position?: string; + height?: number|string; + hideDelay?: number; + offset?: number; + shared?: boolean; + showAfter?: number; + showOn?: string; + width?: number|string; + + + + + } + + + } declare namespace kendo.ui { class AutoComplete extends kendo.ui.Widget { @@ -2553,7 +2636,7 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; - animation?: AutoCompleteAnimation; + animation?: boolean|AutoCompleteAnimation; dataSource?: any|any|kendo.data.DataSource; dataTextField?: string; delay?: number; @@ -2572,7 +2655,7 @@ declare namespace kendo.ui { headerTemplate?: string|Function; template?: string|Function; valuePrimitive?: boolean; - virtual?: AutoCompleteVirtual; + virtual?: boolean|AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; close?(e: AutoCompleteCloseEvent): void; dataBound?(e: AutoCompleteDataBoundEvent): void; @@ -2914,7 +2997,7 @@ declare namespace kendo.ui { text?: string; value?: string; valuePrimitive?: boolean; - virtual?: ComboBoxVirtual; + virtual?: boolean|ComboBoxVirtual; change?(e: ComboBoxChangeEvent): void; close?(e: ComboBoxCloseEvent): void; dataBound?(e: ComboBoxDataBoundEvent): void; @@ -3009,7 +3092,7 @@ declare namespace kendo.ui { interface ContextMenuOptions { name?: string; alignToAnchor?: boolean; - animation?: ContextMenuAnimation; + animation?: boolean|ContextMenuAnimation; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -3119,7 +3202,7 @@ declare namespace kendo.ui { interface DatePickerOptions { name?: string; - animation?: DatePickerAnimation; + animation?: boolean|DatePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; @@ -3209,7 +3292,7 @@ declare namespace kendo.ui { interface DateTimePickerOptions { name?: string; - animation?: DateTimePickerAnimation; + animation?: boolean|DateTimePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; @@ -3252,6 +3335,7 @@ declare namespace kendo.ui { static fn: DropDownList; options: DropDownListOptions; + popup: kendo.ui.Popup; dataSource: kendo.data.DataSource; span: JQuery; @@ -3319,7 +3403,7 @@ declare namespace kendo.ui { interface DropDownListOptions { name?: string; - animation?: DropDownListAnimation; + animation?: boolean|DropDownListAnimation; autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; @@ -3344,7 +3428,7 @@ declare namespace kendo.ui { text?: string; value?: string; valuePrimitive?: boolean; - virtual?: DropDownListVirtual; + virtual?: boolean|DropDownListVirtual; change?(e: DropDownListChangeEvent): void; close?(e: DropDownListCloseEvent): void; dataBound?(e: DropDownListDataBoundEvent): void; @@ -3418,6 +3502,10 @@ declare namespace kendo.ui { } + interface EditorDeserialization { + custom?: Function; + } + interface EditorFileBrowserMessages { uploadFile?: string; orderBy?: string; @@ -3646,6 +3734,18 @@ declare namespace kendo.ui { deleteColumn?: string; } + interface EditorPasteCleanup { + all?: boolean; + css?: boolean; + custom?: Function; + keepNewLines?: boolean; + msAllFormatting?: boolean; + msConvertLists?: boolean; + msTags?: boolean; + none?: boolean; + span?: boolean; + } + interface EditorPdfMargin { bottom?: number|string; left?: number|string; @@ -3678,6 +3778,7 @@ declare namespace kendo.ui { } interface EditorSerialization { + custom?: Function; entities?: boolean; scripts?: boolean; semantic?: boolean; @@ -3707,11 +3808,13 @@ declare namespace kendo.ui { interface EditorOptions { name?: string; + deserialization?: EditorDeserialization; domain?: string; encoded?: boolean; messages?: EditorMessages; + pasteCleanup?: EditorPasteCleanup; pdf?: EditorPdf; - resizable?: EditorResizable; + resizable?: boolean|EditorResizable; serialization?: EditorSerialization; stylesheets?: any; tools?: EditorTool[]; @@ -3745,6 +3848,101 @@ declare namespace kendo.ui { } + class FilterMenu extends kendo.ui.Widget { + + static fn: FilterMenu; + + options: FilterMenuOptions; + + field: string; + + element: JQuery; + wrapper: JQuery; + + static extend(proto: Object): FilterMenu; + + constructor(element: Element, options?: FilterMenuOptions); + + + clear(): void; + + } + + interface FilterMenuMessages { + and?: string; + clear?: string; + filter?: string; + info?: string; + isFalse?: string; + isTrue?: string; + or?: string; + selectValue?: string; + } + + interface FilterMenuOperatorsDate { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterMenuOperatorsEnums { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + } + + interface FilterMenuOperatorsNumber { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + gte?: string; + gt?: string; + lte?: string; + lt?: string; + } + + interface FilterMenuOperatorsString { + eq?: string; + neq?: string; + isnull?: string; + isnotnull?: string; + isempty?: string; + isnotempty?: string; + startswith?: string; + contains?: string; + doesnotcontain?: string; + endswith?: string; + } + + interface FilterMenuOperators { + string?: FilterMenuOperatorsString; + number?: FilterMenuOperatorsNumber; + date?: FilterMenuOperatorsDate; + enums?: FilterMenuOperatorsEnums; + } + + interface FilterMenuOptions { + name?: string; + dataSource?: any|any|kendo.data.DataSource; + extra?: boolean; + field?: string; + messages?: FilterMenuMessages; + operators?: FilterMenuOperators; + } + interface FilterMenuEvent { + sender: FilterMenu; + preventDefault: Function; + isDefaultPrevented(): boolean; + } + + class FlatColorPicker extends kendo.ui.Widget { static fn: FlatColorPicker; @@ -3964,10 +4162,10 @@ declare namespace kendo.ui { autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GanttColumn[]; - currentTimeMarker?: GanttCurrentTimeMarker; + currentTimeMarker?: boolean|GanttCurrentTimeMarker; dataSource?: any|any|kendo.data.GanttDataSource; dependencies?: any|any|kendo.data.GanttDependencyDataSource; - editable?: GanttEditable; + editable?: boolean|GanttEditable; navigatable?: boolean; workDayStart?: Date; workDayEnd?: Date; @@ -4253,7 +4451,8 @@ declare namespace kendo.ui { command?: GridColumnCommandItem[]; encoded?: boolean; field?: string; - filterable?: GridColumnFilterable; + filterable?: boolean|GridColumnFilterable; + footerAttributes?: any; footerTemplate?: string|Function; format?: string; groupable?: boolean; @@ -4265,7 +4464,7 @@ declare namespace kendo.ui { locked?: boolean; lockable?: boolean; minScreenWidth?: number; - sortable?: GridColumnSortable; + sortable?: boolean|GridColumnSortable; template?: string|Function; title?: string; width?: string|number; @@ -4301,8 +4500,10 @@ declare namespace kendo.ui { isFalse?: string; isTrue?: string; or?: string; + search?: string; selectValue?: string; cancel?: string; + selectedItemsFormat?: string; operator?: string; value?: string; checkAll?: string; @@ -4441,7 +4642,7 @@ declare namespace kendo.ui { paperSize?: string|any; template?: string; repeatHeaders?: boolean; - scale?: number|any|any; + scale?: number; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -4465,31 +4666,31 @@ declare namespace kendo.ui { interface GridOptions { name?: string; - allowCopy?: GridAllowCopy; + allowCopy?: boolean|GridAllowCopy; altRowTemplate?: string|Function; autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GridColumn[]; - columnMenu?: GridColumnMenu; + columnMenu?: boolean|GridColumnMenu; dataSource?: any|any|kendo.data.DataSource; detailTemplate?: string|Function; - editable?: GridEditable; + editable?: boolean|GridEditable; excel?: GridExcel; - filterable?: GridFilterable; - groupable?: GridGroupable; + filterable?: boolean|GridFilterable; + groupable?: boolean|GridGroupable; height?: number|string; messages?: GridMessages; mobile?: boolean|string; navigatable?: boolean; - noRecords?: GridNoRecords; - pageable?: GridPageable; + noRecords?: boolean|GridNoRecords; + pageable?: boolean|GridPageable; pdf?: GridPdf; reorderable?: boolean; resizable?: boolean; rowTemplate?: string|Function; - scrollable?: GridScrollable; + scrollable?: boolean|GridScrollable; selectable?: boolean|string; - sortable?: GridSortable; + sortable?: boolean|GridSortable; toolbar?: string | ((...args:any[]) => string) | GridToolbarItem[]; cancel?(e: GridCancelEvent): void; change?(e: GridChangeEvent): void; @@ -4806,7 +5007,7 @@ declare namespace kendo.ui { interface MenuOptions { name?: string; - animation?: MenuAnimation; + animation?: boolean|MenuAnimation; closeOnClick?: boolean; dataSource?: any|any; direction?: string; @@ -4913,7 +5114,7 @@ declare namespace kendo.ui { interface MultiSelectOptions { name?: string; - animation?: MultiSelectAnimation; + animation?: boolean|MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; dataSource?: any|any|kendo.data.DataSource; @@ -4937,7 +5138,7 @@ declare namespace kendo.ui { tagMode?: string; value?: any; valuePrimitive?: boolean; - virtual?: MultiSelectVirtual; + virtual?: boolean|MultiSelectVirtual; change?(e: MultiSelectChangeEvent): void; close?(e: MultiSelectCloseEvent): void; dataBound?(e: MultiSelectDataBoundEvent): void; @@ -5274,7 +5475,7 @@ declare namespace kendo.ui { interface PanelBarOptions { name?: string; - animation?: PanelBarAnimation; + animation?: boolean|PanelBarAnimation; contentUrls?: any; dataSource?: any|any; expandMode?: string; @@ -5382,7 +5583,7 @@ declare namespace kendo.ui { name?: string; dataSource?: any|kendo.data.PivotDataSource; filterable?: boolean; - sortable?: PivotConfiguratorSortable; + sortable?: boolean|PivotConfiguratorSortable; height?: number|string; messages?: PivotConfiguratorMessages; } @@ -5494,7 +5695,7 @@ declare namespace kendo.ui { excel?: PivotGridExcel; pdf?: PivotGridPdf; filterable?: boolean; - sortable?: PivotGridSortable; + sortable?: boolean|PivotGridSortable; columnWidth?: number; height?: number|string; columnHeaderTemplate?: string|Function; @@ -5583,7 +5784,7 @@ declare namespace kendo.ui { interface PopupOptions { name?: string; adjustSize?: any; - animation?: PopupAnimation; + animation?: boolean|PopupAnimation; anchor?: string|JQuery; appendTo?: string|JQuery; collision?: string; @@ -6021,7 +6222,7 @@ declare namespace kendo.ui { columnWidth?: number; dateHeaderTemplate?: string|Function; dayTemplate?: string|Function; - editable?: SchedulerViewEditable; + editable?: boolean|SchedulerViewEditable; endTime?: Date; eventHeight?: number; eventTemplate?: string|Function; @@ -6055,14 +6256,14 @@ declare namespace kendo.ui { allDayEventTemplate?: string|Function; allDaySlot?: boolean; autoBind?: boolean; - currentTimeMarker?: SchedulerCurrentTimeMarker; + currentTimeMarker?: boolean|SchedulerCurrentTimeMarker; dataSource?: any|any|kendo.data.SchedulerDataSource; date?: Date; dateHeaderTemplate?: string|Function; - editable?: SchedulerEditable; + editable?: boolean|SchedulerEditable; endTime?: Date; eventTemplate?: string|Function; - footer?: SchedulerFooter; + footer?: boolean|SchedulerFooter; group?: SchedulerGroup; height?: number|string; majorTick?: number; @@ -6574,6 +6775,7 @@ declare namespace kendo.ui { format?: string; formula?: string; index?: number; + link?: string; textAlign?: string; underline?: boolean; value?: number|string|boolean|Date; @@ -6643,7 +6845,7 @@ declare namespace kendo.ui { rows?: number; sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; - toolbar?: SpreadsheetToolbar; + toolbar?: boolean|SpreadsheetToolbar; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6769,7 +6971,7 @@ declare namespace kendo.ui { interface TabStripOptions { name?: string; - animation?: TabStripAnimation; + animation?: boolean|TabStripAnimation; collapsible?: boolean; contentUrls?: any; dataContentField?: string; @@ -6780,7 +6982,7 @@ declare namespace kendo.ui { dataTextField?: string; dataUrlField?: string; navigatable?: boolean; - scrollable?: TabStripScrollable; + scrollable?: boolean|TabStripScrollable; tabPosition?: string; value?: string; activate?(e: TabStripActivateEvent): void; @@ -6871,7 +7073,7 @@ declare namespace kendo.ui { interface TimePickerOptions { name?: string; - animation?: TimePickerAnimation; + animation?: boolean|TimePickerAnimation; culture?: string; dates?: any; format?: string; @@ -7078,7 +7280,7 @@ declare namespace kendo.ui { interface TooltipOptions { name?: string; autoHide?: boolean; - animation?: TooltipAnimation; + animation?: boolean|TooltipAnimation; content?: TooltipContent; callout?: boolean; filter?: string; @@ -7241,6 +7443,9 @@ declare namespace kendo.ui { addRow(parentRow: string): void; addRow(parentRow: Element): void; addRow(parentRow: JQuery): void; + autoFitColumn(column: number): void; + autoFitColumn(column: string): void; + autoFitColumn(column: any): void; cancelRow(): void; clearSelection(): void; collapse(): void; @@ -7313,13 +7518,13 @@ declare namespace kendo.ui { encoded?: boolean; expandable?: boolean; field?: string; - filterable?: TreeListColumnFilterable; + filterable?: boolean|TreeListColumnFilterable; footerTemplate?: string|Function; format?: string; headerAttributes?: any; headerTemplate?: string|Function; minScreenWidth?: number; - sortable?: TreeListColumnSortable; + sortable?: boolean|TreeListColumnSortable; template?: string|Function; title?: string; width?: string|number; @@ -7420,17 +7625,17 @@ declare namespace kendo.ui { columns?: TreeListColumn[]; resizable?: boolean; reorderable?: boolean; - columnMenu?: TreeListColumnMenu; + columnMenu?: boolean|TreeListColumnMenu; dataSource?: any|any|kendo.data.TreeListDataSource; - editable?: TreeListEditable; + editable?: boolean|TreeListEditable; excel?: TreeListExcel; - filterable?: TreeListFilterable; + filterable?: boolean|TreeListFilterable; height?: number|string; messages?: TreeListMessages; pdf?: TreeListPdf; scrollable?: boolean|any; selectable?: boolean|string; - sortable?: TreeListSortable; + sortable?: boolean|TreeListSortable; toolbar?: TreeListToolbarItem[]; cancel?(e: TreeListCancelEvent): void; change?(e: TreeListChangeEvent): void; @@ -7645,8 +7850,8 @@ declare namespace kendo.ui { } interface TreeViewAnimation { - collapse?: TreeViewAnimationCollapse; - expand?: TreeViewAnimationExpand; + collapse?: boolean|TreeViewAnimationCollapse; + expand?: boolean|TreeViewAnimationExpand; } interface TreeViewCheckboxes { @@ -7663,10 +7868,10 @@ declare namespace kendo.ui { interface TreeViewOptions { name?: string; - animation?: TreeViewAnimation; + animation?: boolean|TreeViewAnimation; autoBind?: boolean; autoScroll?: boolean; - checkboxes?: TreeViewCheckboxes; + checkboxes?: boolean|TreeViewCheckboxes; dataImageUrlField?: string; dataSource?: any|any|kendo.data.HierarchicalDataSource; dataSpriteCssClassField?: string; @@ -7978,7 +8183,7 @@ declare namespace kendo.ui { interface WindowOptions { name?: string; actions?: any; - animation?: WindowAnimation; + animation?: boolean|WindowAnimation; appendTo?: any|string; autoFocus?: boolean; content?: WindowContent; @@ -9211,7 +9416,7 @@ declare namespace kendo.dataviz.ui { size?: number; sizeField?: string; spacing?: number; - stack?: ChartSeriesItemStack; + stack?: boolean|ChartSeriesItemStack; startAngle?: number; target?: ChartSeriesItemTarget; targetField?: string; @@ -9427,7 +9632,7 @@ declare namespace kendo.dataviz.ui { scatter?: any; scatterLine?: any; spacing?: number; - stack?: ChartSeriesDefaultsStack; + stack?: boolean|ChartSeriesDefaultsStack; type?: string; tooltip?: ChartSeriesDefaultsTooltip; verticalArea?: any; @@ -10357,8 +10562,8 @@ declare namespace kendo.dataviz.ui { } interface ChartZoomable { - mousewheel?: ChartZoomableMousewheel; - selection?: ChartZoomableSelection; + mousewheel?: boolean|ChartZoomableMousewheel; + selection?: boolean|ChartZoomableSelection; } interface ChartExportImageOptions { @@ -10397,7 +10602,7 @@ declare namespace kendo.dataviz.ui { dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; panes?: ChartPane[]; - pannable?: ChartPannable; + pannable?: boolean|ChartPannable; pdf?: ChartPdf; plotArea?: ChartPlotArea; renderAs?: string; @@ -10411,7 +10616,7 @@ declare namespace kendo.dataviz.ui { valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; - zoomable?: ChartZoomable; + zoomable?: boolean|ChartZoomable; axisLabelClick?(e: ChartAxisLabelClickEvent): void; legendItemClick?(e: ChartLegendItemClickEvent): void; legendItemHover?(e: ChartLegendItemHoverEvent): void; @@ -10422,6 +10627,7 @@ declare namespace kendo.dataviz.ui { noteClick?(e: ChartNoteClickEvent): void; noteHover?(e: ChartNoteHoverEvent): void; plotAreaClick?(e: ChartPlotAreaClickEvent): void; + plotAreaHover?(e: ChartPlotAreaHoverEvent): void; render?(e: ChartEvent): void; select?(e: ChartSelectEvent): void; selectEnd?(e: ChartSelectEndEvent): void; @@ -10508,6 +10714,15 @@ declare namespace kendo.dataviz.ui { y?: any; } + interface ChartPlotAreaHoverEvent extends ChartEvent { + category?: any; + element?: any; + originalEvent?: any; + value?: any; + x?: any; + y?: any; + } + interface ChartSelectEvent extends ChartEvent { axis?: any; from?: any; @@ -10571,9 +10786,9 @@ declare namespace kendo.dataviz.ui { options: DiagramOptions; dataSource: kendo.data.DataSource; - connections: DiagramConnection[]; + connections: kendo.dataviz.diagram.Connection[]; connectionsDataSource: kendo.data.DataSource; - shapes: DiagramShape[]; + shapes: kendo.dataviz.diagram.Shape[]; element: JQuery; wrapper: JQuery; @@ -10604,7 +10819,13 @@ declare namespace kendo.dataviz.ui { exportPDF(options?: kendo.drawing.PDFOptions): JQueryPromise; exportSVG(options: any): JQueryPromise; focus(): void; + getConnectionByModelId(id: string): kendo.dataviz.diagram.Connection; + getConnectionByModelId(id: number): kendo.dataviz.diagram.Connection; + getConnectionByModelUid(uid: string): kendo.dataviz.diagram.Connection; getShapeById(id: string): any; + getShapeByModelId(id: string): kendo.dataviz.diagram.Shape; + getShapeByModelId(id: number): kendo.dataviz.diagram.Shape; + getShapeByModelUid(uid: string): kendo.dataviz.diagram.Shape; layerToModel(point: any): any; layout(options: any): void; load(json: string): void; @@ -10643,6 +10864,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -10724,7 +10947,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnectionDefaults { content?: DiagramConnectionDefaultsContent; - editable?: DiagramConnectionDefaultsEditable; + editable?: boolean|DiagramConnectionDefaultsEditable; endCap?: DiagramConnectionDefaultsEndCap; fromConnector?: string; hover?: DiagramConnectionDefaultsHover; @@ -10740,6 +10963,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -10834,7 +11059,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnection { content?: DiagramConnectionContent; - editable?: DiagramConnectionEditable; + editable?: boolean|DiagramConnectionEditable; endCap?: DiagramConnectionEndCap; from?: DiagramConnectionFrom; fromConnector?: string; @@ -10853,7 +11078,7 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditableDrag { - snap?: DiagramEditableDragSnap; + snap?: boolean|DiagramEditableDragSnap; } interface DiagramEditableResizeHandlesFill { @@ -10917,10 +11142,10 @@ declare namespace kendo.dataviz.ui { interface DiagramEditable { connectionTemplate?: string|Function; - drag?: DiagramEditableDrag; + drag?: boolean|DiagramEditableDrag; remove?: boolean; - resize?: DiagramEditableResize; - rotate?: DiagramEditableRotate; + resize?: boolean|DiagramEditableResize; + rotate?: boolean|DiagramEditableRotate; shapeTemplate?: string|Function; tools?: DiagramEditableTool[]; } @@ -11067,6 +11292,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; } @@ -11127,7 +11354,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeDefaultsConnector[]; connectorDefaults?: DiagramShapeDefaultsConnectorDefaults; content?: DiagramShapeDefaultsContent; - editable?: DiagramShapeDefaultsEditable; + editable?: boolean|DiagramShapeDefaultsEditable; fill?: DiagramShapeDefaultsFill; height?: number; hover?: DiagramShapeDefaultsHover; @@ -11223,6 +11450,8 @@ declare namespace kendo.dataviz.ui { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; } @@ -11281,7 +11510,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeConnector[]; connectorDefaults?: DiagramShapeConnectorDefaults; content?: DiagramShapeContent; - editable?: DiagramShapeEditable; + editable?: boolean|DiagramShapeEditable; fill?: DiagramShapeFill; height?: number; hover?: DiagramShapeHover; @@ -11320,11 +11549,11 @@ declare namespace kendo.dataviz.ui { connections?: DiagramConnection[]; connectionsDataSource?: any|any|kendo.data.DataSource; dataSource?: any|any|kendo.data.DataSource; - editable?: DiagramEditable; + editable?: boolean|DiagramEditable; layout?: DiagramLayout; - pannable?: DiagramPannable; + pannable?: boolean|DiagramPannable; pdf?: DiagramPdf; - selectable?: DiagramSelectable; + selectable?: boolean|DiagramSelectable; shapeDefaults?: DiagramShapeDefaults; shapes?: DiagramShape[]; template?: string|Function; @@ -11385,16 +11614,19 @@ declare namespace kendo.dataviz.ui { } interface DiagramDragEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } interface DiagramDragEndEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } interface DiagramDragStartEvent extends DiagramEvent { + connectionHandle?: string; connections?: any; shapes?: any; } @@ -11700,9 +11932,9 @@ declare namespace kendo.dataviz.ui { } interface MapControls { - attribution?: MapControlsAttribution; - navigator?: MapControlsNavigator; - zoom?: MapControlsZoom; + attribution?: boolean|MapControlsAttribution; + navigator?: boolean|MapControlsNavigator; + zoom?: boolean|MapControlsZoom; } interface MapLayerDefaultsBing { @@ -11995,6 +12227,7 @@ declare namespace kendo.dataviz.ui { reset?(e: MapResetEvent): void; shapeClick?(e: MapShapeClickEvent): void; shapeCreated?(e: MapShapeCreatedEvent): void; + shapeFeatureCreated?(e: MapShapeFeatureCreatedEvent): void; shapeMouseEnter?(e: MapShapeMouseEnterEvent): void; shapeMouseLeave?(e: MapShapeMouseLeaveEvent): void; zoomStart?(e: MapZoomStartEvent): void; @@ -12056,6 +12289,13 @@ declare namespace kendo.dataviz.ui { originalEvent?: any; } + interface MapShapeFeatureCreatedEvent extends MapEvent { + dataItem?: any; + layer?: kendo.dataviz.map.layer.Shape; + group?: kendo.drawing.Group; + properties?: any; + } + interface MapShapeMouseEnterEvent extends MapEvent { layer?: kendo.dataviz.map.layer.Shape; shape?: kendo.drawing.Element; @@ -12773,7 +13013,7 @@ declare namespace kendo.dataviz.ui { size?: number; startAngle?: number; spacing?: number; - stack?: SparklineSeriesItemStack; + stack?: boolean|SparklineSeriesItemStack; tooltip?: SparklineSeriesItemTooltip; width?: number; target?: SparklineSeriesItemTarget; @@ -12836,7 +13076,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: SparklineSeriesDefaultsStack; + stack?: boolean|SparklineSeriesDefaultsStack; type?: string; tooltip?: SparklineSeriesDefaultsTooltip; } @@ -14041,7 +14281,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartNavigatorSeriesItemOverlay; spacing?: number; - stack?: StockChartNavigatorSeriesItemStack; + stack?: boolean|StockChartNavigatorSeriesItemStack; tooltip?: StockChartNavigatorSeriesItemTooltip; width?: number; } @@ -14311,7 +14551,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartSeriesItemOverlay; spacing?: number; - stack?: StockChartSeriesItemStack; + stack?: boolean|StockChartSeriesItemStack; tooltip?: StockChartSeriesItemTooltip; visibleInLegend?: boolean; width?: number; @@ -14376,7 +14616,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: StockChartSeriesDefaultsStack; + stack?: boolean|StockChartSeriesDefaultsStack; type?: string; tooltip?: StockChartSeriesDefaultsTooltip; } @@ -14702,6 +14942,7 @@ declare namespace kendo.dataviz.ui { noteClick?(e: StockChartNoteClickEvent): void; noteHover?(e: StockChartNoteHoverEvent): void; plotAreaClick?(e: StockChartPlotAreaClickEvent): void; + plotAreaHover?(e: StockChartPlotAreaHoverEvent): void; render?(e: StockChartEvent): void; seriesClick?(e: StockChartSeriesClickEvent): void; seriesHover?(e: StockChartSeriesHoverEvent): void; @@ -14782,6 +15023,15 @@ declare namespace kendo.dataviz.ui { y?: any; } + interface StockChartPlotAreaHoverEvent extends StockChartEvent { + category?: any; + element?: any; + originalEvent?: any; + value?: any; + x?: any; + y?: any; + } + interface StockChartSeriesClickEvent extends StockChartEvent { value?: any; category?: any; @@ -14920,7 +15170,7 @@ declare namespace kendo.dataviz.map { nw: kendo.dataviz.map.Location; se: kendo.dataviz.map.Location; - constructor(nw: kendo.dataviz.map.Location, se: kendo.dataviz.map.Location); + constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any); static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; @@ -15167,15 +15417,15 @@ declare namespace kendo.dataviz { range(): any; - slot(from: string, to?: string): kendo.geometry.Rect; - slot(from: string, to?: number): kendo.geometry.Rect; - slot(from: string, to?: Date): kendo.geometry.Rect; - slot(from: number, to?: string): kendo.geometry.Rect; - slot(from: number, to?: number): kendo.geometry.Rect; - slot(from: number, to?: Date): kendo.geometry.Rect; - slot(from: Date, to?: string): kendo.geometry.Rect; - slot(from: Date, to?: number): kendo.geometry.Rect; - slot(from: Date, to?: Date): kendo.geometry.Rect; + slot(from: string, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: string, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: string, to?: Date, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: number, to?: Date, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: string, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: number, limit?: boolean): kendo.geometry.Rect; + slot(from: Date, to?: Date, limit?: boolean): kendo.geometry.Rect; } @@ -15196,6 +15446,7 @@ declare namespace kendo.dataviz.diagram { options: CircleOptions; + drawingElement: kendo.drawing.Circle; constructor(options?: CircleOptions); @@ -15285,6 +15536,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; template?: string|Function; text?: string; visual?: Function; @@ -15425,6 +15678,7 @@ declare namespace kendo.dataviz.diagram { options: GroupOptions; + drawingElement: kendo.drawing.Group; constructor(options?: GroupOptions); @@ -15457,6 +15711,7 @@ declare namespace kendo.dataviz.diagram { options: ImageOptions; + drawingElement: kendo.drawing.Image; constructor(options?: ImageOptions); @@ -15489,6 +15744,7 @@ declare namespace kendo.dataviz.diagram { options: LayoutOptions; + drawingElement: kendo.drawing.Layout; constructor(rect: kendo.dataviz.diagram.Rect, options?: LayoutOptions); @@ -15526,6 +15782,7 @@ declare namespace kendo.dataviz.diagram { options: LineOptions; + drawingElement: kendo.drawing.Path; constructor(options?: LineOptions); @@ -15561,6 +15818,7 @@ declare namespace kendo.dataviz.diagram { options: PathOptions; + drawingElement: kendo.drawing.Path; constructor(options?: PathOptions); @@ -15680,6 +15938,7 @@ declare namespace kendo.dataviz.diagram { options: PolylineOptions; + drawingElement: kendo.drawing.Path; constructor(options?: PolylineOptions); @@ -15801,6 +16060,7 @@ declare namespace kendo.dataviz.diagram { options: RectangleOptions; + drawingElement: kendo.drawing.Path; constructor(options?: RectangleOptions); @@ -15873,6 +16133,7 @@ declare namespace kendo.dataviz.diagram { getConnector(): void; getPosition(side: string): void; redraw(options: any): void; + redrawVisual(): void; } @@ -15922,6 +16183,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; text?: string; } @@ -15972,7 +16235,7 @@ declare namespace kendo.dataviz.diagram { interface ShapeOptions { name?: string; id?: string; - editable?: ShapeEditable; + editable?: boolean|ShapeEditable; path?: string; stroke?: ShapeStroke; type?: string; @@ -16003,6 +16266,7 @@ declare namespace kendo.dataviz.diagram { options: TextBlockOptions; + drawingElement: kendo.drawing.Text; constructor(options?: TextBlockOptions); @@ -16022,6 +16286,8 @@ declare namespace kendo.dataviz.diagram { color?: string; fontFamily?: string; fontSize?: number; + fontStyle?: string; + fontWeight?: string; height?: number; text?: string; width?: number; @@ -16222,6 +16488,8 @@ declare namespace kendo.spreadsheet { isFilterable(): boolean; italic(): boolean; italic(value?: boolean): void; + link(): string; + link(url?: string): void; merge(): void; select(): void; sort(sort: number): void; @@ -16280,10 +16548,10 @@ declare namespace kendo.spreadsheet { rowHeight(): void; rowHeight(index: number, width?: number): void; selection(): kendo.spreadsheet.Range; + setDataSource(dataSource: kendo.data.DataSource, columns?: any): void; showGridLines(): boolean; showGridLines(showGridLiens?: boolean): void; toJSON(): void; - setDataSource(dataSource: kendo.data.DataSource, columns?: any): void; unhideColumn(index: number): void; unhideRow(index: number): void; @@ -16752,7 +17020,7 @@ declare namespace kendo.mobile.ui { style?: string; template?: string|Function; type?: string; - filterable?: ListViewFilterable; + filterable?: boolean|ListViewFilterable; virtualViewSize?: number; click?(e: ListViewClickEvent): void; dataBound?(e: ListViewEvent): void; @@ -17360,22 +17628,22 @@ declare namespace kendo.ooxml { interface WorkbookSheetRowCellBorderBottom { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderLeft { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderRight { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCellBorderTop { color?: string; - size?: string; + size?: number; } interface WorkbookSheetRowCell { @@ -17607,7 +17875,7 @@ declare namespace kendo.dataviz.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point, size: kendo.geometry.Size); + constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -17717,6 +17985,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Arc; geometry(value: kendo.geometry.Arc): void; fill(color: string, opacity?: number): kendo.drawing.Arc; @@ -17737,6 +18006,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17760,6 +18030,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Circle; geometry(value: kendo.geometry.Circle): void; fill(color: string, opacity?: number): kendo.drawing.Circle; @@ -17780,6 +18051,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17795,6 +18067,7 @@ declare namespace kendo.dataviz.drawing { options: ElementOptions; + parent: kendo.drawing.Group; constructor(options?: ElementOptions); @@ -17803,6 +18076,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; transform(): kendo.geometry.Transformation; @@ -17907,6 +18181,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; insert(position: number, element: kendo.drawing.Element): void; opacity(): number; opacity(opacity: number): void; @@ -17923,6 +18198,7 @@ declare namespace kendo.dataviz.drawing { cursor?: string; opacity?: number; pdf?: kendo.drawing.PDFOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -17946,6 +18222,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; opacity(): number; opacity(opacity: number): void; src(): string; @@ -17964,6 +18241,7 @@ declare namespace kendo.dataviz.drawing { clip?: kendo.drawing.Path; cursor?: string; opacity?: number; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18053,6 +18331,7 @@ declare namespace kendo.dataviz.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.MultiPath; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.MultiPath; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.MultiPath; @@ -18085,6 +18364,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18158,6 +18438,7 @@ declare namespace kendo.dataviz.drawing { clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; close(): kendo.drawing.Path; + containsPoint(point: kendo.geometry.Point): boolean; curveTo(controlOut: any, controlIn: any, endPoint: any): kendo.drawing.Path; curveTo(controlOut: any, controlIn: any, endPoint: kendo.geometry.Point): kendo.drawing.Path; curveTo(controlOut: any, controlIn: kendo.geometry.Point, endPoint: any): kendo.drawing.Path; @@ -18190,6 +18471,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18246,6 +18528,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; geometry(): kendo.geometry.Rect; geometry(value: kendo.geometry.Rect): void; fill(color: string, opacity?: number): kendo.drawing.Rect; @@ -18266,6 +18549,7 @@ declare namespace kendo.dataviz.drawing { fill?: kendo.drawing.FillOptions; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18336,18 +18620,43 @@ declare namespace kendo.dataviz.drawing { clear(): void; draw(element: kendo.drawing.Element): void; eventTarget(e: any): kendo.drawing.Element; + hideTooltip(): void; resize(force?: boolean): void; + showTooltip(element: kendo.drawing.Element, options?: any): void; } + interface SurfaceTooltipAnimationClose { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimationOpen { + effects?: string; + duration?: number; + } + + interface SurfaceTooltipAnimation { + close?: SurfaceTooltipAnimationClose; + open?: SurfaceTooltipAnimationOpen; + } + + interface SurfaceTooltip { + animation?: boolean|SurfaceTooltipAnimation; + appendTo?: string|JQuery; + } + interface SurfaceOptions { name?: string; type?: string; height?: string; width?: string; + tooltip?: SurfaceTooltip; click?(e: SurfaceClickEvent): void; mouseenter?(e: SurfaceMouseenterEvent): void; mouseleave?(e: SurfaceMouseleaveEvent): void; + tooltipClose?(e: SurfaceTooltipCloseEvent): void; + tooltipOpen?(e: SurfaceTooltipOpenEvent): void; } interface SurfaceEvent { sender: Surface; @@ -18370,6 +18679,16 @@ declare namespace kendo.dataviz.drawing { originalEvent?: any; } + interface SurfaceTooltipCloseEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + + interface SurfaceTooltipOpenEvent extends SurfaceEvent { + element?: kendo.drawing.Element; + target?: kendo.drawing.Element; + } + class Text extends kendo.drawing.Element { @@ -18384,6 +18703,7 @@ declare namespace kendo.dataviz.drawing { clip(): kendo.drawing.Path; clip(clip: kendo.drawing.Path): void; clippedBBox(): kendo.geometry.Rect; + containsPoint(point: kendo.geometry.Point): boolean; content(): string; content(value: string): void; fill(color: string, opacity?: number): kendo.drawing.Text; @@ -18407,6 +18727,7 @@ declare namespace kendo.dataviz.drawing { font?: string; opacity?: number; stroke?: kendo.drawing.StrokeOptions; + tooltip?: kendo.drawing.TooltipOptions; transform?: kendo.geometry.Transformation; visible?: boolean; } @@ -18417,6 +18738,28 @@ declare namespace kendo.dataviz.drawing { } + interface TooltipOptions { + + + + autoHide?: boolean; + content?: string|Function; + position?: string; + height?: number|string; + hideDelay?: number; + offset?: number; + shared?: boolean; + showAfter?: number; + showOn?: string; + width?: number|string; + + + + + } + + + } interface HTMLElement { @@ -18501,6 +18844,10 @@ interface JQuery { kendoEditor(options: kendo.ui.EditorOptions): JQuery; data(key: "kendoEditor"): kendo.ui.Editor; + kendoFilterMenu(): JQuery; + kendoFilterMenu(options: kendo.ui.FilterMenuOptions): JQuery; + data(key: "kendoFilterMenu"): kendo.ui.FilterMenu; + kendoFlatColorPicker(): JQuery; kendoFlatColorPicker(options: kendo.ui.FlatColorPickerOptions): JQuery; data(key: "kendoFlatColorPicker"): kendo.ui.FlatColorPicker; diff --git a/kii-cloud-sdk/kii-cloud-sdk-tests.ts b/kii-cloud-sdk/kii-cloud-sdk-tests.ts index a7118d78d3..6ca7d611db 100644 --- a/kii-cloud-sdk/kii-cloud-sdk-tests.ts +++ b/kii-cloud-sdk/kii-cloud-sdk-tests.ts @@ -26,6 +26,9 @@ function main() { endpoint.installationID; }); + user.setLocale("en"); + var locale: string = user.getLocale(); + var anotherUser: KiiUser = KiiUserBuilder .builderWithIdentifier("id", "password") .setEmailAddress("mail@example.org") @@ -67,4 +70,30 @@ function main() { removeMembersArray: KiiUser[]) { } }); + + Kii.authenticateAsThing("thing id", "password", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + Kii.authenticateAsThingWithToken("thing id", "token", { + success: function (thingAuthContext: KiiThingContext) { + thingAuthContext.bucketWithName(""); + }, + failure: function (error) { + } + }) + .then(function (thingAuthContext: KiiThingContext) { + }); + + KiiThing.loadWithVendorThingID("thing ID") + .then(function (thing) { + var isOnline: boolean = thing.isOnline(); + var onlineStatusModifiedAt: Date = thing.getOnlineStatusModifiedAt(); + }); } diff --git a/kii-cloud-sdk/kii-cloud-sdk.d.ts b/kii-cloud-sdk/kii-cloud-sdk.d.ts index 970061e8d1..26decd07a0 100644 --- a/kii-cloud-sdk/kii-cloud-sdk.d.ts +++ b/kii-cloud-sdk/kii-cloud-sdk.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kii Cloud SDK v2.4.3 +// Type definitions for Kii Cloud SDK v2.4.6 // Project: http://en.kii.com/ // Definitions by: Kii Consortium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,7 +17,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } export enum KiiAnalyticsSite { @@ -25,7 +26,8 @@ declare namespace KiiCloud { JP, CN, SG, - CN3 + CN3, + EU } enum KiiSocialNetworkName { @@ -512,6 +514,104 @@ declare namespace KiiCloud { * ); */ static listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Authenticate as Thing. + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param vendorThingID vendorThingID of a registered Thing. + * @param password password for the registered Thing. + * @param callbacks The callback methods called when authentication succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingAuthContext). thingAuthContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThing("vendor thing id", "password of this thing", { + * success: function(thingAuthContext) { + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * }, + * failure: function(error) { + * // Authentication failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThing("vendor thing id", "password of this thing").then( + * function(thingAuthContext) { // fulfill callback function + * // thingAuthContext : KiiThingContext instance + * // Operate entities with thingAuthContext. + * + * }, + * function(error) { // reject callback function + * // Authentication failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThing(vendorThingID: string, password: string, callbacks?: { success(thingAuthContext: KiiThingContext): any; failure(error: Error): any; }): Promise; + + /** + * Create a KiiThingContext reference + *

+ * This api is intended to be used in a Thing device, where the user + * credentials or app admin context is not configured. This Thing must be + * already registered in Kii Cloud. + * + * + * @param thingID thingID of a registered Thing. + * @param token token for the registered Thing. + * @param callbacks The callback methods called when creation succeeded/failed. + * + * @return return promise object. + *
    + *
  • fulfill callback function: function(thingContext). thingContext is a KiiThingContext instance.
  • + *
  • reject callback function: function(error). error is an Error instance. + *
      + *
    • error.message
    • + *
    + *
  • + *
+ * + * @example + * // example to use callbacks directly + * Kii.authenticateAsThingWithToken("thing_id", "thing_token", { + * success: function(thingContext) { + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * }, + * failure: function(error) { + * // Creation failed. + * } + * ); + * + * // example to use Promise + * Kii.authenticateAsThingWithToken("thing_id", "thing_token").then( + * function(thingContext) { // fulfill callback function + * // thingContext : KiiThingContext instance + * // Operate entities with thingContext. + * + * }, + * function(error) { // reject callback function + * // Creation failed. + * var errorString = error.message; + * } + * ); + */ + static authenticateAsThingWithToken(thingID: string, token: string, callbacks?: { success(thingContext: KiiThingContext): any; failure(error: Error): any; }): Promise; } /** @@ -3744,7 +3844,7 @@ declare namespace KiiCloud { *
  • response.username is username to use for connecting to the MQTT broker.
  • *
  • response.password is assword to use for connecting to the MQTT broker.
  • *
  • response.mqttTopic is topic to subscribe in the MQTT broker.
  • - *
  • response.host is URL of the MQTT broker host to connect.
  • + *
  • response.host is hostname of the MQTT broker.
  • *
  • response.X-MQTT-TTL is the amount of time in seconds that specifies how long the mqttTopic will be valid, after that the client needs to request new MQTT endpoint info.
  • *
  • response.portTCP is port to connect using plain TCP.
  • *
  • response.portSSL is port to connect using SSL/TLS.
  • @@ -4986,6 +5086,20 @@ declare namespace KiiCloud { */ getDisabled(): boolean; + /** + * Get online status of the thing. + * + * @return true if the thing is online, false otherwise. The return value will be null initially until the thing is connected for the first time. + */ + isOnline(): boolean; + + /** + * Get online status modified date of the thing. + * + * @return online status modified time of this thing. The date will be null initially until the thing is connected for the first time. + */ + getOnlineStatusModifiedAt(): Date; + /** * Register thing in KiiCloud.
    * This API doesnt require users login Anonymous user can register thing. @@ -5794,6 +5908,156 @@ declare namespace KiiCloud { pushSubscription(): KiiPushSubscription; } + /** + * represents a KiiThingContext object + */ + export class KiiThingContext { + /** + * Creates a reference to a bucket in App scope operated by thing. + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.bucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + bucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to a encrypted bucket in App scope operated by thing. + *

    The bucket will be created/accessed within this app's scope + * + * @param bucketName The name of the bucket the app should create/access + * + * @return A working KiiBucket object + * + * @example + * Kii.authenticateAsThing("vendorThingID", "password", { + * success: function(thingAuthContext) { + * var bucket = thingAuthContext.encryptedBucketWithName("myAppBucket"); + * }, + * failure: function(errorString, errorCode) { + * // auth failed. + * } + * }); + */ + encryptedBucketWithName(bucketName: string): KiiBucket; + + /** + * Creates a reference to an object operated by thing using object`s URI. + * + * @param object URI. + * + * @return A working KiiObject instance + * + * @throws If the URI is null, empty or does not have correct format. + */ + objectWithURI(object: string): KiiObject; + + /** + * Creates a reference to a topic in App scope operated by thing. + *

    The Topic will be created/accessed within this app's scope + * + * @param topicName name of the topic. Must be a not empty string. + * + * @return topic instance. + */ + topicWithName(topicName: string): KiiTopic; + + /** + * Gets a list of topics in app scope + * + * @param callbacks An object with callback methods defined + * @param paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified. + * + * @return return promise object. + *
      + *
    • fulfill callback function: function(params). params is Array instance. + *
        + *
      • params[0] is array of KiiTopic instances.
      • + *
      • params[1] is string of nextPaginationKey.
      • + *
      + *
    • + *
    • reject callback function: function(error). error is an Error instance. + *
        + *
      • error.target is a KiiAppAdminContext instance which this method was called on.
      • + *
      • error.message
      • + *
      + *
    • + *
    + * + * @example + * // example to use callbacks directly + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) { + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics({ + * success: function(topicList, nextPaginationKey) {...}, + * failure: function(anErrorString) {...} + * }, nextPaginationKey); + * } + * }, + * failure: function(anErrorString) { + * // do something with the error response + * } + * }); + * + * // example to use Promise + * // Assume you already have thingAuthContext instance. + * thingAuthContext.listTopics().then( + * function(params) { + * var topicList = params[0]; + * var nextPaginationKey = params[1]; + * // do something with the result + * for(var i=0; i<topicList.length; i++){ + * var topic = topicList[i]; + * } + * if (nextPaginationKey != null) { + * thingAuthContext.listTopics(null, nextPaginationKey).then( + * function(params) {...}, + * function(error) {...} + * ); + * } + * }, + * function(error) { + * // do something with the error response + * } + * ); + */ + listTopics(callbacks?: { success(topicList: KiiTopic[], nextPaginationKey: string): any; failure(anErrorString: string): any; }, paginationKey?: string): Promise<[KiiTopic[], string]>; + + /** + * Gets authenticated KiiThing instance. + *
    Returned thing instance only have thingID, vendorThingID and accessToken. + * (vendorThingID is not included when you used + * {@link Kii.authenticateAsThingWithToken()} to obtain KiiThingContext.) + *
    Please execute {@link KiiThing#refresh()} to obtain other properties. + * + * @return return authenticated KiiThing instance. + */ + getAuthenticatedThing(): KiiThing; + + /** + * Instantiate push installation for this thing. + * + * @return push installation object. + */ + pushInstallation(): KiiPushInstallation; + } + /** * Represents a Topic object. */ @@ -6059,6 +6323,18 @@ declare namespace KiiCloud { */ getEmailAddress(): string; + /** + * Get the email of this user that has not been verified. + * When the user's email has been changed and email verification is required in you app configuration, + * New email is stored as pending email. + * After the new email has been verified, the address can be obtained by {@link KiiUser.getEmailAddress} + * + * @return User's new email address has not been verified. + * null if no pending email field is included in refresh + * response or undefined when no refresh operation has been done before. + */ + getPendingEmailAddress(): string; + /** * Get the phone number associated with this user * @@ -6066,6 +6342,18 @@ declare namespace KiiCloud { */ getPhoneNumber(): string; + /** + * Get the phone of this user that has not been verified. + * When the user's phone has been changed and phone verification is required in you app configuration, + * New phone is stored as pending phone. + * After the new phone has been verified, the address can be obtained by {@link KiiUser.getPhoneNumber} + * + * @return User's new phone number has not been verified. + * null if no pending phone field is included in refresh + * response or undefined when no refresh operation has been done before. + */ + getPendingPhoneNumber(): string; + /** * Get the country code associated with this user * @@ -6082,6 +6370,25 @@ declare namespace KiiCloud { */ setCountry(value: string): void; + /** + * Get the locale associated with this user + * + * @return + */ + getLocale(): string; + + /** + * Set the locale associated with this user + * The locale argument must be BCP 47 language tag. + * Examples: + * "en": English + * "de-AT": German as used in Austria. + * "zh-Hans-CN": Chinese written in simplified characters as used in China. + * + * @param value The locale to set. + */ + setLocale(value: string): void; + /** * Get the server's creation date of this user * @@ -6172,7 +6479,7 @@ declare namespace KiiCloud { /** * Sets a key/value pair to a KiiUser * - *

    If the key already exists, its value will be written over. If the object is of invalid type, it will return false and a KiiError will be thrown (quietly). Accepted types are any JSON-encodable objects. + *

    If the key already exists, its value will be written over. If key is empty or starting with '_', it will do nothing. Accepted types are any JSON-encodable objects. * * @param key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_) * @param value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc) @@ -7126,7 +7433,12 @@ declare namespace KiiCloud { ownerOfGroups(callbacks?: { success(theUser: KiiUser, groupList: KiiGroup[]): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise<[KiiUser, KiiGroup[]]>; /** - * Updates the user's phone number on the server + * Change phone number of logged in user. + * If the phone number verification is required by your app configuration, + * User's phone number would not changed to new one until the new phone number verification has been done. + * In this case, new phone can be obtained by {@link KiiUser#getPendingPhoneNumber()}. + * This API does not refresh the KiiUser automatically. + * Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getPhoneNumber()} or {@link KiiUser#getPendingPhoneNumber()}. * * @param newPhoneNumber The new phone number to change to * @param callbacks An object with callback methods defined @@ -7169,7 +7481,12 @@ declare namespace KiiCloud { changePhone(newPhoneNumber: string, callbacks?: { success(theUser: KiiUser): any; failure(theUser: KiiUser, anErrorString: string): any; }): Promise; /** - * Updates the user's email address on the server + * Change email of logged in user. + * If the email address verification is required by your app configuration, + * User's email would not changed to new one until the new email verification has been done. + * In this case, new mail address can be obtained by {@link KiiUser#getPendingEmailAddress()}. + * This API does not refresh the KiiUser automatically. + * Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getEmailAddress()} or {@link KiiUser#getPendingEmailAddress()} * * @param newEmail The new email address to change to * @param callbacks An object with callback methods defined @@ -7792,6 +8109,7 @@ import KiiServerCodeEntry = KiiCloud.KiiServerCodeEntry; import KiiServerCodeExecResult = KiiCloud.KiiServerCodeExecResult; import KiiSocialConnect = KiiCloud.KiiSocialConnect; import KiiThing = KiiCloud.KiiThing; +import KiiThingContext = KiiCloud.KiiThingContext; import KiiTopic = KiiCloud.KiiTopic; import KiiUser = KiiCloud.KiiUser; import KiiUserBuilder = KiiCloud.KiiUserBuilder; diff --git a/knex/knex-tests.ts b/knex/knex-tests.ts index e983ec1084..c01c54691e 100644 --- a/knex/knex-tests.ts +++ b/knex/knex-tests.ts @@ -1,8 +1,10 @@ /// + /// -import Knex = require('knex'); -import _ = require('lodash'); -'use strict'; + +import * as Knex from 'knex'; +import * as _ from 'lodash'; + // Initializing the Library var knex = Knex({ client: 'sqlite3', @@ -160,6 +162,8 @@ knex.select('*').from('users').join('accounts', function() { knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); +knex.raw('select * from users where id = :user_id', { user_id: 1 }); + knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); @@ -594,8 +598,8 @@ knex.migrate.latest(); knex.migrate.rollback(config); knex.migrate.rollback(); -knex.migrate.currentversion(config); -knex.migrate.currentversion(); +knex.migrate.currentVersion(config); +knex.migrate.currentVersion(); knex.seed.make(name, config); knex.seed.make(name); diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 5aa1a46d18..e5d796350c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date; + type Value = string|number|boolean|Date|Array|Array|Array|Array; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; interface Knex extends Knex.QueryInterface { @@ -28,9 +28,10 @@ declare module "knex" { schema: Knex.SchemaBuilder; client: any; - migrate: any; + migrate: Knex.Migrator; seed: any; fn: any; + on(eventName: string, callback: Function): Knex.QueryBuilder; } function Knex(config: Knex.Config) : Knex; @@ -127,7 +128,7 @@ declare module "knex" { insert(data: any, returning?: string | string[]): QueryBuilder; update(data: any, returning?: string | string[]): QueryBuilder; update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; - returning(column: string): QueryBuilder; + returning(column: string | string[]): QueryBuilder; del(returning?: string | string[]): QueryBuilder; delete(returning?: string | string[]): QueryBuilder; @@ -249,6 +250,7 @@ declare module "knex" { (value: Value): Raw; (sql: string, ...bindings: Value[]): Raw; (sql: string, bindings: Value[]): Raw; + (sql: string, bindings: Object): Raw; } // @@ -301,8 +303,9 @@ declare module "knex" { interface SchemaBuilder extends Promise { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; + createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; - dropTable(tableName: string): Promise; + dropTable(tableName: string): SchemaBuilder; hasTable(tableName: string): Promise; hasColumn(tableName: string, columnName: string): Promise; table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Promise; @@ -312,6 +315,7 @@ declare module "knex" { interface TableBuilder { increments(columnName?: string): ColumnBuilder; + bigIncrements(columnName?: string): ColumnBuilder; dropColumn(columnName: string): TableBuilder; dropColumns(...columnNames: string[]): TableBuilder; renameColumn(from: string, to: string): ColumnBuilder; @@ -370,15 +374,15 @@ declare module "knex" { nullable(): ColumnBuilder; comment(value: string): ColumnBuilder; } - + interface ForeignConstraintBuilder { references(columnName: string): ReferencingColumnBuilder; } - + interface MultikeyForeignConstraintBuilder { references(columnNames: string[]): ReferencingColumnBuilder; } - + interface PostgreSqlColumnBuilder extends ColumnBuilder { index(indexName?: string, indexType?: string): ColumnBuilder; } @@ -413,7 +417,7 @@ declare module "knex" { connection?: string|ConnectionConfig|MariaSqlConnectionConfig| Sqlite3ConnectionConfig|SocketConnectionConfig; pool?: PoolConfig; - migrations?: MigrationConfig; + migrations?: MigratorConfig; } interface ConnectionConfig { @@ -487,12 +491,20 @@ declare module "knex" { log?: boolean; } - interface MigrationConfig { + interface MigratorConfig { database?: string; directory?: string; extension?: string; tableName?: string; } + + interface Migrator { + make(name:string, config?: MigratorConfig):Promise; + latest(config?: MigratorConfig):Promise; + rollback(config?: MigratorConfig):Promise; + status(config?: MigratorConfig):Promise; + currentVersion(config?: MigratorConfig):Promise; + } } export = Knex; diff --git a/knockout.es5/knockout.es5.d.ts b/knockout.es5/knockout.es5.d.ts index 06309059ef..10e0054bf6 100644 --- a/knockout.es5/knockout.es5.d.ts +++ b/knockout.es5/knockout.es5.d.ts @@ -6,10 +6,10 @@ /// interface KnockoutStatic { - track(obj: any, propertyNames?: Array): any; - untrack(obj: any, propertyNames?: Array): any; - defineProperty(obj: any, propertyName: string, evaluator: Function): any; - defineProperty(obj: any, propertyName: string, options: KnockoutDefinePropertyOptions): any; + track(obj: T, propertyNames?: Array): T; + untrack(obj: any, propertyNames?: Array): void; + defineProperty(obj: T, propertyName: string, evaluator: Function): T; + defineProperty(obj: T, propertyName: string, options: KnockoutDefinePropertyOptions): T; getObservable(obj: any, propertyName: string): KnockoutObservable; valueHasMutated(obj: any, propertyName: string): void; } diff --git a/knockout.kogrid/ko-grid.d.ts b/knockout.kogrid/ko-grid.d.ts index cc10fa4d9e..a8f3984acf 100644 --- a/knockout.kogrid/ko-grid.d.ts +++ b/knockout.kogrid/ko-grid.d.ts @@ -6,188 +6,274 @@ // These are very definitely preliminary. Please feel free to improve. /// +/// declare namespace kg { - export interface DomUtilityService { - UpdateGridLayout(grid: Grid): void; - BuildStyles(grid: Grid): void; - } + interface DomUtilityService { + UpdateGridLayout(grid: Grid): void; + BuildStyles(grid: Grid): void; + } - var domUtilityService: DomUtilityService; + interface Row { + selected: KnockoutObservable; + entity: EntityType; + } - export interface Row { - selected: KnockoutObservable; - entity: EntityType; - } + interface RowFactory { + rowCache: Row[]; + } - export interface RowFactory { - rowCache: Row[]; - } + interface SelectionService { + setSelection(row: Row, selected: boolean): void; + multi: boolean; + lastClickedRow: Row; + } - export interface SelectionService { - setSelection(row: Row, selected: boolean): void; - multi: boolean; - lastClickedRow: Row; - } + interface Grid { + configureColumnWidths(): void; + rowFactory: RowFactory; + config: GridOptions; + $$selectionPhase: boolean; + selectionService: SelectionService; + } - export interface Grid { - configureColumnWidths(): void; - rowFactory: RowFactory; - config: GridOptions; - $$selectionPhase: boolean; - selectionService: SelectionService; - } + interface Plugin { + onGridInit(grid: Grid): void; + } - export interface Plugin { - onGridInit(grid: Grid): void; - } + interface GridOptions { + /** Callback for when you want to validate something after selection. */ + afterSelectionChange?(row: Row): void; - export interface GridOptions { - /** Callback for when you want to validate something after selection. */ - afterSelectionChange?(row: Row): void; + /** Callback if you want to inspect something before selection, + return false if you want to cancel the selection. return true otherwise. + If you need to wait for an async call to proceed with selection you can + use rowItem.changeSelection(event) method after returning false initially. + Note: when shift+ Selecting multiple items in the grid this will only get called + once and the rowItem will be an array of items that are queued to be selected. */ + beforeSelectionChange?(row: Row): boolean; - /** Callback if you want to inspect something before selection, - return false if you want to cancel the selection. return true otherwise. - If you need to wait for an async call to proceed with selection you can - use rowItem.changeSelection(event) method after returning false initially. - Note: when shift+ Selecting multiple items in the grid this will only get called - once and the rowItem will be an array of items that are queued to be selected. */ - beforeSelectionChange?: Function; + /** To be able to have selectable rows in grid. */ + canSelectRows?:boolean; - /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ - columnDefs?: ColumnDef[]; + /** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */ + columnDefs?: ColumnDef[] | KnockoutObservable; - /** Column width of columns in grid. */ - columnWidth?: number; + /** Column width of columns in grid. */ + columnWidth?: number; - /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ - data?: KnockoutObservableArray; + /** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */ + data?: KnockoutObservableArray; - /** Row selection check boxes appear as the first column. */ - displaySelectionCheckbox: boolean; + /** Row selection check boxes appear as the first column. */ + displaySelectionCheckbox: boolean; - /** Enable or disable resizing of columns */ - enableColumnResize?: boolean; + /** Enable or disable resizing of columns */ + enableColumnResize?: boolean; - /** Enables the server-side paging feature */ - enablePaging?: boolean; + /** Enables the server-side paging feature */ + enablePaging?: boolean; - /** Enable column pinning */ - enablePinning?: boolean; + /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ + enableRowReordering?: boolean; - /** Enable drag and drop row reordering. Only works in HTML5 compliant browsers. */ - enableRowReordering?: boolean; + /** Enables or disables sorting in grid. */ + enableSorting?: boolean; - /** To be able to have selectable rows in grid. */ - enableRowSelection?: boolean; + /** filterOptions - + filterText: The text bound to the built-in search box. + useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. + */ + filterOptions?: FilterOptions; - /** Enables or disables sorting in grid. */ - enableSorting?: boolean; + /** Defining the height of the footer in pixels. */ + footerRowHeight?: number; - /** filterOptions - - filterText: The text bound to the built-in search box. - useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box. - */ - filterOptions?: FilterOptions; + /** Show or hide the footer alltogether the footer is enabled by default */ + footerVisible?: boolean; - /** Defining the height of the footer in pixels. */ - footerRowHeight?: number; + /** Initial fields to group data by. Array of field names, not displayName. */ + groups?: string[]; - /** Show or hide the footer alltogether the footer is enabled by default */ - footerVisible?: boolean; + /** The height of the header row in pixels. */ + headerRowHeight?: number; - /** Initial fields to group data by. Array of field names, not displayName. */ - groups?: string[]; + /** Define a header row template for further customization. See github wiki for more details. */ + headerRowTemplate?: string | JQueryGenericPromise; - /** The height of the header row in pixels. */ - headerRowHeight?: number; + /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. + Useful if you want drag + drop but your users insist on crappy browsers. */ + jqueryUIDraggable?: boolean; - /** Define a header row template for further customization. See github wiki for more details. */ - headerRowTemplate?: any; + /** Enable the use jqueryUIThemes */ + jqueryUITheme?: boolean; - /** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled. - Useful if you want drag + drop but your users insist on crappy browsers. */ - jqueryUIDraggable?: boolean; + /** Prevent unselections when in single selection mode. */ + keepLastSelected?: boolean; - /** Enable the use jqueryUIThemes */ - jqueryUITheme?: boolean; + /** Maintains the column widths while resizing. + Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ + maintainColumnRatios?: any; - /** Prevent unselections when in single selection mode. */ - keepLastSelected?: boolean; + /** Set this to false if you only want one item selected at a time */ + multiSelect?: boolean; - /** Maintains the column widths while resizing. - Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */ - maintainColumnRatios?: any; + /** pagingOptions - */ + pagingOptions?: PagingOptions; - /** Set this to false if you only want one item selected at a time */ - multiSelect?: boolean; + /** Array of plugin functions to register in ng-grid */ + plugins?: Plugin[]; - /** pagingOptions - */ - pagingOptions?: PagingOptions; + /** Row height of rows in grid. */ + rowHeight?: number; - /** Array of plugin functions to register in ng-grid */ - plugins?: Plugin[]; + /** Define a row template to customize output. See github wiki for more details. */ + rowTemplate?: string | JQueryGenericPromise; - /** Row height of rows in grid. */ - rowHeight?: number; + /** Defines the binding to select all at once */ + selectAllState?: KnockoutObservable; - /** Define a row template to customize output. See github wiki for more details. */ - rowTemplate?: any; + /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ + selectedItems?: KnockoutObservableArray; - /** all of the items selected in the grid. In single select mode there will only be one item in the array. */ - selectedItems?: KnockoutObservableArray; + /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ + selectWithCheckboxOnly?: boolean; - /** Disable row selections by clicking on the row and only when the checkbox is clicked. */ - selectWithCheckboxOnly?: boolean; + /** Enables menu to choose which columns to display and group by. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showColumnMenu?: boolean; - /** Enables menu to choose which columns to display and group by. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showColumnMenu?: boolean; + /** Enables display of the filterbox in the column menu. + If both showColumnMenu and showFilter are false the menu button will not display.*/ + showFilter?: boolean; - /** Enables display of the filterbox in the column menu. - If both showColumnMenu and showFilter are false the menu button will not display.*/ - showFilter?: boolean; + /** Show the dropzone for drag and drop grouping */ + showGroupPanel?: boolean; - /** Show the dropzone for drag and drop grouping */ - showGroupPanel?: boolean; + /** Define a sortInfo object to specify a default sorting state. + You can also observe this variable to utilize server-side sorting (see useExternalSorting). + Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ + sortInfo?: SortInfo | KnockoutObservable; - /** Define a sortInfo object to specify a default sorting state. - You can also observe this variable to utilize server-side sorting (see useExternalSorting). - Syntax is sortinfo: { fields: ['fieldName1',' fieldName2'], direction: 'ASC'/'asc' || 'desc'/'DESC'}*/ - sortInfo?: any; + /** Set the tab index of the Vieport. */ + tabIndex?: number; - /** Set the tab index of the Vieport. */ - tabIndex?: number; + /** Prevents the internal sorting from executing. + The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ + useExternalSorting?: boolean; + } - /** Prevents the internal sorting from executing. - The sortInfo object will be updated with the sorting information so you can handle sorting (see sortInfo)*/ - useExternalSorting?: boolean; - } + type Direction = "asc" | "desc"; - export interface ColumnDef { - /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ - field: string; + interface SortInfo { + /** Which column to sort */ + column: SortColumn; - /** Sets the pretty display name of the column. default is the field given */ - displayName?: string; + /** Which direction to sort */ + direction: Direction; + } + + interface SortColumn { + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; - /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ - width?: string; - } + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortingAlgorithm?: ((a:any, b:any) => number); + } - export interface FilterOptions { - filterText?: string; - useExternalFilter?: boolean; - } + interface ColumnDef { + /** Appends a css class for the column cells */ + cellClass?:string; - export interface PagingOptions { - /** pageSizes: list of available page sizes. */ - pageSizes?: number[]; - /** pageSize: currently selected page size. */ - pageSize?: number; - /** totalServerItems: Total items are on the server. */ - totalServerItems?: number; - /** currentPage: the uhm... current page. */ - currentPage?: number; - } + /** + * A function which takes the value of the cell and returns the display value. Useful when your data model has an underlying value which you need to convert to a human readable format. + * @param val + * @returns the display value + * @example function(unixTimeTicks) { return new Date(unixTimeTicks); } + */ + cellFormatter?(val:any): string; + + /**Sets the cell template for the column. See github wiki for more details.*/ + cellTemplate?: string | JQueryGenericPromise; + + /** Sets the pretty display name of the column. default is the field given */ + displayName?: string; + + /** The string name of the property in your data model you want that column to represent. Can also be a property path on your data model. 'foo.bar.myField', 'Name.First', etc.. */ + field: string; + + /** Sets the template for the column header cell. See github wiki for more details. */ + headerCellTemplate?: string | JQueryGenericPromise; + + /** Appends a css class for the column header. */ + headerClass?: string; + + /**Sets the maximum width of the column.*/ + maxWidth?: number; + + /**Whether or not column is resizable. */ + resizable?: boolean; + + /**Whether or not column is sortable. */ + sortable?: boolean; + + /** Sets the sort function for the column. Useful when you have data that is formatted in an unusal way or if you want to sort on an underlying data type. Example: function(a,b){return a > b} */ + sortFn?: ((a: any, b: any) => number); + + /** Sets the width of the column. Can be a fixed width in pixels as an int (42), string px('42px'), percentage string ('42%'), weighted asterisks (width divided by total number of *'s is all column definition widths) See github wiki for more details. */ + width?: string; + } + + interface FilterOptions { + /** Variable to contain the current search filter */ + filterText?: KnockoutObservable; + + /** Is the filtering internal or does it require a server visit. You should subscribe to filterText to refresh */ + useExternalFilter?: boolean; + + /** Number of seconds to throttle before reapplying search */ + filterThrottle?: number; + } + + interface PagingOptions { + /** pageSizes: list of available page sizes. */ + pageSizes?: KnockoutObservableArray; + + /** pageSize: currently selected page size. */ + pageSize?: KnockoutObservable; + + /** totalServerItems: Total items are on the server. */ + totalServerItems?: KnockoutObservable; + + /** currentPage: the uhm... current page. */ + currentPage?: KnockoutObservable; + } +} + +interface IKg { + domUtilityService: kg.DomUtilityService; + + /** Default grid template */ + defaultGridTemplate():string; + + /** Default row template. Can be overriden in GridOptions.rowTemplate */ + defaultRowTemplate(): string; + + /** Default cell template. Can be overriden in GridOptions.cellTemplate */ + defaultCellTemplate(): string; + + /** Default aggregate template */ + aggregateTemplate(): string; + + /** Default headerrow template. Can be overriden in GridOptions.headerRowTemplate */ + defaultHeaderRowTemplate(): string; + + /** Default headercell template. Can be overriden in GridOptions.headerCellTemplate */ + defaultHeaderCellTemplate():string; +} + +declare var kg: IKg; + +declare module "kg" { + export = kg; } diff --git a/koa/koa-tests.ts b/koa/koa-tests.ts index e984364973..71814fe4fc 100644 --- a/koa/koa-tests.ts +++ b/koa/koa-tests.ts @@ -9,6 +9,7 @@ app.use((ctx, next) => { const end: any = new Date(); const ms = end - start; console.log(`${ctx.method} ${ctx.url} - ${ms}ms`); + ctx.assert(true, 404, 'Yep!'); }); }); diff --git a/koa/koa.d.ts b/koa/koa.d.ts index 922b243511..b005067b1f 100644 --- a/koa/koa.d.ts +++ b/koa/koa.d.ts @@ -38,7 +38,7 @@ declare module "koa" { toJSON(): any; inspect(): any; throw(code?: any, message?: any): void; - assert(): void; + assert(test: any, status: number, message: string): void; } export interface Request { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index c9a3140fda..7d8757be03 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -51,9 +51,10 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. + * Decreasing will make more, smaller clusters. You can also use a function that accepts + * the current map zoom and returns the maximum cluster radius in pixels */ - maxClusterRadius?: number; + maxClusterRadius?: number | ((zoom: number) => number); /* * Options to pass when creating the L.Polygon(points, options) to show the bounds of a cluster. @@ -82,11 +83,21 @@ declare namespace L { * Function used to create the cluster icon */ iconCreateFunction?: any; + + /* + * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. + */ + chunkedLoading?: boolean; + + /* + * Time delay (in ms) between consecutive periods of processing for addLayers. Default to 50ms. + */ + chunkDelay?: number; } export class MarkerClusterGroup extends FeatureGroup { - initialize(): void; - initialize(options: MarkerClusterGroupOptions): void; + constructor(); + constructor(options: MarkerClusterGroupOptions); /* * Bulk methods for adding and removing markers and should be favoured over the @@ -121,5 +132,11 @@ declare namespace L { * Returns the array of total markers contained within that cluster. */ getAllChildMarkers(): Marker[]; + + /* + * Zooms to show the given marker (spiderfying if required), + * calls the callback when the marker is visible on the map. + */ + zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 37abb90fb1..94cbe8499a 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,11 +1,14 @@ -// Type definitions for Leaflet.js 0.7.3 +// Type definitions for Leaflet.js 1.0.0 // Project: https://github.com/Leaflet/Leaflet // Definitions by: Vladimir Zotov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + declare namespace L { type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; } declare namespace L { @@ -16,7 +19,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomright'. */ - position?: string; + position?: PositionString; /** * The HTML text shown before the attributions. Pass false to disable. @@ -219,7 +222,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -254,11 +257,6 @@ declare namespace L { * Sets the radius of a circle marker. Units are in pixels. */ setRadius(radius: number): CircleMarker; - - /** - * Returns a GeoJSON representation of the circle marker (GeoJSON Point Feature). - */ - toGeoJSON(): any; } } @@ -343,12 +341,12 @@ declare namespace L { /** * Sets the position of the control. See control positions. */ - setPosition(position: string): Control; + setPosition(position: PositionString): Control; /** * Returns the current position of the control. */ - getPosition(): string; + getPosition(): PositionString; /** * Adds the control to the map. @@ -400,7 +398,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; // 'topleft' | 'topright' | 'bottomleft' | 'bottomright' + position?: PositionString; /** * The text set on the zoom in button. @@ -550,7 +548,7 @@ declare namespace L { * positions. * Default value: 'topright'. */ - position?: string; + position?: PositionString; } } @@ -1504,7 +1502,7 @@ declare namespace L { * Returns a new LatLng object with the longitude wrapped around left and right * boundaries (-180 to 180 by default). */ - wrap(left: number, right: number): LatLng; + wrap(left?: number, right?: number): LatLng; /** * Latitude in degrees. @@ -1709,8 +1707,9 @@ declare namespace L { /** * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; //////////// //////////// @@ -1739,7 +1738,7 @@ declare namespace L { * * Default value: 'topright'. */ - position?: string; + position?: PositionString; /** * If true, the control will be collapsed into an icon and expanded on mouse hover @@ -2000,7 +1999,7 @@ declare namespace L { export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show * polyline points that are on the screen or near, increasing performance. Returns * either false or a length-2 array of clipped points. */ @@ -2734,6 +2733,22 @@ declare namespace L.Map { * If true, it will delay moveend event so that it doesn't happen many times in a row. */ debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; } export interface FitBoundsOptions extends ZoomPanOptions { @@ -2921,7 +2936,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; /** * Marker dragging handler (by both mouse and touch). @@ -3081,7 +3096,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3122,7 +3137,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3384,7 +3399,7 @@ declare namespace L { className?: string; /** - * Sets the radius of a circle marker. + * Sets the radius of a circle marker. */ radius?: number; @@ -3543,7 +3558,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). */ - toGeoJSON(): any; + toGeoJSON(): GeoJSON.Feature; } } @@ -3858,7 +3873,7 @@ declare namespace L { * The position of the control (one of the map corners). See control positions. * Default value: 'bottomleft'. */ - position?: string; + position?: PositionString; /** * Maximum width of the control in pixels. The width is set dynamically to show diff --git a/less/less.d.ts b/less/less.d.ts index d8d04809ec..f8389d3d9b 100644 --- a/less/less.d.ts +++ b/less/less.d.ts @@ -47,6 +47,11 @@ declare namespace Less { sourceMapFileInline: boolean; } + interface StaticOptions { + async: boolean; + fileAsync: boolean; + } + interface Options { sourceMap?: SourceMapOption; filename?: string; @@ -72,6 +77,8 @@ declare namespace Less { } interface LessStatic { + options: Less.StaticOptions; + render(input: string, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; render(input: string, options: Less.Options, callback: (error: Less.RenderError, output: Less.RenderOutput) => void): void; diff --git a/linq/linq-tests.ts b/linq/linq-tests.ts index fb9c3f3d6e..d30ccc8f8c 100644 --- a/linq/linq-tests.ts +++ b/linq/linq-tests.ts @@ -30,7 +30,7 @@ describe("Linq.js tests", function () { it("Grouping Methods", function () { expect(Enumerable.From(["a","aa","aaa","a","a","aaa"]) .GroupBy((item:string) => item.length) - .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) + .Select((g: linq.Grouping) => { return { key: g.Key(), count: g.Count() }; }) .OrderBy(g => g.key) .Select(g => g.key+":"+g.count) .ToString(",")).toBe("1:3,2:1,3:2"); diff --git a/linq/linq.3.0.3-Beta4.d.ts b/linq/linq.3.0.3-Beta4.d.ts deleted file mode 100644 index 812d4a4494..0000000000 --- a/linq/linq.3.0.3-Beta4.d.ts +++ /dev/null @@ -1,196 +0,0 @@ -// Type definitions for linq.js v3.0.3-Beta4 -// Project: http://linqjs.codeplex.com/ -// Definitions by: neuecc -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace linqjs { - interface IEnumerator { - current(): any; - moveNext(): boolean; - dispose(): void; - } - - interface EnumerableStatic { - Utils: { - createLambda(expression: any): (...params: any[]) => any; - createEnumerable(getEnumerator: () => IEnumerator): Enumerable; - createEnumerator(initialize: () => void , tryGetNext: () => boolean, dispose: () => void ): IEnumerator; - extendTo(type: any): void; - }; - choice(...params: any[]): Enumerable; - cycle(...params: any[]): Enumerable; - empty(): Enumerable; - from(): Enumerable; - from(obj: Enumerable): Enumerable; - from(obj: string): Enumerable; - from(obj: number): Enumerable; - from(obj: { length: number;[x: number]: any; }): Enumerable; - from(obj: any): Enumerable; - make(element: any): Enumerable; - matches(input: string, pattern: RegExp): Enumerable; - matches(input: string, pattern: string, flags?: string): Enumerable; - range(start: number, count: number, step?: number): Enumerable; - rangeDown(start: number, count: number, step?: number): Enumerable; - rangeTo(start: number, to: number, step?: number): Enumerable; - repeat(element: any, count?: number): Enumerable; - repeatWithFinalize(initializer: () => any, finalizer: (element: any) => void ): Enumerable; - generate(func: () => any, count?: number): Enumerable; - toInfinity(start?: number, step?: number): Enumerable; - toNegativeInfinity(start?: number, step?: number): Enumerable; - unfold(seed: any, func: (value: any) => any): Enumerable; - defer(enumerableFactory: () => Enumerable): Enumerable; - } - - interface Enumerable { - constructor(getEnumerator: () => IEnumerator): Enumerable; - getEnumerator(): IEnumerator; - - // Extension Methods - traverseBreadthFirst(func: (element: any) => Enumerable, resultSelector?: (element: any, nestLevel: number) => any): Enumerable; - traverseDepthFirst(func: (element: any) => Enumerable, resultSelector?: (element: any, nestLevel: number) => any): Enumerable; - flatten(): Enumerable; - pairwise(selector: (prev: any, current: any) => any): Enumerable; - scan(func: (prev: any, current: any) => any): Enumerable; - scan(seed: any, func: (prev: any, current: any) => any): Enumerable; - select(selector: (element: any, index: number) => any): Enumerable; - selectMany(collectionSelector: (element: any, index: number) => any[], resultSelector?: (outer: any, inner: any) => any): Enumerable; - selectMany(collectionSelector: (element: any, index: number) => Enumerable, resultSelector?: (outer: any, inner: any) => any): Enumerable; - selectMany(collectionSelector: (element: any, index: number) => { length: number;[x: number]: any; }, resultSelector?: (outer: any, inner: any) => any): Enumerable; - where(predicate: (element: any, index: number) => boolean): Enumerable; - choose(selector: (element: any, index: number) => any): Enumerable; - ofType(type: any): Enumerable; - zip(second: any[], resultSelector: (first: any, second: any, index: number) => any): Enumerable; - zip(second: Enumerable, resultSelector: (first: any, second: any, index: number) => any): Enumerable; - zip(second: { length: number;[x: number]: any; }, resultSelector: (first: any, second: any, index: number) => any): Enumerable; - zip(...params: any[]): Enumerable; // last one is selector - merge(second: any[], resultSelector: (first: any, second: any, index: number) => any): Enumerable; - merge(second: Enumerable, resultSelector: (first: any, second: any, index: number) => any): Enumerable; - merge(second: { length: number;[x: number]: any; }, resultSelector: (first: any, second: any, index: number) => any): Enumerable; - merge(...params: any[]): Enumerable; // last one is selector - join(inner: Enumerable, outerKeySelector: (outer: any) =>any, innerKeySelector: (inner: any) =>any, resultSelector: (outer: any, inner: any) => any, compareSelector?: (obj: any) => any): Enumerable; - groupJoin(inner: Enumerable, outerKeySelector: (outer: any) =>any, innerKeySelector: (inner: any) =>any, resultSelector: (outer: any, inner: any) => any, compareSelector?: (obj: any) => any): Enumerable; - all(predicate: (element: any) => boolean): boolean; - any(predicate?: (element: any) => boolean): boolean; - isEmpty(): boolean; - concat(...sequences: any[]): Enumerable; - insert(index: number, second: any[]): Enumerable; - insert(index: number, second: Enumerable): Enumerable; - insert(index: number, second: { length: number;[x: number]: any; }): Enumerable; - alternate(alternateValue: any): Enumerable; - alternate(alternateSequence: any[]): Enumerable; - alternate(alternateSequence: Enumerable): Enumerable; - contains(value: any, compareSelector: (element: any) => any): Enumerable; - contains(value: any): Enumerable; - defaultIfEmpty(defaultValue?: any): Enumerable; - distinct(compareSelector?: (element: any) => any): Enumerable; - distinctUntilChanged(compareSelector: (element: any) => any): Enumerable; - except(second: any[], compareSelector?: (element: any) => any): Enumerable; - except(second: { length: number;[x: number]: any; }, compareSelector?: (element: any) => any): Enumerable; - except(second: Enumerable, compareSelector?: (element: any) => any): Enumerable; - intersect(second: any[], compareSelector?: (element: any) => any): Enumerable; - intersect(second: { length: number;[x: number]: any; }, compareSelector?: (element: any) => any): Enumerable; - intersect(second: Enumerable, compareSelector?: (element: any) => any): Enumerable; - sequenceEqual(second: any[], compareSelector?: (element: any) => any): Enumerable; - sequenceEqual(second: { length: number;[x: number]: any; }, compareSelector?: (element: any) => any): Enumerable; - sequenceEqual(second: Enumerable, compareSelector?: (element: any) => any): Enumerable; - union(second: any[], compareSelector?: (element: any) => any): Enumerable; - union(second: { length: number;[x: number]: any; }, compareSelector?: (element: any) => any): Enumerable; - union(second: Enumerable, compareSelector?: (element: any) => any): Enumerable; - orderBy(keySelector: (element: any) => any): OrderedEnumerable; - orderByDescending(keySelector: (element: any) => any): OrderedEnumerable; - reverse(): Enumerable; - shuffle(): Enumerable; - weightedSample(weightSelector: (element: any) => any): Enumerable; - groupBy(keySelector: (element: any) => any, elementSelector?: (element: any) => any, resultSelector?: (key: any, element: any) => any, compareSelector?: (element: any) => any): Enumerable; - partitionBy(keySelector: (element: any) => any, elementSelector?: (element: any) => any, resultSelector?: (key: any, element: any) => any, compareSelector?: (element: any) => any): Enumerable; - buffer(count: number): Enumerable; - aggregate(func: (prev: any, current: any) => any): any; - aggregate(seed: any, func: (prev: any, current: any) => any, resultSelector?: (last: any) => any): any; - average(selector?: (element: any) => any): number; - count(predicate?: (element: any, index: number) => boolean): number; - max(selector?: (element: any) => any): number; - min(selector?: (element: any) => any): number; - maxBy(keySelector: (element: any) => any): any; - minBy(keySelector: (element: any) => any): any; - sum(selector?: (element: any) => any): number; - elementAt(index: number): any; - elementAtOrDefault(index: number, defaultValue?: any): any; - first(predicate?: (element: any, index: number) => boolean): any; - firstOrDefault(predicate?: (element: any, index: number) => boolean, defaultValue?: any): any; - last(predicate?: (element: any, index: number) => boolean): any; - lastOrDefault(predicate?: (element: any, index: number) => boolean, defaultValue?: any): any; - single(predicate?: (element: any, index: number) => boolean): any; - singleOrDefault(predicate?: (element: any, index: number) => boolean, defaultValue?: any): any; - skip(count: number): Enumerable; - skipWhile(predicate: (element: any, index: number) => boolean): Enumerable; - take(count: number): Enumerable; - takeWhile(predicate: (element: any, index: number) => boolean): Enumerable; - takeExceptLast(count?: number): Enumerable; - takeFromLast(count: number): Enumerable; - indexOf(item: any): number; - indexOf(predicate: (element: any, index: number) => boolean): number; - lastIndexOf(item: any): number; - lastIndexOf(predicate: (element: any, index: number) => boolean): number; - asEnumerable(): Enumerable; - toArray(): any[]; - toLookup(keySelector: (element: any) => any, elementSelector?: (element: any) => any, compareSelector?: (element: any) => any): Lookup; - toObject(keySelector: (element: any) => any, elementSelector?: (element: any) => any): Object; - toDictionary(keySelector: (element: any) => any, elementSelector?: (element: any) => any, compareSelector?: (element: any) => any): Dictionary; - toJSONString(replacer: (key: string, value: any) => any): string; - toJSONString(replacer: any[]): string; - toJSONString(replacer: (key: string, value: any) => any, space: any): string; - toJSONString(replacer: any[], space: any): string; - toJoinedString(separator?: string, selector?: (element: any, index: number) => any): string; - doAction(action: (element: any, index: number) => void ): Enumerable; - doAction(action: (element: any, index: number) => boolean): Enumerable; - forEach(action: (element: any, index: number) => void ): void; - forEach(action: (element: any, index: number) => boolean): void; - write(separator?: string, selector?: (element: any) => any): void; - writeLine(selector?: (element: any) => any): void; - force(): void; - letBind(func: (source: Enumerable) => any[]): Enumerable; - letBind(func: (source: Enumerable) => { length: number;[x: number]: any; }): Enumerable; - letBind(func: (source: Enumerable) => Enumerable): Enumerable; - share(): DisposableEnumerable; - memoize(): DisposableEnumerable; - catchError(handler: (exception: any) => void ): Enumerable; - finallyAction(finallyAction: () => void ): Enumerable; - log(selector?: (element: any) => void ): Enumerable; - trace(message?: string, selector?: (element: any) => void ): Enumerable; - } - - interface OrderedEnumerable extends Enumerable { - createOrderedEnumerable(keySelector: (element: any) => any, descending: boolean): OrderedEnumerable; - thenBy(keySelector: (element: any) => any): OrderedEnumerable; - thenByDescending(keySelector: (element: any) => any): OrderedEnumerable; - } - - interface DisposableEnumerable extends Enumerable { - dispose(): void; - } - - interface Dictionary { - add(key: any, value: any): void; - get(key: any): any; - set(key: any, value: any): boolean; - contains(key: any): boolean; - clear(): void; - remove(key: any): void; - count(): number; - toEnumerable(): Enumerable; // Enumerable - } - - interface Lookup { - count(): number; - get(key: any): Enumerable; - contains(key: any): boolean; - toEnumerable(): Enumerable; // Enumerable - } - - interface Grouping extends Enumerable { - key(): any; - } -} - -// export definition -declare var Enumerable: linqjs.EnumerableStatic; diff --git a/linq/linq.3.0.4-Beta5.d.ts b/linq/linq.3.0.4-Beta5.d.ts new file mode 100644 index 0000000000..a6c32690ce --- /dev/null +++ b/linq/linq.3.0.4-Beta5.d.ts @@ -0,0 +1,276 @@ +// Type definitions for linq.js v3.0.4-Beta5 +// Project: https://linqjs.codeplex.com/ +// Definitions by: neuecc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module linqjs { + interface IEnumerator { + current(): T; + moveNext(): boolean; + dispose(): void; + } + + interface IEqualityComparer { + equals(x: T, y: T): boolean; + getHashCode(obj: any): string; + } + + interface ITuple { + equals(other: ITuple): boolean; + getHashCode(): string; + } + + interface ITupleArray { + equals(other: ITupleArray): boolean; + getHashCode(): string; + } + + interface Enumerable { + Utils: { + createLambda(expression: any): (...params: any[]) => any; + createEnumerable(getEnumerator: () => IEnumerator): IEnumerable; + createEnumerator(initialize: () => void, tryGetNext: () => boolean, dispose: () => void): IEnumerator; + getDefaultEqualityComparer(): IEqualityComparer; + createEqualityComparer(equals: (x: T, y: T) => boolean, getHashCode: (obj: any) => string): IEqualityComparer; + createKeyedEqualityComparer(keySelector: (element: TValue) => TKey): IEqualityComparer; + createDictionary(compareSelector: (element: TValue) => TKey): IDictionary; + createDictionary(equalityComparer: IEqualityComparer): IDictionary; + createList(): IList; + createTuple(item1: T1, item2: T2, item3?: T3, item4?: T4, item5?: T5, item6?: T6, item7?: T7, item8?: T8): ITuple; + extendTo(type: any, forceAppend?: boolean): void; + }; + choice(...params: T[]): IEnumerable; + cycle(...params: T[]): IEnumerable; + empty(): IEnumerable; + // from, obj as JScript's IEnumerable or WinMD IIterable is IEnumerable but it can't define. + from(): IEnumerable; // empty + from(obj: IEnumerable): IEnumerable; + from(obj: number): IEnumerable; + from(obj: boolean): IEnumerable; + from(obj: string): IEnumerable; + from(obj: T[]): IEnumerable; + from(obj: { length: number; [x: number]: T; }): IEnumerable; + from(obj: any): IEnumerable<{ key: string; value: any }>; + make(element: T): IEnumerable; + matches(input: string, pattern: RegExp): IEnumerable; + matches(input: string, pattern: string, flags?: string): IEnumerable; + range(start: number, count: number, step?: number): IEnumerable; + rangeDown(start: number, count: number, step?: number): IEnumerable; + rangeTo(start: number, to: number, step?: number): IEnumerable; + repeat(element: T, count?: number): IEnumerable; + repeatWithFinalize(initializer: () => T, finalizer: (element: T) => void): IEnumerable; + generate(func: () => T, count?: number): IEnumerable; + toInfinity(start?: number, step?: number): IEnumerable; + toNegativeInfinity(start?: number, step?: number): IEnumerable; + unfold(seed: T, func: (value: T) => T): IEnumerable; + defer(enumerableFactory: () => IEnumerable): IEnumerable; + } + + interface IEnumerable { + constructor(getEnumerator: () => IEnumerator): IEnumerable; + getEnumerator(): IEnumerator; + + // Extension Methods + traverseBreadthFirst(func: (element: T) => IEnumerable): IEnumerable; + traverseBreadthFirst(func: (element: T) => IEnumerable, resultSelector: (element: T, nestLevel: number) => TResult): IEnumerable; + traverseDepthFirst(func: (element: T) => Enumerable): IEnumerable; + traverseDepthFirst(func: (element: T) => Enumerable, resultSelector?: (element: T, nestLevel: number) => TResult): IEnumerable; + flatten(): IEnumerable; + pairwise(selector: (prev: T, current: T) => TResult): IEnumerable; + scan(func: (prev: T, current: T) => T): IEnumerable; + scan(seed: TAccumulate, func: (prev: TAccumulate, current: T) => TAccumulate): IEnumerable; + select(selector: (element: T, index: number) => TResult): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => IEnumerable): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => IEnumerable, resultSelector: (outer: T, inner: TCollection) => TResult): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => TOther[]): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => TCollection[], resultSelector: (outer: T, inner: TCollection) => TResult): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => { length: number; [x: number]: TOther; }): IEnumerable; + selectMany(collectionSelector: (element: T, index: number) => { length: number; [x: number]: TCollection; }, resultSelector: (outer: T, inner: TCollection) => TResult): IEnumerable; + where(predicate: (element: T, index: number) => boolean): IEnumerable; + choose(selector: (element: T, index: number) => T): IEnumerable; + ofType(type: any): IEnumerable; + zip(second: IEnumerable, resultSelector: (first: T, second: T, index: number) => TResult): IEnumerable; + zip(second: { length: number; [x: number]: T; }, resultSelector: (first: T, second: T, index: number) => TResult): IEnumerable; + zip(second: T[], resultSelector: (first: T, second: T, index: number) => TResult): IEnumerable; + zip(...params: any[]): IEnumerable; // last one is selector + merge(...params: IEnumerable[]): IEnumerable; + merge(...params: { length: number; [x: number]: T; }[]): IEnumerable; + merge(...params: T[][]): IEnumerable; + join(inner: IEnumerable, outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + join(inner: { length: number; [x: number]: TInner; }, outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + join(inner: TInner[], outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + groupJoin(inner: IEnumerable, outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + groupJoin(inner: { length: number; [x: number]: TInner; }, outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + groupJoin(inner: TInner[], outerKeySelector: (outer: T) => TKey, innerKeySelector: (inner: TInner) => TKey, resultSelector: (outer: T, inner: TKey) => TResult, compareSelector?: (obj: T) => TKey): IEnumerable; + all(predicate: (element: T) => boolean): boolean; + any(predicate?: (element: T) => boolean): boolean; + isEmpty(): boolean; + concat(...sequences: IEnumerable[]): IEnumerable; + concat(...sequences: { length: number; [x: number]: T; }[]): IEnumerable; + concat(...sequences: T[]): IEnumerable; + insert(index: number, second: IEnumerable): IEnumerable; + insert(index: number, second: { length: number; [x: number]: T; }): IEnumerable; + alternate(alternateValue: T): IEnumerable; + alternate(alternateSequence: { length: number; [x: number]: T; }): IEnumerable; + alternate(alternateSequence: IEnumerable): IEnumerable; + alternate(alternateSequence: T[]): IEnumerable; + contains(value: T): boolean; + contains(value: T, compareSelector?: (element: T) => TCompare): boolean; + contains(value: T, equalityComparer?: IEqualityComparer): boolean; + defaultIfEmpty(defaultValue?: T): IEnumerable; + distinct(): IEnumerable; + distinct(compareSelector: (element: T) => TCompare): IEnumerable; + distinctUntilChanged(): IEnumerable; + distinctUntilChanged(compareSelector: (element: T) => TCompare): IEnumerable; + except(second: { length: number; [x: number]: T; }): IEnumerable; + except(second: { length: number; [x: number]: T; }, compareSelector: (element: T) => TCompare): IEnumerable; + except(second: IEnumerable): IEnumerable; + except(second: IEnumerable, compareSelector: (element: T) => TCompare): IEnumerable; + except(second: T[]): IEnumerable; + except(second: T[], compareSelector: (element: T) => TCompare): IEnumerable; + intersect(second: { length: number; [x: number]: T; }): IEnumerable; + intersect(second: { length: number; [x: number]: T; }, compareSelector: (element: T) => TCompare): IEnumerable; + intersect(second: IEnumerable): IEnumerable; + intersect(second: IEnumerable, compareSelector: (element: T) => TCompare): IEnumerable; + intersect(second: T[]): IEnumerable; + intersect(second: T[], compareSelector: (element: T) => TCompare): IEnumerable; + union(second: { length: number; [x: number]: T; }): IEnumerable; + union(second: { length: number; [x: number]: T; }, compareSelector: (element: T) => TCompare): IEnumerable; + union(second: IEnumerable): IEnumerable; + union(second: IEnumerable, compareSelector: (element: T) => TCompare): IEnumerable; + union(second: T[]): IEnumerable; + union(second: T[], compareSelector: (element: T) => TCompare): IEnumerable; + sequenceEqual(second: { length: number; [x: number]: T; }): boolean; + sequenceEqual(second: { length: number; [x: number]: T; }, compareSelector: (element: T) => TCompare): boolean; + sequenceEqual(second: IEnumerable): boolean; + sequenceEqual(second: IEnumerable, compareSelector: (element: T) => TCompare): boolean; + sequenceEqual(second: T[]): boolean; + sequenceEqual(second: T[], compareSelector: (element: T) => TCompare): boolean; + orderBy(keySelector: (element: T) => TKey): IOrderedEnumerable; + orderBy(keySelector: (element: T) => TKey, comparison: (x: TKey, y: TKey) => number): IOrderedEnumerable; + orderByDescending(keySelector: (element: T) => TKey): IOrderedEnumerable; + orderByDescending(keySelector: (element: T) => TKey, comparison: (x: TKey, y: TKey) => number): IOrderedEnumerable; + reverse(): IEnumerable; + shuffle(): IEnumerable; + weightedSample(weightSelector: (element: T) => number): IEnumerable; + // truly, return type is IEnumerable> but Visual Studio + TypeScript Compiler can't compile. + groupBy(keySelector: (element: T) => TKey): IEnumerable>; + groupBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement): IEnumerable>; + groupBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement, resultSelector: (key: TKey, element: IEnumerable) => TResult): IEnumerable; + groupBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement, resultSelector: (key: TKey, element: IEnumerable) => TResult, compareSelector: (element: T) => TCompare): IEnumerable; + // :IEnumerable> + partitionBy(keySelector: (element: T) => TKey): IEnumerable>; + // :IEnumerable> + partitionBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement): IEnumerable>; + partitionBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement, resultSelector: (key: TKey, element: IEnumerable) => TResult): IEnumerable; + partitionBy(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement, resultSelector: (key: TKey, element: IEnumerable) => TResult, compareSelector: (element: T) => TCompare): IEnumerable; + buffer(count: number): IEnumerable; + aggregate(func: (prev: T, current: T) => T): T; + aggregate(seed: TAccumulate, func: (prev: TAccumulate, current: T) => TAccumulate): TAccumulate; + aggregate(seed: TAccumulate, func: (prev: TAccumulate, current: T) => TAccumulate, resultSelector: (last: TAccumulate) => TResult): TResult; + average(selector?: (element: T) => number): number; + count(predicate?: (element: T, index: number) => boolean): number; + max(selector?: (element: T) => number): number; + min(selector?: (element: T) => number): number; + maxBy(keySelector: (element: T) => TKey): T; + minBy(keySelector: (element: T) => TKey): T; + sum(selector?: (element: T) => number): number; + elementAt(index: number): T; + elementAtOrDefault(index: number, defaultValue?: T): T; + first(predicate?: (element: T, index: number) => boolean): T; + firstOrDefault(predicate?: (element: T, index: number) => boolean, defaultValue?: T): T; + last(predicate?: (element: T, index: number) => boolean): T; + lastOrDefault(predicate?: (element: T, index: number) => boolean, defaultValue?: T): T; + single(predicate?: (element: T, index: number) => boolean): T; + singleOrDefault(predicate?: (element: T, index: number) => boolean, defaultValue?: T): T; + skip(count: number): IEnumerable; + skipWhile(predicate: (element: T, index: number) => boolean): IEnumerable; + take(count: number): IEnumerable; + takeWhile(predicate: (element: T, index: number) => boolean): IEnumerable; + takeExceptLast(count?: number): IEnumerable; + takeFromLast(count: number): IEnumerable; + indexOf(item: T): number; + indexOf(predicate: (element: T, index: number) => boolean): number; + lastIndexOf(item: T): number; + lastIndexOf(predicate: (element: T, index: number) => boolean): number; + asEnumerable(): IEnumerable; + cast(): IEnumerable; + toArray(): T[]; + toList(): IList; + // truly, return type is ILookup but Visual Studio + TypeScript Compiler can't compile. + toLookup(keySelector: (element: T) => TKey): ILookup; + toLookup(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement): ILookup; + toLookup(keySelector: (element: T) => TKey, elementSelector: (element: T) => TElement, compareSelector: (key: TKey) => TCompare): ILookup; + toObject(keySelector: (element: T) => any, elementSelector?: (element: T) => any): Object; + // :IDictionary + toDictionary(keySelector: (element: T) => TKey): IDictionary; + toDictionary(keySelector: (element: T) => TKey, elementSelector: (element: T) => TValue): IDictionary; + toDictionary(keySelector: (element: T) => TKey, elementSelector: (element: T) => TValue, compareSelector: (key: TKey) => TCompare): IDictionary; + toJSONString(replacer: (key: string, value: any) => any): string; + toJSONString(replacer: any[]): string; + toJSONString(replacer: (key: string, value: any) => any, space: any): string; + toJSONString(replacer: any[], space: any): string; + toJoinedString(separator?: string): string; + toJoinedString(separator: string, selector: (element: T, index: number) => TResult): string; + doAction(action: (element: T, index: number) => void): IEnumerable; + doAction(action: (element: T, index: number) => boolean): IEnumerable; + forEach(action: (element: T, index: number) => void): void; + forEach(action: (element: T, index: number) => boolean): void; + write(separator?: string): void; + write(separator: string, selector: (element: T) => TResult): void; + writeLine(): void; + writeLine(selector: (element: T) => TResult): void; + force(): void; + letBind(func: (source: IEnumerable) => { length: number; [x: number]: TResult; }): IEnumerable; + letBind(func: (source: IEnumerable) => TResult[]): IEnumerable; + letBind(func: (source: IEnumerable) => IEnumerable): IEnumerable; + share(): IDisposableEnumerable; + memoize(): IDisposableEnumerable; + catchError(handler: (exception: any) => void): IEnumerable; + finallyAction(finallyAction: () => void): IEnumerable; + log(): IEnumerable; + log(selector: (element: T) => TValue): IEnumerable; + trace(message?: string): IEnumerable; + trace(message: string, selector: (element: T) => TValue): IEnumerable; + } + + interface IOrderedEnumerable extends IEnumerable { + createOrderedEnumerable(keySelector: (element: T) => TKey, comparison: (x: TKey, y: TKey) => number, descending: boolean): IOrderedEnumerable; + thenBy(keySelector: (element: T) => TKey) : IOrderedEnumerable; + thenBy(keySelector: (element: T) => TKey, comparison: (x: TKey, y: TKey) => number) : IOrderedEnumerable; + thenByDescending(keySelector: (element: T) => TKey): IOrderedEnumerable; + thenByDescending(keySelector: (element: T) => TKey, comparison: (x: TKey, y: TKey) => number): IOrderedEnumerable; + } + + interface IDisposableEnumerable extends IEnumerable { + dispose(): void; + } + + interface IDictionary { + add(key: TKey, value: TValue): void; + get(key: TKey): TValue; + set(key: TKey, value: TValue): boolean; + contains(key: TKey): boolean; + clear(): void; + remove(key: TKey): void; + count(): number; + toEnumerable(): IEnumerable<{ key: TKey; value: TValue }>; + } + + interface ILookup { + count(): number; + get(key: TKey): IEnumerable; + contains(key: TKey): boolean; + toEnumerable(): IEnumerable>; + } + + interface IGrouping extends IEnumerable { + key(): TKey; + } + + interface IList extends Array { + } +} + +// export definition +declare var Enumerable: linqjs.Enumerable; diff --git a/linq/linq.d.ts b/linq/linq.d.ts index e9fa44df41..f7417fc8da 100644 --- a/linq/linq.d.ts +++ b/linq/linq.d.ts @@ -30,43 +30,45 @@ declare namespace linq { Generate(func: string, count?: number): Enumerable; ToInfinity(start?: number, step?: number): Enumerable; ToNegativeInfinity(start?: number, step?: number): Enumerable; - Unfold(seed, func: ($) => T): Enumerable; - Unfold(seed, func: string): Enumerable; + Unfold(seed: T, func: ($: T) => T): Enumerable; + Unfold(seed: any, func: string): Enumerable; } interface Enumerable { //Projection and Filtering Methods - CascadeBreadthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeBreadthFirst(func: ($: T) => any[], resultSelector: (v: any, i: number) => any): Enumerable; CascadeBreadthFirst(func: string, resultSelector: string): Enumerable; - CascadeDepthFirst(func: ($) => any[], resultSelector: (v, i: number) => any): Enumerable; + CascadeDepthFirst(func: ($: T) => any[], resultSelector: (v: any, i: number) => any): Enumerable; CascadeDepthFirst(func: string, resultSelector: string): Enumerable; Flatten(...items: any[]): Enumerable; - Pairwise(selector: (prev, next) => any): Enumerable; + Pairwise(selector: (prev: any, next: any) => any): Enumerable; Pairwise(selector: string): Enumerable; - Scan(func: (a, b) => any): Enumerable; + Scan(func: (a: any, b: any) => any): Enumerable; Scan(func: string): Enumerable; - Scan(seed, func: (a, b) => any, resultSelector?: ($) => any): Enumerable; - Scan(seed, func: string, resultSelector?: string): Enumerable; + Scan(seed: any, func: (a: any, b: any) => any, resultSelector?: ($: T) => any): Enumerable; + Scan(seed: any, func: string, resultSelector?: string): Enumerable; Select(selector: ($: T, i: number) => TResult): Enumerable; Select(selector: string): Enumerable; - SelectMany(collectionSelector: ($, i: number) => any[], resultSelector?: ($, item) => any): Enumerable; - SelectMany(collectionSelector: ($, i: number) => Enumerable, resultSelector?: ($, item) => any): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TResult[]): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => TCollectionItem[], resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; + SelectMany(collectionSelector: ($: T, i: number) => Enumerable, resultSelector: ($: T, item: TCollectionItem) => TResult): Enumerable; SelectMany(collectionSelector: string, resultSelector?: string): Enumerable; Where(predicate: ($ : T, i: number) => boolean): Enumerable; Where(predicate: string): Enumerable; OfType(type: Function): Enumerable; - Zip(second: any[], selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: any[], selector: (v1: any, v2: any, i: number) => any): Enumerable; Zip(second: any[], selector: string): Enumerable; - Zip(second: Enumerable, selector: (v1, v2, i: number) => any): Enumerable; + Zip(second: Enumerable, selector: (v1: any, v2: any, i: number) => any): Enumerable; Zip(second: Enumerable, selector: string): Enumerable; //Join Methods - Join(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: any[], outerKeySelector: (v1: any) => any, innerKeySelector: (v1: any) => any, resultSelector: (v1: any, v2: any) => any, compareSelector?: (v: any) => any): Enumerable; Join(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - Join(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2) => any, compareSelector?: (v) => any): Enumerable; + Join(inner: Enumerable, outerKeySelector: (v1: any) => any, innerKeySelector: (v1: any) => any, resultSelector: (v1: any, v2: any) => any, compareSelector?: (v: any) => any): Enumerable; Join(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - GroupJoin(inner: any[], outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: any[], outerKeySelector: (v1: any) => any, innerKeySelector: (v1: any) => any, resultSelector: (v1: any, v2: Enumerable) => any, compareSelector?: (v: any) => any): Enumerable; GroupJoin(inner: any[], outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; - GroupJoin(inner: Enumerable, outerKeySelector: (v1) => any, innerKeySelector: (v1) => any, resultSelector: (v1, v2: Enumerable) => any, compareSelector?: (v) => any): Enumerable; + GroupJoin(inner: Enumerable, outerKeySelector: (v1: any) => any, innerKeySelector: (v1: any) => any, resultSelector: (v1: any, v2: Enumerable) => any, compareSelector?: (v: any) => any): Enumerable; GroupJoin(inner: Enumerable, outerKeySelector: string, innerKeySelector: string, resultSelector: string, compareSelector?: string): Enumerable; //Set Methods All(predicate: ($ : T) => boolean): boolean; @@ -77,49 +79,49 @@ declare namespace linq { Concat(second: Enumerable): Enumerable; Insert(index: number, second: any[]): Enumerable; Insert(index: number, second: Enumerable): Enumerable; - Alternate(value): Enumerable; - Contains(value, compareSelector?: ($) => any): boolean; - Contains(value, compareSelector?: string): boolean; - DefaultIfEmpty(defaultValue): Enumerable; - Distinct(compareSelector?: ($) => any): Enumerable; + Alternate(value: any): Enumerable; + Contains(value: any, compareSelector?: ($: T) => any): boolean; + Contains(value: any, compareSelector?: string): boolean; + DefaultIfEmpty(defaultValue: any): Enumerable; + Distinct(compareSelector?: ($: T) => any): Enumerable; Distinct(compareSelector?: string): Enumerable; - Except(second: any[], compareSelector?: ($) => any): Enumerable; + Except(second: any[], compareSelector?: ($: T) => any): Enumerable; Except(second: any[], compareSelector?: string): Enumerable; - Except(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Except(second: Enumerable, compareSelector?: ($: T) => any): Enumerable; Except(second: Enumerable, compareSelector?: string): Enumerable; - Intersect(second: any[], compareSelector?: ($) => any): Enumerable; + Intersect(second: any[], compareSelector?: ($: T) => any): Enumerable; Intersect(second: any[], compareSelector?: string): Enumerable; - Intersect(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Intersect(second: Enumerable, compareSelector?: ($: T) => any): Enumerable; Intersect(second: Enumerable, compareSelector?: string): Enumerable; - SequenceEqual(second: any[], compareSelector?: ($) => any): boolean; + SequenceEqual(second: any[], compareSelector?: ($: T) => any): boolean; SequenceEqual(second: any[], compareSelector?: string): boolean; - SequenceEqual(second: Enumerable, compareSelector?: ($) => any): boolean; + SequenceEqual(second: Enumerable, compareSelector?: ($: T) => any): boolean; SequenceEqual(second: Enumerable, compareSelector?: string): boolean; - Union(second: any[], compareSelector?: ($) => any): Enumerable; + Union(second: any[], compareSelector?: ($: T) => any): Enumerable; Union(second: any[], compareSelector?: string): Enumerable; - Union(second: Enumerable, compareSelector?: ($) => any): Enumerable; + Union(second: Enumerable, compareSelector?: ($: T) => any): Enumerable; Union(second: Enumerable, compareSelector?: string): Enumerable; //Ordering Methods OrderBy(keySelector?: ($: T) => any): OrderedEnumerable; OrderBy(keySelector?: string): OrderedEnumerable; - OrderByDescending(keySelector?: ($) => any): OrderedEnumerable; + OrderByDescending(keySelector?: ($: T) => any): OrderedEnumerable; OrderByDescending(keySelector?: string): OrderedEnumerable; Reverse(): Enumerable; Shuffle(): Enumerable; //Grouping Methods - GroupBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + GroupBy(keySelector: ($: T) => any, elementSelector?: ($: T) => any, resultSelector?: (key: any, e: any) => any, compareSelector?: ($: T) =>any): Enumerable; GroupBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; - PartitionBy(keySelector: ($) => any, elementSelector?: ($) => any, resultSelector?: (key, e) => any, compareSelector?: ($) =>any): Enumerable; + PartitionBy(keySelector: ($: T) => any, elementSelector?: ($: T) => any, resultSelector?: (key: any, e: any) => any, compareSelector?: ($: T) =>any): Enumerable; PartitionBy(keySelector: string, elementSelector?: string, resultSelector?: string, compareSelector?: string): Enumerable; BufferWithCount(count: number): Enumerable; // Aggregate Methods - Aggregate(func: (a, b) => any); - Aggregate(seed, func: (a, b) => any, resultSelector?: ($) => any); - Aggregate(func: string); - Aggregate(seed, func: string, resultSelector?: string); - Average(selector?: ($) => number): number; + Aggregate(func: (a: any, b: any) => any): any; + Aggregate(seed: any, func: (a: any, b: any) => any, resultSelector?: ($: T) => any): any; + Aggregate(func: string): any; + Aggregate(seed: any, func: string, resultSelector?: string): any; + Average(selector?: ($: T) => number): number; Average(selector?: string): number; - Count(predicate?: ($) => boolean): number; + Count(predicate?: ($: T) => boolean): number; Count(predicate?: string): number; Max(selector?: ($: T) => any): any; Max(selector?: ($: T) => Date): Date; @@ -141,7 +143,7 @@ declare namespace linq { MinBy(selector: ($: T) => string): string; MinBy(selector: ($: T) => any): any; MinBy(selector: string): any; - Sum(selector?: ($) => number): number; + Sum(selector?: ($: T) => number): number; Sum(selector?: string): number; //Paging Methods ElementAt(index: number): T; @@ -166,29 +168,29 @@ declare namespace linq { TakeWhile(predicate: string): Enumerable; TakeExceptLast(count?: number): Enumerable; TakeFromLast(count: number): Enumerable; - IndexOf(item): number; - LastIndexOf(item): number; + IndexOf(item: T): number; + LastIndexOf(item: T): number; // Convert Methods ToArray(): T[]; - ToLookup(keySelector: ($) => any, elementSelector?: ($) => any, compareSelector?: (key) => any): Lookup; - ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; - ToObject(keySelector: ($) => string, elementSelector: ($) => any): any; + ToLookup(keySelector: ($: T) => TKey, elementSelector?: ($: T) => TValue, compareSelector?: (key: TKey) => any): Lookup; + ToLookup(keySelector: string, elementSelector?: string, compareSelector?: string): Lookup; + ToObject(keySelector: ($: T) => string, elementSelector: ($: T) => any): any; ToObject(keySelector: string, elementSelector: string): any; - ToDictionary(keySelector: ($) => any, elementSelector: ($) => any, compareSelector?: (key) => any): Dictionary; - ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; - ToJSON(replacer?: (key, value) => any, space?: number): string; + ToDictionary(keySelector: ($: T) => TKey, elementSelector: ($: T) => TValue, compareSelector?: (key: TKey) => any): Dictionary; + ToDictionary(keySelector: string, elementSelector: string, compareSelector?: string): Dictionary; + ToJSON(replacer?: (key: any, value: any) => any, space?: number): string; ToJSON(replacer?: string, space?: number): string; - ToString(separator?: string, selector?: ($) =>any): string; + ToString(separator?: string, selector?: ($: T) =>any): string; ToString(separator?: string, selector?: string): string; //Action Methods - Do(action: ($, i: number) => void ): Enumerable; + Do(action: ($: T, i: number) => void ): Enumerable; Do(action: string): Enumerable; ForEach(action: ($: T, i: number) => void ): void; ForEach(func: ($: T, i: number) => boolean): void; ForEach(action_func: string): void; - Write(separator?: string, selector?: ($) =>any): void; + Write(separator?: string, selector?: ($: T) =>any): void; Write(separator?: string, selector?: string): void; - WriteLine(selector?: ($) =>any): void; + WriteLine(selector?: ($: T) =>any): void; Force(): void; //Functional Methods Let(func: (e: Enumerable) => Enumerable): Enumerable; @@ -200,7 +202,7 @@ declare namespace linq { Finally(finallyAction: () => void ): Enumerable; Finally(finallyAction: string): Enumerable; //For Debug Methods - Trace(message?: string, selector?: ($) =>any): Enumerable; + Trace(message?: string, selector?: ($: T) =>any): Enumerable; Trace(message?: string, selector?: string): Enumerable; } @@ -211,26 +213,26 @@ declare namespace linq { ThenByDescending(keySelector: string): OrderedEnumerable; } - interface Grouping extends Enumerable { - Key(); + interface Grouping extends Enumerable { + Key(): TKey; } - interface Lookup { + interface Lookup { Count(): number; - Get(key): Enumerable; - Contains(key): boolean; - ToEnumerable(): Enumerable; + Get(key: TKey): Enumerable; + Contains(key: TKey): boolean; + ToEnumerable(): Enumerable>; } - interface Dictionary { - Add(key, value): void; - Get(key): any; - Set(key, value): boolean; - Contains(key): boolean; + interface Dictionary { + Add(key: TKey, value: TValue): void; + Get(key: TKey): TValue; + Set(key: TKey, value: TValue): boolean; + Contains(key: TKey): boolean; Clear(): void; - Remove(key): void; + Remove(key: TKey): void; Count(): number; - ToEnumerable(): Enumerable; + ToEnumerable(): Enumerable>; } interface KeyValuePair { diff --git a/linq/linq.jquery.3.0.4-Beta5.d.ts b/linq/linq.jquery.3.0.4-Beta5.d.ts new file mode 100644 index 0000000000..4f80a55769 --- /dev/null +++ b/linq/linq.jquery.3.0.4-Beta5.d.ts @@ -0,0 +1,18 @@ +// Type definitions for linq.jquery (from linq.js) +// Project: https://linqjs.codeplex.com/ +// Definitions by: neuecc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module linqjs { + interface IEnumerable { + tojQuery(): JQuery; + tojQueryAsArray(): JQuery; + } +} + +interface JQuery { + toEnumerable(): linqjs.IEnumerable; +} diff --git a/locutus/locutus-tests.ts b/locutus/locutus-tests.ts new file mode 100644 index 0000000000..a465bbd4fa --- /dev/null +++ b/locutus/locutus-tests.ts @@ -0,0 +1,353 @@ +/// +import locutus_c_math_abs = require('locutus/c/math/abs'); +import locutus_golang_strings_Contains = require('locutus/golang/strings/Contains'); +import locutus_golang_strings_Count = require('locutus/golang/strings/Count'); +import locutus_golang_strings_Index = require('locutus/golang/strings/Index'); +import locutus_golang_strings_LastIndex = require('locutus/golang/strings/LastIndex'); +import locutus_php_array_array_change_key_case = require('locutus/php/array/array_change_key_case'); +import locutus_php_array_array_chunk = require('locutus/php/array/array_chunk'); +import locutus_php_array_array_combine = require('locutus/php/array/array_combine'); +import locutus_php_array_array_count_values = require('locutus/php/array/array_count_values'); +import locutus_php_array_array_diff = require('locutus/php/array/array_diff'); +import locutus_php_array_array_diff_assoc = require('locutus/php/array/array_diff_assoc'); +import locutus_php_array_array_diff_key = require('locutus/php/array/array_diff_key'); +import locutus_php_array_array_diff_uassoc = require('locutus/php/array/array_diff_uassoc'); +import locutus_php_array_array_diff_ukey = require('locutus/php/array/array_diff_ukey'); +import locutus_php_array_array_fill = require('locutus/php/array/array_fill'); +import locutus_php_array_array_fill_keys = require('locutus/php/array/array_fill_keys'); +import locutus_php_array_array_filter = require('locutus/php/array/array_filter'); +import locutus_php_array_array_flip = require('locutus/php/array/array_flip'); +import locutus_php_array_array_intersect = require('locutus/php/array/array_intersect'); +import locutus_php_array_array_intersect_assoc = require('locutus/php/array/array_intersect_assoc'); +import locutus_php_array_array_intersect_key = require('locutus/php/array/array_intersect_key'); +import locutus_php_array_array_intersect_uassoc = require('locutus/php/array/array_intersect_uassoc'); +import locutus_php_array_array_intersect_ukey = require('locutus/php/array/array_intersect_ukey'); +import locutus_php_array_array_key_exists = require('locutus/php/array/array_key_exists'); +import locutus_php_array_array_keys = require('locutus/php/array/array_keys'); +import locutus_php_array_array_map = require('locutus/php/array/array_map'); +import locutus_php_array_array_merge = require('locutus/php/array/array_merge'); +import locutus_php_array_array_merge_recursive = require('locutus/php/array/array_merge_recursive'); +import locutus_php_array_array_multisort = require('locutus/php/array/array_multisort'); +import locutus_php_array_array_pad = require('locutus/php/array/array_pad'); +import locutus_php_array_array_pop = require('locutus/php/array/array_pop'); +import locutus_php_array_array_product = require('locutus/php/array/array_product'); +import locutus_php_array_array_push = require('locutus/php/array/array_push'); +import locutus_php_array_array_rand = require('locutus/php/array/array_rand'); +import locutus_php_array_array_reduce = require('locutus/php/array/array_reduce'); +import locutus_php_array_array_replace = require('locutus/php/array/array_replace'); +import locutus_php_array_array_replace_recursive = require('locutus/php/array/array_replace_recursive'); +import locutus_php_array_array_reverse = require('locutus/php/array/array_reverse'); +import locutus_php_array_array_search = require('locutus/php/array/array_search'); +import locutus_php_array_array_shift = require('locutus/php/array/array_shift'); +import locutus_php_array_array_slice = require('locutus/php/array/array_slice'); +import locutus_php_array_array_splice = require('locutus/php/array/array_splice'); +import locutus_php_array_array_sum = require('locutus/php/array/array_sum'); +import locutus_php_array_array_udiff = require('locutus/php/array/array_udiff'); +import locutus_php_array_array_udiff_assoc = require('locutus/php/array/array_udiff_assoc'); +import locutus_php_array_array_udiff_uassoc = require('locutus/php/array/array_udiff_uassoc'); +import locutus_php_array_array_uintersect = require('locutus/php/array/array_uintersect'); +import locutus_php_array_array_uintersect_uassoc = require('locutus/php/array/array_uintersect_uassoc'); +import locutus_php_array_array_unique = require('locutus/php/array/array_unique'); +import locutus_php_array_array_unshift = require('locutus/php/array/array_unshift'); +import locutus_php_array_array_values = require('locutus/php/array/array_values'); +import locutus_php_array_array_walk = require('locutus/php/array/array_walk'); +import locutus_php_array_arsort = require('locutus/php/array/arsort'); +import locutus_php_array_asort = require('locutus/php/array/asort'); +import locutus_php_array_count = require('locutus/php/array/count'); +import locutus_php_array_current = require('locutus/php/array/current'); +import locutus_php_array_each = require('locutus/php/array/each'); +import locutus_php_array_end = require('locutus/php/array/end'); +import locutus_php_array_in_array = require('locutus/php/array/in_array'); +import locutus_php_array_key = require('locutus/php/array/key'); +import locutus_php_array_krsort = require('locutus/php/array/krsort'); +import locutus_php_array_ksort = require('locutus/php/array/ksort'); +import locutus_php_array_natcasesort = require('locutus/php/array/natcasesort'); +import locutus_php_array_natsort = require('locutus/php/array/natsort'); +import locutus_php_array_next = require('locutus/php/array/next'); +import locutus_php_array_pos = require('locutus/php/array/pos'); +import locutus_php_array_prev = require('locutus/php/array/prev'); +import locutus_php_array_range = require('locutus/php/array/range'); +import locutus_php_array_reset = require('locutus/php/array/reset'); +import locutus_php_array_rsort = require('locutus/php/array/rsort'); +import locutus_php_array_shuffle = require('locutus/php/array/shuffle'); +import locutus_php_array_sizeof = require('locutus/php/array/sizeof'); +import locutus_php_array_sort = require('locutus/php/array/sort'); +import locutus_php_array_uasort = require('locutus/php/array/uasort'); +import locutus_php_array_uksort = require('locutus/php/array/uksort'); +import locutus_php_array_usort = require('locutus/php/array/usort'); +import locutus_php_bc_bcadd = require('locutus/php/bc/bcadd'); +import locutus_php_bc_bccomp = require('locutus/php/bc/bccomp'); +import locutus_php_bc_bcdiv = require('locutus/php/bc/bcdiv'); +import locutus_php_bc_bcmul = require('locutus/php/bc/bcmul'); +import locutus_php_bc_bcround = require('locutus/php/bc/bcround'); +import locutus_php_bc_bcscale = require('locutus/php/bc/bcscale'); +import locutus_php_bc_bcsub = require('locutus/php/bc/bcsub'); +import locutus_php_ctype_ctype_alnum = require('locutus/php/ctype/ctype_alnum'); +import locutus_php_ctype_ctype_alpha = require('locutus/php/ctype/ctype_alpha'); +import locutus_php_ctype_ctype_cntrl = require('locutus/php/ctype/ctype_cntrl'); +import locutus_php_ctype_ctype_digit = require('locutus/php/ctype/ctype_digit'); +import locutus_php_ctype_ctype_graph = require('locutus/php/ctype/ctype_graph'); +import locutus_php_ctype_ctype_lower = require('locutus/php/ctype/ctype_lower'); +import locutus_php_ctype_ctype_print = require('locutus/php/ctype/ctype_print'); +import locutus_php_ctype_ctype_punct = require('locutus/php/ctype/ctype_punct'); +import locutus_php_ctype_ctype_space = require('locutus/php/ctype/ctype_space'); +import locutus_php_ctype_ctype_upper = require('locutus/php/ctype/ctype_upper'); +import locutus_php_ctype_ctype_xdigit = require('locutus/php/ctype/ctype_xdigit'); +import locutus_php_datetime_checkdate = require('locutus/php/datetime/checkdate'); +import locutus_php_datetime_date = require('locutus/php/datetime/date'); +import locutus_php_datetime_date_parse = require('locutus/php/datetime/date_parse'); +import locutus_php_datetime_getdate = require('locutus/php/datetime/getdate'); +import locutus_php_datetime_gettimeofday = require('locutus/php/datetime/gettimeofday'); +import locutus_php_datetime_gmdate = require('locutus/php/datetime/gmdate'); +import locutus_php_datetime_gmmktime = require('locutus/php/datetime/gmmktime'); +import locutus_php_datetime_gmstrftime = require('locutus/php/datetime/gmstrftime'); +import locutus_php_datetime_idate = require('locutus/php/datetime/idate'); +import locutus_php_datetime_microtime = require('locutus/php/datetime/microtime'); +import locutus_php_datetime_mktime = require('locutus/php/datetime/mktime'); +import locutus_php_datetime_strftime = require('locutus/php/datetime/strftime'); +import locutus_php_datetime_strptime = require('locutus/php/datetime/strptime'); +import locutus_php_datetime_strtotime = require('locutus/php/datetime/strtotime'); +import locutus_php_datetime_time = require('locutus/php/datetime/time'); +import locutus_php_exec_escapeshellarg = require('locutus/php/exec/escapeshellarg'); +import locutus_php_filesystem_basename = require('locutus/php/filesystem/basename'); +import locutus_php_filesystem_dirname = require('locutus/php/filesystem/dirname'); +import locutus_php_filesystem_file_get_contents = require('locutus/php/filesystem/file_get_contents'); +import locutus_php_filesystem_pathinfo = require('locutus/php/filesystem/pathinfo'); +import locutus_php_filesystem_realpath = require('locutus/php/filesystem/realpath'); +import locutus_php_funchand_call_user_func = require('locutus/php/funchand/call_user_func'); +import locutus_php_funchand_call_user_func_array = require('locutus/php/funchand/call_user_func_array'); +import locutus_php_funchand_create_function = require('locutus/php/funchand/create_function'); +import locutus_php_funchand_function_exists = require('locutus/php/funchand/function_exists'); +import locutus_php_funchand_get_defined_functions = require('locutus/php/funchand/get_defined_functions'); +import locutus_php_i18n_i18n_loc_get_default = require('locutus/php/i18n/i18n_loc_get_default'); +import locutus_php_i18n_i18n_loc_set_default = require('locutus/php/i18n/i18n_loc_set_default'); +import locutus_php_info_assert_options = require('locutus/php/info/assert_options'); +import locutus_php_info_getenv = require('locutus/php/info/getenv'); +import locutus_php_info_ini_get = require('locutus/php/info/ini_get'); +import locutus_php_info_ini_set = require('locutus/php/info/ini_set'); +import locutus_php_info_set_time_limit = require('locutus/php/info/set_time_limit'); +import locutus_php_info_version_compare = require('locutus/php/info/version_compare'); +import locutus_php_json_json_decode = require('locutus/php/json/json_decode'); +import locutus_php_json_json_encode = require('locutus/php/json/json_encode'); +import locutus_php_json_json_last_error = require('locutus/php/json/json_last_error'); +import locutus_php_math_abs = require('locutus/php/math/abs'); +import locutus_php_math_acos = require('locutus/php/math/acos'); +import locutus_php_math_acosh = require('locutus/php/math/acosh'); +import locutus_php_math_asin = require('locutus/php/math/asin'); +import locutus_php_math_asinh = require('locutus/php/math/asinh'); +import locutus_php_math_atan = require('locutus/php/math/atan'); +import locutus_php_math_atan2 = require('locutus/php/math/atan2'); +import locutus_php_math_atanh = require('locutus/php/math/atanh'); +import locutus_php_math_base_convert = require('locutus/php/math/base_convert'); +import locutus_php_math_bindec = require('locutus/php/math/bindec'); +import locutus_php_math_ceil = require('locutus/php/math/ceil'); +import locutus_php_math_cos = require('locutus/php/math/cos'); +import locutus_php_math_cosh = require('locutus/php/math/cosh'); +import locutus_php_math_decbin = require('locutus/php/math/decbin'); +import locutus_php_math_dechex = require('locutus/php/math/dechex'); +import locutus_php_math_decoct = require('locutus/php/math/decoct'); +import locutus_php_math_deg2rad = require('locutus/php/math/deg2rad'); +import locutus_php_math_exp = require('locutus/php/math/exp'); +import locutus_php_math_expm1 = require('locutus/php/math/expm1'); +import locutus_php_math_floor = require('locutus/php/math/floor'); +import locutus_php_math_fmod = require('locutus/php/math/fmod'); +import locutus_php_math_getrandmax = require('locutus/php/math/getrandmax'); +import locutus_php_math_hexdec = require('locutus/php/math/hexdec'); +import locutus_php_math_hypot = require('locutus/php/math/hypot'); +import locutus_php_math_is_finite = require('locutus/php/math/is_finite'); +import locutus_php_math_is_infinite = require('locutus/php/math/is_infinite'); +import locutus_php_math_is_nan = require('locutus/php/math/is_nan'); +import locutus_php_math_lcg_value = require('locutus/php/math/lcg_value'); +import locutus_php_math_log = require('locutus/php/math/log'); +import locutus_php_math_log10 = require('locutus/php/math/log10'); +import locutus_php_math_log1p = require('locutus/php/math/log1p'); +import locutus_php_math_max = require('locutus/php/math/max'); +import locutus_php_math_min = require('locutus/php/math/min'); +import locutus_php_math_mt_getrandmax = require('locutus/php/math/mt_getrandmax'); +import locutus_php_math_mt_rand = require('locutus/php/math/mt_rand'); +import locutus_php_math_octdec = require('locutus/php/math/octdec'); +import locutus_php_math_pi = require('locutus/php/math/pi'); +import locutus_php_math_pow = require('locutus/php/math/pow'); +import locutus_php_math_rad2deg = require('locutus/php/math/rad2deg'); +import locutus_php_math_rand = require('locutus/php/math/rand'); +import locutus_php_math_round = require('locutus/php/math/round'); +import locutus_php_math_sin = require('locutus/php/math/sin'); +import locutus_php_math_sinh = require('locutus/php/math/sinh'); +import locutus_php_math_sqrt = require('locutus/php/math/sqrt'); +import locutus_php_math_tan = require('locutus/php/math/tan'); +import locutus_php_math_tanh = require('locutus/php/math/tanh'); +import locutus_php_misc_pack = require('locutus/php/misc/pack'); +import locutus_php_misc_uniqid = require('locutus/php/misc/uniqid'); +import locutus_php_net_gopher_gopher_parsedir = require('locutus/php/net-gopher/gopher_parsedir'); +import locutus_php_network_inet_ntop = require('locutus/php/network/inet_ntop'); +import locutus_php_network_inet_pton = require('locutus/php/network/inet_pton'); +import locutus_php_network_ip2long = require('locutus/php/network/ip2long'); +import locutus_php_network_long2ip = require('locutus/php/network/long2ip'); +import locutus_php_network_setcookie = require('locutus/php/network/setcookie'); +import locutus_php_network_setrawcookie = require('locutus/php/network/setrawcookie'); +import locutus_php_pcre_preg_quote = require('locutus/php/pcre/preg_quote'); +import locutus_php_pcre_sql_regcase = require('locutus/php/pcre/sql_regcase'); +import locutus_php_strings_addcslashes = require('locutus/php/strings/addcslashes'); +import locutus_php_strings_addslashes = require('locutus/php/strings/addslashes'); +import locutus_php_strings_bin2hex = require('locutus/php/strings/bin2hex'); +import locutus_php_strings_chop = require('locutus/php/strings/chop'); +import locutus_php_strings_chr = require('locutus/php/strings/chr'); +import locutus_php_strings_chunk_split = require('locutus/php/strings/chunk_split'); +import locutus_php_strings_convert_cyr_string = require('locutus/php/strings/convert_cyr_string'); +import locutus_php_strings_convert_uuencode = require('locutus/php/strings/convert_uuencode'); +import locutus_php_strings_count_chars = require('locutus/php/strings/count_chars'); +import locutus_php_strings_crc32 = require('locutus/php/strings/crc32'); +import locutus_php_strings_echo = require('locutus/php/strings/echo'); +import locutus_php_strings_explode = require('locutus/php/strings/explode'); +import locutus_php_strings_get_html_translation_table = require('locutus/php/strings/get_html_translation_table'); +import locutus_php_strings_hex2bin = require('locutus/php/strings/hex2bin'); +import locutus_php_strings_html_entity_decode = require('locutus/php/strings/html_entity_decode'); +import locutus_php_strings_htmlentities = require('locutus/php/strings/htmlentities'); +import locutus_php_strings_htmlspecialchars = require('locutus/php/strings/htmlspecialchars'); +import locutus_php_strings_htmlspecialchars_decode = require('locutus/php/strings/htmlspecialchars_decode'); +import locutus_php_strings_implode = require('locutus/php/strings/implode'); +import locutus_php_strings_join = require('locutus/php/strings/join'); +import locutus_php_strings_lcfirst = require('locutus/php/strings/lcfirst'); +import locutus_php_strings_levenshtein = require('locutus/php/strings/levenshtein'); +import locutus_php_strings_localeconv = require('locutus/php/strings/localeconv'); +import locutus_php_strings_ltrim = require('locutus/php/strings/ltrim'); +import locutus_php_strings_md5 = require('locutus/php/strings/md5'); +import locutus_php_strings_md5_file = require('locutus/php/strings/md5_file'); +import locutus_php_strings_metaphone = require('locutus/php/strings/metaphone'); +import locutus_php_strings_money_format = require('locutus/php/strings/money_format'); +import locutus_php_strings_nl2br = require('locutus/php/strings/nl2br'); +import locutus_php_strings_nl_langinfo = require('locutus/php/strings/nl_langinfo'); +import locutus_php_strings_number_format = require('locutus/php/strings/number_format'); +import locutus_php_strings_ord = require('locutus/php/strings/ord'); +import locutus_php_strings_parse_str = require('locutus/php/strings/parse_str'); +import locutus_php_strings_printf = require('locutus/php/strings/printf'); +import locutus_php_strings_quoted_printable_decode = require('locutus/php/strings/quoted_printable_decode'); +import locutus_php_strings_quoted_printable_encode = require('locutus/php/strings/quoted_printable_encode'); +import locutus_php_strings_quotemeta = require('locutus/php/strings/quotemeta'); +import locutus_php_strings_rtrim = require('locutus/php/strings/rtrim'); +import locutus_php_strings_setlocale = require('locutus/php/strings/setlocale'); +import locutus_php_strings_sha1 = require('locutus/php/strings/sha1'); +import locutus_php_strings_sha1_file = require('locutus/php/strings/sha1_file'); +import locutus_php_strings_similar_text = require('locutus/php/strings/similar_text'); +import locutus_php_strings_soundex = require('locutus/php/strings/soundex'); +import locutus_php_strings_split = require('locutus/php/strings/split'); +import locutus_php_strings_sprintf = require('locutus/php/strings/sprintf'); +import locutus_php_strings_sscanf = require('locutus/php/strings/sscanf'); +import locutus_php_strings_str_getcsv = require('locutus/php/strings/str_getcsv'); +import locutus_php_strings_str_ireplace = require('locutus/php/strings/str_ireplace'); +import locutus_php_strings_str_pad = require('locutus/php/strings/str_pad'); +import locutus_php_strings_str_repeat = require('locutus/php/strings/str_repeat'); +import locutus_php_strings_str_replace = require('locutus/php/strings/str_replace'); +import locutus_php_strings_str_rot13 = require('locutus/php/strings/str_rot13'); +import locutus_php_strings_str_shuffle = require('locutus/php/strings/str_shuffle'); +import locutus_php_strings_str_split = require('locutus/php/strings/str_split'); +import locutus_php_strings_str_word_count = require('locutus/php/strings/str_word_count'); +import locutus_php_strings_strcasecmp = require('locutus/php/strings/strcasecmp'); +import locutus_php_strings_strchr = require('locutus/php/strings/strchr'); +import locutus_php_strings_strcmp = require('locutus/php/strings/strcmp'); +import locutus_php_strings_strcoll = require('locutus/php/strings/strcoll'); +import locutus_php_strings_strcspn = require('locutus/php/strings/strcspn'); +import locutus_php_strings_strip_tags = require('locutus/php/strings/strip_tags'); +import locutus_php_strings_stripos = require('locutus/php/strings/stripos'); +import locutus_php_strings_stripslashes = require('locutus/php/strings/stripslashes'); +import locutus_php_strings_stristr = require('locutus/php/strings/stristr'); +import locutus_php_strings_strlen = require('locutus/php/strings/strlen'); +import locutus_php_strings_strnatcasecmp = require('locutus/php/strings/strnatcasecmp'); +import locutus_php_strings_strnatcmp = require('locutus/php/strings/strnatcmp'); +import locutus_php_strings_strncasecmp = require('locutus/php/strings/strncasecmp'); +import locutus_php_strings_strncmp = require('locutus/php/strings/strncmp'); +import locutus_php_strings_strpbrk = require('locutus/php/strings/strpbrk'); +import locutus_php_strings_strpos = require('locutus/php/strings/strpos'); +import locutus_php_strings_strrchr = require('locutus/php/strings/strrchr'); +import locutus_php_strings_strrev = require('locutus/php/strings/strrev'); +import locutus_php_strings_strripos = require('locutus/php/strings/strripos'); +import locutus_php_strings_strrpos = require('locutus/php/strings/strrpos'); +import locutus_php_strings_strspn = require('locutus/php/strings/strspn'); +import locutus_php_strings_strstr = require('locutus/php/strings/strstr'); +import locutus_php_strings_strtok = require('locutus/php/strings/strtok'); +import locutus_php_strings_strtolower = require('locutus/php/strings/strtolower'); +import locutus_php_strings_strtoupper = require('locutus/php/strings/strtoupper'); +import locutus_php_strings_strtr = require('locutus/php/strings/strtr'); +import locutus_php_strings_substr = require('locutus/php/strings/substr'); +import locutus_php_strings_substr_compare = require('locutus/php/strings/substr_compare'); +import locutus_php_strings_substr_count = require('locutus/php/strings/substr_count'); +import locutus_php_strings_substr_replace = require('locutus/php/strings/substr_replace'); +import locutus_php_strings_trim = require('locutus/php/strings/trim'); +import locutus_php_strings_ucfirst = require('locutus/php/strings/ucfirst'); +import locutus_php_strings_ucwords = require('locutus/php/strings/ucwords'); +import locutus_php_strings_vprintf = require('locutus/php/strings/vprintf'); +import locutus_php_strings_vsprintf = require('locutus/php/strings/vsprintf'); +import locutus_php_strings_wordwrap = require('locutus/php/strings/wordwrap'); +import locutus_php_url_base64_decode = require('locutus/php/url/base64_decode'); +import locutus_php_url_base64_encode = require('locutus/php/url/base64_encode'); +import locutus_php_url_http_build_query = require('locutus/php/url/http_build_query'); +import locutus_php_url_parse_url = require('locutus/php/url/parse_url'); +import locutus_php_url_rawurldecode = require('locutus/php/url/rawurldecode'); +import locutus_php_url_rawurlencode = require('locutus/php/url/rawurlencode'); +import locutus_php_url_urldecode = require('locutus/php/url/urldecode'); +import locutus_php_url_urlencode = require('locutus/php/url/urlencode'); +import locutus_php_var_doubleval = require('locutus/php/var/doubleval'); +import locutus_php_var_empty = require('locutus/php/var/empty'); +import locutus_php_var_floatval = require('locutus/php/var/floatval'); +import locutus_php_var_gettype = require('locutus/php/var/gettype'); +import locutus_php_var_intval = require('locutus/php/var/intval'); +import locutus_php_var_is_array = require('locutus/php/var/is_array'); +import locutus_php_var_is_binary = require('locutus/php/var/is_binary'); +import locutus_php_var_is_bool = require('locutus/php/var/is_bool'); +import locutus_php_var_is_buffer = require('locutus/php/var/is_buffer'); +import locutus_php_var_is_callable = require('locutus/php/var/is_callable'); +import locutus_php_var_is_double = require('locutus/php/var/is_double'); +import locutus_php_var_is_float = require('locutus/php/var/is_float'); +import locutus_php_var_is_int = require('locutus/php/var/is_int'); +import locutus_php_var_is_integer = require('locutus/php/var/is_integer'); +import locutus_php_var_is_long = require('locutus/php/var/is_long'); +import locutus_php_var_is_null = require('locutus/php/var/is_null'); +import locutus_php_var_is_numeric = require('locutus/php/var/is_numeric'); +import locutus_php_var_is_object = require('locutus/php/var/is_object'); +import locutus_php_var_is_real = require('locutus/php/var/is_real'); +import locutus_php_var_is_scalar = require('locutus/php/var/is_scalar'); +import locutus_php_var_is_string = require('locutus/php/var/is_string'); +import locutus_php_var_is_unicode = require('locutus/php/var/is_unicode'); +import locutus_php_var_isset = require('locutus/php/var/isset'); +import locutus_php_var_print_r = require('locutus/php/var/print_r'); +import locutus_php_var_serialize = require('locutus/php/var/serialize'); +import locutus_php_var_strval = require('locutus/php/var/strval'); +import locutus_php_var_unserialize = require('locutus/php/var/unserialize'); +import locutus_php_var_var_dump = require('locutus/php/var/var_dump'); +import locutus_php_var_var_export = require('locutus/php/var/var_export'); +import locutus_php_xdiff_xdiff_string_diff = require('locutus/php/xdiff/xdiff_string_diff'); +import locutus_php_xdiff_xdiff_string_patch = require('locutus/php/xdiff/xdiff_string_patch'); +import locutus_php_xml_utf8_decode = require('locutus/php/xml/utf8_decode'); +import locutus_php_xml_utf8_encode = require('locutus/php/xml/utf8_encode'); +import locutus_python_string_capwords = require('locutus/python/string/capwords'); +import locutus_ruby_Math_acos = require('locutus/ruby/Math/acos'); +import locutus_c_math = require('locutus/c/math'); +import locutus_golang_strings = require('locutus/golang/strings'); +import locutus_php_array = require('locutus/php/array'); +import locutus_php_bc = require('locutus/php/bc'); +import locutus_php_ctype = require('locutus/php/ctype'); +import locutus_php_datetime = require('locutus/php/datetime'); +import locutus_php_exec = require('locutus/php/exec'); +import locutus_php_filesystem = require('locutus/php/filesystem'); +import locutus_php_funchand = require('locutus/php/funchand'); +import locutus_php_i18n = require('locutus/php/i18n'); +import locutus_php_info = require('locutus/php/info'); +import locutus_php_json = require('locutus/php/json'); +import locutus_php_math = require('locutus/php/math'); +import locutus_php_misc = require('locutus/php/misc'); +import locutus_php_net_gopher = require('locutus/php/net-gopher'); +import locutus_php_network = require('locutus/php/network'); +import locutus_php_pcre = require('locutus/php/pcre'); +import locutus_php_strings = require('locutus/php/strings'); +import locutus_php_url = require('locutus/php/url'); +import locutus_php_var = require('locutus/php/var'); +import locutus_php_xdiff = require('locutus/php/xdiff'); +import locutus_php_xml = require('locutus/php/xml'); +import locutus_python_string = require('locutus/python/string'); +import locutus_ruby_Math = require('locutus/ruby/Math'); +import locutus_c = require('locutus/c'); +import locutus_golang = require('locutus/golang'); +import locutus_php = require('locutus/php'); +import locutus_python = require('locutus/python'); +import locutus_ruby = require('locutus/ruby'); +import locutus = require('locutus'); diff --git a/locutus/locutus.d.ts b/locutus/locutus.d.ts new file mode 100644 index 0000000000..4e1077a937 --- /dev/null +++ b/locutus/locutus.d.ts @@ -0,0 +1,1734 @@ +// Type definitions for locutus +// Project: http://locutusjs.io +// Definitions by: Hookclaw +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "locutus/c/math/abs" { + function abs(mixedNumber?:any):any; + export = abs; +} +declare module "locutus/golang/strings/Contains" { + function Contains(s?:any, substr?:any):any; + export = Contains; +} +declare module "locutus/golang/strings/Count" { + function Count(s?:any, sep?:any):any; + export = Count; +} +declare module "locutus/golang/strings/Index" { + function Index(s?:any, sep?:any):any; + export = Index; +} +declare module "locutus/golang/strings/LastIndex" { + function LastIndex(s?:any, sep?:any):any; + export = LastIndex; +} +declare module "locutus/php/array/array_change_key_case" { + function array_change_key_case(array?:any, cs?:any):any; + export = array_change_key_case; +} +declare module "locutus/php/array/array_chunk" { + function array_chunk(input?:any, size?:any, preserveKeys?:any):any; + export = array_chunk; +} +declare module "locutus/php/array/array_combine" { + function array_combine(keys?:any, values?:any):any; + export = array_combine; +} +declare module "locutus/php/array/array_count_values" { + function array_count_values(array?:any):any; + export = array_count_values; +} +declare module "locutus/php/array/array_diff" { + function array_diff(...args:any[]):any; + export = array_diff; +} +declare module "locutus/php/array/array_diff_assoc" { + function array_diff_assoc(...args:any[]):any; + export = array_diff_assoc; +} +declare module "locutus/php/array/array_diff_key" { + function array_diff_key(...args:any[]):any; + export = array_diff_key; +} +declare module "locutus/php/array/array_diff_uassoc" { + function array_diff_uassoc(...args:any[]):any; + export = array_diff_uassoc; +} +declare module "locutus/php/array/array_diff_ukey" { + function array_diff_ukey(...args:any[]):any; + export = array_diff_ukey; +} +declare module "locutus/php/array/array_fill" { + function array_fill(startIndex?:any, num?:any, mixedVal?:any):any; + export = array_fill; +} +declare module "locutus/php/array/array_fill_keys" { + function array_fill_keys(keys?:any, value?:any):any; + export = array_fill_keys; +} +declare module "locutus/php/array/array_filter" { + function array_filter(arr?:any, func?:any):any; + export = array_filter; +} +declare module "locutus/php/array/array_flip" { + function array_flip(trans?:any):any; + export = array_flip; +} +declare module "locutus/php/array/array_intersect" { + function array_intersect(...args:any[]):any; + export = array_intersect; +} +declare module "locutus/php/array/array_intersect_assoc" { + function array_intersect_assoc(...args:any[]):any; + export = array_intersect_assoc; +} +declare module "locutus/php/array/array_intersect_key" { + function array_intersect_key(...args:any[]):any; + export = array_intersect_key; +} +declare module "locutus/php/array/array_intersect_uassoc" { + function array_intersect_uassoc(...args:any[]):any; + export = array_intersect_uassoc; +} +declare module "locutus/php/array/array_intersect_ukey" { + function array_intersect_ukey(...args:any[]):any; + export = array_intersect_ukey; +} +declare module "locutus/php/array/array_key_exists" { + function array_key_exists(key?:any, search?:any):any; + export = array_key_exists; +} +declare module "locutus/php/array/array_keys" { + function array_keys(input?:any, searchValue?:any, argStrict?:any):any; + export = array_keys; +} +declare module "locutus/php/array/array_map" { + function array_map(...args:any[]):any; + export = array_map; +} +declare module "locutus/php/array/array_merge" { + function array_merge(...args:any[]):any; + export = array_merge; +} +declare module "locutus/php/array/array_merge_recursive" { + function array_merge_recursive(arr1?:any, arr2?:any):any; + export = array_merge_recursive; +} +declare module "locutus/php/array/array_multisort" { + function array_multisort(...args:any[]):any; + export = array_multisort; +} +declare module "locutus/php/array/array_pad" { + function array_pad(input?:any, padSize?:any, padValue?:any):any; + export = array_pad; +} +declare module "locutus/php/array/array_pop" { + function array_pop(inputArr?:any):any; + export = array_pop; +} +declare module "locutus/php/array/array_product" { + function array_product(input?:any):any; + export = array_product; +} +declare module "locutus/php/array/array_push" { + function array_push(...args:any[]):any; + export = array_push; +} +declare module "locutus/php/array/array_rand" { + function array_rand(input?:any, numReq?:any):any; + export = array_rand; +} +declare module "locutus/php/array/array_reduce" { + function array_reduce(aInput?:any, callback?:any):any; + export = array_reduce; +} +declare module "locutus/php/array/array_replace" { + function array_replace(...args:any[]):any; + export = array_replace; +} +declare module "locutus/php/array/array_replace_recursive" { + function array_replace_recursive(...args:any[]):any; + export = array_replace_recursive; +} +declare module "locutus/php/array/array_reverse" { + function array_reverse(array?:any, preserveKeys?:any):any; + export = array_reverse; +} +declare module "locutus/php/array/array_search" { + function array_search(needle?:any, haystack?:any, argStrict?:any):any; + export = array_search; +} +declare module "locutus/php/array/array_shift" { + function array_shift(inputArr?:any):any; + export = array_shift; +} +declare module "locutus/php/array/array_slice" { + function array_slice(arr?:any, offst?:any, lgth?:any, preserveKeys?:any):any; + export = array_slice; +} +declare module "locutus/php/array/array_splice" { + function array_splice(arr?:any, offst?:any, lgth?:any, replacement?:any):any; + export = array_splice; +} +declare module "locutus/php/array/array_sum" { + function array_sum(array?:any):any; + export = array_sum; +} +declare module "locutus/php/array/array_udiff" { + function array_udiff(...args:any[]):any; + export = array_udiff; +} +declare module "locutus/php/array/array_udiff_assoc" { + function array_udiff_assoc(...args:any[]):any; + export = array_udiff_assoc; +} +declare module "locutus/php/array/array_udiff_uassoc" { + function array_udiff_uassoc(...args:any[]):any; + export = array_udiff_uassoc; +} +declare module "locutus/php/array/array_uintersect" { + function array_uintersect(...args:any[]):any; + export = array_uintersect; +} +declare module "locutus/php/array/array_uintersect_uassoc" { + function array_uintersect_uassoc(...args:any[]):any; + export = array_uintersect_uassoc; +} +declare module "locutus/php/array/array_unique" { + function array_unique(inputArr?:any):any; + export = array_unique; +} +declare module "locutus/php/array/array_unshift" { + function array_unshift(...args:any[]):any; + export = array_unshift; +} +declare module "locutus/php/array/array_values" { + function array_values(input?:any):any; + export = array_values; +} +declare module "locutus/php/array/array_walk" { + function array_walk(...args:any[]):any; + export = array_walk; +} +declare module "locutus/php/array/arsort" { + function arsort(inputArr?:any, sortFlags?:any):any; + export = arsort; +} +declare module "locutus/php/array/asort" { + function asort(inputArr?:any, sortFlags?:any):any; + export = asort; +} +declare module "locutus/php/array/count" { + function count(mixedVar?:any, mode?:any):any; + export = count; +} +declare module "locutus/php/array/current" { + function current(arr?:any):any; + export = current; +} +declare module "locutus/php/array/each" { + function each(arr?:any):any; + export = each; +} +declare module "locutus/php/array/end" { + function end(arr?:any):any; + export = end; +} +declare module "locutus/php/array/in_array" { + function in_array(needle?:any, haystack?:any, argStrict?:any):any; + export = in_array; +} +declare module "locutus/php/array/key" { + function key(arr?:any):any; + export = key; +} +declare module "locutus/php/array/krsort" { + function krsort(inputArr?:any, sortFlags?:any):any; + export = krsort; +} +declare module "locutus/php/array/ksort" { + function ksort(inputArr?:any, sortFlags?:any):any; + export = ksort; +} +declare module "locutus/php/array/natcasesort" { + function natcasesort(inputArr?:any):any; + export = natcasesort; +} +declare module "locutus/php/array/natsort" { + function natsort(inputArr?:any):any; + export = natsort; +} +declare module "locutus/php/array/next" { + function next(arr?:any):any; + export = next; +} +declare module "locutus/php/array/pos" { + function pos(arr?:any):any; + export = pos; +} +declare module "locutus/php/array/prev" { + function prev(arr?:any):any; + export = prev; +} +declare module "locutus/php/array/range" { + function range(low?:any, high?:any, step?:any):any; + export = range; +} +declare module "locutus/php/array/reset" { + function reset(arr?:any):any; + export = reset; +} +declare module "locutus/php/array/rsort" { + function rsort(inputArr?:any, sortFlags?:any):any; + export = rsort; +} +declare module "locutus/php/array/shuffle" { + function shuffle(inputArr?:any):any; + export = shuffle; +} +declare module "locutus/php/array/sizeof" { + function sizeof(mixedVar?:any, mode?:any):any; + export = sizeof; +} +declare module "locutus/php/array/sort" { + function sort(inputArr?:any, sortFlags?:any):any; + export = sort; +} +declare module "locutus/php/array/uasort" { + function uasort(inputArr?:any, sorter?:any):any; + export = uasort; +} +declare module "locutus/php/array/uksort" { + function uksort(inputArr?:any, sorter?:any):any; + export = uksort; +} +declare module "locutus/php/array/usort" { + function usort(inputArr?:any, sorter?:any):any; + export = usort; +} +declare module "locutus/php/bc/bcadd" { + function bcadd(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcadd; +} +declare module "locutus/php/bc/bccomp" { + function bccomp(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bccomp; +} +declare module "locutus/php/bc/bcdiv" { + function bcdiv(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcdiv; +} +declare module "locutus/php/bc/bcmul" { + function bcmul(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcmul; +} +declare module "locutus/php/bc/bcround" { + function bcround(val?:any, precision?:any):any; + export = bcround; +} +declare module "locutus/php/bc/bcscale" { + function bcscale(scale?:any):any; + export = bcscale; +} +declare module "locutus/php/bc/bcsub" { + function bcsub(leftOperand?:any, rightOperand?:any, scale?:any):any; + export = bcsub; +} +declare module "locutus/php/ctype/ctype_alnum" { + function ctype_alnum(text?:any):any; + export = ctype_alnum; +} +declare module "locutus/php/ctype/ctype_alpha" { + function ctype_alpha(text?:any):any; + export = ctype_alpha; +} +declare module "locutus/php/ctype/ctype_cntrl" { + function ctype_cntrl(text?:any):any; + export = ctype_cntrl; +} +declare module "locutus/php/ctype/ctype_digit" { + function ctype_digit(text?:any):any; + export = ctype_digit; +} +declare module "locutus/php/ctype/ctype_graph" { + function ctype_graph(text?:any):any; + export = ctype_graph; +} +declare module "locutus/php/ctype/ctype_lower" { + function ctype_lower(text?:any):any; + export = ctype_lower; +} +declare module "locutus/php/ctype/ctype_print" { + function ctype_print(text?:any):any; + export = ctype_print; +} +declare module "locutus/php/ctype/ctype_punct" { + function ctype_punct(text?:any):any; + export = ctype_punct; +} +declare module "locutus/php/ctype/ctype_space" { + function ctype_space(text?:any):any; + export = ctype_space; +} +declare module "locutus/php/ctype/ctype_upper" { + function ctype_upper(text?:any):any; + export = ctype_upper; +} +declare module "locutus/php/ctype/ctype_xdigit" { + function ctype_xdigit(text?:any):any; + export = ctype_xdigit; +} +declare module "locutus/php/datetime/checkdate" { + function checkdate(m?:any, d?:any, y?:any):any; + export = checkdate; +} +declare module "locutus/php/datetime/date" { + function date(format?:any, timestamp?:any):any; + export = date; +} +declare module "locutus/php/datetime/date_parse" { + function date_parse(date?:any):any; + export = date_parse; +} +declare module "locutus/php/datetime/getdate" { + function getdate(timestamp?:any):any; + export = getdate; +} +declare module "locutus/php/datetime/gettimeofday" { + function gettimeofday(returnFloat?:any):any; + export = gettimeofday; +} +declare module "locutus/php/datetime/gmdate" { + function gmdate(format?:any, timestamp?:any):any; + export = gmdate; +} +declare module "locutus/php/datetime/gmmktime" { + function gmmktime(...args:any[]):any; + export = gmmktime; +} +declare module "locutus/php/datetime/gmstrftime" { + function gmstrftime(format?:any, timestamp?:any):any; + export = gmstrftime; +} +declare module "locutus/php/datetime/idate" { + function idate(format?:any, timestamp?:any):any; + export = idate; +} +declare module "locutus/php/datetime/microtime" { + function microtime(getAsFloat?:any):any; + export = microtime; +} +declare module "locutus/php/datetime/mktime" { + function mktime(...args:any[]):any; + export = mktime; +} +declare module "locutus/php/datetime/strftime" { + function strftime(fmt?:any, timestamp?:any):any; + export = strftime; +} +declare module "locutus/php/datetime/strptime" { + function strptime(dateStr?:any, format?:any):any; + export = strptime; +} +declare module "locutus/php/datetime/strtotime" { + function strtotime(text?:any, now?:any):any; + export = strtotime; +} +declare module "locutus/php/datetime/time" { + function time():any; + export = time; +} +declare module "locutus/php/exec/escapeshellarg" { + function escapeshellarg(arg?:any):any; + export = escapeshellarg; +} +declare module "locutus/php/filesystem/basename" { + function basename(path?:any, suffix?:any):any; + export = basename; +} +declare module "locutus/php/filesystem/dirname" { + function dirname(path?:any):any; + export = dirname; +} +declare module "locutus/php/filesystem/file_get_contents" { + function file_get_contents(url?:any, flags?:any, context?:any, offset?:any, maxLen?:any):any; + export = file_get_contents; +} +declare module "locutus/php/filesystem/pathinfo" { + function pathinfo(...args:any[]):any; + export = pathinfo; +} +declare module "locutus/php/filesystem/realpath" { + function realpath(path?:any):any; + export = realpath; +} +declare module "locutus/php/funchand/call_user_func" { + function call_user_func(...args:any[]):any; + export = call_user_func; +} +declare module "locutus/php/funchand/call_user_func_array" { + function call_user_func_array(cb?:any, parameters?:any):any; + export = call_user_func_array; +} +declare module "locutus/php/funchand/create_function" { + function create_function(args?:any, code?:any):any; + export = create_function; +} +declare module "locutus/php/funchand/function_exists" { + function function_exists(funcName?:any):any; + export = function_exists; +} +declare module "locutus/php/funchand/get_defined_functions" { + function get_defined_functions():any; + export = get_defined_functions; +} +declare module "locutus/php/i18n/i18n_loc_get_default" { + function i18n_loc_get_default():any; + export = i18n_loc_get_default; +} +declare module "locutus/php/i18n/i18n_loc_set_default" { + function i18n_loc_set_default(name?:any):any; + export = i18n_loc_set_default; +} +declare module "locutus/php/info/assert_options" { + function assert_options(what?:any, value?:any):any; + export = assert_options; +} +declare module "locutus/php/info/getenv" { + function getenv(varname?:any):any; + export = getenv; +} +declare module "locutus/php/info/ini_get" { + function ini_get(varname?:any):any; + export = ini_get; +} +declare module "locutus/php/info/ini_set" { + function ini_set(varname?:any, newvalue?:any):any; + export = ini_set; +} +declare module "locutus/php/info/set_time_limit" { + function set_time_limit(seconds?:any):any; + export = set_time_limit; +} +declare module "locutus/php/info/version_compare" { + function version_compare(v1?:any, v2?:any, operator?:any):any; + export = version_compare; +} +declare module "locutus/php/json/json_decode" { + function json_decode(strJson?:any):any; + export = json_decode; +} +declare module "locutus/php/json/json_encode" { + function json_encode(mixedVal?:any):any; + export = json_encode; +} +declare module "locutus/php/json/json_last_error" { + function json_last_error():any; + export = json_last_error; +} +declare module "locutus/php/math/abs" { + function abs(mixedNumber?:any):any; + export = abs; +} +declare module "locutus/php/math/acos" { + function acos(arg?:any):any; + export = acos; +} +declare module "locutus/php/math/acosh" { + function acosh(arg?:any):any; + export = acosh; +} +declare module "locutus/php/math/asin" { + function asin(arg?:any):any; + export = asin; +} +declare module "locutus/php/math/asinh" { + function asinh(arg?:any):any; + export = asinh; +} +declare module "locutus/php/math/atan" { + function atan(arg?:any):any; + export = atan; +} +declare module "locutus/php/math/atan2" { + function atan2(y?:any, x?:any):any; + export = atan2; +} +declare module "locutus/php/math/atanh" { + function atanh(arg?:any):any; + export = atanh; +} +declare module "locutus/php/math/base_convert" { + function base_convert(number?:any, frombase?:any, tobase?:any):any; + export = base_convert; +} +declare module "locutus/php/math/bindec" { + function bindec(binaryString?:any):any; + export = bindec; +} +declare module "locutus/php/math/ceil" { + function ceil(value?:any):any; + export = ceil; +} +declare module "locutus/php/math/cos" { + function cos(arg?:any):any; + export = cos; +} +declare module "locutus/php/math/cosh" { + function cosh(arg?:any):any; + export = cosh; +} +declare module "locutus/php/math/decbin" { + function decbin(number?:any):any; + export = decbin; +} +declare module "locutus/php/math/dechex" { + function dechex(number?:any):any; + export = dechex; +} +declare module "locutus/php/math/decoct" { + function decoct(number?:any):any; + export = decoct; +} +declare module "locutus/php/math/deg2rad" { + function deg2rad(angle?:any):any; + export = deg2rad; +} +declare module "locutus/php/math/exp" { + function exp(arg?:any):any; + export = exp; +} +declare module "locutus/php/math/expm1" { + function expm1(x?:any):any; + export = expm1; +} +declare module "locutus/php/math/floor" { + function floor(value?:any):any; + export = floor; +} +declare module "locutus/php/math/fmod" { + function fmod(x?:any, y?:any):any; + export = fmod; +} +declare module "locutus/php/math/getrandmax" { + function getrandmax():any; + export = getrandmax; +} +declare module "locutus/php/math/hexdec" { + function hexdec(hexString?:any):any; + export = hexdec; +} +declare module "locutus/php/math/hypot" { + function hypot(x?:any, y?:any):any; + export = hypot; +} +declare module "locutus/php/math/is_finite" { + function is_finite(val?:any):any; + export = is_finite; +} +declare module "locutus/php/math/is_infinite" { + function is_infinite(val?:any):any; + export = is_infinite; +} +declare module "locutus/php/math/is_nan" { + function is_nan(val?:any):any; + export = is_nan; +} +declare module "locutus/php/math/lcg_value" { + function lcg_value():any; + export = lcg_value; +} +declare module "locutus/php/math/log" { + function log(arg?:any, base?:any):any; + export = log; +} +declare module "locutus/php/math/log10" { + function log10(arg?:any):any; + export = log10; +} +declare module "locutus/php/math/log1p" { + function log1p(x?:any):any; + export = log1p; +} +declare module "locutus/php/math/max" { + function max(...args:any[]):any; + export = max; +} +declare module "locutus/php/math/min" { + function min(...args:any[]):any; + export = min; +} +declare module "locutus/php/math/mt_getrandmax" { + function mt_getrandmax():any; + export = mt_getrandmax; +} +declare module "locutus/php/math/mt_rand" { + function mt_rand(...args:any[]):any; + export = mt_rand; +} +declare module "locutus/php/math/octdec" { + function octdec(octString?:any):any; + export = octdec; +} +declare module "locutus/php/math/pi" { + function pi():any; + export = pi; +} +declare module "locutus/php/math/pow" { + function pow(base?:any, exp?:any):any; + export = pow; +} +declare module "locutus/php/math/rad2deg" { + function rad2deg(angle?:any):any; + export = rad2deg; +} +declare module "locutus/php/math/rand" { + function rand(...args:any[]):any; + export = rand; +} +declare module "locutus/php/math/round" { + function round(...args:any[]):any; + export = round; +} +declare module "locutus/php/math/sin" { + function sin(arg?:any):any; + export = sin; +} +declare module "locutus/php/math/sinh" { + function sinh(arg?:any):any; + export = sinh; +} +declare module "locutus/php/math/sqrt" { + function sqrt(arg?:any):any; + export = sqrt; +} +declare module "locutus/php/math/tan" { + function tan(arg?:any):any; + export = tan; +} +declare module "locutus/php/math/tanh" { + function tanh(arg?:any):any; + export = tanh; +} +declare module "locutus/php/misc/pack" { + function pack(...args:any[]):any; + export = pack; +} +declare module "locutus/php/misc/uniqid" { + function uniqid(prefix?:any, moreEntropy?:any):any; + export = uniqid; +} +declare module "locutus/php/net-gopher/gopher_parsedir" { + function gopher_parsedir(dirent?:any):any; + export = gopher_parsedir; +} +declare module "locutus/php/network/inet_ntop" { + function inet_ntop(a?:any):any; + export = inet_ntop; +} +declare module "locutus/php/network/inet_pton" { + function inet_pton(a?:any):any; + export = inet_pton; +} +declare module "locutus/php/network/ip2long" { + function ip2long(argIP?:any):any; + export = ip2long; +} +declare module "locutus/php/network/long2ip" { + function long2ip(ip?:any):any; + export = long2ip; +} +declare module "locutus/php/network/setcookie" { + function setcookie(name?:any, value?:any, expires?:any, path?:any, domain?:any, secure?:any):any; + export = setcookie; +} +declare module "locutus/php/network/setrawcookie" { + function setrawcookie(name?:any, value?:any, expires?:any, path?:any, domain?:any, secure?:any):any; + export = setrawcookie; +} +declare module "locutus/php/pcre/preg_quote" { + function preg_quote(str?:any, delimiter?:any):any; + export = preg_quote; +} +declare module "locutus/php/pcre/sql_regcase" { + function sql_regcase(str?:any):any; + export = sql_regcase; +} +declare module "locutus/php/strings/addcslashes" { + function addcslashes(str?:any, charlist?:any):any; + export = addcslashes; +} +declare module "locutus/php/strings/addslashes" { + function addslashes(str?:any):any; + export = addslashes; +} +declare module "locutus/php/strings/bin2hex" { + function bin2hex(s?:any):any; + export = bin2hex; +} +declare module "locutus/php/strings/chop" { + function chop(str?:any, charlist?:any):any; + export = chop; +} +declare module "locutus/php/strings/chr" { + function chr(codePt?:any):any; + export = chr; +} +declare module "locutus/php/strings/chunk_split" { + function chunk_split(body?:any, chunklen?:any, end?:any):any; + export = chunk_split; +} +declare module "locutus/php/strings/convert_cyr_string" { + function convert_cyr_string(str?:any, from?:any, to?:any):any; + export = convert_cyr_string; +} +declare module "locutus/php/strings/convert_uuencode" { + function convert_uuencode(str?:any):any; + export = convert_uuencode; +} +declare module "locutus/php/strings/count_chars" { + function count_chars(str?:any, mode?:any):any; + export = count_chars; +} +declare module "locutus/php/strings/crc32" { + function crc32(str?:any):any; + export = crc32; +} +declare module "locutus/php/strings/echo" { + function echo(...args:any[]):any; + export = echo; +} +declare module "locutus/php/strings/explode" { + function explode(...args:any[]):any; + export = explode; +} +declare module "locutus/php/strings/get_html_translation_table" { + function get_html_translation_table(...args:any[]):any; + export = get_html_translation_table; +} +declare module "locutus/php/strings/hex2bin" { + function hex2bin(s?:any):any; + export = hex2bin; +} +declare module "locutus/php/strings/html_entity_decode" { + function html_entity_decode(string?:any, quoteStyle?:any):any; + export = html_entity_decode; +} +declare module "locutus/php/strings/htmlentities" { + function htmlentities(string?:any, quoteStyle?:any, charset?:any, doubleEncode?:any):any; + export = htmlentities; +} +declare module "locutus/php/strings/htmlspecialchars" { + function htmlspecialchars(string?:any, quoteStyle?:any, charset?:any, doubleEncode?:any):any; + export = htmlspecialchars; +} +declare module "locutus/php/strings/htmlspecialchars_decode" { + function htmlspecialchars_decode(string?:any, quoteStyle?:any):any; + export = htmlspecialchars_decode; +} +declare module "locutus/php/strings/implode" { + function implode(...args:any[]):any; + export = implode; +} +declare module "locutus/php/strings/join" { + function join(glue?:any, pieces?:any):any; + export = join; +} +declare module "locutus/php/strings/lcfirst" { + function lcfirst(str?:any):any; + export = lcfirst; +} +declare module "locutus/php/strings/levenshtein" { + function levenshtein(s1?:any, s2?:any, costIns?:any, costRep?:any, costDel?:any):any; + export = levenshtein; +} +declare module "locutus/php/strings/localeconv" { + function localeconv():any; + export = localeconv; +} +declare module "locutus/php/strings/ltrim" { + function ltrim(str?:any, charlist?:any):any; + export = ltrim; +} +declare module "locutus/php/strings/md5" { + function md5(str?:any):any; + export = md5; +} +declare module "locutus/php/strings/md5_file" { + function md5_file(str_filename?:any):any; + export = md5_file; +} +declare module "locutus/php/strings/metaphone" { + function metaphone(word?:any, maxPhonemes?:any):any; + export = metaphone; +} +declare module "locutus/php/strings/money_format" { + function money_format(format?:any, number?:any):any; + export = money_format; +} +declare module "locutus/php/strings/nl2br" { + function nl2br(str?:any, isXhtml?:any):any; + export = nl2br; +} +declare module "locutus/php/strings/nl_langinfo" { + function nl_langinfo(item?:any):any; + export = nl_langinfo; +} +declare module "locutus/php/strings/number_format" { + function number_format(number?:any, decimals?:any, decPoint?:any, thousandsSep?:any):any; + export = number_format; +} +declare module "locutus/php/strings/ord" { + function ord(string?:any):any; + export = ord; +} +declare module "locutus/php/strings/parse_str" { + function parse_str(str?:any, array?:any):any; + export = parse_str; +} +declare module "locutus/php/strings/printf" { + function printf(...args:any[]):any; + export = printf; +} +declare module "locutus/php/strings/quoted_printable_decode" { + function quoted_printable_decode(str?:any):any; + export = quoted_printable_decode; +} +declare module "locutus/php/strings/quoted_printable_encode" { + function quoted_printable_encode(str?:any):any; + export = quoted_printable_encode; +} +declare module "locutus/php/strings/quotemeta" { + function quotemeta(str?:any):any; + export = quotemeta; +} +declare module "locutus/php/strings/rtrim" { + function rtrim(str?:any, charlist?:any):any; + export = rtrim; +} +declare module "locutus/php/strings/setlocale" { + function setlocale(category?:any, locale?:any):any; + export = setlocale; +} +declare module "locutus/php/strings/sha1" { + function sha1(str?:any):any; + export = sha1; +} +declare module "locutus/php/strings/sha1_file" { + function sha1_file(str_filename?:any):any; + export = sha1_file; +} +declare module "locutus/php/strings/similar_text" { + function similar_text(first?:any, second?:any, percent?:any):any; + export = similar_text; +} +declare module "locutus/php/strings/soundex" { + function soundex(str?:any):any; + export = soundex; +} +declare module "locutus/php/strings/split" { + function split(delimiter?:any, string?:any):any; + export = split; +} +declare module "locutus/php/strings/sprintf" { + function sprintf(...args:any[]):any; + export = sprintf; +} +declare module "locutus/php/strings/sscanf" { + function sscanf(...args:any[]):any; + export = sscanf; +} +declare module "locutus/php/strings/str_getcsv" { + function str_getcsv(input?:any, delimiter?:any, enclosure?:any, escape?:any):any; + export = str_getcsv; +} +declare module "locutus/php/strings/str_ireplace" { + function str_ireplace(search?:any, replace?:any, subject?:any, countObj?:any):any; + export = str_ireplace; +} +declare module "locutus/php/strings/str_pad" { + function str_pad(input?:any, padLength?:any, padString?:any, padType?:any):any; + export = str_pad; +} +declare module "locutus/php/strings/str_repeat" { + function str_repeat(input?:any, multiplier?:any):any; + export = str_repeat; +} +declare module "locutus/php/strings/str_replace" { + function str_replace(search?:any, replace?:any, subject?:any, countObj?:any):any; + export = str_replace; +} +declare module "locutus/php/strings/str_rot13" { + function str_rot13(str?:any):any; + export = str_rot13; +} +declare module "locutus/php/strings/str_shuffle" { + function str_shuffle(...args:any[]):any; + export = str_shuffle; +} +declare module "locutus/php/strings/str_split" { + function str_split(string?:any, splitLength?:any):any; + export = str_split; +} +declare module "locutus/php/strings/str_word_count" { + function str_word_count(str?:any, format?:any, charlist?:any):any; + export = str_word_count; +} +declare module "locutus/php/strings/strcasecmp" { + function strcasecmp(fString1?:any, fString2?:any):any; + export = strcasecmp; +} +declare module "locutus/php/strings/strchr" { + function strchr(haystack?:any, needle?:any, bool?:any):any; + export = strchr; +} +declare module "locutus/php/strings/strcmp" { + function strcmp(str1?:any, str2?:any):any; + export = strcmp; +} +declare module "locutus/php/strings/strcoll" { + function strcoll(str1?:any, str2?:any):any; + export = strcoll; +} +declare module "locutus/php/strings/strcspn" { + function strcspn(str?:any, mask?:any, start?:any, length?:any):any; + export = strcspn; +} +declare module "locutus/php/strings/strip_tags" { + function strip_tags(input?:any, allowed?:any):any; + export = strip_tags; +} +declare module "locutus/php/strings/stripos" { + function stripos(fHaystack?:any, fNeedle?:any, fOffset?:any):any; + export = stripos; +} +declare module "locutus/php/strings/stripslashes" { + function stripslashes(str?:any):any; + export = stripslashes; +} +declare module "locutus/php/strings/stristr" { + function stristr(haystack?:any, needle?:any, bool?:any):any; + export = stristr; +} +declare module "locutus/php/strings/strlen" { + function strlen(string?:any):any; + export = strlen; +} +declare module "locutus/php/strings/strnatcasecmp" { + function strnatcasecmp(str1?:any, str2?:any):any; + export = strnatcasecmp; +} +declare module "locutus/php/strings/strnatcmp" { + function strnatcmp(fString1?:any, fString2?:any, fVersion?:any):any; + export = strnatcmp; +} +declare module "locutus/php/strings/strncasecmp" { + function strncasecmp(argStr1?:any, argStr2?:any, len?:any):any; + export = strncasecmp; +} +declare module "locutus/php/strings/strncmp" { + function strncmp(str1?:any, str2?:any, lgth?:any):any; + export = strncmp; +} +declare module "locutus/php/strings/strpbrk" { + function strpbrk(haystack?:any, charList?:any):any; + export = strpbrk; +} +declare module "locutus/php/strings/strpos" { + function strpos(haystack?:any, needle?:any, offset?:any):any; + export = strpos; +} +declare module "locutus/php/strings/strrchr" { + function strrchr(haystack?:any, needle?:any):any; + export = strrchr; +} +declare module "locutus/php/strings/strrev" { + function strrev(string?:any):any; + export = strrev; +} +declare module "locutus/php/strings/strripos" { + function strripos(haystack?:any, needle?:any, offset?:any):any; + export = strripos; +} +declare module "locutus/php/strings/strrpos" { + function strrpos(haystack?:any, needle?:any, offset?:any):any; + export = strrpos; +} +declare module "locutus/php/strings/strspn" { + function strspn(str1?:any, str2?:any, start?:any, lgth?:any):any; + export = strspn; +} +declare module "locutus/php/strings/strstr" { + function strstr(haystack?:any, needle?:any, bool?:any):any; + export = strstr; +} +declare module "locutus/php/strings/strtok" { + function strtok(str?:any, tokens?:any):any; + export = strtok; +} +declare module "locutus/php/strings/strtolower" { + function strtolower(str?:any):any; + export = strtolower; +} +declare module "locutus/php/strings/strtoupper" { + function strtoupper(str?:any):any; + export = strtoupper; +} +declare module "locutus/php/strings/strtr" { + function strtr(str?:any, trFrom?:any, trTo?:any):any; + export = strtr; +} +declare module "locutus/php/strings/substr" { + function substr(str?:any, start?:any, len?:any):any; + export = substr; +} +declare module "locutus/php/strings/substr_compare" { + function substr_compare(mainStr?:any, str?:any, offset?:any, length?:any, caseInsensitivity?:any):any; + export = substr_compare; +} +declare module "locutus/php/strings/substr_count" { + function substr_count(haystack?:any, needle?:any, offset?:any, length?:any):any; + export = substr_count; +} +declare module "locutus/php/strings/substr_replace" { + function substr_replace(str?:any, replace?:any, start?:any, length?:any):any; + export = substr_replace; +} +declare module "locutus/php/strings/trim" { + function trim(str?:any, charlist?:any):any; + export = trim; +} +declare module "locutus/php/strings/ucfirst" { + function ucfirst(str?:any):any; + export = ucfirst; +} +declare module "locutus/php/strings/ucwords" { + function ucwords(str?:any):any; + export = ucwords; +} +declare module "locutus/php/strings/vprintf" { + function vprintf(format?:any, args?:any):any; + export = vprintf; +} +declare module "locutus/php/strings/vsprintf" { + function vsprintf(format?:any, args?:any):any; + export = vsprintf; +} +declare module "locutus/php/strings/wordwrap" { + function wordwrap(...args:any[]):any; + export = wordwrap; +} +declare module "locutus/php/url/base64_decode" { + function base64_decode(encodedData?:any):any; + export = base64_decode; +} +declare module "locutus/php/url/base64_encode" { + function base64_encode(stringToEncode?:any):any; + export = base64_encode; +} +declare module "locutus/php/url/http_build_query" { + function http_build_query(formdata?:any, numericPrefix?:any, argSeparator?:any):any; + export = http_build_query; +} +declare module "locutus/php/url/parse_url" { + function parse_url(str?:any, component?:any):any; + export = parse_url; +} +declare module "locutus/php/url/rawurldecode" { + function rawurldecode(str?:any):any; + export = rawurldecode; +} +declare module "locutus/php/url/rawurlencode" { + function rawurlencode(str?:any):any; + export = rawurlencode; +} +declare module "locutus/php/url/urldecode" { + function urldecode(str?:any):any; + export = urldecode; +} +declare module "locutus/php/url/urlencode" { + function urlencode(str?:any):any; + export = urlencode; +} +declare module "locutus/php/var/doubleval" { + function doubleval(mixedVar?:any):any; + export = doubleval; +} +declare module "locutus/php/var/empty" { + function empty(mixedVar?:any):any; + export = empty; +} +declare module "locutus/php/var/floatval" { + function floatval(mixedVar?:any):any; + export = floatval; +} +declare module "locutus/php/var/gettype" { + function gettype(mixedVar?:any):any; + export = gettype; +} +declare module "locutus/php/var/intval" { + function intval(mixedVar?:any, base?:any):any; + export = intval; +} +declare module "locutus/php/var/is_array" { + function is_array(mixedVar?:any):any; + export = is_array; +} +declare module "locutus/php/var/is_binary" { + function is_binary(vr?:any):any; + export = is_binary; +} +declare module "locutus/php/var/is_bool" { + function is_bool(mixedVar?:any):any; + export = is_bool; +} +declare module "locutus/php/var/is_buffer" { + function is_buffer(vr?:any):any; + export = is_buffer; +} +declare module "locutus/php/var/is_callable" { + function is_callable(mixedVar?:any, syntaxOnly?:any, callableName?:any):any; + export = is_callable; +} +declare module "locutus/php/var/is_double" { + function is_double(mixedVar?:any):any; + export = is_double; +} +declare module "locutus/php/var/is_float" { + function is_float(mixedVar?:any):any; + export = is_float; +} +declare module "locutus/php/var/is_int" { + function is_int(mixedVar?:any):any; + export = is_int; +} +declare module "locutus/php/var/is_integer" { + function is_integer(mixedVar?:any):any; + export = is_integer; +} +declare module "locutus/php/var/is_long" { + function is_long(mixedVar?:any):any; + export = is_long; +} +declare module "locutus/php/var/is_null" { + function is_null(mixedVar?:any):any; + export = is_null; +} +declare module "locutus/php/var/is_numeric" { + function is_numeric(mixedVar?:any):any; + export = is_numeric; +} +declare module "locutus/php/var/is_object" { + function is_object(mixedVar?:any):any; + export = is_object; +} +declare module "locutus/php/var/is_real" { + function is_real(mixedVar?:any):any; + export = is_real; +} +declare module "locutus/php/var/is_scalar" { + function is_scalar(mixedVar?:any):any; + export = is_scalar; +} +declare module "locutus/php/var/is_string" { + function is_string(mixedVar?:any):any; + export = is_string; +} +declare module "locutus/php/var/is_unicode" { + function is_unicode(vr?:any):any; + export = is_unicode; +} +declare module "locutus/php/var/isset" { + function isset(...args:any[]):any; + export = isset; +} +declare module "locutus/php/var/print_r" { + function print_r(array?:any, returnVal?:any):any; + export = print_r; +} +declare module "locutus/php/var/serialize" { + function serialize(mixedValue?:any):any; + export = serialize; +} +declare module "locutus/php/var/strval" { + function strval(str?:any):any; + export = strval; +} +declare module "locutus/php/var/unserialize" { + function unserialize(data?:any):any; + export = unserialize; +} +declare module "locutus/php/var/var_dump" { + function var_dump(...args:any[]):any; + export = var_dump; +} +declare module "locutus/php/var/var_export" { + function var_export(...args:any[]):any; + export = var_export; +} +declare module "locutus/php/xdiff/xdiff_string_diff" { + function xdiff_string_diff(...args:any[]):any; + export = xdiff_string_diff; +} +declare module "locutus/php/xdiff/xdiff_string_patch" { + function xdiff_string_patch(...args:any[]):any; + export = xdiff_string_patch; +} +declare module "locutus/php/xml/utf8_decode" { + function utf8_decode(strData?:any):any; + export = utf8_decode; +} +declare module "locutus/php/xml/utf8_encode" { + function utf8_encode(argString?:any):any; + export = utf8_encode; +} +declare module "locutus/python/string/capwords" { + function capwords(str?:any):any; + export = capwords; +} +declare module "locutus/ruby/Math/acos" { + function acos(arg?:any):any; + export = acos; +} +declare module "locutus/c/math" { + import abs = require("locutus/c/math/abs"); + export {abs}; +} +declare module "locutus/golang/strings" { + import Contains = require("locutus/golang/strings/Contains"); + import Count = require("locutus/golang/strings/Count"); + import Index = require("locutus/golang/strings/Index"); + import LastIndex = require("locutus/golang/strings/LastIndex"); + export {Contains,Count,Index,LastIndex}; +} +declare module "locutus/php/array" { + import array_change_key_case = require("locutus/php/array/array_change_key_case"); + import array_chunk = require("locutus/php/array/array_chunk"); + import array_combine = require("locutus/php/array/array_combine"); + import array_count_values = require("locutus/php/array/array_count_values"); + import array_diff = require("locutus/php/array/array_diff"); + import array_diff_assoc = require("locutus/php/array/array_diff_assoc"); + import array_diff_key = require("locutus/php/array/array_diff_key"); + import array_diff_uassoc = require("locutus/php/array/array_diff_uassoc"); + import array_diff_ukey = require("locutus/php/array/array_diff_ukey"); + import array_fill = require("locutus/php/array/array_fill"); + import array_fill_keys = require("locutus/php/array/array_fill_keys"); + import array_filter = require("locutus/php/array/array_filter"); + import array_flip = require("locutus/php/array/array_flip"); + import array_intersect = require("locutus/php/array/array_intersect"); + import array_intersect_assoc = require("locutus/php/array/array_intersect_assoc"); + import array_intersect_key = require("locutus/php/array/array_intersect_key"); + import array_intersect_uassoc = require("locutus/php/array/array_intersect_uassoc"); + import array_intersect_ukey = require("locutus/php/array/array_intersect_ukey"); + import array_key_exists = require("locutus/php/array/array_key_exists"); + import array_keys = require("locutus/php/array/array_keys"); + import array_map = require("locutus/php/array/array_map"); + import array_merge = require("locutus/php/array/array_merge"); + import array_merge_recursive = require("locutus/php/array/array_merge_recursive"); + import array_multisort = require("locutus/php/array/array_multisort"); + import array_pad = require("locutus/php/array/array_pad"); + import array_pop = require("locutus/php/array/array_pop"); + import array_product = require("locutus/php/array/array_product"); + import array_push = require("locutus/php/array/array_push"); + import array_rand = require("locutus/php/array/array_rand"); + import array_reduce = require("locutus/php/array/array_reduce"); + import array_replace = require("locutus/php/array/array_replace"); + import array_replace_recursive = require("locutus/php/array/array_replace_recursive"); + import array_reverse = require("locutus/php/array/array_reverse"); + import array_search = require("locutus/php/array/array_search"); + import array_shift = require("locutus/php/array/array_shift"); + import array_slice = require("locutus/php/array/array_slice"); + import array_splice = require("locutus/php/array/array_splice"); + import array_sum = require("locutus/php/array/array_sum"); + import array_udiff = require("locutus/php/array/array_udiff"); + import array_udiff_assoc = require("locutus/php/array/array_udiff_assoc"); + import array_udiff_uassoc = require("locutus/php/array/array_udiff_uassoc"); + import array_uintersect = require("locutus/php/array/array_uintersect"); + import array_uintersect_uassoc = require("locutus/php/array/array_uintersect_uassoc"); + import array_unique = require("locutus/php/array/array_unique"); + import array_unshift = require("locutus/php/array/array_unshift"); + import array_values = require("locutus/php/array/array_values"); + import array_walk = require("locutus/php/array/array_walk"); + import arsort = require("locutus/php/array/arsort"); + import asort = require("locutus/php/array/asort"); + import count = require("locutus/php/array/count"); + import current = require("locutus/php/array/current"); + import each = require("locutus/php/array/each"); + import end = require("locutus/php/array/end"); + import in_array = require("locutus/php/array/in_array"); + import key = require("locutus/php/array/key"); + import krsort = require("locutus/php/array/krsort"); + import ksort = require("locutus/php/array/ksort"); + import natcasesort = require("locutus/php/array/natcasesort"); + import natsort = require("locutus/php/array/natsort"); + import next = require("locutus/php/array/next"); + import pos = require("locutus/php/array/pos"); + import prev = require("locutus/php/array/prev"); + import range = require("locutus/php/array/range"); + import reset = require("locutus/php/array/reset"); + import rsort = require("locutus/php/array/rsort"); + import shuffle = require("locutus/php/array/shuffle"); + import sizeof = require("locutus/php/array/sizeof"); + import sort = require("locutus/php/array/sort"); + import uasort = require("locutus/php/array/uasort"); + import uksort = require("locutus/php/array/uksort"); + import usort = require("locutus/php/array/usort"); + export {array_change_key_case,array_chunk,array_combine,array_count_values,array_diff,array_diff_assoc,array_diff_key,array_diff_uassoc,array_diff_ukey,array_fill,array_fill_keys,array_filter,array_flip,array_intersect,array_intersect_assoc,array_intersect_key,array_intersect_uassoc,array_intersect_ukey,array_key_exists,array_keys,array_map,array_merge,array_merge_recursive,array_multisort,array_pad,array_pop,array_product,array_push,array_rand,array_reduce,array_replace,array_replace_recursive,array_reverse,array_search,array_shift,array_slice,array_splice,array_sum,array_udiff,array_udiff_assoc,array_udiff_uassoc,array_uintersect,array_uintersect_uassoc,array_unique,array_unshift,array_values,array_walk,arsort,asort,count,current,each,end,in_array,key,krsort,ksort,natcasesort,natsort,next,pos,prev,range,reset,rsort,shuffle,sizeof,sort,uasort,uksort,usort}; +} +declare module "locutus/php/bc" { + import bcadd = require("locutus/php/bc/bcadd"); + import bccomp = require("locutus/php/bc/bccomp"); + import bcdiv = require("locutus/php/bc/bcdiv"); + import bcmul = require("locutus/php/bc/bcmul"); + import bcround = require("locutus/php/bc/bcround"); + import bcscale = require("locutus/php/bc/bcscale"); + import bcsub = require("locutus/php/bc/bcsub"); + export {bcadd,bccomp,bcdiv,bcmul,bcround,bcscale,bcsub}; +} +declare module "locutus/php/ctype" { + import ctype_alnum = require("locutus/php/ctype/ctype_alnum"); + import ctype_alpha = require("locutus/php/ctype/ctype_alpha"); + import ctype_cntrl = require("locutus/php/ctype/ctype_cntrl"); + import ctype_digit = require("locutus/php/ctype/ctype_digit"); + import ctype_graph = require("locutus/php/ctype/ctype_graph"); + import ctype_lower = require("locutus/php/ctype/ctype_lower"); + import ctype_print = require("locutus/php/ctype/ctype_print"); + import ctype_punct = require("locutus/php/ctype/ctype_punct"); + import ctype_space = require("locutus/php/ctype/ctype_space"); + import ctype_upper = require("locutus/php/ctype/ctype_upper"); + import ctype_xdigit = require("locutus/php/ctype/ctype_xdigit"); + export {ctype_alnum,ctype_alpha,ctype_cntrl,ctype_digit,ctype_graph,ctype_lower,ctype_print,ctype_punct,ctype_space,ctype_upper,ctype_xdigit}; +} +declare module "locutus/php/datetime" { + import checkdate = require("locutus/php/datetime/checkdate"); + import date = require("locutus/php/datetime/date"); + import date_parse = require("locutus/php/datetime/date_parse"); + import getdate = require("locutus/php/datetime/getdate"); + import gettimeofday = require("locutus/php/datetime/gettimeofday"); + import gmdate = require("locutus/php/datetime/gmdate"); + import gmmktime = require("locutus/php/datetime/gmmktime"); + import gmstrftime = require("locutus/php/datetime/gmstrftime"); + import idate = require("locutus/php/datetime/idate"); + import microtime = require("locutus/php/datetime/microtime"); + import mktime = require("locutus/php/datetime/mktime"); + import strftime = require("locutus/php/datetime/strftime"); + import strptime = require("locutus/php/datetime/strptime"); + import strtotime = require("locutus/php/datetime/strtotime"); + import time = require("locutus/php/datetime/time"); + export {checkdate,date,date_parse,getdate,gettimeofday,gmdate,gmmktime,gmstrftime,idate,microtime,mktime,strftime,strptime,strtotime,time}; +} +declare module "locutus/php/exec" { + import escapeshellarg = require("locutus/php/exec/escapeshellarg"); + export {escapeshellarg}; +} +declare module "locutus/php/filesystem" { + import basename = require("locutus/php/filesystem/basename"); + import dirname = require("locutus/php/filesystem/dirname"); + import file_get_contents = require("locutus/php/filesystem/file_get_contents"); + import pathinfo = require("locutus/php/filesystem/pathinfo"); + import realpath = require("locutus/php/filesystem/realpath"); + export {basename,dirname,file_get_contents,pathinfo,realpath}; +} +declare module "locutus/php/funchand" { + import call_user_func = require("locutus/php/funchand/call_user_func"); + import call_user_func_array = require("locutus/php/funchand/call_user_func_array"); + import create_function = require("locutus/php/funchand/create_function"); + import function_exists = require("locutus/php/funchand/function_exists"); + import get_defined_functions = require("locutus/php/funchand/get_defined_functions"); + export {call_user_func,call_user_func_array,create_function,function_exists,get_defined_functions}; +} +declare module "locutus/php/i18n" { + import i18n_loc_get_default = require("locutus/php/i18n/i18n_loc_get_default"); + import i18n_loc_set_default = require("locutus/php/i18n/i18n_loc_set_default"); + export {i18n_loc_get_default,i18n_loc_set_default}; +} +declare module "locutus/php/info" { + import assert_options = require("locutus/php/info/assert_options"); + import getenv = require("locutus/php/info/getenv"); + import ini_get = require("locutus/php/info/ini_get"); + import ini_set = require("locutus/php/info/ini_set"); + import set_time_limit = require("locutus/php/info/set_time_limit"); + import version_compare = require("locutus/php/info/version_compare"); + export {assert_options,getenv,ini_get,ini_set,set_time_limit,version_compare}; +} +declare module "locutus/php/json" { + import json_decode = require("locutus/php/json/json_decode"); + import json_encode = require("locutus/php/json/json_encode"); + import json_last_error = require("locutus/php/json/json_last_error"); + export {json_decode,json_encode,json_last_error}; +} +declare module "locutus/php/math" { + import abs = require("locutus/php/math/abs"); + import acos = require("locutus/php/math/acos"); + import acosh = require("locutus/php/math/acosh"); + import asin = require("locutus/php/math/asin"); + import asinh = require("locutus/php/math/asinh"); + import atan = require("locutus/php/math/atan"); + import atan2 = require("locutus/php/math/atan2"); + import atanh = require("locutus/php/math/atanh"); + import base_convert = require("locutus/php/math/base_convert"); + import bindec = require("locutus/php/math/bindec"); + import ceil = require("locutus/php/math/ceil"); + import cos = require("locutus/php/math/cos"); + import cosh = require("locutus/php/math/cosh"); + import decbin = require("locutus/php/math/decbin"); + import dechex = require("locutus/php/math/dechex"); + import decoct = require("locutus/php/math/decoct"); + import deg2rad = require("locutus/php/math/deg2rad"); + import exp = require("locutus/php/math/exp"); + import expm1 = require("locutus/php/math/expm1"); + import floor = require("locutus/php/math/floor"); + import fmod = require("locutus/php/math/fmod"); + import getrandmax = require("locutus/php/math/getrandmax"); + import hexdec = require("locutus/php/math/hexdec"); + import hypot = require("locutus/php/math/hypot"); + import is_finite = require("locutus/php/math/is_finite"); + import is_infinite = require("locutus/php/math/is_infinite"); + import is_nan = require("locutus/php/math/is_nan"); + import lcg_value = require("locutus/php/math/lcg_value"); + import log = require("locutus/php/math/log"); + import log10 = require("locutus/php/math/log10"); + import log1p = require("locutus/php/math/log1p"); + import max = require("locutus/php/math/max"); + import min = require("locutus/php/math/min"); + import mt_getrandmax = require("locutus/php/math/mt_getrandmax"); + import mt_rand = require("locutus/php/math/mt_rand"); + import octdec = require("locutus/php/math/octdec"); + import pi = require("locutus/php/math/pi"); + import pow = require("locutus/php/math/pow"); + import rad2deg = require("locutus/php/math/rad2deg"); + import rand = require("locutus/php/math/rand"); + import round = require("locutus/php/math/round"); + import sin = require("locutus/php/math/sin"); + import sinh = require("locutus/php/math/sinh"); + import sqrt = require("locutus/php/math/sqrt"); + import tan = require("locutus/php/math/tan"); + import tanh = require("locutus/php/math/tanh"); + export {abs,acos,acosh,asin,asinh,atan,atan2,atanh,base_convert,bindec,ceil,cos,cosh,decbin,dechex,decoct,deg2rad,exp,expm1,floor,fmod,getrandmax,hexdec,hypot,is_finite,is_infinite,is_nan,lcg_value,log,log10,log1p,max,min,mt_getrandmax,mt_rand,octdec,pi,pow,rad2deg,rand,round,sin,sinh,sqrt,tan,tanh}; +} +declare module "locutus/php/misc" { + import pack = require("locutus/php/misc/pack"); + import uniqid = require("locutus/php/misc/uniqid"); + export {pack,uniqid}; +} +declare module "locutus/php/net-gopher" { + import gopher_parsedir = require("locutus/php/net-gopher/gopher_parsedir"); + export {gopher_parsedir}; +} +declare module "locutus/php/network" { + import inet_ntop = require("locutus/php/network/inet_ntop"); + import inet_pton = require("locutus/php/network/inet_pton"); + import ip2long = require("locutus/php/network/ip2long"); + import long2ip = require("locutus/php/network/long2ip"); + import setcookie = require("locutus/php/network/setcookie"); + import setrawcookie = require("locutus/php/network/setrawcookie"); + export {inet_ntop,inet_pton,ip2long,long2ip,setcookie,setrawcookie}; +} +declare module "locutus/php/pcre" { + import preg_quote = require("locutus/php/pcre/preg_quote"); + import sql_regcase = require("locutus/php/pcre/sql_regcase"); + export {preg_quote,sql_regcase}; +} +declare module "locutus/php/strings" { + import addcslashes = require("locutus/php/strings/addcslashes"); + import addslashes = require("locutus/php/strings/addslashes"); + import bin2hex = require("locutus/php/strings/bin2hex"); + import chop = require("locutus/php/strings/chop"); + import chr = require("locutus/php/strings/chr"); + import chunk_split = require("locutus/php/strings/chunk_split"); + import convert_cyr_string = require("locutus/php/strings/convert_cyr_string"); + import convert_uuencode = require("locutus/php/strings/convert_uuencode"); + import count_chars = require("locutus/php/strings/count_chars"); + import crc32 = require("locutus/php/strings/crc32"); + import echo = require("locutus/php/strings/echo"); + import explode = require("locutus/php/strings/explode"); + import get_html_translation_table = require("locutus/php/strings/get_html_translation_table"); + import hex2bin = require("locutus/php/strings/hex2bin"); + import html_entity_decode = require("locutus/php/strings/html_entity_decode"); + import htmlentities = require("locutus/php/strings/htmlentities"); + import htmlspecialchars = require("locutus/php/strings/htmlspecialchars"); + import htmlspecialchars_decode = require("locutus/php/strings/htmlspecialchars_decode"); + import implode = require("locutus/php/strings/implode"); + import join = require("locutus/php/strings/join"); + import lcfirst = require("locutus/php/strings/lcfirst"); + import levenshtein = require("locutus/php/strings/levenshtein"); + import localeconv = require("locutus/php/strings/localeconv"); + import ltrim = require("locutus/php/strings/ltrim"); + import md5 = require("locutus/php/strings/md5"); + import md5_file = require("locutus/php/strings/md5_file"); + import metaphone = require("locutus/php/strings/metaphone"); + import money_format = require("locutus/php/strings/money_format"); + import nl2br = require("locutus/php/strings/nl2br"); + import nl_langinfo = require("locutus/php/strings/nl_langinfo"); + import number_format = require("locutus/php/strings/number_format"); + import ord = require("locutus/php/strings/ord"); + import parse_str = require("locutus/php/strings/parse_str"); + import printf = require("locutus/php/strings/printf"); + import quoted_printable_decode = require("locutus/php/strings/quoted_printable_decode"); + import quoted_printable_encode = require("locutus/php/strings/quoted_printable_encode"); + import quotemeta = require("locutus/php/strings/quotemeta"); + import rtrim = require("locutus/php/strings/rtrim"); + import setlocale = require("locutus/php/strings/setlocale"); + import sha1 = require("locutus/php/strings/sha1"); + import sha1_file = require("locutus/php/strings/sha1_file"); + import similar_text = require("locutus/php/strings/similar_text"); + import soundex = require("locutus/php/strings/soundex"); + import split = require("locutus/php/strings/split"); + import sprintf = require("locutus/php/strings/sprintf"); + import sscanf = require("locutus/php/strings/sscanf"); + import str_getcsv = require("locutus/php/strings/str_getcsv"); + import str_ireplace = require("locutus/php/strings/str_ireplace"); + import str_pad = require("locutus/php/strings/str_pad"); + import str_repeat = require("locutus/php/strings/str_repeat"); + import str_replace = require("locutus/php/strings/str_replace"); + import str_rot13 = require("locutus/php/strings/str_rot13"); + import str_shuffle = require("locutus/php/strings/str_shuffle"); + import str_split = require("locutus/php/strings/str_split"); + import str_word_count = require("locutus/php/strings/str_word_count"); + import strcasecmp = require("locutus/php/strings/strcasecmp"); + import strchr = require("locutus/php/strings/strchr"); + import strcmp = require("locutus/php/strings/strcmp"); + import strcoll = require("locutus/php/strings/strcoll"); + import strcspn = require("locutus/php/strings/strcspn"); + import strip_tags = require("locutus/php/strings/strip_tags"); + import stripos = require("locutus/php/strings/stripos"); + import stripslashes = require("locutus/php/strings/stripslashes"); + import stristr = require("locutus/php/strings/stristr"); + import strlen = require("locutus/php/strings/strlen"); + import strnatcasecmp = require("locutus/php/strings/strnatcasecmp"); + import strnatcmp = require("locutus/php/strings/strnatcmp"); + import strncasecmp = require("locutus/php/strings/strncasecmp"); + import strncmp = require("locutus/php/strings/strncmp"); + import strpbrk = require("locutus/php/strings/strpbrk"); + import strpos = require("locutus/php/strings/strpos"); + import strrchr = require("locutus/php/strings/strrchr"); + import strrev = require("locutus/php/strings/strrev"); + import strripos = require("locutus/php/strings/strripos"); + import strrpos = require("locutus/php/strings/strrpos"); + import strspn = require("locutus/php/strings/strspn"); + import strstr = require("locutus/php/strings/strstr"); + import strtok = require("locutus/php/strings/strtok"); + import strtolower = require("locutus/php/strings/strtolower"); + import strtoupper = require("locutus/php/strings/strtoupper"); + import strtr = require("locutus/php/strings/strtr"); + import substr = require("locutus/php/strings/substr"); + import substr_compare = require("locutus/php/strings/substr_compare"); + import substr_count = require("locutus/php/strings/substr_count"); + import substr_replace = require("locutus/php/strings/substr_replace"); + import trim = require("locutus/php/strings/trim"); + import ucfirst = require("locutus/php/strings/ucfirst"); + import ucwords = require("locutus/php/strings/ucwords"); + import vprintf = require("locutus/php/strings/vprintf"); + import vsprintf = require("locutus/php/strings/vsprintf"); + import wordwrap = require("locutus/php/strings/wordwrap"); + export {addcslashes,addslashes,bin2hex,chop,chr,chunk_split,convert_cyr_string,convert_uuencode,count_chars,crc32,echo,explode,get_html_translation_table,hex2bin,html_entity_decode,htmlentities,htmlspecialchars,htmlspecialchars_decode,implode,join,lcfirst,levenshtein,localeconv,ltrim,md5,md5_file,metaphone,money_format,nl2br,nl_langinfo,number_format,ord,parse_str,printf,quoted_printable_decode,quoted_printable_encode,quotemeta,rtrim,setlocale,sha1,sha1_file,similar_text,soundex,split,sprintf,sscanf,str_getcsv,str_ireplace,str_pad,str_repeat,str_replace,str_rot13,str_shuffle,str_split,str_word_count,strcasecmp,strchr,strcmp,strcoll,strcspn,strip_tags,stripos,stripslashes,stristr,strlen,strnatcasecmp,strnatcmp,strncasecmp,strncmp,strpbrk,strpos,strrchr,strrev,strripos,strrpos,strspn,strstr,strtok,strtolower,strtoupper,strtr,substr,substr_compare,substr_count,substr_replace,trim,ucfirst,ucwords,vprintf,vsprintf,wordwrap}; +} +declare module "locutus/php/url" { + import base64_decode = require("locutus/php/url/base64_decode"); + import base64_encode = require("locutus/php/url/base64_encode"); + import http_build_query = require("locutus/php/url/http_build_query"); + import parse_url = require("locutus/php/url/parse_url"); + import rawurldecode = require("locutus/php/url/rawurldecode"); + import rawurlencode = require("locutus/php/url/rawurlencode"); + import urldecode = require("locutus/php/url/urldecode"); + import urlencode = require("locutus/php/url/urlencode"); + export {base64_decode,base64_encode,http_build_query,parse_url,rawurldecode,rawurlencode,urldecode,urlencode}; +} +declare module "locutus/php/var" { + import doubleval = require("locutus/php/var/doubleval"); + import empty = require("locutus/php/var/empty"); + import floatval = require("locutus/php/var/floatval"); + import gettype = require("locutus/php/var/gettype"); + import intval = require("locutus/php/var/intval"); + import is_array = require("locutus/php/var/is_array"); + import is_binary = require("locutus/php/var/is_binary"); + import is_bool = require("locutus/php/var/is_bool"); + import is_buffer = require("locutus/php/var/is_buffer"); + import is_callable = require("locutus/php/var/is_callable"); + import is_double = require("locutus/php/var/is_double"); + import is_float = require("locutus/php/var/is_float"); + import is_int = require("locutus/php/var/is_int"); + import is_integer = require("locutus/php/var/is_integer"); + import is_long = require("locutus/php/var/is_long"); + import is_null = require("locutus/php/var/is_null"); + import is_numeric = require("locutus/php/var/is_numeric"); + import is_object = require("locutus/php/var/is_object"); + import is_real = require("locutus/php/var/is_real"); + import is_scalar = require("locutus/php/var/is_scalar"); + import is_string = require("locutus/php/var/is_string"); + import is_unicode = require("locutus/php/var/is_unicode"); + import isset = require("locutus/php/var/isset"); + import print_r = require("locutus/php/var/print_r"); + import serialize = require("locutus/php/var/serialize"); + import strval = require("locutus/php/var/strval"); + import unserialize = require("locutus/php/var/unserialize"); + import var_dump = require("locutus/php/var/var_dump"); + import var_export = require("locutus/php/var/var_export"); + export {doubleval,empty,floatval,gettype,intval,is_array,is_binary,is_bool,is_buffer,is_callable,is_double,is_float,is_int,is_integer,is_long,is_null,is_numeric,is_object,is_real,is_scalar,is_string,is_unicode,isset,print_r,serialize,strval,unserialize,var_dump,var_export}; +} +declare module "locutus/php/xdiff" { + import xdiff_string_diff = require("locutus/php/xdiff/xdiff_string_diff"); + import xdiff_string_patch = require("locutus/php/xdiff/xdiff_string_patch"); + export {xdiff_string_diff,xdiff_string_patch}; +} +declare module "locutus/php/xml" { + import utf8_decode = require("locutus/php/xml/utf8_decode"); + import utf8_encode = require("locutus/php/xml/utf8_encode"); + export {utf8_decode,utf8_encode}; +} +declare module "locutus/python/string" { + import capwords = require("locutus/python/string/capwords"); + export {capwords}; +} +declare module "locutus/ruby/Math" { + import acos = require("locutus/ruby/Math/acos"); + export {acos}; +} +declare module "locutus/c" { + import math = require("locutus/c/math"); + export {math}; +} +declare module "locutus/golang" { + import strings = require("locutus/golang/strings"); + export {strings}; +} +declare module "locutus/php" { + import array = require("locutus/php/array"); + import bc = require("locutus/php/bc"); + import ctype = require("locutus/php/ctype"); + import datetime = require("locutus/php/datetime"); + import exec = require("locutus/php/exec"); + import filesystem = require("locutus/php/filesystem"); + import funchand = require("locutus/php/funchand"); + import i18n = require("locutus/php/i18n"); + import info = require("locutus/php/info"); + import json = require("locutus/php/json"); + import math = require("locutus/php/math"); + import misc = require("locutus/php/misc"); + // import net_gopher = require("locutus/php/net-gopher"); + import network = require("locutus/php/network"); + import pcre = require("locutus/php/pcre"); + import strings = require("locutus/php/strings"); + import url = require("locutus/php/url"); + // import Var = require("locutus/php/var"); + import xdiff = require("locutus/php/xdiff"); + import xml = require("locutus/php/xml"); + export {array,bc,ctype,datetime,exec,filesystem,funchand,i18n,info,json,math,misc,network,pcre,strings,url,xdiff,xml /* ,"net-gopher":net_gopher */ /* ,"var":Var */}; +} +declare module "locutus/python" { + import string = require("locutus/python/string"); + export {string}; +} +declare module "locutus/ruby" { + import Math = require("locutus/ruby/Math"); + export {Math}; +} +declare module "locutus" { + import c = require("locutus/c"); + import golang = require("locutus/golang"); + import php = require("locutus/php"); + import python = require("locutus/python"); + import ruby = require("locutus/ruby"); + export {c,golang,php,python,ruby}; +} diff --git a/locutus/locutus_print.ts b/locutus/locutus_print.ts new file mode 100644 index 0000000000..fc21294639 --- /dev/null +++ b/locutus/locutus_print.ts @@ -0,0 +1,188 @@ +// Automatically generate script for locutus +// Written by: Hookclaw + +/* Usage + tsc locutus_print.ts + node locutus_print.js define + */ + +/// +/// + +var locutus = require('locutus'); + +type f = (...args:any[]) => any; +type e = {[key:string]:f}; +type d = {[key:string]:e}; +type c = {[key:string]:d}; + +let loc:c = locutus; + +let run = ():void => { + if(process.argv.length > 1) { + switch(process.argv[2]) { + case 'define': + define(); + return; + case 'test': + test(); + return; + case 'settings': + settings(); + return; + } + } + console.log('settings,list,define'); +}; + +let define = ():void => { + console.log('// Type definitions for locutus'); + console.log('// Project: http://locutusjs.io'); + console.log('// Definitions by: Hookclaw '); + console.log('// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped'); + console.log(''); + + for(let key1 in loc) { + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + printSingle(loc,key1,key2,key3); + } + } + } + for(let key1 in loc) { + for(let key2 in loc[key1]) { + let modulename = 'locutus/' + key1 + '/' + key2; + printGroup(modulename, loc[key1][key2]); + } + } + for(let key1 in loc) { + let modulename = 'locutus/' + key1; + printGroup(modulename, loc[key1]); + } + let modulename = 'locutus'; + printGroup(modulename, loc); +} + +let printSingle = (loc:c,key1:string,key2:string,key3:string):void => { + console.log('declare module "locutus/' + key1 + '/' + key2 + '/' + key3 + '" {'); + console.log('\tfunction ' + key3 + arg(loc,key1,key2,key3) + ':any;'); + console.log('\texport = ' + key3 + ';'); + console.log('}'); +} + +let printGroup = (modulename:string,loc:{}):void => { + let s:string[] = []; + let c = ''; + console.log('declare module "' + modulename + '" {'); + for(let key in loc) { + let com = ''; + let tmp = replace(key); + if(tmp == key) { + s.push(key); + } else { + com = '// '; + // s.push('"' + key + '":' + tmp); + c += ' /* ,"' + key + '":' + tmp + ' */'; + } + console.log('\t' + com + 'import ' + tmp + ' = require("' + modulename + '/' + key + '");'); + } + console.log('\texport {' + s.join(',') + c + '};'); + console.log('}'); +} + +let replace = (name:string):string => { + if(name == 'var') { + return 'Var'; + } + // if(name == 'string') { + // return 'String'; + // } + return name.replace('-','_'); +} + +let func = (loc:c,key1:string,key2:string,key3:string):string => { + return '"' + key3 + '":' + arg(loc,key1,key2,key3) + ' => any'; +} + +const ARG1 = "(...args:any[])"; + +let arg = (loc:c,key1:string,key2:string,key3:string):string => { + let src = loc[key1][key2][key3].toString(); + let mArguments = /[^a-zA-Z0-9_]arguments[^a-zA-Z0-9_]/; + if(mArguments.test(src)) { + return ARG1; + } + let mFunction = /^function [a-zA-Z0-9_]+\(/g; + let result1 = mFunction.exec(src); + if(result1 == null) { + return ARG1; + } + let mFunction2 = /(\s*[,]?\s*[a-zA-Z0-9_]+)*\)/g; + mFunction2.lastIndex = mFunction.lastIndex; + let result12 = mFunction2.exec(src); + let mParameter = /\s*[,]?\s*[a-zA-Z0-9_]+/g; + let args:string[] = []; + let i = 0; + let result2:any; + while((result2 = mParameter.exec(result12[0])) != null) { + args.push(result2[0]+'?:any'); + i++; + } + return '('+args.join('')+')'; +} + +let test = ():void => { + console.log('/// '); + for(let key1 in loc) { + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + let modulename = 'locutus/' + key1 + '/' + key2 + '/' + key3; + testsub(modulename); + } + } + } + for(let key1 in loc) { + for(let key2 in loc[key1]) { + let modulename = 'locutus/' + key1 + '/' + key2; + testsub(modulename); + } + } + for(let key1 in loc) { + let modulename = 'locutus/' + key1; + testsub(modulename); + } + let modulename = 'locutus'; + testsub(modulename); +} + +let testsub = (modulename:string):void => { + let varname = modulename.replace(/[-/]/g,'_'); + console.log("import " + varname + " = require('" + modulename + "');"); +} + +let settings = ():void => { + let s = ''; + for(let key1 in loc) { + if(key1 != 'php') { + continue; + } + for(let key2 in loc[key1]) { + for(let key3 in loc[key1][key2]) { + if(s != '') { + s += ',\n'; + } + let len = 21 - key3.length; + let tab = ''; + while(len > 0) { + tab += '\t'; + len -= 4; + } + //"var_dump": {"cod":"var_dump", "mod":["var_dump","locutus/php/var/var_dump"]} + s += '\t\t\t\t"' + key3 + '":' + tab + '{"cod":"' + key3 + '","mod":["' + key3 + '","locutus/' + key1 + '/' + key2 + '/' + key3 + '"]}'; + } + } + } + console.log(s); +} + +run(); diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index b92de15c89..3948215468 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -7732,6 +7732,53 @@ declare module _ { thisArg?: any): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + inject( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + accumulator: TResult, + thisArg?: any): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + foldl( + callback: MemoIterator, + thisArg?: any): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 2d5f5b50f3..ec20e06b1f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -973,19 +973,26 @@ namespace TestFlattenDeep { // _.fromPairs namespace TestFromPairs { - let array: string[][]; - let result: _.Dictionary; + let twoDimensionalArray: string[][]; + let numberTupleArray: [string, number][]; + let stringDict: _.Dictionary; + let numberDict: _.Dictionary; { - result = _.fromPairs(array); + stringDict = _.fromPairs(twoDimensionalArray); + numberDict = _.fromPairs(numberTupleArray); + // Ensure we're getting the parameterized overload rather than the 'any' catch-all. + numberDict = _.fromPairs(numberTupleArray); + // This doesn't compile because you can't assign arrays to tuples. + // stringDict = _.fromPairs(twoDimensionalArray); } { - result = _(array).fromPairs().value(); + stringDict = _(twoDimensionalArray).fromPairs().value(); } { - result = _.chain(array).fromPairs().value(); + stringDict = _.chain(twoDimensionalArray).fromPairs().value(); } } @@ -5724,6 +5731,21 @@ namespace TestFlip { namespace TestFlow { let Fn1: (n: number) => number; let Fn2: (m: number, n: number) => number; + let Fn3: (a: number) => string; + let Fn4: (a: string) => number; + + { + // type infer test + let result: (m: number, n: number) => number; + + result = _.flow(Fn2, Fn1); + result = _.flow(Fn2, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn1, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn1, Fn1, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn1, Fn1, Fn1, Fn1, Fn1); + result = _.flow(Fn2, Fn1, Fn3, Fn4); + } { let result: (m: number, n: number) => number; @@ -8014,12 +8036,12 @@ namespace TestRandom { // _.assign namespace TestAssign { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8033,37 +8055,37 @@ namespace TestAssign { { let result: Obj; - result = _.assign(obj); + result = _.assign(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.assign(obj, s1); + result = _.assign(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.assign(obj, s1, s2); + result = _.assign(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.assign(obj, s1, s2, s3); + result = _.assign(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.assign(obj, s1, s2, s3, s4); + result = _.assign(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.assign(obj, s1, s2, s3, s4, s5); + result = _.assign<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8073,33 +8095,33 @@ namespace TestAssign { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).assign(s1); + result = _(obj).assign(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).assign(s1, s2); + result = _(obj).assign(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).assign(s1, s2, s3); + result = _(obj).assign(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).assign(s1, s2, s3, s4); + result = _(obj).assign(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8109,44 +8131,44 @@ namespace TestAssign { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().assign(s1); + result = _(obj).chain().assign(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().assign(s1, s2); + result = _(obj).chain().assign(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().assign(s1, s2, s3); + result = _(obj).chain().assign(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().assign(s1, s2, s3, s4); + result = _(obj).chain().assign(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assign<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).chain().assign<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } } // _.assignWith namespace TestAssignWith { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8160,32 +8182,32 @@ namespace TestAssignWith { { let result: Obj; - result = _.assignWith(obj); + result = _.assignWith(obj); } { - let result: {a: number}; - result = _.assignWith(obj, s1, customizer); + let result: { a: number }; + result = _.assignWith(obj, s1, customizer); } { - let result: {a: number, b: number}; - result = _.assignWith(obj, s1, s2, customizer); + let result: { a: number, b: number }; + result = _.assignWith(obj, s1, s2, customizer); } { - let result: {a: number, b: number, c: number}; - result = _.assignWith(obj, s1, s2, s3, customizer); + let result: { a: number, b: number, c: number }; + result = _.assignWith(obj, s1, s2, s3, customizer); } { - let result: {a: number, b: number, c: number, d: number}; - result = _.assignWith(obj, s1, s2, s3, s4, customizer); + let result: { a: number, b: number, c: number, d: number }; + result = _.assignWith(obj, s1, s2, s3, s4, customizer); } { - let result: {a: number, b: number, c: number, d: number, e: number}; - result = _.assignWith(obj, s1, s2, s3, s4, s5, customizer); + let result: { a: number, b: number, c: number, d: number, e: number }; + result = _.assignWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); } { @@ -8195,28 +8217,28 @@ namespace TestAssignWith { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; - result = _(obj).assignWith(s1, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + result = _(obj).assignWith(s1, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).assignWith(s1, s2, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).assignWith(s1, s2, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).assignWith(s1, s2, s3, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).assignWith(s1, s2, s3, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).assignWith(s1, s2, s3, s4, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).assignWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).assignWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).assignWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } { @@ -8226,39 +8248,39 @@ namespace TestAssignWith { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; - result = _(obj).chain().assignWith(s1, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + result = _(obj).chain().assignWith(s1, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).chain().assignWith(s1, s2, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).chain().assignWith(s1, s2, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).chain().assignWith(s1, s2, s3, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).chain().assignWith(s1, s2, s3, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).chain().assignWith(s1, s2, s3, s4, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).chain().assignWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).chain().assignWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).chain().assignWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } // _.assignIn namespace TestAssignIn { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8272,37 +8294,37 @@ namespace TestAssignIn { { let result: Obj; - result = _.assignIn(obj); + result = _.assignIn(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.assignIn(obj, s1); + result = _.assignIn(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.assignIn(obj, s1, s2); + result = _.assignIn(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.assignIn(obj, s1, s2, s3); + result = _.assignIn(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.assignIn(obj, s1, s2, s3, s4); + result = _.assignIn(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.assignIn(obj, s1, s2, s3, s4, s5); + result = _.assignIn<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8312,33 +8334,33 @@ namespace TestAssignIn { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).assignIn(s1); + result = _(obj).assignIn(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).assignIn(s1, s2); + result = _(obj).assignIn(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).assignIn(s1, s2, s3); + result = _(obj).assignIn(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).assignIn(s1, s2, s3, s4); + result = _(obj).assignIn(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).assignIn<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).assignIn<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8348,44 +8370,44 @@ namespace TestAssignIn { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().assignIn(s1); + result = _(obj).chain().assignIn(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().assignIn(s1, s2); + result = _(obj).chain().assignIn(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().assignIn(s1, s2, s3); + result = _(obj).chain().assignIn(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().assignIn(s1, s2, s3, s4); + result = _(obj).chain().assignIn(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().assignIn<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); + result = _(obj).chain().assignIn<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } } // _.assignInWith namespace TestAssignInWith { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; let obj: Obj; let s1: S1; @@ -8399,32 +8421,32 @@ namespace TestAssignInWith { { let result: Obj; - result = _.assignInWith(obj); + result = _.assignInWith(obj); } { - let result: {a: number}; - result = _.assignInWith(obj, s1, customizer); + let result: { a: number }; + result = _.assignInWith(obj, s1, customizer); } { - let result: {a: number, b: number}; - result = _.assignInWith(obj, s1, s2, customizer); + let result: { a: number, b: number }; + result = _.assignInWith(obj, s1, s2, customizer); } { - let result: {a: number, b: number, c: number}; - result = _.assignInWith(obj, s1, s2, s3, customizer); + let result: { a: number, b: number, c: number }; + result = _.assignInWith(obj, s1, s2, s3, customizer); } { - let result: {a: number, b: number, c: number, d: number}; - result = _.assignInWith(obj, s1, s2, s3, s4, customizer); + let result: { a: number, b: number, c: number, d: number }; + result = _.assignInWith(obj, s1, s2, s3, s4, customizer); } { - let result: {a: number, b: number, c: number, d: number, e: number}; - result = _.assignInWith(obj, s1, s2, s3, s4, s5, customizer); + let result: { a: number, b: number, c: number, d: number, e: number }; + result = _.assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); } { @@ -8434,28 +8456,28 @@ namespace TestAssignInWith { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; - result = _(obj).assignInWith(s1, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + result = _(obj).assignInWith(s1, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).assignInWith(s1, s2, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).assignInWith(s1, s2, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).assignInWith(s1, s2, s3, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).assignInWith(s1, s2, s3, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).assignInWith(s1, s2, s3, s4, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).assignInWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).assignInWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } { @@ -8465,28 +8487,28 @@ namespace TestAssignInWith { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; - result = _(obj).chain().assignInWith(s1, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + result = _(obj).chain().assignInWith(s1, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; - result = _(obj).chain().assignInWith(s1, s2, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + result = _(obj).chain().assignInWith(s1, s2, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; - result = _(obj).chain().assignInWith(s1, s2, s3, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + result = _(obj).chain().assignInWith(s1, s2, s3, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; - result = _(obj).chain().assignInWith(s1, s2, s3, s4, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + result = _(obj).chain().assignInWith(s1, s2, s3, s4, customizer); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; - result = _(obj).chain().assignInWith<{a: number, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5, customizer); + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + result = _(obj).chain().assignInWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } @@ -8520,151 +8542,153 @@ namespace TestCreate { } } + // _.defaults namespace TestDefaults { - interface Obj {a: string}; - interface S1 {a: number}; - interface S2 {b: number}; - interface S3 {c: number}; - interface S4 {d: number}; - interface S5 {e: number}; + interface Obj { a: string }; + interface S1 { a: number }; + interface S2 { b: number }; + interface S3 { c: number }; + interface S4 { d: number }; + interface S5 { e: number }; - let obj: Obj; - let s1: S1; - let s2: S2; - let s3: S3; - let s4: S4; - let s5: S5; + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; - { - let result: Obj; + { + let result: Obj; - result = _.defaults(obj); - } + result = _.defaults(obj); + } - { - let result: {a: string}; + { + let result: { a: string }; - result = _.defaults(obj, s1); - } + result = _.defaults(obj, s1); + } - { - let result: {a: string, b: number}; + { + let result: { a: string, b: number }; - result = _.defaults(obj, s1, s2); - } + result = _.defaults(obj, s1, s2); + } - { - let result: {a: string, b: number, c: number}; + { + let result: { a: string, b: number, c: number }; - result = _.defaults(obj, s1, s2, s3); - } + result = _.defaults(obj, s1, s2, s3); + } - { - let result: {a: string, b: number, c: number, d: number}; + { + let result: { a: string, b: number, c: number, d: number }; - result = _.defaults(obj, s1, s2, s3, s4); - } + result = _.defaults(obj, s1, s2, s3, s4); + } - { - let result: {a: string, b: number, c: number, d: number, e: number}; + { + let result: { a: string, b: number, c: number, d: number, e: number }; - result = _.defaults(obj, s1, s2, s3, s4, s5); - } + result = _.defaults<{ a: string, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); + } - { - let result: _.LoDashImplicitObjectWrapper; + { + let result: _.LoDashImplicitObjectWrapper; - result = _(obj).defaults(); - } + result = _(obj).defaults(); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string }>; - result = _(obj).defaults(s1); - } + result = _(obj).defaults(s1); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number }>; - result = _(obj).defaults(s1, s2); - } + result = _(obj).defaults(s1, s2); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number }>; - result = _(obj).defaults(s1, s2, s3); - } + result = _(obj).defaults(s1, s2, s3); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number, d: number }>; - result = _(obj).defaults(s1, s2, s3, s4); - } + result = _(obj).defaults(s1, s2, s3, s4); + } - { - let result: _.LoDashImplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + { + let result: _.LoDashImplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); - } + result = _(obj).defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } - { - let result: _.LoDashExplicitObjectWrapper; + { + let result: _.LoDashExplicitObjectWrapper; - result = _(obj).chain().defaults(); - } + result = _(obj).chain().defaults(); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string }>; - result = _(obj).chain().defaults(s1); - } + result = _(obj).chain().defaults(s1); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number }>; - result = _(obj).chain().defaults(s1, s2); - } + result = _(obj).chain().defaults(s1, s2); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number }>; - result = _(obj).chain().defaults(s1, s2, s3); - } + result = _(obj).chain().defaults(s1, s2, s3); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number, d: number }>; - result = _(obj).chain().defaults(s1, s2, s3, s4); - } + result = _(obj).chain().defaults(s1, s2, s3, s4); + } - { - let result: _.LoDashExplicitObjectWrapper<{a: string, b: number, c: number, d: number, e: number}>; + { + let result: _.LoDashExplicitObjectWrapper<{ a: string, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().defaults<{a: string, b: number, c: number, d: number, e: number}>(s1, s2, s3, s4, s5); - } + result = _(obj).chain().defaults<{ a: string, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } } //_.defaultsDeep interface DefaultsDeepResult { - user: { - name: string; - age: number; - } + user: { + name: string; + age: number; + } } -var TestDefaultsDeepObject = {'user': {'name': 'barney'}}; -var TestDefaultsDeepSource = {'user': {'name': 'fred', 'age': 36}}; +var TestDefaultsDeepObject = { 'user': { 'name': 'barney' } }; +var TestDefaultsDeepSource = { 'user': { 'name': 'fred', 'age': 36 } }; result = _.defaultsDeep(TestDefaultsDeepObject, TestDefaultsDeepSource); result = _(TestDefaultsDeepObject).defaultsDeep(TestDefaultsDeepSource).value(); + // _.extend namespace TestExtend { - type Obj = {a: string}; - type S1 = {a: number}; - type S2 = {b: number}; - type S3 = {c: number}; - type S4 = {d: number}; - type S5 = {e: number}; + type Obj = { a: string }; + type S1 = { a: number }; + type S2 = { b: number }; + type S3 = { c: number }; + type S4 = { d: number }; + type S5 = { e: number }; let obj: Obj; let s1: S1; @@ -8678,42 +8702,37 @@ namespace TestExtend { { let result: Obj; - result = _.extend(obj); + result = _.extend(obj); } { - let result: {a: number}; + let result: { a: number }; - result = _.extend(obj, s1); - result = _.extend(obj, s1, customizer); + result = _.extend(obj, s1); } { - let result: {a: number, b: number}; + let result: { a: number, b: number }; - result = _.extend(obj, s1, s2); - result = _.extend(obj, s1, s2, customizer); + result = _.extend(obj, s1, s2); } { - let result: {a: number, b: number, c: number}; + let result: { a: number, b: number, c: number }; - result = _.extend(obj, s1, s2, s3); - result = _.extend(obj, s1, s2, s3, customizer); + result = _.extend(obj, s1, s2, s3); } { - let result: {a: number, b: number, c: number, d: number}; + let result: { a: number, b: number, c: number, d: number }; - result = _.extend(obj, s1, s2, s3, s4); - result = _.extend(obj, s1, s2, s3, s4, customizer); + result = _.extend(obj, s1, s2, s3, s4); } { - let result: {a: number, b: number, c: number, d: number, e: number}; + let result: { a: number, b: number, c: number, d: number, e: number }; - result = _.extend(obj, s1, s2, s3, s4, s5); - result = _.extend(obj, s1, s2, s3, s4, s5, customizer); + result = _.extend<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5); } { @@ -8723,38 +8742,33 @@ namespace TestExtend { } { - let result: _.LoDashImplicitObjectWrapper<{a: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; - result = _(obj).extend(s1); - result = _(obj).extend(s1, customizer); + result = _(obj).extend(s1); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).extend(s1, s2); - result = _(obj).extend(s1, s2, customizer); + result = _(obj).extend(s1, s2); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).extend(s1, s2, s3); - result = _(obj).extend(s1, s2, s3, customizer); + result = _(obj).extend(s1, s2, s3); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).extend(s1, s2, s3, s4); - result = _(obj).extend(s1, s2, s3, s4, customizer); + result = _(obj).extend(s1, s2, s3, s4); } { - let result: _.LoDashImplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).extend(s1, s2, s3, s4, s5); - result = _(obj).extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); } { @@ -8764,38 +8778,161 @@ namespace TestExtend { } { - let result: _.LoDashExplicitObjectWrapper<{a: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; - result = _(obj).chain().extend(s1); - result = _(obj).chain().extend(s1, customizer); + result = _(obj).chain().extend(s1); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; - result = _(obj).chain().extend(s1, s2); - result = _(obj).chain().extend(s1, s2, customizer); + result = _(obj).chain().extend(s1, s2); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; - result = _(obj).chain().extend(s1, s2, s3); - result = _(obj).chain().extend(s1, s2, s3, customizer); + result = _(obj).chain().extend(s1, s2, s3); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; - result = _(obj).chain().extend(s1, s2, s3, s4); - result = _(obj).chain().extend(s1, s2, s3, s4, customizer); + result = _(obj).chain().extend(s1, s2, s3, s4); } { - let result: _.LoDashExplicitObjectWrapper<{a: number, b: number, c: number, d: number, e: number}>; + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; - result = _(obj).chain().extend(s1, s2, s3, s4, s5); - result = _(obj).chain().extend(s1, s2, s3, s4, s5, customizer); + result = _(obj).chain().extend<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5); + } +} + + +// _.extendWith +namespace TestExtendWith { + type Obj = { a: string }; + type S1 = { a: number }; + type S2 = { b: number }; + type S3 = { c: number }; + type S4 = { d: number }; + type S5 = { e: number }; + + let obj: Obj; + let s1: S1; + let s2: S2; + let s3: S3; + let s4: S4; + let s5: S5; + + let customizer: (objectValue: any, sourceValue: any, key?: string, object?: {}, source?: {}) => any; + + { + let result: Obj; + + result = _.extendWith(obj); + } + + { + let result: { a: number }; + + result = _.extendWith(obj, s1, customizer); + } + + { + let result: { a: number, b: number }; + + result = _.extendWith(obj, s1, s2, customizer); + } + + { + let result: { a: number, b: number, c: number }; + + result = _.extendWith(obj, s1, s2, s3, customizer); + } + + { + let result: { a: number, b: number, c: number, d: number }; + + result = _.extendWith(obj, s1, s2, s3, s4, customizer); + } + + { + let result: { a: number, b: number, c: number, d: number, e: number }; + + result = _.extendWith<{ a: number, b: number, c: number, d: number, e: number }>(obj, s1, s2, s3, s4, s5, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(obj).extendWith(); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number }>; + + result = _(obj).extendWith(s1, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number }>; + + result = _(obj).extendWith(s1, s2, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number }>; + + result = _(obj).extendWith(s1, s2, s3, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + + result = _(obj).extendWith(s1, s2, s3, s4, customizer); + } + + { + let result: _.LoDashImplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + + result = _(obj).extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(obj).chain().extendWith(); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number }>; + + result = _(obj).chain().extendWith(s1, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number }>; + + result = _(obj).chain().extendWith(s1, s2, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number }>; + + result = _(obj).chain().extendWith(s1, s2, s3, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number }>; + + result = _(obj).chain().extendWith(s1, s2, s3, s4, customizer); + } + + { + let result: _.LoDashExplicitObjectWrapper<{ a: number, b: number, c: number, d: number, e: number }>; + + result = _(obj).chain().extendWith<{ a: number, b: number, c: number, d: number, e: number }>(s1, s2, s3, s4, s5, customizer); } } @@ -10162,7 +10299,14 @@ namespace TestValues { { let result: TResult[]; - result = _.values(object); + result = _.values(object); + } + + { + let result: TResult[]; + + // Without this type hint, this will fail to compile, as expected. + result = _.values(new Object); } { @@ -10185,7 +10329,20 @@ namespace TestValuesIn { { let result: TResult[]; - result = _.valuesIn(object); + result = _.valuesIn(object); + } + + { + let result: TResult[]; + + // Without this type hint, this will fail to compile, as expected. + result = _.valuesIn(new Object); + } + + { + let result: TResult[]; + + result = _.values(object); } { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 1e39d223f0..f1772191cd 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2000,7 +2000,7 @@ declare module _ { flattenDeep(): LoDashExplicitArrayWrapper; } - //_.fromPairs DUMMY + //_.fromPairs interface LoDashStatic { /** * The inverse of `_.toPairs`; this method returns an object composed @@ -2016,8 +2016,15 @@ declare module _ { * _.fromPairs([['fred', 30], ['barney', 40]]); * // => { 'fred': 30, 'barney': 40 } */ + fromPairs( + array: List<[_.StringRepresentable, T]> + ): Dictionary; + + /** + @see _.fromPairs + */ fromPairs( - array: any[]|List + array: List ): Dictionary; } @@ -8540,6 +8547,21 @@ declare module _ { callback: MemoIterator): TResult; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitObjectWrapper; + + /** + * @see _.reduce + **/ + reduce( + callback: MemoIterator): LoDashExplicitObjectWrapper; + } + //_.reduceRight interface LoDashStatic { /** @@ -10253,6 +10275,35 @@ declare module _ { * @param funcs Functions to invoke. * @return Returns the new function. */ + // 1-argument first function + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2): (a1: A1) => R2; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1) => R3; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1) => R4; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1) => R5; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1) => R6; + flow(f1: (a1: A1) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1) => R7; + // 2-argument first function + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2) => R2; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2) => R3; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2) => R4; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2) => R5; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2) => R6; + flow(f1: (a1: A1, a2: A2) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2) => R7; + // 3-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3) => R7; + // 4-argument first function + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2): (a1: A1, a2: A2, a3: A3, a4: A4) => R2; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3): (a1: A1, a2: A2, a3: A3, a4: A4) => R3; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4): (a1: A1, a2: A2, a3: A3, a4: A4) => R4; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5): (a1: A1, a2: A2, a3: A3, a4: A4) => R5; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6): (a1: A1, a2: A2, a3: A3, a4: A4) => R6; + flow(f1: (a1: A1, a2: A2, a3: A3, a4: A4) => R1, f2: (a: R1) => R2, f3: (a: R2) => R3, f4: (a: R3) => R4, f5: (a: R4) => R5, f6: (a: R5) => R6, f7: (a: R6) => R7): (a1: A1, a2: A2, a3: A3, a4: A4) => R7; + // generic function flow(...funcs: Function[]): TResult; } @@ -13761,53 +13812,52 @@ declare module _ { * _.assign({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3, 'e': 5 } */ - assign( + assign( object: TObject, source: TSource - ): TResult; + ): TObject & TSource; /** * @see assign */ - assign( + assign( object: TObject, source1: TSource1, source2: TSource2 - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assign */ - assign( + assign( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assign */ - assign - ( + assign( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assign */ - assign(object: TObject): TObject; + assign(object: TObject): TObject; /** * @see _.assign */ - assign( - object: TObject, ...otherArgs: any[] + assign( + object: any, + ...otherArgs: any[] ): TResult; } @@ -13815,36 +13865,36 @@ declare module _ { /** * @see _.assign */ - assign( + assign( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assign @@ -13854,43 +13904,43 @@ declare module _ { /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assign */ - assign( + assign( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assign */ - assign( + assign( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assign @@ -13900,7 +13950,7 @@ declare module _ { /** * @see _.assign */ - assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assign(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignWith @@ -13935,57 +13985,56 @@ declare module _ { * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ - assignWith( + assignWith( object: TObject, source: TSource, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource; /** * @see assignWith */ - assignWith( + assignWith( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignWith */ - assignWith( + assignWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignWith */ - assignWith - ( + assignWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignWith */ - assignWith(object: TObject): TObject; + assignWith(object: TObject): TObject; /** * @see _.assignWith */ - assignWith( - object: TObject, ...otherArgs: any[] + assignWith( + object: any, + ...otherArgs: any[] ): TResult; } @@ -13993,40 +14042,40 @@ declare module _ { /** * @see _.assignWith */ - assignWith( + assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignWith @@ -14036,47 +14085,47 @@ declare module _ { /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignWith */ - assignWith( + assignWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignWith */ - assignWith( + assignWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignWith @@ -14086,7 +14135,7 @@ declare module _ { /** * @see _.assignWith */ - assignWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignIn @@ -14120,53 +14169,52 @@ declare module _ { * _.assignIn({ 'a': 1 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5 } */ - assignIn( + assignIn( object: TObject, source: TSource - ): TResult; + ): TObject & TSource; /** * @see assignIn */ - assignIn( + assignIn( object: TObject, source1: TSource1, source2: TSource2 - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignIn */ - assignIn( + assignIn( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignIn */ - assignIn - ( + assignIn( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignIn */ - assignIn(object: TObject): TObject; + assignIn(object: TObject): TObject; /** * @see _.assignIn */ - assignIn( - object: TObject, ...otherArgs: any[] + assignIn( + object: any, + ...otherArgs: any[] ): TResult; } @@ -14174,36 +14222,36 @@ declare module _ { /** * @see _.assignIn */ - assignIn( + assignIn( source: TSource - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignIn @@ -14213,43 +14261,43 @@ declare module _ { /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignIn */ - assignIn( + assignIn( source: TSource - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignIn */ - assignIn( + assignIn( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4 - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignIn @@ -14259,7 +14307,7 @@ declare module _ { /** * @see _.assignIn */ - assignIn(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignIn(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.assignInWith @@ -14295,57 +14343,56 @@ declare module _ { * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ - assignInWith( + assignInWith( object: TObject, source: TSource, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource; /** * @see assignInWith */ - assignInWith( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2; /** * @see assignInWith */ - assignInWith( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3; /** * @see assignInWith */ - assignInWith - ( + assignInWith( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): TResult; + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** * @see _.assignInWith */ - assignInWith(object: TObject): TObject; + assignInWith(object: TObject): TObject; /** * @see _.assignInWith */ - assignInWith( - object: TObject, ...otherArgs: any[] + assignInWith( + object: any, + ...otherArgs: any[] ): TResult; } @@ -14353,40 +14400,40 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith( + assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashImplicitObjectWrapper; + ): LoDashImplicitObjectWrapper; /** * @see _.assignInWith @@ -14396,47 +14443,47 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.assignInWith */ - assignInWith( + assignInWith( source: TSource, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see assignInWith */ - assignInWith( + assignInWith( source1: TSource1, source2: TSource2, source3: TSource3, source4: TSource4, customizer: AssignCustomizer - ): LoDashExplicitObjectWrapper; + ): LoDashExplicitObjectWrapper; /** * @see _.assignInWith @@ -14446,7 +14493,7 @@ declare module _ { /** * @see _.assignInWith */ - assignInWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; + assignInWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.create @@ -14479,6 +14526,7 @@ declare module _ { create(properties?: U): LoDashExplicitObjectWrapper; } + //_.defaults interface LoDashStatic { /** @@ -14492,59 +14540,52 @@ declare module _ { * @param sources The source objects. * @return The destination object. */ - defaults( - object: Obj, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source: TSource + ): TSource & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): TSource3 & TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): TResult; + defaults( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): TSource4 & TSource3 & TSource2 & TSource1 & TObject; /** * @see _.defaults */ - defaults( - object: Obj, - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): TResult; + defaults(object: TObject): TObject; /** * @see _.defaults */ - defaults( - object: {}, - ...sources: {}[] + defaults( + object: any, + ...sources: any[] ): TResult; } @@ -14552,40 +14593,36 @@ declare module _ { /** * @see _.defaults */ - defaults( - source1: S1, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source: TSource + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): LoDashImplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashImplicitObjectWrapper; /** * @see _.defaults @@ -14595,47 +14632,43 @@ declare module _ { /** * @see _.defaults */ - defaults(...sources: {}[]): LoDashImplicitObjectWrapper; + defaults(...sources: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.defaults */ - defaults( - source1: S1, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source: TSource + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults */ - defaults( - source1: S1, - source2: S2, - source3: S3, - source4: S4, - ...sources: {}[] - ): LoDashExplicitObjectWrapper; + defaults( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4 + ): LoDashExplicitObjectWrapper; /** * @see _.defaults @@ -14645,7 +14678,7 @@ declare module _ { /** * @see _.defaults */ - defaults(...sources: {}[]): LoDashExplicitObjectWrapper; + defaults(...sources: any[]): LoDashExplicitObjectWrapper; } //_.defaultsDeep @@ -14668,163 +14701,307 @@ declare module _ { defaultsDeep(...sources: any[]): LoDashImplicitObjectWrapper } - //_.extend + // _.extend interface LoDashStatic { /** - * @see assign + * @see _.assignIn */ - extend( + extend( object: TObject, - source: TSource, - customizer?: AssignCustomizer - ): TResult; + source: TSource + ): TObject & TSource; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + object: TObject, + source1: TSource1, + source2: TSource2 + ): TObject & TSource1 & TSource2; + + /** + * @see _.assignIn + */ + extend( object: TObject, source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): TResult; + source3: TSource3 + ): TObject & TSource1 & TSource2 & TSource3; /** - * @see assign + * @see _.assignIn */ - extend( + extend( object: TObject, source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): TResult; + source4: TSource4 + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; /** - * @see assign + * @see _.assignIn */ - extend - ( - object: TObject, - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): TResult; + extend(object: TObject): TObject; /** - * @see _.assign + * @see _.assignIn */ - extend(object: TObject): TObject; - - /** - * @see _.assign - */ - extend( - object: TObject, ...otherArgs: any[] + extend( + object: any, + ...otherArgs: any[] ): TResult; } interface LoDashImplicitObjectWrapper { /** - * @see _.assign + * @see _.assignIn */ - extend( - source: TSource, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + extend( + source: TSource + ): LoDashImplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + source1: TSource1, + source2: TSource2 + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignIn + */ + extend( source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + source3: TSource3 + ): LoDashImplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; + source4: TSource4 + ): LoDashImplicitObjectWrapper; /** - * @see assign - */ - extend( - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): LoDashImplicitObjectWrapper; - - /** - * @see _.assign + * @see _.assignIn */ extend(): LoDashImplicitObjectWrapper; /** - * @see _.assign + * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashImplicitObjectWrapper; } interface LoDashExplicitObjectWrapper { /** - * @see _.assign + * @see _.assignIn */ - extend( - source: TSource, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + extend( + source: TSource + ): LoDashExplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( + source1: TSource1, + source2: TSource2 + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignIn + */ + extend( source1: TSource1, source2: TSource2, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + source3: TSource3 + ): LoDashExplicitObjectWrapper; /** - * @see assign + * @see _.assignIn */ - extend( + extend( source1: TSource1, source2: TSource2, source3: TSource3, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; + source4: TSource4 + ): LoDashExplicitObjectWrapper; /** - * @see assign - */ - extend( - source1: TSource1, - source2: TSource2, - source3: TSource3, - source4: TSource4, - customizer?: AssignCustomizer - ): LoDashExplicitObjectWrapper; - - /** - * @see _.assign + * @see _.assignIn */ extend(): LoDashExplicitObjectWrapper; /** - * @see _.assign + * @see _.assignIn */ - extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + extend(...otherArgs: any[]): LoDashExplicitObjectWrapper; + } + + interface LoDashStatic { + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source: TSource, + customizer: AssignCustomizer + ): TObject & TSource; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3; + + /** + * @see _.assignInWith + */ + extendWith( + object: TObject, + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): TObject & TSource1 & TSource2 & TSource3 & TSource4; + + /** + * @see _.assignInWith + */ + extendWith(object: TObject): TObject; + + /** + * @see _.assignInWith + */ + extendWith( + object: any, + ...otherArgs: any[] + ): TResult; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.assignInWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(): LoDashImplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(...otherArgs: any[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.assignInWith + */ + extendWith( + source: TSource, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith( + source1: TSource1, + source2: TSource2, + source3: TSource3, + source4: TSource4, + customizer: AssignCustomizer + ): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(): LoDashExplicitObjectWrapper; + + /** + * @see _.assignInWith + */ + extendWith(...otherArgs: any[]): LoDashExplicitObjectWrapper; } //_.findKey @@ -16878,6 +17055,11 @@ declare module _ { * @param object The object to query. * @return Returns an array of property values. */ + values(object?: Dictionary): T[]; + + /** + * @see _.values + */ values(object?: any): T[]; } @@ -16903,6 +17085,11 @@ declare module _ { * @param object The object to query. * @return Returns the array of property values. */ + valuesIn(object?: Dictionary): T[]; + + /** + * @see _.valuesIn + */ valuesIn(object?: any): T[]; } @@ -19907,15 +20094,12 @@ declare module "lodash/extend" { export = extend; } -/** -* uncoment it if definition exists -*/ -/* + declare module "lodash/extendWith" { const extendWith: typeof _.extendWith; export = extendWith; } -*/ + declare module "lodash/add" { const add: typeof _.add; diff --git a/log4javascript/log4javascript-tests.ts b/log4javascript/log4javascript-tests.ts index c3b77c5b69..b05626b297 100644 --- a/log4javascript/log4javascript-tests.ts +++ b/log4javascript/log4javascript-tests.ts @@ -2,7 +2,14 @@ function aSimpleLoggingMessageString() { var log = log4javascript.getDefaultLogger(); - log.info("Hello World"); + log.info("Hello World"); +} + +function compareLogLevelsAndLog() { + var log = log4javascript.getDefaultLogger(); + if (log4javascript.Level.INFO.isGreaterOrEqual(log.getLevel())) { + log.log(log4javascript.Level.INFO, ["Info"]); + } } function loggingAnErrorWithAMessage() { diff --git a/log4javascript/log4javascript.d.ts b/log4javascript/log4javascript.d.ts index 460e17c91f..55d7726563 100644 --- a/log4javascript/log4javascript.d.ts +++ b/log4javascript/log4javascript.d.ts @@ -1,4 +1,4 @@ -// Type definitions for log4javascript v1.4.10 +// Type definitions for log4javascript v1.4.13 // Project: http://log4javascript.org/ // Definitions by: Markus Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -89,7 +89,22 @@ declare namespace log4javascript { /** * Levels are available as static properties of the log4javascript.Level object. */ - export enum Level { ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF } + export class Level { + static ALL: Level; + static TRACE: Level; + static DEBUG: Level; + static INFO: Level; + static WARN: Level; + static ERROR: Level; + static FATAL: Level; + static OFF: Level; + + constructor(level: number, name: string); + + toString(): string; + equals(level: Level): boolean; + isGreaterOrEqual(level: Level): boolean; + } // #endregion @@ -126,6 +141,11 @@ declare namespace log4javascript { */ removeAllAppenders(): void; + /** + * Returns all appenders which will log a message. + */ + getEffectiveAppenders(): Appender[]; + /** * Sets the level. Log messages of a lower level than level will not be logged. Default value is DEBUG. */ diff --git a/log4js/log4js-tests.ts b/log4js/log4js-tests.ts index 4fefc1caab..4e4f1ce4c6 100644 --- a/log4js/log4js-tests.ts +++ b/log4js/log4js-tests.ts @@ -72,3 +72,30 @@ log4js.configure({ }); log4js.configure('file.json', { reloadSecs: 300 }); + +class MyAppenderConfig implements log4js.CustomAppenderConfig { + public type: string; + public mycfg: string; +} + +var myAppender: log4js.AppenderModule = { + + appender: function (mycfg: string): log4js.Appender { + + return function (event: log4js.LogEvent): void { + console.log(mycfg); + console.log(event); + } + }, + + shutdown: function (cb: (error: Error) => void): void { + return cb(null); + }, + + configure: function (config: MyAppenderConfig, options?: { [key: string]: any }): log4js.Appender { + var mycfg = config.mycfg; + return this.appender(mycfg); + } +} + +log4js.loadAppender("my-log4js-appender", myAppender); \ No newline at end of file diff --git a/log4js/log4js.d.ts b/log4js/log4js.d.ts index c79fd60818..38af275833 100644 --- a/log4js/log4js.d.ts +++ b/log4js/log4js.d.ts @@ -57,6 +57,16 @@ declare module "log4js" { */ export function addAppender(...appenders: any[]): void; + /** + * Load appender + * + * @param {string} appender type + * @param {AppenderModule} the appender module. by default, require('./appenders/' + appender) + * @returns {void} + * @static + */ + export function loadAppender(appenderType: string, appenderModule?: AppenderModule): void; + /** * Claer configured appenders * @@ -93,6 +103,26 @@ declare module "log4js" { export function connectLogger(logger: Logger, options: { format?: string; level?: string; nolog?: any; }): express.Handler; export function connectLogger(logger: Logger, options: { format?: string; level?: Level; nolog?: any; }): express.Handler; + export var layouts: { + basicLayout: Layout, + messagePassThroughLayout: Layout, + patternLayout: Layout, + colouredLayout: Layout, + coloredLayout: Layout, + dummyLayout: Layout, + + /** + * Register your custom layout generator + */ + addLayout: (name: string, serializerGenerator: (config?: LayoutConfig) => Layout) => void, + + /** + * Get layout. Available predified layout names: + * messagePassThrough, basic, colored, coloured, pattern, dummy + * + */ + layout: (name: string, config: LayoutConfig) => Layout + } export var appenders: any; export var levels: { @@ -147,6 +177,7 @@ declare module "log4js" { export interface AppenderConfigBase { type: string; category?: string; + layout?: { type: string;[key: string]: any } } export interface ConsoleAppenderConfig extends AppenderConfigBase {} @@ -252,4 +283,36 @@ declare module "log4js" { } type AppenderConfig = CoreAppenderConfig | CustomAppenderConfig; + + export interface LogEvent { + /** + * new Date() + */ + startTime: number; + categoryName: string; + data: any[]; + level: Level; + logger: Logger; + } + + export interface Appender { + (event: LogEvent): void; + } + + export interface AppenderModule { + appender: (...args: any[]) => Appender; + shutdown?: (cb: (error: Error) => void) => void; + configure: (config: CustomAppenderConfig, options?: { [key: string]: any }) => Appender; + } + + export interface LayoutConfig { + [key: string]: any; + } + export interface LayoutGenerator { + (config?: LayoutConfig): Layout + } + + export interface Layout { + (event: LogEvent): string; + } } diff --git a/long/long.d.ts b/long/long.d.ts index 514eb5677a..1ef1052651 100644 --- a/long/long.d.ts +++ b/long/long.d.ts @@ -348,6 +348,5 @@ declare class Long } declare module 'long' { - namespace Long {} export = Long; } diff --git a/mCustomScrollbar/mCustomScrollbar-tests.ts b/mCustomScrollbar/mCustomScrollbar-tests.ts index 7dcf793564..9c5f030679 100644 --- a/mCustomScrollbar/mCustomScrollbar-tests.ts +++ b/mCustomScrollbar/mCustomScrollbar-tests.ts @@ -9,7 +9,8 @@ class SimpleTest { this.element.mCustomScrollbar({ scrollButtons: { - enable: true + enable: true, + scrollAmount: 2 } }); } @@ -22,38 +23,78 @@ class SimpleTestAllParams { this.element = $(".content"); this.element.mCustomScrollbar({ - setWidth: false, - setHeight: false, + setWidth: 22, + setHeight: "40%", + setTop: 0, + setLeft: 22, axis: "y", + scrollbarPosition: "inside", scrollInertia: 950, - mouseWheel: true, - mouseWheelPixels: "auto", autoDraggerLength: true, autoHideScrollbar: false, + autoExpandScrollbar: false, + alwaysShowScrollbar: 0, + snapAmount: [3,3], + snapOffset: 3, + mouseWheel: { + enable: true, + scrollAmount: 1, + axis:"x", + preventDefault: false, + deltaFactor:12, + normalizeDelta:true, + invert: false, + disableOver: ["select","option"] + + }, scrollButtons: { enable: false, - scrollType: "continuous", - scrollSpeed: "auto", - scrollAmount: 40 + scrollType: "stepped", + scrollAmount: 40, + tabindex: 33, + }, + keyboard:{ + enable: true, + scrollAmount:5, + scrollType:"stepless" }, advanced: { updateOnBrowserResize: true, updateOnContentResize: false, + updateOnImageLoad: true, + updateOnSelectorChange: "ul li", + extraDraggableSelectors: ".myClass", + releaseDraggableSelectors: ".myClass", + autoUpdateTimeout:60, autoExpandHorizontalScroll: false, - autoScrollOnFocus: true, - normalizeMouseWheelDelta: false + autoScrollOnFocus: "input", }, contentTouchScroll: true, + documentTouchScroll: false, + callbacks: { + onCreate: () => { }, + onInit: () => { }, onScrollStart: () => { }, onScroll: () => { }, onTotalScroll: () => { }, onTotalScrollBack: () => { }, onTotalScrollOffset: 0, onTotalScrollBackOffset: 0, - whileScrolling: () => { } + whileScrolling: () => { }, + alwaysTriggerOffsets: false, + onOverflowY: () => { }, + onOverflowX: () => { }, + onOverflowYNone: () => {}, + onOverflowXNone: () => {}, + onBeforeUpdate: () => {}, + onUpdate: () => {}, + onImageLoad: () => {}, + onSelectorChange: () => {}, }, - theme: "light" + theme: "light", + live: true, + liveSelector: ".myClass" }); } } diff --git a/mCustomScrollbar/mCustomScrollbar.d.ts b/mCustomScrollbar/mCustomScrollbar.d.ts index 4aad109c66..aa088d6f5c 100644 --- a/mCustomScrollbar/mCustomScrollbar.d.ts +++ b/mCustomScrollbar/mCustomScrollbar.d.ts @@ -10,16 +10,35 @@ declare namespace MCustomScrollbar { /** * Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string) */ - setWidth?: any; + setWidth?: boolean|number|string; /** * Set the height of your content (overwirtes CSS height), value in pixels (integer) or percentage (string) */ - setHeight?: any; + setHeight?: boolean|number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setTop? : number|string; + /** + * Set the initial css top property of content, accepts string values (css top position). + * Example: setTop: "-100px". + */ + setLeft? : number|string; /** * Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal). - * Available values: "y", "x", "yx". y -vertical, x - horizontal + * Available values: "y", "x", "yx". y -vertical, x - horizontal, yx - vertical and horizontal */ - axis?: string; + axis?: "x"|"y"|"yx"; + /** + * Set the position of scrollbar in relation to content. + * Available values: "inside", "outside". + * Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. + * Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. + * Note that setting the value to "outside" requires your element (or parent elements) + * to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element). + */ + scrollbarPosition?: "inside"|"outside"; /** * Always keep scrollbar(s) visible, even when there’s nothing to scroll. * 0 – disable (default) @@ -28,6 +47,18 @@ declare namespace MCustomScrollbar { */ alwaysShowScrollbar?: number; /** + * Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, + * image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. + * Note that your elements must be of equal width or height in order for this to work properly. + * To set different values for vertical and horizontal scrolling, use an array: [y,x] + */ + snapAmount?: number|[number,number]; + /** + * Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the + * snap amount of table rows by the table header. + */ + snapOffset?: number; + /** * Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar. */ autoExpandScrollbar?: boolean; @@ -36,9 +67,68 @@ declare namespace MCustomScrollbar { */ scrollInertia?: number; /** - * Mouse wheel support, value: true, false + * Mouse wheel support */ - mouseWheel?: boolean; + mouseWheel?: { + /** + * Enable or disable content scrolling via mouse-wheel. + */ + enable?: boolean; + /** + * Set the mouse-wheel scrolling amount (in pixels). + * The default value "auto" adjusts scrolling amount according to scrollable content length. + */ + scrollAmount?: "auto"|number; + /** + * Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present. + * Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling. + */ + axis?: "x"|"y"; + /** + * Prevent the default behaviour which automatically scrolls the parent element when end + * or beginning of scrolling is reached (same bahavior with browser’s native scrollbar). + */ + preventDefault?: boolean; + /** + * Set the number of pixels one wheel notch scrolls. The default value “auto” uses the OS/browser value. + */ + deltaFactor?: number; + /** + * Enable or disable mouse-wheel (delta) acceleration. + * Setting normalizeDelta: true translates mouse-wheel delta value to -1 or 1. + */ + normalizeDelta?:boolean; + /** + * Invert mouse-wheel scrolling direction. + * Set to true to scroll down or right when mouse-wheel is turned upwards. + */ + invert?: boolean; + /** + * Set the tags that disable mouse-wheel when cursor is over them. + * Default value: ["select","option","keygen","datalist","textarea"] + */ + disableOver?: string[]; + } + /** + * Keyboard support + */ + keyboard?:{ + /** + * Enable or disable content scrolling via keyboard. + */ + enable?: boolean; + /** + * Set the keyboard arrows scrolling amount (in pixels). + * The default value "auto" adjusts scrolling amount according to scrollable content length. + */ + scrollAmount?: "auto"|number; + /** + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) + */ + scrollType?: "stepless"|"stepped"; + } /** * Mouse wheel scrolling pixels amount, value in pixels (integer) or "auto" (script calculates and sets pixels amount according to content length) */ @@ -57,19 +147,21 @@ declare namespace MCustomScrollbar { */ enable?: boolean; /** - * Scroll buttons scroll type, values: "continuous" (scroll continuously while pressing the button), "pixels" (scrolls by a fixed number of pixels on each click") + * Define the buttons scrolling type/behavior. + * scrollType: "stepless" – continuously scroll content while pressing the button (default) + * scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above) */ - scrollType?: string; + scrollType?: "stepless"|"stepped"; /** - * Scroll buttons continuous scrolling speed, integer value or "auto" (script calculates and sets the speed according to content length) + * Set a tabindex value for the buttons. */ - scrollSpeed?: number | string; + tabindex?: number; /** * Scroll buttons pixels scrolling amount, value in pixels or "auto" */ - scrollAmount?: number | string; + scrollAmount?: "auto"|number ; } - advanced?: { + advanced?: { /** * Update scrollbars on browser resize (for fluid content blocks and layouts based on percentages), values: true, false. Set to false only when you content has fixed dimensions */ @@ -80,27 +172,75 @@ declare namespace MCustomScrollbar { */ updateOnContentResize?: boolean; /** + * Update scrollbar(s) automatically each time an image inside the element is fully loaded. + * Default value is auto which triggers the function only on "x" and "yx" axis (if needed). + * The value should be true when your content contains images and you need the function to trigger on any axis. + */ + updateOnImageLoad?: "auto"|boolean; + /** + * Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc. + * Example: extraDraggableSelectors: ".myClass, #myID" + */ + extraDraggableSelectors?: string; + /** + * Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc. + * Example: releaseDraggableSelectors: ".myClass, #myID" + */ + releaseDraggableSelectors?: string; + /** + * Set the auto-update timeout in milliseconds. + * Default timeout: 60 + */ + autoUpdateTimeout?: number; + /** + * Update scrollbar(s) automatically when the amount and size of specific selectors changes. + * Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size. + * For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed. + * Setting the value to true, will update scrollbars each time any element is changed. + * To disable (default) set to false. + */ + updateOnSelectorChange?: string|boolean; + /** * Auto-expanding content's width on horizontal scrollbars, values: true, false. Set to true if you have horizontal scrollbr on content that change on-the-fly. Demo contains * blocks with images and horizontal scrollbars that use this option parameter */ autoExpandHorizontalScroll?: boolean; /** - * Auto-scrolling on elements that have focus (e.g. scrollbar automatically scrolls to form text fields when the TAB key is pressed), values: true, false + * Set the list of elements/selectors that will auto-scroll content to their position when focused. + * For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content + * will scroll to its top/left position (same bahavior with browser’s native scrollbar). + * To completely disable this functionality, set autoScrollOnFocus: false. + * Default: + * "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']" */ - autoScrollOnFocus?: boolean; + autoScrollOnFocus?: boolean|string; /** * Normalize mouse wheel delta (-1/1), values: true, false */ normalizeMouseWheelDelta?: boolean; } - /** - * Additional scrolling method by touch-swipe content (for touch enabled devices), value: true, false - */ - contentTouchScroll?: boolean; + /** + * Enable or disable content touch-swipe scrolling for touch-enabled devices. + * To completely disable, set contentTouchScroll: false. + * Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25). + */ + contentTouchScroll?: boolean|number; + /** + * Enable or disable document touch-swipe scrolling for touch-enabled devices. + */ + documentTouchScroll?: boolean; /** * All of the following callbacks option have examples in the callback demo - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/callbacks_example.html */ callbacks?: { + /** + * A function to call when plugin markup is created. + */ + onCreate?: () => void; + /** + * A function to call when scrollbars have initialized + */ + onInit?: () => void; /** * User defined callback function, triggered on scroll start event. You can call your own function(s) each time a scroll event begins */ @@ -137,11 +277,56 @@ declare namespace MCustomScrollbar { * Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached. */ alwaysTriggerOffsets?: boolean; + /** + * A function to call when content becomes long enough and vertical scrollbar is added. + */ + onOverflowY?: () => void; + /** + * A function to call when content becomes wide enough and horizontal scrollbar is added. + */ + onOverflowX?: () => void; + /** + * A function to call when content becomes short enough and vertical scrollbar is removed. + */ + onOverflowYNone?: () => void; + /** + * A function to call when content becomes narrow enough and horizontal scrollbar is removed. + */ + onOverflowXNone?: () => void; + /** + * A function to call right before scrollbar(s) are updated. + */ + onBeforeUpdate?: () => void; + /** + * A function to call when scrollbar(s) are updated. + */ + onUpdate?: () => void; + /** + * A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated. + */ + onImageLoad?: () => void; + /** + * A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated. + */ + onSelectorChange?: () => void; } - /** - * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html - */ - theme?: string; + /** + * Set a scrollbar ready-to-use theme. See themes demo for all themes - http://manos.malihu.gr/tuts/custom-scrollbar-plugin/scrollbar_themes_demo.html + */ + theme?: string; + /** + * Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future. + * Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. + * These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link). + * If you need at any time to disable or enable the live option, set live: "off" and "on" respectively. + * You can also tell the script to disable live option after the first invocation by setting live: "once". + */ + live?: string|boolean; + /** + * Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future. + */ + liveSelector?: string; + } interface ScrollToParameterOptions { diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index e314f09669..ef32f885ff 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -25,11 +25,11 @@ function test() { } function testAngle() { - makerjs.angle.areEqual(12, 13); makerjs.angle.mirror(45, true, false); makerjs.angle.noRevolutions(90); makerjs.angle.ofArcEnd(paths.arc); makerjs.angle.ofArcMiddle(paths.arc); + makerjs.angle.ofArcSpan(paths.arc); makerjs.angle.ofLineInDegrees(paths.line); makerjs.angle.ofPointInDegrees([0,0], [1,1]); makerjs.angle.ofPointInRadians([0,0], [1,1]); @@ -67,7 +67,9 @@ function test() { } function testMeasure() { - makerjs.measure.arcAngle(paths.arc); + makerjs.measure.isPointEqual(p1, p2); + makerjs.measure.isPathEqual(paths.line, paths.circle, 4); + makerjs.measure.isAngleEqual(12, 13); makerjs.measure.isArcConcaveTowardsPoint(paths.arc, [0,0]); makerjs.measure.isBetween(7, 8, 9, false); makerjs.measure.isBetweenArcAngles(7, paths.arc, false); @@ -119,7 +121,6 @@ function test() { } function testPath() { - makerjs.path.areEqual(paths.line, paths.circle, 4); makerjs.path.breakAtPoint(paths.arc, [0,0]).type; makerjs.path.dogbone(paths.line, paths.line, 7); makerjs.path.fillet(paths.arc, paths.line, 4); @@ -129,7 +130,6 @@ function test() { makerjs.path.moveRelative(paths.circle, [0,0]); makerjs.path.rotate(paths.line, 5, [0,0]); makerjs.path.scale(paths.arc, 8); - makerjs.path.slopeIntersectionPoint(paths.line, paths.line); } function testPaths() { @@ -156,8 +156,6 @@ function test() { function testPoint() { makerjs.point.add(p1, p2); - makerjs.point.areEqual(p1, p2); - makerjs.point.areEqualRounded(p1, p2); makerjs.point.average(p1, p2); makerjs.point.clone(p1); makerjs.point.closest([0,0], [p1, p2]); @@ -170,7 +168,6 @@ function test() { makerjs.point.rotate(p1, 5, p2); makerjs.point.rounded(p1); makerjs.point.scale(p2, 8); - makerjs.point.serialize(p1); makerjs.point.subtract(p2, p1); makerjs.point.zero(); } diff --git a/maker.js/makerjs.d.ts b/maker.js/makerjs.d.ts index fdfade36da..28db25f854 100644 --- a/maker.js/makerjs.d.ts +++ b/maker.js/makerjs.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/Microsoft/maker.js // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// /** * Root module for Maker.js. * @@ -37,6 +38,13 @@ declare namespace MakerJs { * @param accuracy Optional exemplar of number of decimal places. */ function round(n: number, accuracy?: number): number; + /** + * Create a string representation of a route array. + * + * @param route Array of strings which are segments of a route. + * @returns String of the flattened array. + */ + function createRouteKey(route: string[]): string; /** * Clone an object. * @@ -89,6 +97,12 @@ declare namespace MakerJs { */ high: IPoint; } + /** + * A map of measurements. + */ + interface IMeasureMap { + [key: string]: IMeasure; + } /** * A line, curved line or other simple two dimensional shape. */ @@ -181,7 +195,6 @@ declare namespace MakerJs { function isPathArc(item: any): boolean; /** * A map of functions which accept a path as a parameter. - * @private */ interface IPathFunctionMap { /** @@ -191,7 +204,6 @@ declare namespace MakerJs { } /** * A map of functions which accept a path and an origin point as parameters. - * @private */ interface IPathOriginFunctionMap { /** @@ -213,10 +225,31 @@ declare namespace MakerJs { Circle: string; Arc: string; }; + /** + * Slope and y-intercept of a line. + */ + interface ISlope { + /** + * Boolean to see if line has slope or is vertical. + */ + hasSlope: boolean; + /** + * Optional value of non-vertical slope. + */ + slope?: number; + /** + * Line used to calculate this slope. + */ + line: IPathLine; + /** + * Optional value of y when x = 0. + */ + yIntercept?: number; + } /** * Options to pass to path.intersection() */ - interface IPathIntersectionOptions { + interface IPathIntersectionBaseOptions { /** * Optional boolean to only return deep intersections, i.e. not on an end point or tangent. */ @@ -226,6 +259,19 @@ declare namespace MakerJs { */ out_AreOverlapped?: boolean; } + /** + * Options to pass to path.intersection() + */ + interface IPathIntersectionOptions extends IPathIntersectionBaseOptions { + /** + * Optional boolean to only return deep intersections, i.e. not on an end point or tangent. + */ + path1Offset?: IPoint; + /** + * Optional output variable which will be set to true if the paths are overlapped. + */ + path2Offset?: IPoint; + } /** * An intersection of two paths. */ @@ -268,6 +314,14 @@ declare namespace MakerJs { * Point which is known to be outside of the model. */ farPoint?: IPoint; + /** + * Cached measurements for model A. + */ + measureA?: measure.Atlas; + /** + * Cached measurements for model B. + */ + measureB?: measure.Atlas; } /** * Options to pass to model.findLoops. @@ -278,6 +332,19 @@ declare namespace MakerJs { */ removeFromOriginal?: boolean; } + /** + * Options to pass to model.simplify() + */ + interface ISimplifyOptions { + /** + * Optional + */ + pointMatchingDistance?: number; + /** + * Optional + */ + scalarMatchingDistance?: number; + } /** * A path that may be indicated to "flow" in either direction between its endpoints. */ @@ -370,11 +437,104 @@ declare namespace MakerJs { pathId: string; } /** - * Path and its reference id within a model + * A route to either a path or a model, and the absolute offset of it. */ - interface IRefPathInModel extends IRefPathIdInModel { + interface IRouteOffset { + layer: string; + offset: IPoint; + route: string[]; + routeKey: string; + } + /** + * A path reference in a walk. + */ + interface IWalkPath extends IRefPathIdInModel, IRouteOffset { pathContext: IPath; } + /** + * Callback signature for path in model.walk(). + */ + interface IWalkPathCallback { + (context: IWalkPath): void; + } + /** + * A link in a chain, with direction of flow. + */ + interface IChainLink { + /** + * Reference to the path. + */ + walkedPath: IWalkPath; + /** + * Path flows forwards or reverse. + */ + reversed: boolean; + /** + * The endpoints of the path, in absolute coords. + */ + endPoints: IPoint[]; + } + /** + * A chain of paths which connect end to end. + */ + interface IChain { + /** + * The links in this chain. + */ + links: IChainLink[]; + /** + * Flag if this chain forms a loop end to end. + */ + endless?: boolean; + } + /** + * Callback to model.findChains() with resulting array of chains and unchained paths. + */ + interface IChainCallback { + (chains: IChain[], loose: IWalkPath[], layer: string): void; + } + /** + * Options to pass to model.findLoops. + */ + interface IFindChainsOptions extends IPointMatchOptions { + /** + * Flag to separate chains by layers. + */ + byLayers?: boolean; + } + /** + * Reference to a model within a model. + */ + interface IRefModelInModel { + parentModel: IModel; + childId: string; + childModel: IModel; + } + /** + * A model reference in a walk. + */ + interface IWalkModel extends IRefModelInModel, IRouteOffset { + } + /** + * Callback signature for model.walk(). + */ + interface IWalkModelCallback { + (context: IWalkModel): void; + } + /** + * Callback signature for model.walk(), which may return false to halt any further walking. + */ + interface IWalkModelCancellableCallback { + (context: IWalkModel): boolean; + } + /** + * Options to pass to model.walk(). + */ + interface IWalkOptions { + onPath?: IWalkPathCallback; + beforeChildWalk?: IWalkModelCancellableCallback; + afterChildWalk?: IWalkModelCallback; + } /** * Describes a parameter and its limits. */ @@ -425,14 +585,6 @@ declare namespace MakerJs { } } declare namespace MakerJs.angle { - /** - * Find out if two angles are equal. - * - * @param a First angle. - * @param b Second angle. - * @returns true if angles are the same, false if they are not - */ - function areEqual(angle1: number, angle2: number, accuracy?: number): boolean; /** * Ensures an angle is not greater than 360 * @@ -469,6 +621,13 @@ declare namespace MakerJs.angle { * @returns Middle angle of arc. */ function ofArcMiddle(arc: IPathArc, ratio?: number): number; + /** + * Total angle of an arc between its start and end angles. + * + * @param arc The arc to measure. + * @returns Angle of arc. + */ + function ofArcSpan(arc: IPathArc): number; /** * Angle of a line path. * @@ -512,23 +671,6 @@ declare namespace MakerJs.point { * @returns A new point object. */ function add(a: IPoint, b: IPoint, subtract?: boolean): IPoint; - /** - * Find out if two points are equal. - * - * @param a First point. - * @param b Second point. - * @returns true if points are the same, false if they are not - */ - function areEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean; - /** - * Find out if two points are equal after rounding. - * - * @param a First point. - * @param b Second point. - * @param accuracy Optional exemplar of number of decimal places. - * @returns true if points are the same, false if they are not - */ - function areEqualRounded(a: IPoint, b: IPoint, accuracy?: number): boolean; /** * Get the average of two points. * @@ -580,7 +722,16 @@ declare namespace MakerJs.point { * @param pathContext The path object. * @returns Array with 2 elements: [0] is the point object corresponding to the origin, [1] is the point object corresponding to the end. */ - function fromPathEnds(pathContext: IPath): IPoint[]; + function fromPathEnds(pathContext: IPath, pathOffset?: IPoint): IPoint[]; + /** + * Calculates the intersection of slopes of two lines. + * + * @param lineA First line to use for slope. + * @param lineB Second line to use for slope. + * @param options Optional IPathIntersectionOptions. + * @returns point of intersection of the two slopes, or null if the slopes did not intersect. + */ + function fromSlopeIntersection(lineA: IPathLine, lineB: IPathLine, options?: IPathIntersectionBaseOptions): IPoint; /** * Get the middle point of a path. * @@ -623,14 +774,6 @@ declare namespace MakerJs.point { * @returns A new point. */ function scale(pointToScale: IPoint, scaleValue: number): IPoint; - /** - * Get a string representation of a point. - * - * @param pointContext The point to serialize. - * @param accuracy Optional exemplar of number of decimal places. - * @returns String representing the point. - */ - function serialize(pointContext: IPoint, accuracy?: number): string; /** * Subtract a point from another point, and return the result as a new point. Shortcut to Add(a, b, subtract = true). * @@ -649,13 +792,12 @@ declare namespace MakerJs.point { } declare namespace MakerJs.path { /** - * Find out if two paths are equal. + * Create a clone of a path. This is faster than cloneObject. * - * @param a First path. - * @param b Second path. - * @returns true if paths are the same, false if they are not + * @param pathToClone The path to clone. + * @returns Cloned path. */ - function areEqual(path1: IPath, path2: IPath, withinPointDistance?: number): boolean; + function clone(pathToClone: IPath): IPath; /** * Create a clone of a path, mirrored on either or both x and y axes. * @@ -679,9 +821,18 @@ declare namespace MakerJs.path { * * @param pathToMove The path to move. * @param delta The x & y adjustments as a point object. + * @param subtract Optional boolean to subtract instead of add. * @returns The original path (for chaining). */ - function moveRelative(pathToMove: IPath, delta: IPoint): IPath; + function moveRelative(pathToMove: IPath, delta: IPoint, subtract?: boolean): IPath; + /** + * Move some paths relatively during a task execution, then unmove them. + * + * @param pathsToMove The paths to move. + * @param deltas The x & y adjustments as a point object array. + * @param task The function to call while the paths are temporarily moved. + */ + function moveTemporary(pathsToMove: IPath[], deltas: IPoint[], task: Function): void; /** * Rotate a path. * @@ -715,11 +866,6 @@ declare namespace MakerJs.path { declare namespace MakerJs.paths { /** * Class for arc path. - * - * @param origin The center point of the arc. - * @param radius The radius of the arc. - * @param startAngle The start angle of the arc. - * @param endAngle The end angle of the arc. */ class Arc implements IPathArc { origin: IPoint; @@ -727,19 +873,71 @@ declare namespace MakerJs.paths { startAngle: number; endAngle: number; type: string; + /** + * Class for arc path, created from origin point, radius, start angle, and end angle. + * + * @param origin The center point of the arc. + * @param radius The radius of the arc. + * @param startAngle The start angle of the arc. + * @param endAngle The end angle of the arc. + */ constructor(origin: IPoint, radius: number, startAngle: number, endAngle: number); + /** + * Class for arc path, created from 2 points, radius, large Arc flag, and clockwise flag. + * + * @param pointA First end point of the arc. + * @param pointB Second end point of the arc. + * @param radius The radius of the arc. + * @param largeArc Boolean flag to indicate clockwise direction. + * @param clockwise Boolean flag to indicate clockwise direction. + */ + constructor(pointA: IPoint, pointB: IPoint, radius: number, largeArc: boolean, clockwise: boolean); + /** + * Class for arc path, created from 2 points and optional boolean flag indicating clockwise. + * + * @param pointA First end point of the arc. + * @param pointB Second end point of the arc. + * @param clockwise Boolean flag to indicate clockwise direction. + */ + constructor(pointA: IPoint, pointB: IPoint, clockwise?: boolean); + /** + * Class for arc path, created from 3 points. + * + * @param pointA First end point of the arc. + * @param pointB Middle point on the arc. + * @param pointC Second end point of the arc. + */ + constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint); } /** * Class for circle path. - * - * @param origin The center point of the circle. - * @param radius The radius of the circle. */ class Circle implements IPathCircle { + type: string; origin: IPoint; radius: number; - type: string; + /** + * Class for circle path, created from origin point and radius. + * + * @param origin The center point of the circle. + * @param radius The radius of the circle. + */ constructor(origin: IPoint, radius: number); + /** + * Class for circle path, created from 2 points. + * + * @param pointA First point on the circle. + * @param pointB Second point on the circle. + */ + constructor(pointA: IPoint, pointB: IPoint); + /** + * Class for circle path, created from 3 points. + * + * @param pointA First point on the circle. + * @param pointB Second point on the circle. + * @param pointC Third point on the circle. + */ + constructor(pointA: IPoint, pointB: IPoint, pointC: IPoint); } /** * Class for line path. @@ -832,6 +1030,14 @@ declare namespace MakerJs.model { * @returns The original model (for chaining). */ function moveRelative(modelToMove: IModel, delta: IPoint): IModel; + /** + * Prefix the ids of paths in a model. + * + * @param modelToPrefix The model to prefix. + * @param prefix The prefix to prepend on paths ids. + * @returns The original model (for chaining). + */ + function prefixPathIds(modelToPrefix: IModel, prefix: string): IModel; /** * Rotate a model. * @@ -865,6 +1071,15 @@ declare namespace MakerJs.model { * @param callback Callback for each path. */ function walkPaths(modelContext: IModel, callback: IModelPathCallback): void; + /** + * Recursively walk through all paths for a given model. + * + * @param modelContext The model to walk. + * @param pathCallback Callback for each path. + * @param modelCallbackBeforeWalk Callback for each model prior to recursion, which can cancel the recursion if it returns false. + * @param modelCallbackAfterWalk Callback for each model after recursion. + */ + function walk(modelContext: IModel, options: IWalkOptions): void; } declare namespace MakerJs.model { /** @@ -875,7 +1090,7 @@ declare namespace MakerJs.model { * @param farPoint Optional point of reference which is outside the bounds of the modelContext. * @returns Boolean true if the path is inside of the modelContext. */ - function isPathInsideModel(pathContext: IPath, modelContext: IModel, farPoint?: IPoint): boolean; + function isPathInsideModel(pathContext: IPath, modelContext: IModel, pathOffset?: IPoint, farPoint?: IPoint, measureAtlas?: measure.Atlas): boolean; /** * Break a model's paths everywhere they intersect with another path. * @@ -884,7 +1099,7 @@ declare namespace MakerJs.model { */ function breakPathsAtIntersections(modelToBreak: IModel, modelToIntersect?: IModel): void; /** - * Combine 2 models. The models should be originated, and every path within each model should be part of a loop. + * Combine 2 models. * * @param modelA First model to combine. * @param modelB Second model to combine. @@ -896,6 +1111,106 @@ declare namespace MakerJs.model { * @param farPoint Optional point of reference which is outside the bounds of both models. */ function combine(modelA: IModel, modelB: IModel, includeAInsideB?: boolean, includeAOutsideB?: boolean, includeBInsideA?: boolean, includeBOutsideA?: boolean, options?: ICombineOptions): void; + /** + * Combine 2 models, resulting in a intersection. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineIntersection(modelA: IModel, modelB: IModel): void; + /** + * Combine 2 models, resulting in a subtraction of B from A. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineSubtraction(modelA: IModel, modelB: IModel): void; + /** + * Combine 2 models, resulting in a union. + * + * @param modelA First model to combine. + * @param modelB Second model to combine. + */ + function combineUnion(modelA: IModel, modelB: IModel): void; +} +declare namespace MakerJs { + /** + * Compare keys to see if they are equal. + */ + interface ICollectionKeyComparer { + (a: K, b: K): boolean; + } + /** + * A collection for items that share a common key. + */ + interface ICollection { + key: K; + items: T[]; + } + /** + * Collects items that share a common key. + */ + class Collector { + private comparer; + collections: ICollection[]; + constructor(comparer?: ICollectionKeyComparer); + addItemToCollection(key: K, item: T): void; + findCollection(key: K, action?: (index: number) => void): T[]; + removeCollection(key: K): boolean; + removeItemFromCollection(key: K, item: T): boolean; + getCollectionsOfMultiple(cb: (key: K, items: T[]) => void): void; + } +} +declare namespace MakerJs.model { + /** + * Simplify a model's paths by reducing redundancy: combine multiple overlapping paths into a single path. The model must be originated. + * + * @param modelContext The originated model to search for similar paths. + * @param options Optional options object. + * @returns The simplified model (for chaining). + */ + function simplify(modelToSimplify: IModel, options?: ISimplifyOptions): IModel; +} +declare namespace MakerJs.path { + /** + * Expand path by creating a model which surrounds it. + * + * @param pathToExpand Path to expand. + * @param expansion Distance to expand. + * @param isolateCaps Optional flag to put the end caps into a separate model named "caps". + * @returns Model which surrounds the path. + */ + function expand(pathToExpand: IPath, expansion: number, isolateCaps?: boolean): IModel; + /** + * Represent an arc using straight lines. + * + * @param arc Arc to straighten. + * @param bevel Optional flag to bevel the angle to prevent it from being too sharp. + * @param prefix Optional prefix to apply to path ids. + * @returns Model of straight lines with same endpoints as the arc. + */ + function straighten(arc: IPathArc, bevel?: boolean, prefix?: string): IModel; +} +declare namespace MakerJs.model { + /** + * Expand all paths in a model, then combine the resulting expansions. + * + * @param modelToExpand Model to expand. + * @param distance Distance to expand. + * @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints. + * @returns Model which surrounds the paths of the original model. + */ + function expandPaths(modelToExpand: IModel, distance: number, joints?: number, combineOptions?: ICombineOptions): IModel; + /** + * Outline a model by a specified distance. Useful for accommodating for kerf. + * + * @param modelToOutline Model to outline. + * @param distance Distance to outline. + * @param joints Number of points at a joint between paths. Use 0 for round joints, 1 for pointed joints, 2 for beveled joints. + * @param inside Optional boolean to draw lines inside the model instead of outside. + * @returns Model which surrounds the paths outside of the original model. + */ + function outline(modelToOutline: IModel, distance: number, joints?: number, inside?: boolean): IModel; } declare namespace MakerJs.units { /** @@ -909,12 +1224,48 @@ declare namespace MakerJs.units { } declare namespace MakerJs.measure { /** - * Total angle of an arc between its start and end angles. + * Find out if two angles are equal. * - * @param arc The arc to measure. - * @returns Angle of arc. + * @param angleA First angle. + * @param angleB Second angle. + * @returns true if angles are the same, false if they are not */ - function arcAngle(arc: IPathArc): number; + function isAngleEqual(angleA: number, angleB: number, accuracy?: number): boolean; + /** + * Find out if two paths are equal. + * + * @param pathA First path. + * @param pathB Second path. + * @returns true if paths are the same, false if they are not + */ + function isPathEqual(pathA: IPath, pathB: IPath, withinPointDistance?: number, pathAOffset?: IPoint, pathBOffset?: IPoint): boolean; + /** + * Find out if two points are equal. + * + * @param a First point. + * @param b Second point. + * @returns true if points are the same, false if they are not + */ + function isPointEqual(a: IPoint, b: IPoint, withinDistance?: number): boolean; + /** + * Check for slope equality. + * + * @param slopeA The ISlope to test. + * @param slopeB The ISlope to check for equality. + * @returns Boolean true if slopes are equal. + */ + function isSlopeEqual(slopeA: ISlope, slopeB: ISlope): boolean; +} +declare namespace MakerJs.measure { + /** + * Increase a measurement by an additional measurement. + * + * @param baseMeasure The measurement to increase. + * @param addMeasure The additional measurement. + * @param addOffset Optional offset point of the additional measurement. + * @returns The increased original measurement (for chaining). + */ + function increase(baseMeasure: IMeasure, addMeasure: IMeasure): IMeasure; /** * Check for arc being concave or convex towards a given point. * @@ -923,16 +1274,25 @@ declare namespace MakerJs.measure { * @returns Boolean true if arc is concave towards point. */ function isArcConcaveTowardsPoint(arc: IPathArc, towardsPoint: IPoint): boolean; + /** + * Check for arc overlapping another arc. + * + * @param arcA The arc to test. + * @param arcB The arc to check for overlap. + * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. + * @returns Boolean true if arc1 is overlapped with arcB. + */ + function isArcOverlapping(arcA: IPathArc, arcB: IPathArc, excludeTangents: boolean): boolean; /** * Check if a given number is between two given limits. * * @param valueInQuestion The number to test. - * @param limit1 First limit. - * @param limit2 Second limit. + * @param limitA First limit. + * @param limitB Second limit. * @param exclusive Flag to exclude equaling the limits. * @returns Boolean true if value is between (or equal to) the limits. */ - function isBetween(valueInQuestion: number, limit1: number, limit2: number, exclusive: boolean): boolean; + function isBetween(valueInQuestion: number, limitA: number, limitB: number, exclusive: boolean): boolean; /** * Check if a given angle is between an arc's start and end angles. * @@ -951,6 +1311,27 @@ declare namespace MakerJs.measure { * @returns Boolean true if point is between (or equal to) the line's origin and end points. */ function isBetweenPoints(pointInQuestion: IPoint, line: IPathLine, exclusive: boolean): boolean; + /** + * Check for line overlapping another line. + * + * @param lineA The line to test. + * @param lineB The line to check for overlap. + * @param excludeTangents Boolean to exclude exact endpoints and only look for deep overlaps. + * @returns Boolean true if line1 is overlapped with lineB. + */ + function isLineOverlapping(lineA: IPathLine, lineB: IPathLine, excludeTangents: boolean): boolean; + /** + * Check for measurement overlapping another measurement. + * + * @param measureA The measurement to test. + * @param measureB The measurement to check for overlap. + * @returns Boolean true if measure1 is overlapped with measureB. + */ + function isMeasurementOverlapping(measureA: IMeasure, measureB: IMeasure): boolean; + /** + * Gets the slope of a line. + */ + function lineSlope(line: IPathLine): ISlope; /** * Calculates the distance between two points. * @@ -965,7 +1346,7 @@ declare namespace MakerJs.measure { * @param pathToMeasure The path to measure. * @returns object with low and high points. */ - function pathExtents(pathToMeasure: IPath): IMeasure; + function pathExtents(pathToMeasure: IPath, addOffset?: IPoint): IMeasure; /** * Measures the length of a path. * @@ -977,9 +1358,38 @@ declare namespace MakerJs.measure { * Measures the smallest rectangle which contains a model. * * @param modelToMeasure The model to measure. + * @param atlas Optional atlas to save measurements. * @returns object with low and high points. */ - function modelExtents(modelToMeasure: IModel): IMeasure; + function modelExtents(modelToMeasure: IModel, atlas?: measure.Atlas): IMeasure; + /** + * A list of maps of measurements. + * + * @param modelToMeasure The model to measure. + * @param atlas Optional atlas to save measurements. + * @returns object with low and high points. + */ + class Atlas { + modelContext: IModel; + /** + * Flag that models have been measured. + */ + modelsMeasured: boolean; + /** + * Map of model measurements, mapped by routeKey. + */ + modelMap: IMeasureMap; + /** + * Map of path measurements, mapped by routeKey. + */ + pathMap: IMeasureMap; + /** + * Constructor. + * @param modelContext The model to measure. + */ + constructor(modelContext: IModel); + measureModels(): void; + } } declare namespace MakerJs.exporter { /** @@ -1050,12 +1460,12 @@ declare namespace MakerJs.solvers { /** * Solves for the angle of a triangle when you know lengths of 3 sides. * - * @param length1 Length of side of triangle, opposite of the angle you are trying to find. - * @param length2 Length of any other side of the triangle. - * @param length3 Length of the remaining side of the triangle. + * @param lengthA Length of side of triangle, opposite of the angle you are trying to find. + * @param lengthB Length of any other side of the triangle. + * @param lengthC Length of the remaining side of the triangle. * @returns Angle opposite of the side represented by the first parameter. */ - function solveTriangleSSS(length1: number, length2: number, length3: number): number; + function solveTriangleSSS(lengthA: number, lengthB: number, lengthC: number): number; /** * Solves for the length of a side of a triangle when you know length of one side and 2 angles. * @@ -1076,33 +1486,24 @@ declare namespace MakerJs.path { * @returns IPathIntersection object, with points(s) of intersection (and angles, when a path is an arc or circle); or null if the paths did not intersect. */ function intersection(path1: IPath, path2: IPath, options?: IPathIntersectionOptions): IPathIntersection; - /** - * Calculates the intersection of slopes of two lines. - * - * @param line1 First line to use for slope. - * @param line2 Second line to use for slope. - * @param options Optional IPathIntersectionOptions. - * @returns point of intersection of the two slopes, or null if the slopes did not intersect. - */ - function slopeIntersectionPoint(line1: IPathLine, line2: IPathLine, options?: IPathIntersectionOptions): IPoint; } declare namespace MakerJs.path { /** * Adds a round corner to the outside angle between 2 lines. The lines must meet at one point. * - * @param line1 First line to fillet, which will be modified to fit the fillet. - * @param line2 Second line to fillet, which will be modified to fit the fillet. + * @param lineA First line to fillet, which will be modified to fit the fillet. + * @param lineB Second line to fillet, which will be modified to fit the fillet. * @returns Arc path object of the new fillet. */ - function dogbone(line1: IPathLine, line2: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc; + function dogbone(lineA: IPathLine, lineB: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc; /** * Adds a round corner to the inside angle between 2 paths. The paths must meet at one point. * - * @param path1 First path to fillet, which will be modified to fit the fillet. - * @param path2 Second path to fillet, which will be modified to fit the fillet. + * @param pathA First path to fillet, which will be modified to fit the fillet. + * @param pathB Second path to fillet, which will be modified to fit the fillet. * @returns Arc path object of the new fillet. */ - function fillet(path1: IPath, path2: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; + function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; } declare namespace MakerJs.kit { /** @@ -1123,22 +1524,15 @@ declare namespace MakerJs.kit { } declare namespace MakerJs.model { /** - * @private + * Find paths that have common endpoints and form chains. + * + * @param modelContext The model to search for chains. + * @param options Optional options object. + * @returns A list of chains. */ - interface IPointMappedItem { - averagePoint: IPoint; - item: T; - } - /** - * @private - */ - class PointMap { - matchingDistance: number; - list: IPointMappedItem[]; - constructor(matchingDistance?: number); - add(pointToAdd: IPoint, item: T): void; - find(pointToFind: IPoint, saveAverage: boolean): T; - } + function findChains(modelContext: IModel, callback: IChainCallback, options?: IFindChainsOptions): void; +} +declare namespace MakerJs.model { /** * Find paths that have common endpoints and form loops. * @@ -1153,7 +1547,14 @@ declare namespace MakerJs.model { * @param loopToDetach The model to search for loops. */ function detachLoop(loopToDetach: IModel): void; - function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): void; + /** + * Remove paths from a model which have endpoints that do not connect to other paths. + * + * @param modelContext The model to search for dead ends. + * @param options Optional options object. + * @returns The input model (for chaining). + */ + function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): IModel; } declare namespace MakerJs.exporter { /** @@ -1249,6 +1650,37 @@ declare namespace MakerJs.exporter { } } declare namespace MakerJs.exporter { + /** + * Injects drawing into a PDFKit document. + * + * @param modelToExport Model object to export. + * @param options Export options object. + * @returns String of PDF file contents. + */ + function toPDF(doc: PDFKit.PDFDocument, modelToExport: IModel, options?: IPDFRenderOptions): void; + /** + * PDF rendering options. + */ + interface IPDFRenderOptions extends IExportOptions { + /** + * Rendered reference origin. + */ + origin?: IPoint; + /** + * SVG color of the rendered paths. + */ + stroke?: string; + } +} +declare namespace MakerJs.exporter { + /** + * Convert a chain to SVG path data. + */ + function chainToSVGPathData(chain: IChain, offset: IPoint): string; + /** + * Convert a path to SVG path data. + */ + function pathToSVGPathData(pathToExport: IPath, offset: IPoint, offset2: IPoint): string; function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string; function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string; function toSVG(pathToExport: IPath, options?: ISVGRenderOptions): string; @@ -1273,6 +1705,10 @@ declare namespace MakerJs.exporter { * Optional attributes to add to the root svg tag. */ svgAttrs?: IXmlTagAttrs; + /** + * SVG fill color. + */ + fill?: string; /** * SVG font size and font size units. */ @@ -1314,9 +1750,11 @@ declare namespace MakerJs.models { } } declare namespace MakerJs.models { - class Polygon extends ConnectTheDots { - constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number); - static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number): IPoint[]; + class Polygon implements IModel { + paths: IPathMap; + constructor(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean); + static circumscribedRadius(radius: number, angleInRadians: number): number; + static getPoints(numberOfSides: number, radius: number, firstCornerAngleInDegrees?: number, circumscribed?: boolean): IPoint[]; } } declare namespace MakerJs.models { @@ -1344,19 +1782,24 @@ declare namespace MakerJs.models { } } declare namespace MakerJs.models { - class Oval extends RoundRectangle { + class Oval implements IModel { + paths: IPathMap; constructor(width: number, height: number); } } declare namespace MakerJs.models { class OvalArc implements IModel { paths: IPathMap; - constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean); + models: IModelMap; + constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean, isolateCaps?: boolean); } } declare namespace MakerJs.models { - class Rectangle extends ConnectTheDots { + class Rectangle implements IModel { + paths: IPathMap; + origin: IPoint; constructor(width: number, height: number); + constructor(measurement: IMeasure); } } declare namespace MakerJs.models { @@ -1375,11 +1818,13 @@ declare namespace MakerJs.models { class Slot implements IModel { paths: IPathMap; origin: IPoint; - constructor(origin: IPoint, endPoint: IPoint, radius: number); + models: IModelMap; + constructor(origin: IPoint, endPoint: IPoint, radius: number, isolateCaps?: boolean); } } declare namespace MakerJs.models { - class Square extends Rectangle { + class Square implements IModel { + paths: IPathMap; constructor(side: number); } } diff --git a/material-ui/legacy/material-ui-0.14.4-tests.tsx b/material-ui/legacy/material-ui-0.14.4-tests.tsx new file mode 100644 index 0000000000..0d112fcaa8 --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4-tests.tsx @@ -0,0 +1,2302 @@ +/// +/// +/// + +import * as React from "react"; +import * as LinkedStateMixin from "react-addons-linked-state-mixin"; +import * as MaterialUi from "material-ui"; +import ActionGrade from "material-ui/lib/svg-icons/action/grade"; +import AppBar from "material-ui/lib/app-bar"; +import ArrowDropRight from "material-ui/lib/svg-icons/navigation-arrow-drop-right"; +import AutoComplete from 'material-ui/lib/auto-complete'; +import Avatar from "material-ui/lib/avatar"; +import Badge from "material-ui/lib/badge"; +import Card from "material-ui/lib/card/card"; +import CardActions from "material-ui/lib/card/card-actions"; +import CardHeader from "material-ui/lib/card/card-header"; +import CardMedia from 'material-ui/lib/card/card-media'; +import CardText from "material-ui/lib/card/card-text"; +import CardTitle from 'material-ui/lib/card/card-title'; +import Checkbox from "material-ui/lib/checkbox"; +import CircularProgress from 'material-ui/lib/circular-progress'; +import ColorManipulator from 'material-ui/lib/utils/color-manipulator'; +import Colors from "material-ui/lib/styles/colors"; +import DatePicker from "material-ui/lib/date-picker/date-picker"; +import Dialog from "material-ui/lib/dialog"; +import Divider from 'material-ui/lib/divider'; +import DropDownMenu from "material-ui/lib/drop-down-menu"; +import FileFolder from "material-ui/lib/svg-icons/file/folder"; +import FlatButton from "material-ui/lib/flat-button"; +import FloatingActionButton from "material-ui/lib/floating-action-button"; +import FontIcon from "material-ui/lib/font-icon"; +import GridList from 'material-ui/lib/grid-list/grid-list'; +import GridTile from 'material-ui/lib/grid-list/grid-tile'; +import IconButton from "material-ui/lib/icon-button"; +import IconMenu from "material-ui/lib/menus/icon-menu"; +import LeftNav from 'material-ui/lib/left-nav'; +import LinearProgress from 'material-ui/lib/linear-progress'; +import List from 'material-ui/lib/lists/list'; +import ListItem from 'material-ui/lib/lists/list-item'; +import Menu from 'material-ui/lib/menus/menu'; +import MenuItem from 'material-ui/lib/menus/menu-item'; +import Paper from 'material-ui/lib/paper'; +import Popover from 'material-ui/lib/popover/popover'; +import PopoverAnimationFromTop from 'material-ui/lib/popover/popover-animation-from-top'; +import RadioButton from "material-ui/lib/radio-button"; +import RadioButtonGroup from "material-ui/lib/radio-button-group"; +import RaisedButton from "material-ui/lib/raised-button"; +import RefreshIndicator from 'material-ui/lib/refresh-indicator'; +import SelectField from "material-ui/lib/select-field"; +import Slider from 'material-ui/lib/slider'; +import Snackbar from 'material-ui/lib/snackbar'; +import Spacing from "material-ui/lib/styles/spacing"; +import Styles from 'material-ui/lib/styles'; +import SvgIcon from 'material-ui/lib/svg-icon'; +import Tab from 'material-ui/lib/tabs/tab'; +import Table from 'material-ui/lib/table/table'; +import TableBody from 'material-ui/lib/table/table-body'; +import TableFooter from 'material-ui/lib/table/table-footer'; +import TableHeader from 'material-ui/lib/table/table-header'; +import TableHeaderColumn from 'material-ui/lib/table/table-header-column'; +import TableRow from 'material-ui/lib/table/table-row'; +import TableRowColumn from 'material-ui/lib/table/table-row-column'; +import Tabs from 'material-ui/lib/tabs/tabs'; +import TextField from "material-ui/lib/text-field"; +import ThemeDecorator from 'material-ui/lib/styles/theme-decorator'; +import ThemeManager from 'material-ui/lib/styles/theme-manager'; +import TimePicker from "material-ui/lib/time-picker"; +import Toggle from "material-ui/lib/toggle"; +import ToggleStar from "material-ui/lib/svg-icons/toggle/star"; +import ToggleStarBorder from "material-ui/lib/svg-icons/toggle/star-border"; +import Toolbar from 'material-ui/lib/toolbar/toolbar'; +import ToolbarGroup from 'material-ui/lib/toolbar/toolbar-group'; +import ToolbarSeparator from 'material-ui/lib/toolbar/toolbar-separator'; +import ToolbarTitle from 'material-ui/lib/toolbar/toolbar-title'; +import Typography from "material-ui/lib/styles/typography"; +import zIndex from 'material-ui/lib/styles/zIndex'; + +import {SelectableContainerEnhance} from 'material-ui/lib/hoc/selectable-enhance'; + +import * as Icons from "material-ui/lib/svg-icons"; +import ActionAndroid from 'material-ui/lib/svg-icons/action/android'; +import ActionFavorite from 'material-ui/lib/svg-icons/action/favorite'; +import ActionFavoriteBorder from 'material-ui/lib/svg-icons/action/favorite-border'; +import ActionFlightTakeoff from 'material-ui/lib/svg-icons/action/flight-takeoff'; +import ActionHome from 'material-ui/lib/svg-icons/action/home'; +import ActionInfo from 'material-ui/lib/svg-icons/action/info'; +import CommunicationChatBubble from 'material-ui/lib/svg-icons/communication/chat-bubble'; +import ContentAdd from 'material-ui/lib/svg-icons/content/add'; +import ContentCopy from 'material-ui/lib/svg-icons/content/content-copy'; +import ContentDrafts from 'material-ui/lib/svg-icons/content/drafts'; +import ContentFilter from 'material-ui/lib/svg-icons/content/filter-list'; +import ContentInbox from 'material-ui/lib/svg-icons/content/inbox'; +import ContentLink from 'material-ui/lib/svg-icons/content/link'; +import ContentSend from 'material-ui/lib/svg-icons/content/send'; +import Delete from 'material-ui/lib/svg-icons/action/delete'; +import Download from 'material-ui/lib/svg-icons/file/file-download'; +import FileCloudDownload from 'material-ui/lib/svg-icons/file/cloud-download'; +import FolderIcon from 'material-ui/lib/svg-icons/file/folder-open'; +import HardwareVideogameAsset from 'material-ui/lib/svg-icons/hardware/videogame-asset'; +import MapsPlace from 'material-ui/lib/svg-icons/maps/place'; +import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; +import NavigationClose from "material-ui/lib/svg-icons/navigation/close"; +import NavigationExpandMoreIcon from 'material-ui/lib/svg-icons/navigation/expand-more'; +import NotificationsIcon from 'material-ui/lib/svg-icons/social/notifications'; +import PersonAdd from 'material-ui/lib/svg-icons/social/person-add'; +import RemoveRedEye from 'material-ui/lib/svg-icons/image/remove-red-eye'; +import StarBorder from 'material-ui/lib/svg-icons/toggle/star-border'; +import UploadIcon from 'material-ui/lib/svg-icons/file/cloud-upload'; + + +type CheckboxProps = __MaterialUI.CheckboxProps; +type MuiTheme = __MaterialUI.Styles.MuiTheme; +type TouchTapEvent = __MaterialUI.TouchTapEvent; + +interface MaterialUiTestsState { + showDialogStandardActions: boolean; + showDialogCustomActions: boolean; + showDialogScrollable: boolean; + value: number; + dataSource: [string]; + minDate: Date; + maxDate: Date; + autoOk: boolean; + disableYearSelection: boolean; + open: boolean; + valueSingle: string; + valueMultiple: string[]; + anchorEl: Element; + completed: number; + message: string; + autoHideDuration: number; + fixedHeader: boolean; + fixedFooter: boolean; + stripedRows: boolean; + showRowHover: boolean; + selectable: boolean; + multiSelectable: boolean; + enableSelectAll: boolean; + deselectOnClickaway: boolean; + height: string; +} + +// "http://www.material-ui.com/#/customization/themes" +let muiTheme: MuiTheme = ThemeManager.getMuiTheme({ + spacing: Spacing, + zIndex: zIndex, + fontFamily: 'Roboto, sans-serif', + palette: { + primary1Color: Colors.cyan500, + primary2Color: Colors.cyan700, + primary3Color: Colors.lightBlack, + accent1Color: Colors.pinkA200, + accent2Color: Colors.grey100, + accent3Color: Colors.grey500, + textColor: Colors.darkBlack, + alternateTextColor: Colors.white, + canvasColor: Colors.white, + borderColor: Colors.grey300, + disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3), + pickerHeaderColor: Colors.cyan500, + } +}); + +let SelectableList = SelectableContainerEnhance(List); + +@ThemeDecorator(muiTheme) +class MaterialUiTests extends React.Component<{}, MaterialUiTestsState> implements React.LinkedStateMixin { + + // injected with mixin + linkState: (key: string) => React.ReactLink; + + private picker12hr: TimePicker; + private picker24hr: TimePicker; + + private touchTapEventHandler(e: TouchTapEvent) { + console.info("Received touch tap", e); + } + private formEventHandler(e: React.FormEvent) { + } + private selectFieldChangeHandler(e: TouchTapEvent, si: number, mi: any) { + } + private handleRequestClose(buttonClicked: boolean) { + } + private handleRequestCloseReason(reason: string) { + } + private handleToggle() { + this.setState(Object.assign({}, this.state, { open: !this.state.open })); + } + private handleClose() { + this.setState(Object.assign({}, this.state, { open: false })); + } + private handleChangeSingle(event: React.MouseEvent, value: string){ + } + private handleChangeMultiple(event: React.MouseEvent, value: string[]) { + } + + private handleChange = (e: TouchTapEvent, index: number, value: number) => this.setState(Object.assign({}, this.state, { value })); + + private handleUpdateInput(t: string) { + this.setState(Object.assign({}, this.state, { + dataSource: [t, t + t, t + t + t], + })); + } + private handleTouchTap(e: TouchTapEvent) { + alert('onTouchTap triggered on the title component'); + } + private handleActionTouchTap() { + this.setState(Object.assign({}, this.state, {open: false,})); + alert('Event removed from your calendar.'); + } + private handleChangeDuration = (event: React.FormEvent) => { + const value = event.target["value"]; + this.setState(Object.assign({}, this.state, { + autoHideDuration: value.length > 0 ? parseInt(value) : 0, + })); + } + private onRowSelection(selectedRows: number[] | string) { + } + private handleActive(tab: Tab) { + alert(`A tab with this route property ${tab.props.value} was activated.`); + } + private handleChangeTabs(value: any, e: React.FormEvent, tab: Tab) { + } + private handleChangeTimePicker12(err, time) { + this.picker12hr.setTime(time); + }; + + private handleChangeTimePicker24(err, time) { + this.picker24hr.setTime(time); + }; + + render() { + + const styles = { + title: { + cursor: 'pointer', + }, + exampleImageInput: { + cursor: 'pointer', + position: 'absolute', + top: 0, + bottom: 0, + right: 0, + left: 0, + width: '100%', + opacity: 0, + }, + button: { + margin: 12, + }, + floatingButton: { + marginRight: 20, + }, + textField: { + marginLeft: 20, + }, + floatLeft: { + float: 'left', + }, + root: { + display: 'flex', + flexWrap: 'wrap', + justifyContent: 'space-around', + }, + gridList: { + width: 500, + height: 400, + overflowY: 'auto', + marginBottom: 24, + }, + icons: { + marginRight: 24, + }, + menu: { + marginRight: 32, + marginBottom: 32, + float: 'left', + position: 'relative', + zIndex: 0, + }, + rightIcon: { + textAlign: 'center', + lineHeight: '24px', + }, + paper: { + height: 100, + width: 100, + margin: 20, + textAlign: 'center', + display: 'inline-block', + }, + popover: { + padding: 20, + }, + container: { + position: 'relative', + }, + refresh: { + display: 'inline-block', + position: 'relative', + }, + block: { + maxWidth: 250, + }, + checkbox: { + marginBottom: 16, + }, + radioButton: { + marginBottom: 16, + }, + toggle: { + marginBottom: 16, + }, + propContainerStyle: { + width: 200, + overflow: 'hidden', + margin: '20px auto 0', + }, + propToggleHeader: { + margin: '20px auto 10px', + }, + headline: { + fontSize: 24, + paddingTop: 16, + marginBottom: 12, + fontWeight: 400, + }, + errorStyle: { + color: Colors.orange500, + }, + underlineStyle: { + borderColor: Colors.orange500, + }, + }; + const colors = Styles.Colors; + + // "http://www.material-ui.com/#/customization/inline-styles" + let element: React.ReactElement; + element = + element = React.createElement(Checkbox, { + id: "checkboxId1", name: "checkboxName1", value: "checkboxValue1", label: "went for a run today", style: { + width: '50%', + margin: '0 auto' + }, iconStyle: { + fill: '#FF4081' + } + }); + + // "http://www.material-ui.com/#/components/app-bar" + const AppBarExampleIcon = () => ( + + ); + + const AppBarExampleIconButton = () => ( + Title} + onTitleTouchTap={this.handleTouchTap} + iconElementLeft={} + iconElementRight={} + /> + ); + const AppBarExampleIconMenu = () => ( + } + iconElementRight={ + + } + targetOrigin={{ horizontal: 'right', vertical: 'top' }} + anchorOrigin={{ horizontal: 'right', vertical: 'top' }} + > + + + + + } + /> + ); + + // "http://www.material-ui.com/#/components/auto-complete" + element = + + const dataSource1 = [ + { + text: 'text-value1', + value: ( + + ), + }, + { + text: 'text-value2', + value: ( + + ), + }, + ]; + + const dataSource2 = ['12345', '23456', '34567']; + + const AutoCompleteExampleNoFilter = () => ( +
    +
    + +
    + ); + + const AutoCompleteExampleFilters = () => ( +
    + +
    + +
    + ); + + // "http://www.material-ui.com/#/components/avatar" + const AvatarExampleSimple = () => ( + + + } + > + Image Avatar + + } /> + } + > + FontIcon Avatar + + } + color={colors.blue300} + backgroundColor={colors.indigo900} + /> + } + > + FontIcon Avatar with custom colors + + } /> + } + > + SvgIcon Avatar + + } + color={colors.orange200} + backgroundColor={colors.pink400} + /> + } + > + SvgIcon Avatar with custom colors + + A} + > + Letter Avatar + + + A + + } + > + Letter Avatar with custom colors + + + ); + + //image avatar + element = ; + //SvgIcon avatar + element = } />; + //SvgIcon avatar with custom colors + element = } + color={Colors.orange200} + backgroundColor={Colors.pink400} />; + //FontIcon avatar + element = + } />; + //FontIcon avatar with custom colors + element = } + color={Colors.blue300} + backgroundColor={Colors.indigo900} />; + //Letter avatar + element = A; + //Letter avatar with custom colors + element = + + + // "http://www.material-ui.com/#/components/badge" + const BadgeExampleSimple = () => ( +
    + + + + + + + + +
    + ); + const BadgeExampleContent = () => ( +
    + } + > + + + + Company Name + +
    + ); + + // "http://www.material-ui.com/#/components/flat-button" + const FlatButtonExampleSimple = () => ( +
    + + + + +
    + ); + const FlatButtonExampleComplex = () => ( +
    + + + + + } + /> + + } + /> + +
    + ); + + // "http://www.material-ui.com/#/components/raised-button" + const RaisedButtonExampleSimple = () => ( +
    + + + + +
    + ); + const RaisedButtonExampleComplex = () => ( +
    + + + + } + style={styles.button} + /> + } + /> +
    + ); + + // "http://www.material-ui.com/#/components/floating-action-button" + const FloatingActionButtonExampleSimple = () => ( +
    + + + + + + + + + + + + + + + + + + + + + + + +
    + ); + + // "http://www.material-ui.com/#/components/icon-button" + const IconButtonExampleSimple = () => ( +
    + + +
    + ); + const IconButtonExampleComplex = () => ( +
    + + + + + + + + + + home + +
    + ); + const IconButtonExampleTooltip = () => ( +
    + + + + + + +
    + ); + const IconButtonExampleTouch = () => ( +
    + + + + + + + + + + + + + + + + + + +
    + ); + //Method 1: muidocs-icon-github is defined in a style sheet. + element = ; + //Method 2: ActionGrade is a component created using mui.SvgIcon. + element = + + ; + //Method 3: Manually creating a mui.FontIcon component within IconButton + element = + + ; + //Method 4: Using Google material-icons + element = settings_system_daydream; + + + // "http://www.material-ui.com/#/components/card" + const CardExampleWithAvatar = () => ( + + + } + > + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa.Aliquam erat volutpat.Nulla facilisi. + Donec vulputate interdum sollicitudin.Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + + ); + const CardExampleWithoutAvatar = () => ( + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. + Donec mattis pretium massa.Aliquam erat volutpat.Nulla facilisi. + Donec vulputate interdum sollicitudin.Nunc lacinia auctor quam sed pellentesque. + Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio. + + + + + + + ); + + // "http://www.material-ui.com/#/components/date-picker" + const DatePickerExampleSimple = () => ( +
    + + + +
    + ); + const DatePickerExampleInline = () => ( +
    + + +
    + ); + element = ( +
    + +
    + ); + element = ; + element = ; + element = ; + + // "http://material-ui.com/#/components/dialog" + let standardActions = [ + { text: 'Cancel' }, + { text: 'Submit', onTouchTap: this.touchTapEventHandler, ref: 'submit' } + ]; + + element = + The actions in this window are created from the json that's passed in. + ; + + //Custom Actions + let customActions = [ + , + + ]; + + element = + The actions in this window were passed in as an array of react objects. + ; + + element = +
    + Really long content +
    +
    ; + + // "http://www.material-ui.com/#/components/divider" + const DividerExampleForm = () => ( + + + + + + + + + + + ); + const DividerExampleList = () => ( +
    + + + + + + + + + +
    + ); + const DividerExampleMenu = () => ( + + + + + + + ); + + + // "http://www.material-ui.com/#/components/grid-list" + const tilesData = [ + { + img: 'images/grid-list/00-52-29-429_640.jpg', + title: 'Breakfast', + author: 'jill111', + featured: false, + }]; + const GridListExampleSimple = () => ( +
    + + {tilesData.map(tile => ( + by {tile.author}} + actionIcon={} + > + + + )) } + +
    + ); + const GridListExampleComplex = () => ( +
    + + {tilesData.map(tile => ( + } + actionPosition="left" + titlePosition="top" + titleBackground="linear-gradient(to bottom, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)" + cols={tile.featured ? 2 : 1} + rows={tile.featured ? 2 : 1} + > + + + )) } + +
    + ); + + + element = ; + + element = GridTile} + actionPosition="left" + titlePosition="top" + titleBackground="rgba(0, 0, 0, 0.4)" + cols={2} + rows={1} + style={{ color: 'red' }}> +

    Children are Required!

    +
    ; + + + // "http://www.material-ui.com/#/components/font-icon" + const FontIconExampleSimple = () => ( +
    + + + + + +
    + ); + + const FontIconExampleIcons = () => ( +
    + home + flight_takeoff + cloud_download + videogame_asset +
    + ); + + + // "http://www.material-ui.com/#/components/svg-icon" + const HomeIcon = (props) => ( + + + + ); + + const SvgIconExampleSimple = () => ( +
    + + + +
    + ); + const SvgIconExampleIcons = () => ( +
    + + + + +
    + ); + element = ; + element = ; + element = home; + + + // "http://www.material-ui.com/#/components/left-nav" + element = ( +
    + + + Menu Item + Menu Item 2 + +
    + ); + element = ( +
    + + this.setState(Object.assign({}, this.state, { open })) } + > + Menu Item + Menu Item 2 + +
    + ); + element = ( +
    + + + + +
    + ); + + + // "http://material-ui.com/#/components/lists" + const ListExampleSimple = () => ( +
    + + } /> + } /> + } /> + } /> + } /> + + + + } /> + } /> + } /> + } /> + +
    + ); + const ListExampleChat = () => ( +
    + + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + } + rightIcon={} + /> + + + + } + /> + } + /> + +
    + ); + const ListExampleNested = () => ( +
    + + } /> + } /> + } + initiallyOpen={true} + primaryTogglesNestedList={true} + nestedItems={[ + } + />, + } + disabled={true} + nestedItems={[ + } />, + ]} + />, + ]} + /> + +
    + ); + const iconButtonElement = ( + + + + ); + const rightIconMenu = ( + + Reply + Forward + Delete + + ); + const ListExampleMessages = () => ( +
    + + } + rightIconButton={rightIconMenu} + primaryText="Brendan Lim" + secondaryText={ +

    + Brunch this weekend?
    + I' ll be in your neighborhood doing errands this weekend.Do you want to grab brunch? +

    + } + secondaryTextLines={2} + /> +
    +
    + ); + const ListExampleSelectable = () => ( +
    + + } + nestedItems={[ + } + />, + ]} + /> + } + /> + } + /> + } + /> + +
    + ); + + + // "http://www.material-ui.com/#/components/menu" + const MenuExampleSimple = () => ( +
    + + + + + + + + + + + + +
    + ); + const MenuExampleDisable = () => ( +
    + + + + + + + + + + + + + + + + +
    + ); + const MenuExampleIcons = () => ( +
    + + } /> + } /> + } /> + + } /> + } /> + + } /> + + + + } /> + settings}/> + settings + } + /> + ¶} /> + §} /> + +
    + ); + const MenuExampleSecondary = () => ( +
    + + + + + + + + + } /> + } /> + } /> + } /> + } /> + + + + + + + + + + + + + +
    + ); + const MenuExampleNested = () => ( +
    + + + + + } + menuItems={[ + } + menuItems={[ + , + , + , + , + ]} + />, + , + , + , + ]} + /> + + + + + + +
    + ); + + + // "http://www.material-ui.com/#/components/icon-menu" + const IconMenuExampleSimple = () => ( +
    + } + anchorOrigin={{ horizontal: 'left', vertical: 'top' }} + targetOrigin={{ horizontal: 'left', vertical: 'top' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }} + targetOrigin={{ horizontal: 'left', vertical: 'bottom' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }} + targetOrigin={{ horizontal: 'right', vertical: 'bottom' }} + > + + + + + + + } + anchorOrigin={{ horizontal: 'right', vertical: 'top' }} + targetOrigin={{ horizontal: 'right', vertical: 'top' }} + > + + + + + + +
    + ); + element = ( +
    + } + onChange={this.handleChangeSingle} + value={this.state.valueSingle} + > + + + + + + + } + onChange={this.handleChangeMultiple} + value={this.state.valueMultiple} + multiple={true} + > + + + + + + + +
    + ); + const IconMenuExampleScrollable = () => ( +
    } + anchorOrigin={{ horizontal: 'left', vertical: 'top' }} + targetOrigin={{ horizontal: 'left', vertical: 'top' }} + maxHeight={272} + > + + + + ); + + + // "http://www.material-ui.com/#/components/dropdown-menu" + element = + + + + + + ; + const menuItems = []; + element = ( + + {menuItems} + + ); + element = ( + + + + + + + ); + + // "http://material-ui.com/#/components/paper" + const PaperExampleSimple = () => ( +
    + + + + + +
    + ); + const PaperExampleRounded = () => ( +
    + + + + + +
    + ); + const PaperExampleCircle = () => ( +
    + + + + + +
    + ); + + + // "http://www.material-ui.com/#/components/popover" + element = ( +
    + + +
    + +
    +
    +
    + ); + element = ( +
    + + +
    + +
    +
    +
    + ); + + + // "http://www.material-ui.com/#/components/circular-progress" + const CircularProgressExampleSimple = () => ( +
    + + + +
    + ); + element = ( +
    + + + +
    + ); + + + // "http://www.material-ui.com/#/components/linear-progress" + const LinearProgressExampleSimple = () => ( + + ); + element = ( + + ); + + + // "http://www.material-ui.com/#/components/refresh-indicator" + const RefreshIndicatorExampleSimple = () => ( +
    + + + + +
    + ); + const RefreshIndicatorExampleLoading = () => ( +
    + + +
    + ); + + + // "http://www.material-ui.com/#/components/select-field" + element = ( +
    + + + + + + + +
    + + + + +
    + ); + element = ( + + {menuItems} + + ); + element = ( + + + + + + + ); + element = ( +
    + + {menuItems} + +
    + + {menuItems} + +
    + ); + const {value} = this.state; + const night = value === 2 || value === 3; + element = ( +
    + + {menuItems} + +
    + + {menuItems} + +
    + ); + + + // "http://www.material-ui.com/#/components/slider" + const SliderExampleSimple = () => ( +
    + + + +
    + ); + const SliderExampleDisabled = () => ( +
    + + + +
    + ); + const SliderExampleStep = () => ( + + ); + + + // "http://www.material-ui.com/#/components/checkbox" + const CheckboxExampleSimple = () => ( +
    + + + + } + unCheckedIcon={} + label="Custom icon" + style={styles.checkbox} + /> + +
    + ); + + + // "http://www.material-ui.com/#/components/radio-button" + const RadioButtonExampleSimple = () => ( +
    + + + + + + + + + +
    + ); + + + // "http://www.material-ui.com/#/components/toggle" + const ToggleExampleSimple = () => ( +
    + + + + +
    + ); + + + // "http://material-ui.com/#/components/snackbar" + element = ( +
    + + +
    + ); + element = ( +
    + +
    + + +
    + ); + + // "http://www.material-ui.com/#/components/table" + element = ( + + + + ID + Name + Status + + + + + 1 + John Smith + Employed + + + 2 + Randal White + Unemployed + + + 3 + Stephanie Sanders + Employed + + + 4 + Steve Brown + Employed + + +
    + ); + const tableData = [ + { + name: 'John Smith', + status: 'Employed', + selected: true, + }, + ]; + element = ( +
    + + + + + Super Header + + + + ID + Name + Status + + + + {tableData.map( (row, index) => ( + + {index} + {row.name} + {row.status} + + ))} + + + + ID + Name + Status + + + + Super Footer + + + +
    + +
    +

    Table Properties

    + + + + + + +

    TableBody Properties

    + + + +
    +
    + ); + + // "http://www.material-ui.com/#/components/tabs" + const TabsExampleSimple = () => ( + + +
    +

    Tab One

    +

    + This is an example tab. +

    +

    + You can put any sort of HTML or react component in here. It even keeps the component state! +

    + +
    +
    + +
    +

    Tab Two

    +

    + This is another example tab. +

    +
    +
    + +
    +

    Tab Three

    +

    + This is a third example tab. +

    +
    +
    +
    + ); + element = ( + + +
    +

    Controllable Tab A

    +

    + Tabs are also controllable if you want to programmatically pass them their values. + This allows for more functionality in Tabs such as not + having any Tab selected or assigning them different values. +

    +
    +
    + +
    +

    Controllable Tab B

    +

    + This is another example of a controllable tab. Remember, if you + use controllable Tabs, you need to give all of your tabs values or else + you wont be able to select them. +

    +
    +
    +
    + ); + const TabsExampleIcon = () => ( + + } /> + } /> + favorite} /> + + ); + + // "http://www.material-ui.com/#/components/text-field" + const TextFieldExampleSimple = () => ( +
    +
    +
    +
    +
    +
    +
    +
    + +
    + ); + const TextFieldExampleError = () => ( +
    +
    +
    +
    +
    +
    + ); + const TextFieldExampleCustomize = () => ( +
    +
    +
    +
    + +
    + ); + const TextFieldExampleDisabled = () => ( +
    +
    +
    +
    + +
    + ); + element = ; + + + // "http://www.material-ui.com/#/components/time-picker" + const TimePickerExampleSimple = () => ( +
    + + +
    + ); + element = ( +
    + this.picker12hr = t} + format="ampm" + hintText="12hr Format" + onChange={this.handleChangeTimePicker12} + /> + this.picker24hr = t} + format="24hr" + hintText="24hr Format" + onChange={this.handleChangeTimePicker24} + /> +
    + ); + + // "http://www.material-ui.com/#/components/toolbar" + const ToolbarExamplesSimple = () => ( + + + + + + + + + + + + + + + + + + + } + > + + + + + + + + ); + + return element; + } +} diff --git a/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams b/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams new file mode 100644 index 0000000000..855355b85f --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4-tests.tsx.tscparams @@ -0,0 +1 @@ +--experimentalDecorators \ No newline at end of file diff --git a/material-ui/legacy/material-ui-0.14.4.d.ts b/material-ui/legacy/material-ui-0.14.4.d.ts new file mode 100644 index 0000000000..29eeb225bd --- /dev/null +++ b/material-ui/legacy/material-ui-0.14.4.d.ts @@ -0,0 +1,8246 @@ +// Type definitions for material-ui v0.14.4 +// Project: https://github.com/callemall/material-ui +// Definitions by: Nathan Brown , Oliver Herrmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "material-ui" { + export import AppBar = __MaterialUI.AppBar; // require('material-ui/lib/app-bar'); + export import AppCanvas = __MaterialUI.AppCanvas; // require('material-ui/lib/app-canvas'); + export import AutoComplete = __MaterialUI.AutoComplete; // require('material-ui/lib/auto-complete'); + export import Avatar = __MaterialUI.Avatar; // require('material-ui/lib/avatar'); + export import Badge = __MaterialUI.Badge; // require('material-ui/lib/badge'); + export import BeforeAfterWrapper = __MaterialUI.BeforeAfterWrapper; // require('material-ui/lib/before-after-wrapper'); + export import Card = __MaterialUI.Card.Card; // require('material-ui/lib/card/card'); + export import CardActions = __MaterialUI.Card.CardActions; // require('material-ui/lib/card/card-actions'); + export import CardExpandable = __MaterialUI.Card.CardExpandable; // require('material-ui/lib/card/card-expandable'); + export import CardHeader = __MaterialUI.Card.CardHeader; // require('material-ui/lib/card/card-header'); + export import CardMedia = __MaterialUI.Card.CardMedia; // require('material-ui/lib/card/card-media'); + export import CardText = __MaterialUI.Card.CardText; // require('material-ui/lib/card/card-text'); + export import CardTitle = __MaterialUI.Card.CardTitle; // require('material-ui/lib/card/card-title'); + export import Checkbox = __MaterialUI.Checkbox; // require('material-ui/lib/checkbox'); + export import CircularProgress = __MaterialUI.CircularProgress; // require('material-ui/lib/circular-progress'); + export import ClearFix = __MaterialUI.ClearFix; // require('material-ui/lib/clearfix'); + export import DatePicker = __MaterialUI.DatePicker.DatePicker; // require('material-ui/lib/date-picker/date-picker'); + export import DatePickerDialog = __MaterialUI.DatePicker.DatePickerDialog; // require('material-ui/lib/date-picker/date-picker-dialog'); + export import Dialog = __MaterialUI.Dialog // require('material-ui/lib/dialog'); + export import Divider = __MaterialUI.Divider // require('material-ui/lib/divider'); + export import DropDownMenu = __MaterialUI.Menus.DropDownMenu; // require('material-ui/lib/DropDownMenu/DropDownMenu'); + export import EnhancedButton = __MaterialUI.EnhancedButton; // require('material-ui/lib/enhanced-button'); + export import FlatButton = __MaterialUI.FlatButton; // require('material-ui/lib/flat-button'); + export import FloatingActionButton = __MaterialUI.FloatingActionButton; // require('material-ui/lib/floating-action-button'); + export import FontIcon = __MaterialUI.FontIcon; // require('material-ui/lib/font-icon'); + export import GridList = __MaterialUI.GridList.GridList; // require('material-ui/lib/gridlist/grid-list'); + export import GridTile = __MaterialUI.GridList.GridTile; // require('material-ui/lib/gridlist/grid-tile'); + export import IconButton = __MaterialUI.IconButton; // require('material-ui/lib/icon-button'); + export import IconMenu = __MaterialUI.Menus.IconMenu; // require('material-ui/lib/menus/icon-menu'); + export import LeftNav = __MaterialUI.LeftNav; // require('material-ui/lib/left-nav'); + export import LinearProgress = __MaterialUI.LinearProgress; // require('material-ui/lib/linear-progress'); + export import List = __MaterialUI.Lists.List; // require('material-ui/lib/lists/list'); + export import ListDivider = __MaterialUI.Lists.ListDivider; // require('material-ui/lib/lists/list-divider'); + export import ListItem = __MaterialUI.Lists.ListItem; // require('material-ui/lib/lists/list-item'); + export import Menu = __MaterialUI.Menus.Menu; // require('material-ui/lib/menus/menu'); + export import MenuItem = __MaterialUI.Menus.MenuItem; // require('material-ui/lib/menus/menu-item'); + export import Mixins = __MaterialUI.Mixins; // require('material-ui/lib/mixins'); + export import Overlay = __MaterialUI.Overlay; // require('material-ui/lib/overlay'); + export import Paper = __MaterialUI.Paper; // require('material-ui/lib/paper'); + export import Popover = __MaterialUI.Popover.Popover; // require('material-ui/lib/popover/popover'); + export import RadioButton = __MaterialUI.RadioButton; // require('material-ui/lib/radio-button'); + export import RadioButtonGroup = __MaterialUI.RadioButtonGroup; // require('material-ui/lib/radio-button-group'); + export import RaisedButton = __MaterialUI.RaisedButton; // require('material-ui/lib/raised-button'); + export import RefreshIndicator = __MaterialUI.RefreshIndicator; // require('material-ui/lib/refresh-indicator'); + export import Ripples = __MaterialUI.Ripples; // require('material-ui/lib/ripples'); + export import SelectField = __MaterialUI.SelectField; // require('material-ui/lib/select-field'); + export import SelectableContainerEnhance = __MaterialUI.Hoc.SelectableContainerEnhance; // require('material-ui/lib/hoc/selectable-enhance'); + export import Slider = __MaterialUI.Slider; // require('material-ui/lib/slider'); + export import SvgIcon = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon'); + export import Styles = __MaterialUI.Styles; // require('material-ui/lib/styles'); + export import Snackbar = __MaterialUI.Snackbar; // require('material-ui/lib/snackbar'); + export import Tab = __MaterialUI.Tabs.Tab; // require('material-ui/lib/tabs/tab'); + export import Tabs = __MaterialUI.Tabs.Tabs; // require('material-ui/lib/tabs/tabs'); + export import Table = __MaterialUI.Table.Table; // require('material-ui/lib/table/table'); + export import TableBody = __MaterialUI.Table.TableBody; // require('material-ui/lib/table/table-body'); + export import TableFooter = __MaterialUI.Table.TableFooter; // require('material-ui/lib/table/table-footer'); + export import TableHeader = __MaterialUI.Table.TableHeader; // require('material-ui/lib/table/table-header'); + export import TableHeaderColumn = __MaterialUI.Table.TableHeaderColumn; // require('material-ui/lib/table/table-header-column'); + export import TableRow = __MaterialUI.Table.TableRow; // require('material-ui/lib/table/table-row'); + export import TableRowColumn = __MaterialUI.Table.TableRowColumn; // require('material-ui/lib/table/table-row-column'); + export import Toggle = __MaterialUI.Toggle; // require('material-ui/lib/toggle'); + export import ThemeWrapper = __MaterialUI.ThemeWrapper; // require('material-ui/lib/theme-wrapper'); + export import TimePicker = __MaterialUI.TimePicker; // require('material-ui/lib/time-picker'); + export import TextField = __MaterialUI.TextField; // require('material-ui/lib/text-field'); + export import Toolbar = __MaterialUI.Toolbar.Toolbar; // require('material-ui/lib/toolbar/toolbar'); + export import ToolbarGroup = __MaterialUI.Toolbar.ToolbarGroup; // require('material-ui/lib/toolbar/toolbar-group'); + export import ToolbarSeparator = __MaterialUI.Toolbar.ToolbarSeparator; // require('material-ui/lib/toolbar/toolbar-separator'); + export import ToolbarTitle = __MaterialUI.Toolbar.ToolbarTitle; // require('material-ui/lib/toolbar/toolbar-title'); + export import Tooltip = __MaterialUI.Tooltip; // require('material-ui/lib/tooltip'); + export import Utils = __MaterialUI.Utils; // require('material-ui/lib/utils'); + + // svg icons + import NavigationMenu = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/menu'); + import NavigationChevronLeft = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/chevron-left'); + import NavigationChevronRight = __MaterialUI.SvgIcon; // require('material-ui/lib/svg-icon/navigation/chevron-right'); + + export const Icons: { + NavigationMenu: NavigationMenu, + NavigationChevronLeft: NavigationChevronLeft, + NavigationChevronRight: NavigationChevronRight, + }; + + // export type definitions + export type TouchTapEvent = __MaterialUI.TouchTapEvent; + export type TouchTapEventHandler = __MaterialUI.TouchTapEventHandler; + export type DialogAction = __MaterialUI.DialogAction; +} + +declare namespace __MaterialUI { + export import React = __React; + + // ReactLink is from "react/addons" + interface ReactLink { + value: T; + requestChange(newValue: T): void; + } + + // What's common between React.TouchEvent and React.MouseEvent + interface TouchTapEvent extends React.SyntheticEvent { + altKey: boolean; + ctrlKey: boolean; + getModifierState(key: string): boolean; + metaKey: boolean; + shiftKey: boolean; + } + + // What's common between React.TouchEventHandler and React.MouseEventHandler + interface TouchTapEventHandler extends React.EventHandler { } + + interface ThemeWrapperProps extends React.Props { + theme: Styles.MuiTheme; + } + export class ThemeWrapper extends React.Component { + } + + export namespace Styles { + interface AutoPrefix { + all(styles: React.CSSProperties): React.CSSProperties; + set(style: React.CSSProperties, key: string, value: string | number): void; + single(key: string): string; + singleHyphened(key: string): string; + } + export var AutoPrefix: AutoPrefix; + + interface Spacing { + iconSize?: number; + + desktopGutter?: number; + desktopGutterMore?: number; + desktopGutterLess?: number; + desktopGutterMini?: number; + desktopKeylineIncrement?: number; + desktopDropDownMenuItemHeight?: number; + desktopDropDownMenuFontSize?: number; + desktopLeftNavMenuItemHeight?: number; + desktopSubheaderHeight?: number; + desktopToolbarHeight?: number; + } + export var Spacing: Spacing; + + interface ThemePalette { + primary1Color?: string; + primary2Color?: string; + primary3Color?: string; + accent1Color?: string; + accent2Color?: string; + accent3Color?: string; + textColor?: string; + alternateTextColor?: string; + canvasColor?: string; + borderColor?: string; + disabledColor?: string; + pickerHeaderColor?: string; + clockCircleColor?: string; + shadowColor?: string; + } + interface MuiTheme { + isRtl?: boolean; + userAgent?: any; + zIndex?: zIndex; + baseTheme?: RawTheme; + rawTheme?: RawTheme; + appBar?: { + color?: string, + textColor?: string, + height?: number, + }; + avatar?: { + borderColor?: string, + } + badge?: { + color?: string, + textColor?: string, + primaryColor?: string, + primaryTextColor?: string, + secondaryColor?: string, + secondaryTextColor?: string, + }, + button?: { + height?: number, + minWidth?: number, + iconButtonSize?: number, + }, + cardText?: { + textColor?: string, + }, + checkbox?: { + boxColor?: string, + checkedColor?: string, + requiredColor?: string, + disabledColor?: string, + labelColor?: string, + labelDisabledColor?: string, + }, + datePicker?: { + color?: string, + textColor?: string, + calendarTextColor?: string, + selectColor?: string, + selectTextColor?: string, + }, + dropDownMenu?: { + accentColor?: string, + }, + flatButton?: { + color?: string, + buttonFilterColor?: string, + disabledColor?: string, + textColor?: string, + primaryTextColor?: string, + secondaryTextColor?: string, + }, + floatingActionButton?: { + buttonSize?: number, + miniSize?: number, + color?: string, + iconColor?: string, + secondaryColor?: string, + secondaryIconColor?: string, + disabledColor?: string, + disabledTextColor?: string, + }, + gridTile?: { + textColor?: string, + }, + inkBar?: { + backgroundColor?: string, + }, + leftNav?: { + width?: number, + color?: string, + }, + listItem?: { + nestedLevelDepth?: number, + }, + menu?: { + backgroundColor?: string, + containerBackgroundColor?: string, + }, + menuItem?: { + dataHeight?: number, + height?: number, + hoverColor?: string, + padding?: number, + selectedTextColor?: string, + }, + menuSubheader?: { + padding?: number, + borderColor?: string, + textColor?: string, + }, + paper?: { + backgroundColor?: string, + zDepthShadows?: string[], + }, + radioButton?: { + borderColor?: string, + backgroundColor?: string, + checkedColor?: string, + requiredColor?: string, + disabledColor?: string, + size?: number, + labelColor?: string, + labelDisabledColor?: string, + }, + raisedButton?: { + color?: string, + textColor?: string, + primaryColor?: string, + primaryTextColor?: string, + secondaryColor?: string, + secondaryTextColor?: string, + disabledColor?: string, + disabledTextColor?: string, + }, + refreshIndicator?: { + strokeColor?: string, + loadingStrokeColor?: string, + }; + slider?: { + trackSize?: number, + trackColor?: string, + trackColorSelected?: string, + handleSize?: number, + handleSizeDisabled?: number, + handleSizeActive?: number, + handleColorZero?: string, + handleFillColor?: string, + selectionColor?: string, + rippleColor?: string, + }, + snackbar?: { + textColor?: string, + backgroundColor?: string, + actionColor?: string, + }, + table?: { + backgroundColor?: string; + }; + tableHeader?: { + borderColor?: string; + }; + tableHeaderColumn?: { + textColor?: string; + height?: number; + spacing?: number; + }; + tableFooter?: { + borderColor?: string; + textColor?: string; + }; + tableRow?: { + hoverColor?: string; + stripeColor?: string; + selectedColor?: string; + textColor?: string; + borderColor?: string; + height?: number; + }; + tableRowColumn?: { + height?: number; + spacing?: number; + }; + timePicker?: { + color?: string; + textColor?: string; + accentColor?: string; + clockColor?: string; + clockCircleColor?: string; + headerColor?: string; + selectColor?: string; + selectTextColor?: string; + }; + toggle?: { + thumbOnColor?: string, + thumbOffColor?: string, + thumbDisabledColor?: string, + thumbRequiredColor?: string, + trackOnColor?: string, + trackOffColor?: string, + trackDisabledColor?: string, + labelColor?: string, + labelDisabledColor?: string + trackRequiredColor?: string, + }, + toolbar?: { + backgroundColor?: string, + height?: number, + titleFontSize?: number, + iconColor?: string, + separatorColor?: string, + menuHoverColor?: string, + }; + tabs?: { + backgroundColor?: string, + textColor?: string, + selectedTextColor?: string, + }; + textField?: { + textColor?: string; + hintColor?: string; + floatingLabelColor?: string; + disabledTextColor?: string; + errorColor?: string; + focusColor?: string; + backgroundColor?: string; + borderColor?: string; + }; + } + + interface zIndex { + menu: number; + appBar: number; + leftNavOverlay: number; + leftNav: number; + dialogOverlay: number; + dialog: number; + layer: number; + popover: number; + snackbar: number; + tooltip: number; + } + export var zIndex: zIndex; + + interface RawTheme { + spacing?: Spacing; + fontFamily?: string; + palette?: ThemePalette; + zIndex?: zIndex; + } + var lightBaseTheme: RawTheme; + var darkBaseTheme: RawTheme; + + export function ThemeDecorator(muiTheme: Styles.MuiTheme): (Component: TFunction) => TFunction; + + export function getMuiTheme(baseTheme: RawTheme, muiTheme ?: MuiTheme): MuiTheme; + + interface ThemeManager { + getMuiTheme(baseTheme: RawTheme, muiTheme?: MuiTheme): MuiTheme; + modifyRawThemeSpacing(muiTheme: MuiTheme, newSpacing: Spacing): MuiTheme; + modifyRawThemePalette(muiTheme: MuiTheme, newPaletteKeys: ThemePalette): MuiTheme; + modifyRawThemeFontFamily(muiTheme: MuiTheme, newFontFamily: string): MuiTheme; + } + export var ThemeManager: ThemeManager; + + interface Transitions { + easeOut(duration?: string, property?: string | string[], delay?: string, easeFunction?: string): string; + create(duration?: string, property?: string, delay?: string, easeFunction?: string): string; + easeOutFunction: string; + easeInOutFunction: string; + } + export var Transitions: Transitions; + + interface Typography { + textFullBlack: string; + textDarkBlack: string; + textLightBlack: string; + textMinBlack: string; + textFullWhite: string; + textDarkWhite: string; + textLightWhite: string; + + // font weight + fontWeightLight: number; + fontWeightNormal: number; + fontWeightMedium: number; + + fontStyleButtonFontSize: number; + } + export var Typography: Typography; + + export var DarkRawTheme: RawTheme; + export var LightRawTheme: RawTheme; + } + + interface AppBarProps extends React.Props { + className?: string; + iconClassNameLeft?: string; + iconClassNameRight?: string; + iconElementLeft?: React.ReactElement; + iconElementRight?: React.ReactElement; + iconStyleRight?: string; + onLeftIconButtonTouchTap?: TouchTapEventHandler; + onRightIconButtonTouchTap?: TouchTapEventHandler; + onTitleTouchTap?: TouchTapEventHandler; + showMenuIconButton?: boolean; + style?: React.CSSProperties; + title?: React.ReactNode; + titleStyle?: React.CSSProperties; + zDepth?: number; + } + export class AppBar extends React.Component{ + } + + interface AppCanvasProps extends React.Props { + } + export class AppCanvas extends React.Component { + } + + interface Origin { + horizontal: string; // oneOf(['left', 'middle', 'right']) + vertical: string; // oneOf(['top', 'center', 'bottom']) + } + + type AutoCompleteDataItem = { text: string, value: React.ReactNode } | string; + type AutoCompleteDataSource = { text: string, value: React.ReactNode }[] | string[]; + interface AutoCompleteProps extends React.Props { + anchorOrigin?: Origin; + animated?: boolean; + dataSource?: AutoCompleteDataSource; + disableFocusRipple?: boolean; + errorStyle?: React.CSSProperties; + errorText?: string; + filter?: (searchText: string, key: string, item: AutoCompleteDataItem) => boolean; + floatingLabelText?: string; + fullWidth?: boolean; + hintText?: string; + listStyle?: React.CSSProperties; + menuCloseDelay?: number; + menuProps?: any; + menuStyle?: React.CSSProperties; + onNewRequest?: (chosenRequest: string, index: number) => void; + onUpdateInput?: (searchText: string, dataSource: AutoCompleteDataSource) => void; + open?: boolean; + searchText?: string; + /** @deprecated use noFilter instead */ + showAllItems?: boolean; + style?: React.CSSProperties; + targetOrigin?: Origin; + touchTapCloseDelay?: number; + triggerUpdateOnFocus?: boolean; + /** @deprecated updateWhenFocused has been renamed to triggerUpdateOnFocus */ + updateWhenFocused?: boolean; + } + export class AutoComplete extends React.Component { + static noFilter: () => boolean; + static defaultFilter: (searchText: string, key: string) => boolean; + static caseSensitiveFilter: (searchText: string, key: string) => boolean; + static caseInsensitiveFilter: (searchText: string, key: string) => boolean; + static levenshteinDistanceFilter(distanceLessThan: number): (searchText: string, key: string) => boolean; + static fuzzyFilter: (searchText: string, key: string) => boolean; + static Item: Menus.MenuItem; + static Divider: Divider; + } + + interface AvatarProps extends React.Props { + backgroundColor?: string; + className?: string; + color?: string; + icon?: React.ReactElement; + size?: number; + src?: string; + style?: React.CSSProperties; + } + export class Avatar extends React.Component { + } + + interface BadgeProps extends React.Props { + badgeContent: React.ReactNode; + badgeStyle?: React.CSSProperties; + className?: string; + primary?: boolean; + secondary?: boolean; + style?: React.CSSProperties; + } + export class Badge extends React.Component { + } + + interface BeforeAfterWrapperProps extends React.Props { + afterElementType?: string; + afterStyle?: React.CSSProperties; + beforeElementType?: string; + beforeStyle?: React.CSSProperties; + elementType?: string; + style?: React.CSSProperties; + } + export class BeforeAfterWrapper extends React.Component { + } + + // non generally overridden elements of EnhancedButton + interface SharedEnhancedButtonProps extends React.Props { + centerRipple?: boolean; + disableFocusRipple?: boolean; + disableKeyboardFocus?: boolean; + disableTouchRipple?: boolean; + focusRippleColor?: string; + focusRippleOpacity?: number; + keyboardFocused?: boolean; + linkButton?: boolean; + onBlur?: React.FocusEventHandler; + onFocus?: React.FocusEventHandler; + onKeyboardFocus?: (e: React.FocusEvent, isKeyboardFocused: boolean) => void; + onKeyDown?: React.KeyboardEventHandler; + onKeyUp?: React.KeyboardEventHandler; + onTouchTap?: TouchTapEventHandler; + style?: React.CSSProperties; + tabIndex?: number; + touchRippleColor?: string; + touchRippleOpacity?: number; + type?: string; + } + + interface EnhancedButtonProps extends React.HTMLAttributes, SharedEnhancedButtonProps { + // container element,