diff --git a/README.md b/README.md index 82833752d7..7e1d60d874 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped) +# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped) [![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) diff --git a/ace/ace.d.ts.tscparams b/ace/ace.d.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/ace/ace.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-editor_text_edit-tests.ts.tscparams b/ace/tests/ace-editor_text_edit-tests.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/ace/tests/ace-editor_text_edit-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-range-tests.ts.tscparams b/ace/tests/ace-range-tests.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/ace/tests/ace-range-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/ace/tests/ace-search-tests.ts.tscparams b/ace/tests/ace-search-tests.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/ace/tests/ace-search-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/angular-dynamic-locale/angular-dynamic-locale.d.ts b/angular-dynamic-locale/angular-dynamic-locale.d.ts index a30df1d7ed..e404e95328 100644 --- a/angular-dynamic-locale/angular-dynamic-locale.d.ts +++ b/angular-dynamic-locale/angular-dynamic-locale.d.ts @@ -5,6 +5,11 @@ /// +declare module "angular-dynamic-locale" { + import ng = angular.dynamicLocale; + export = ng; +} + declare module angular.dynamicLocale { interface tmhDynamicLocaleService { diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 2bf75af7d7..fce793e7e7 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -70,6 +70,11 @@ declare module AngularFormly { postWrapper?: ITemplateManipulator[]; } + interface ISelectOption { + name: string; + value?: string; + group?: string; + } /** * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator @@ -104,6 +109,12 @@ declare module AngularFormly { description?: string; [key: string]: any; + // types for select/radio fields + options?: Array; + groupProp?: string; // default: group + valueProp?: string; // default: value + labelProp?: string; // default: name + } diff --git a/angular-loading-bar/angular-loading-bar-tests.ts b/angular-loading-bar/angular-loading-bar-tests.ts index b7ca2894ea..b8bde9e933 100644 --- a/angular-loading-bar/angular-loading-bar-tests.ts +++ b/angular-loading-bar/angular-loading-bar-tests.ts @@ -7,9 +7,17 @@ class TestController { constructor($http: ng.IHttpService) { $http.get("http://xyz.com", { ignoreLoadingBar: true }) - + } } app.controller('TestController', TestController); + +var barConfig: angular.loadingBar.ILoadingBarProvider[] = []; +barConfig.push({ + includeSpinner: true, + includeBar: true, + spinnerTemplate: 'template', + latencyThreshold: 100 +}); diff --git a/angular-loading-bar/angular-loading-bar.d.ts b/angular-loading-bar/angular-loading-bar.d.ts index b1a8cd55df..acea6f048f 100644 --- a/angular-loading-bar/angular-loading-bar.d.ts +++ b/angular-loading-bar/angular-loading-bar.d.ts @@ -14,5 +14,30 @@ declare module angular { */ ignoreLoadingBar?: boolean; } +} -} \ No newline at end of file +declare module angular.loadingBar { + + interface ILoadingBarProvider{ + /** + * Turn the spinner on or off + */ + includeSpinner?: boolean; + + /** + * Turn the loading bar on or off + */ + includeBar?: boolean; + + /** + * HTML template + */ + spinnerTemplate?: string; + + /** + * Latency Threshold + */ + latencyThreshold?: number; + } + +} diff --git a/angular-material/angular-material-0.8.3.d.ts b/angular-material/angular-material-0.8.3.d.ts index 1e3eda18af..10724b8122 100644 --- a/angular-material/angular-material-0.8.3.d.ts +++ b/angular-material/angular-material-0.8.3.d.ts @@ -59,7 +59,7 @@ declare module angular.material { show(dialog: MDDialogOptions|MDPresetDialog): angular.IPromise; confirm(): MDConfirmDialog; alert(): MDAlertDialog; - hide(response?: any): void; + hide(response?: any): angular.IPromise; cancel(response?: any): void; } diff --git a/angular-material/angular-material-0.9.0.d.ts b/angular-material/angular-material-0.9.0.d.ts index 1383b0beb5..96134f114f 100644 --- a/angular-material/angular-material-0.9.0.d.ts +++ b/angular-material/angular-material-0.9.0.d.ts @@ -64,7 +64,7 @@ declare module angular.material { show(dialog: MDDialogOptions|MDAlertDialog|MDConfirmDialog): angular.IPromise; confirm(): MDConfirmDialog; alert(): MDAlertDialog; - hide(response?: any): void; + hide(response?: any): angular.IPromise; cancel(response?: any): void; } diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 43e0b9f53b..7d29e7492a 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -83,7 +83,7 @@ declare module angular.material { show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise; confirm(): IConfirmDialog; alert(): IAlertDialog; - hide(response?: any): void; + hide(response?: any): angular.IPromise; cancel(response?: any): void; } diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index 45a5d7edc4..0f98aead12 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -196,6 +196,27 @@ function TestWebDriverUntilModule() { conditionWebElements = protractor.until.elementsLocated(by.className('class')); } +function TestWebDriverExpectedConditionsModule() { + var conditionB: protractor.until.Condition; + var el: protractor.ElementFinder = element(by.id('id')); + + conditionB = protractor.ExpectedConditions.alertIsPresent(); + conditionB = protractor.ExpectedConditions.elementToBeClickable(el); + conditionB = protractor.ExpectedConditions.textToBePresentInElement(el, 'text'); + conditionB = protractor.ExpectedConditions.textToBePresentInElementValue(el, 'text'); + conditionB = protractor.ExpectedConditions.titleContains('text'); + conditionB = protractor.ExpectedConditions.titleIs('text'); + conditionB = protractor.ExpectedConditions.presenceOf(el); + conditionB = protractor.ExpectedConditions.stalenessOf(el); + conditionB = protractor.ExpectedConditions.visibilityOf(el); + conditionB = protractor.ExpectedConditions.invisibilityOf(el); + conditionB = protractor.ExpectedConditions.elementToBeSelected(el); + + conditionB = protractor.ExpectedConditions.not(protractor.ExpectedConditions.alertIsPresent()); + conditionB = protractor.ExpectedConditions.and(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); + conditionB = protractor.ExpectedConditions.or(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); +} + function TestProtractor() { var ptor: protractor.Protractor; var driver: webdriver.WebDriver = new webdriver.Builder(). diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index ff83242381..08f83e27d4 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -501,6 +501,145 @@ declare module protractor { function titleMatches(regex: RegExp): webdriver.until.Condition; } + module ExpectedConditions { + /** + * Negates the result of a promise. + * + * @param {webdriver.until.Condition} expectedCondition + * @return {!webdriver.until.Condition} An expected condition that returns the negated value. + */ + function not(expectedCondition: webdriver.until.Condition): webdriver.until.Condition; + + /** + * Chain a number of expected conditions using logical_and, short circuiting at the + * first expected condition that evaluates to false. + * + * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'and' together. + * @return {!webdriver.until.Condition} An expected condition that returns a promise which evaluates + * to the result of the logical and. + */ + function and(...fns: webdriver.until.Condition[]): webdriver.until.Condition; + + /** + * Chain a number of expected conditions using logical_or, short circuiting at the + * first expected condition that evaluates to true. + * + * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'or' together. + * @return {!webdriver.until.Condition} An expected condition that returns a promise which + * evaluates to the result of the logical or. + */ + function or(...fns: webdriver.until.Condition[]): webdriver.until.Condition; + + /** + * Expect an alert to be present. + * + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether an alert is present. + */ + function alertIsPresent(): webdriver.until.Condition; + + /** + * An Expectation for checking an element is visible and enabled such that you can click it. + * + * @param {ElementFinder} element The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is clickable. + */ + function elementToBeClickable(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking if the given text is present in the element. + * Returns false if the elementFinder does not find an element. + * + * @param {ElementFinder} element The element to check + * @param {string} text The text to verify against + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the text is present in the element. + */ + function textToBePresentInElement(element: ElementFinder, text: string): webdriver.until.Condition; + + /** + * An expectation for checking if the given text is present in the element’s value. + * Returns false if the elementFinder does not find an element. + * + * @param {ElementFinder} element The element to check + * @param {string} text The text to verify against + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the text is present in the element's value. + */ + function textToBePresentInElementValue( + element: ElementFinder, text: string + ): webdriver.until.Condition; + + /** + * An expectation for checking that the title contains a case-sensitive substring. + * + * @param {string} title The fragment of title expected + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the title contains the string. + */ + function titleContains(title: string): webdriver.until.Condition; + + /** + * An expectation for checking the title of a page. + * + * @param {string} title The expected title, which must be an exact match. + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the title equals the string. + */ + function titleIs(title: string): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page. This does not necessarily + * mean that the element is visible. This is the opposite of 'stalenessOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise + * representing whether the element is present. + */ + function presenceOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is not attached to the DOM of a page. + * This is the opposite of 'presenceOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is stale. + */ + function stalenessOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page and visible. + * Visibility means that the element is not only displayed but also has a height and width that is + * greater than 0. This is the opposite of 'invisibilityOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is visible. + */ + function visibilityOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page. This does not necessarily + * mean that the element is visible. This is the opposite of 'stalenessOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is invisible. + */ + function invisibilityOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking the selection is selected. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is selected. + */ + function elementToBeSelected(element: ElementFinder): webdriver.until.Condition; + } + //endregion /** @@ -1667,6 +1806,16 @@ declare module protractor { * @return {Protractor} a protractor instance. */ forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; + + /** + * Get the processed configuration object that is currently being run. This will contain + * the specs and capabilities properties of the current runner instance. + * + * Set by the runner. + * + * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. + */ + getProcessedConfig(): webdriver.promise.Promise; } /** diff --git a/angular-strap/angular-strap-tests.ts b/angular-strap/angular-strap-tests.ts new file mode 100644 index 0000000000..90c7a2bdea --- /dev/null +++ b/angular-strap/angular-strap-tests.ts @@ -0,0 +1,378 @@ +/// +/// + +module angularStrapTests { + + import ngStrap = mgcrea.ngStrap; + + /////////////////////////////////////////////////////////////////////////// + // Modal + /////////////////////////////////////////////////////////////////////////// + + module modalTests { + + interface IDemoCtrlScope extends ngStrap.modal.IModalScope { + showModal: () => void; + } + + angular.module('demoApp') + .config($modalConfig) + .controller('demoCtrl', demoCtrl); + + function demoCtrl($scope: IDemoCtrlScope, + $modal: ngStrap.modal.IModalService): void { + + var myModalOptions: ngStrap.modal.IModalOptions = {}; + myModalOptions.title = 'My Title'; + myModalOptions.content = 'Hello Modal
This is a multiline message!'; + myModalOptions.show = true; + + var myModal = $modal(myModalOptions); + + var myOtherModalOptions: ngStrap.modal.IModalOptions = {}; + myOtherModalOptions.scope = $scope; + myOtherModalOptions.template = 'modal/docs/modal.demo.tpl.html'; + myOtherModalOptions.show = false; + + var myOtherModal = $modal(myOtherModalOptions); + + $scope.showModal = (): void => { + myOtherModal.$promise.then(myOtherModal.show); + }; + } + + function $modalConfig($modalProvider: ngStrap.modal.IModalProvider): void { + var defaults: ngStrap.modal.IModalOptions = { + animation: 'am-flip-x' + } + angular.extend($modalProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Aside + /////////////////////////////////////////////////////////////////////////// + + module asideTests { + + angular.module('demoApp') + .config($asideConfig) + .controller('demoCtrl', demoCtrl); + + function demoCtrl($scope: ngStrap.aside.IAsideScope, + $aside: ngStrap.aside.IAsideService): void { + + var myAsideOptions: ngStrap.aside.IAsideOptions = {}; + myAsideOptions.title = 'My Title'; + myAsideOptions.content = 'My content'; + myAsideOptions.show = true; + + var myAside = $aside(myAsideOptions); + + var myOtherAsideOptions: ngStrap.aside.IAsideOptions = {}; + myOtherAsideOptions.scope = $scope; + myOtherAsideOptions.template = 'aside/docs/aside.demo.tpl.html'; + + var myOtherAside = $aside(); + + myOtherAside.$promise.then(() => { + myOtherAside.show(); + }); + } + + function $asideConfig($asideProvider: ngStrap.aside.IAsideProvider): void { + var defaults: ngStrap.aside.IAsideOptions = {}; + defaults.animation = 'am-fadeAndSlideLeft'; + defaults.placement = 'left'; + + angular.extend($asideProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Alert + /////////////////////////////////////////////////////////////////////////// + + module alertTests { + + angular.module('demoApp') + .config($alertConfig) + .controller('demoCtrl', demoCtrl); + + function demoCtrl($scope: ngStrap.alert.IAlertScope, + $alert: ngStrap.alert.IAlertService): void { + + var options: ngStrap.alert.IAlertOptions = {}; + options.title = 'Holy guacamole!'; + options.content = 'Best check yo self, you\'re not looking too good.'; + options.placement = 'top'; + options.type = 'info'; + options.show = true; + + var myAlert = $alert(); + } + + function $alertConfig($alertProvider: ngStrap.alert.IAlertProvider): void { + var defaults: ngStrap.alert.IAlertOptions = {}; + defaults.animation = 'am-fade-and-slide-top'; + defaults.placement = 'top'; + + angular.extend($alertProvider.defaults, defaults); + }; + } + + + /////////////////////////////////////////////////////////////////////////// + // Tooltip + /////////////////////////////////////////////////////////////////////////// + + module tooltipTests { + + angular.module('demoApp') + .config($tooltipConfig) + .controller('demoDrct', demoDrct); + + function demoDrct($tooltip: ngStrap.tooltip.ITooltipService): ng.IDirective { + var drct: ng.IDirective = {}; + drct.restrict = 'EA'; + drct.link = link; + return drct; + + function link(scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes): void { + var options: ngStrap.tooltip.ITooltipOptions = {}; + options.title = 'My Title'; + $tooltip(elem, options); + } + } + + function $tooltipConfig($tooltipProvider: ngStrap.tooltip.ITooltipProvider): void { + var defaults: ngStrap.tooltip.ITooltipOptions = {}; + defaults.animation = 'am-flip-x'; + defaults.trigger = 'hover'; + + angular.extend($tooltipProvider.defaults, defaults); + }; + } + + + /////////////////////////////////////////////////////////////////////////// + // Popover + /////////////////////////////////////////////////////////////////////////// + + module popoverTests { + + angular.module('demoApp') + .config($popoverConfig) + .controller('demoDrct', demoDrct); + + function demoDrct($popover: ngStrap.popover.IPopoverService): ng.IDirective { + var drct: ng.IDirective = {}; + drct.restrict = 'EA'; + drct.link = link; + return drct; + + function link(scope: ng.IScope, elem: ng.IAugmentedJQuery, attrs: ng.IAttributes): void { + var options: ngStrap.tooltip.ITooltipOptions = {}; + options.title = 'My Title'; + + $popover(elem, options); + } + } + + function $popoverConfig($popoverProvider: ngStrap.popover.IPopoverProvider): void { + var defaults: ngStrap.tooltip.ITooltipOptions = {} + defaults.animation = 'am-flip-x'; + defaults.trigger = 'hover'; + + angular.extend($popoverProvider.defaults, defaults); + }; + } + + + /////////////////////////////////////////////////////////////////////////// + // Typeahead + /////////////////////////////////////////////////////////////////////////// + + module typeaheadTests { + + angular.module('myApp') + .config($typeaheadConfig); + + function $typeaheadConfig($typeaheadProvider: ngStrap.typeahead.ITypeaheadProvider) { + var defaults: ngStrap.typeahead.ITypeaheadOptions = {} + defaults.animation = 'am-flip-x'; + defaults.minLength = 2; + defaults.limit = 8; + + angular.extend($typeaheadProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Datepicker + /////////////////////////////////////////////////////////////////////////// + + module datepickerTests { + + angular.module('myApp') + .config($datepickerConfig); + + function $datepickerConfig($datepickerProvider: ngStrap.datepicker.IDatepickerProvider): void { + var defaults: ngStrap.datepicker.IDatepickerOptions = {}; + defaults.dateFormat = 'dd/MM/yyyy'; + defaults.startWeek = 1; + + angular.extend($datepickerProvider.defaults, defaults); + }; + } + + + /////////////////////////////////////////////////////////////////////////// + // Timepicker + /////////////////////////////////////////////////////////////////////////// + + module timepickerTests { + + angular.module('myApp') + .config($timepickerConfig); + + function $timepickerConfig($timepickerProvider: ngStrap.timepicker.ITimepickerProvider): void { + var defaults: ngStrap.timepicker.ITimepickerOptions = {}; + defaults.timeFormat = 'HH:mm'; + defaults.length = 7; + + angular.extend($timepickerProvider.defaults, defaults); + }; + } + + + /////////////////////////////////////////////////////////////////////////// + // Select + /////////////////////////////////////////////////////////////////////////// + + module selectTests { + + angular.module('myApp') + .config($selectConfig); + + function $selectConfig($selectProvider: ngStrap.select.ISelectProvider): void { + var defaults: ngStrap.select.ISelectOptions = {}; + defaults.animation = 'am-flip-x'; + defaults.sort = false; + + angular.extend($selectProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Tabs + /////////////////////////////////////////////////////////////////////////// + + module tabTests { + + angular.module('myApp') + .config($tabConfig); + + function $tabConfig($tabProvider: ngStrap.tab.ITabProvider) { + var defaults: ngStrap.tab.ITabOptions = {}; + defaults.animation = 'am-flip-x'; + + angular.extend($tabProvider.defaults, defaults); + } + } + + /////////////////////////////////////////////////////////////////////////// + // Collapse + /////////////////////////////////////////////////////////////////////////// + + module collapseTests { + + angular.module('myApp') + .config($collapseConfig); + + function $collapseConfig($collapseProvider: ngStrap.collapse.ICollapseProvider):void { + var defaults: ngStrap.collapse.ICollapseOptions = {}; + defaults.animation = 'am-flip-x'; + + angular.extend($collapseProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Dropdown + /////////////////////////////////////////////////////////////////////////// + + module dropdownTests { + + angular.module('myApp') + .config($dropdownConfig); + + function $dropdownConfig($dropdownProvider: ngStrap.dropdown.IDropdownProvider):void { + var defaults: ngStrap.dropdown.IDropdownOptions = {}; + defaults.animation = 'am-flip-x'; + defaults.trigger = 'hover'; + + angular.extend($dropdownProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Navbar + /////////////////////////////////////////////////////////////////////////// + + module navbarTests { + + angular.module('myApp') + .config($navbarConfig); + + function $navbarConfig($navbarProvider: ngStrap.navbar.INavbarProvider):void { + var defaults: ngStrap.navbar.INavbarOptions = {}; + defaults.activeClass = 'in'; + + angular.extend($navbarProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Scrollspy + /////////////////////////////////////////////////////////////////////////// + + module scrollspyTests { + + angular.module('myApp') + .config($scrollspyConfig); + + function $scrollspyConfig($scrollspyProvider: ngStrap.scrollspy.IScrollspyProvider):void { + var defaults: ngStrap.scrollspy.IScrollspyOptions = {}; + defaults.offset = 0; + defaults.target = 'my-selector'; + + angular.extend($scrollspyProvider.defaults, defaults); + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Affix + /////////////////////////////////////////////////////////////////////////// + + module affixTests { + + angular.module('myApp') + .config($affixConfig); + + function $affixConfig($affixProvider: ngStrap.affix.IAffixProvider):void { + var defaults: ngStrap.affix.IAffixOptions = {}; + defaults.offsetTop = 100; + + angular.extend($affixProvider.defaults, defaults); + } + } +} \ No newline at end of file diff --git a/angular-strap/angular-strap.d.ts b/angular-strap/angular-strap.d.ts new file mode 100644 index 0000000000..10e46bc1c1 --- /dev/null +++ b/angular-strap/angular-strap.d.ts @@ -0,0 +1,600 @@ +// Type definitions for angular-strap v2.2.x +// Project: http://mgcrea.github.io/angular-strap/ +// Definitions by: Sam Herrmann +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +/// + +declare module mgcrea.ngStrap { + + /////////////////////////////////////////////////////////////////////////// + // Modal + // see http://mgcrea.github.io/angular-strap/#/modals + /////////////////////////////////////////////////////////////////////////// + + module modal { + + interface IModalService { + (config?: IModalOptions): IModal; + } + + interface IModalProvider { + defaults: IModalOptions; + } + + interface IModal { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IModalOptions { + animation?: string; + backdropAnimation?: string; + placement?: string; + title?: string; + content?: string; + html?: boolean; + backdrop?: boolean | string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + contentTemplate?: string; + prefixEvent?: string; + id?: string; + scope?: ng.IScope; + } + + interface IModalScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Aside + // see http://mgcrea.github.io/angular-strap/#/asides + /////////////////////////////////////////////////////////////////////////// + + module aside { + + interface IAsideService { + (config?: IAsideOptions): IAside; + } + + interface IAsideProvider { + defaults: IAsideOptions; + } + + interface IAside { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IAsideOptions { + animation?: string; + placement?: string; + title?: string; + content?: string; + html?: boolean; + backdrop?: boolean | string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + contentTemplate?: string; + scope?: ng.IScope; + } + + interface IAsideScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + + /////////////////////////////////////////////////////////////////////////// + // Alert + // see http://mgcrea.github.io/angular-strap/#/alerts + /////////////////////////////////////////////////////////////////////////// + + module alert { + + interface IAlertService { + (config?: IAlertOptions): IAlert; + } + + interface IAlertProvider { + defaults: IAlertOptions; + } + + interface IAlert { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IAlertOptions { + animation?: string; + placement?: string; + title?: string; + content?: string; + type?: string; + keyboard?: boolean; + show?: boolean; + container?: string | boolean; + template?: string; + duration?: number | boolean; + dismissable?: boolean; + } + + interface IAlertScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Tooltip + // see http://mgcrea.github.io/angular-strap/#/tooltips + /////////////////////////////////////////////////////////////////////////// + + module tooltip { + + interface ITooltipService { + (element: ng.IAugmentedJQuery, config?: ITooltipOptions): ITooltip; + } + + interface ITooltipProvider { + defaults: ITooltipOptions; + } + + interface ITooltip { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface ITooltipOptions { + animation?: string; + placement?: string; + trigger?: string; + title?: string; + html?: boolean; + delay?: number | { show: number; hide: number}; + container?: string | boolean; + target?: string | ng.IAugmentedJQuery | boolean; + template?: string; + contentTemplate?: string; + prefixEvent?: string; + id?: string; + viewport?: string | { selector: string; padding: string | number }; + } + + interface ITooltipScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + $setEnabled: (isEnabled: boolean) => void; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Popover + // see http://mgcrea.github.io/angular-strap/#/popovers + /////////////////////////////////////////////////////////////////////////// + + module popover { + + interface IPopoverService { + (element: ng.IAugmentedJQuery, config?: IPopoverOptions): IPopover; + } + + interface IPopoverProvider { + defaults: IPopoverOptions; + } + + interface IPopover { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface IPopoverOptions { + animation?: string; + placement?: string; + trigger?: string; + title?: string; + content?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + target?: string | ng.IAugmentedJQuery | boolean; + template?: string; + contentTemplate?: string; + autoClose?: boolean; + id?: string; + viewport?: string | { selector: string; padding: string | number }; + } + + interface IPopoverScope extends ng.IScope { + $show: () => void; + $hide: () => void; + $toggle: () => void; + } + } + + + + /////////////////////////////////////////////////////////////////////////// + // Typeahead + // see http://mgcrea.github.io/angular-strap/#/typeaheads + /////////////////////////////////////////////////////////////////////////// + + module typeahead { + + interface ITypeaheadService { + (element: ng.IAugmentedJQuery, controller: any, config?: ITypeaheadOptions): ITypeahead; + } + + interface ITypeaheadProvider { + defaults: ITypeaheadOptions; + } + + interface ITypeahead { + $promise: ng.IPromise; + show: () => void; + hide: () => void; + toggle: () => void; + } + + interface ITypeaheadOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + template?: string; + limit?: number; + minLength?: number; + autoSelect?: boolean; + comparator?: string; + id?: string; + watchOptions?: boolean; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Datepicker + // see http://mgcrea.github.io/angular-strap/#/datepickers + /////////////////////////////////////////////////////////////////////////// + + module datepicker { + + interface IDatepickerService { + (element: ng.IAugmentedJQuery, controller: any, config?: IDatepickerOptions): IDatepicker; + } + + interface IDatepickerProvider { + defaults: IDatepickerOptions; + } + + interface IDatepicker { + update: (date: Date) => void; + updateDisabledDates: (dateRanges: IDatepickerDateRange[]) => void; + select: (dateConstructorArg: string | number | number[], keep: boolean) => void; + setMode: (mode: any) => void; + int: () => void; + destroy: () => void; + show: () => void; + hide: () => void; + } + + interface IDatepickerDateRange { + start: Date; + end: Date; + } + + interface IDatepickerOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number }; + container?: string | boolean; + template?: string; + dateFormat?: string; + modelDateFormat?: string; + dateType?: string; + timezone?: string; + autoclose?: boolean; + useNative?: boolean; + minDate?: Date; + maxDate?: Date; + startView?: number; + minView?: number; + startWeek?: number; + startDate?: Date; + iconLeft?: string; + iconRight?: string; + daysOfWeekDisabled?: string; + disabledDates?: IDatepickerDateRange[]; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Timepicker + // see http://mgcrea.github.io/angular-strap/#/timepickers + /////////////////////////////////////////////////////////////////////////// + + module timepicker { + + interface ITimepickerService { + (element: ng.IAugmentedJQuery, controller: any, config?: ITimepickerOptions): ITimepicker; + } + + interface ITimepickerProvider { + defaults: ITimepickerOptions; + } + + interface ITimepicker { + + } + + interface ITimepickerOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + timeFormat?: string; + modelTimeFormat?: string; + timeType?: string; + autoclose?: boolean; + useNative?: boolean; + minTime?: Date; // TODO + maxTime?: Date; // TODO + length?: number; + hourStep?: number; + minuteStep?: number; + secondStep?: number; + roundDisplay?: boolean; + iconUp?: string; + iconDown?: string; + arrowBehaviour?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Button + // see http://mgcrea.github.io/angular-strap/#/buttons + /////////////////////////////////////////////////////////////////////////// + + // No definitions for this module + + + /////////////////////////////////////////////////////////////////////////// + // Select + // see http://mgcrea.github.io/angular-strap/#/selects + /////////////////////////////////////////////////////////////////////////// + + module select { + + interface ISelectService { + (element: ng.IAugmentedJQuery, controller: any, config: ISelectOptions): ISelect; + } + + interface ISelectProvider { + defaults: ISelectOptions; + } + + interface ISelect { + update: (matches: any) => void; + active: (index: number) => number; + select: (index: number) => void; + show: () => void; + hide: () => void; + } + + interface ISelectOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + multiple?: boolean; + allNoneButtons?: boolean; + allText?: string; + noneText?: string; + maxLength?: number; + maxLengthHtml?: string; + sort?: boolean; + placeholder?: string; + iconCheckmark?: string; + id?: string; + } + } + + /////////////////////////////////////////////////////////////////////////// + // Tabs + // see http://mgcrea.github.io/angular-strap/#/tabs + /////////////////////////////////////////////////////////////////////////// + + module tab { + + interface ITabProvider { + defaults: ITabOptions; + } + + interface ITabService { + defaults: ITabOptions; + controller: any; + } + + interface ITabOptions { + animation?: string; + template?: string; + navClass?: string; + activeClass?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Collapses + // see http://mgcrea.github.io/angular-strap/#/collapses + /////////////////////////////////////////////////////////////////////////// + + module collapse { + + interface ICollapseProvider { + defaults: ICollapseOptions; + } + + interface ICollapseOptions { + animation?: string; + activeClass?: string; + disallowToggle?: boolean; + startCollapsed?: boolean; + allowMultiple?: boolean; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Dropdowsn + // see http://mgcrea.github.io/angular-strap/#/dropdowns + /////////////////////////////////////////////////////////////////////////// + + module dropdown { + + interface IDropdownProvider { + defaults: IDropdownOptions; + } + + interface IDropdownService { + (element: ng.IAugmentedJQuery, config: IDropdownOptions): IDropdown; + } + + interface IDropdown { + show: () => void; + hide: () => void; + destroy: () => void; + } + + interface IDropdownOptions { + animation?: string; + placement?: string; + trigger?: string; + html?: boolean; + delay?: number | { show: number; hide: number; }; + container?: string | boolean; + template?: string; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Navbar + // see http://mgcrea.github.io/angular-strap/#/navbars + /////////////////////////////////////////////////////////////////////////// + + module navbar { + + interface INavbarProvider { + defaults: INavbarOptions; + } + + interface INavbarOptions { + activeClass?: string; + routeAttr?: string; + } + + interface INavbarService { + defaults: INavbarOptions; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Scrollspy + // see http://mgcrea.github.io/angular-strap/#/scrollspy + /////////////////////////////////////////////////////////////////////////// + + module scrollspy { + + interface IScrollspyProvider { + defaults: IScrollspyOptions; + } + + interface IScrollspyService { + (element: ng.IAugmentedJQuery, options: IScrollspyOptions): IScrollspy; + } + + interface IScrollspy { + checkOffsets: () => void; + trackElement: (target: any, source: any) => void; + untrackElement: (target: any, source: any) => void; + activate: (index: number) => void; + } + + interface IScrollspyOptions { + target?: string; + offset?: number; + } + } + + + /////////////////////////////////////////////////////////////////////////// + // Affix + // see http://mgcrea.github.io/angular-strap/#/affix + /////////////////////////////////////////////////////////////////////////// + + module affix { + + interface IAffixProvider { + defaults: IAffixOptions; + } + + interface IAffixService { + (element: ng.IAugmentedJQuery, options: IAffixOptions): IAffix; + } + + interface IAffix { + init: () => void; + destroy: () => void; + checkPositionWithEventLoop: () => void; + checkPosition: () => void; + } + + interface IAffixOptions { + offsetTop?: number; + offsetBottom?: number; + offsetParent?: number; + offsetUnpin?: number; + } + } +} diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index c60247f427..a19d27adec 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -36,4 +36,9 @@ app.controller('Ctrl', ($scope: Scope, $translate: angular.translate.ITranslateS $scope['changeLanguage'] = function (key: any) { $translate.use(key); }; +}).run(($filter: ng.IFilterService) => { + var x: string; + x = $filter('translate')('something'); + x = $filter('translate')('something', {}); + x = $filter('translate')('something', {}, ''); }); diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index e4f69c688b..960012a576 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -6,8 +6,8 @@ /// declare module "angular-translate" { - var _: string; - export = _; + import ngt = angular.translate; + export = ngt; } declare module angular.translate { @@ -22,7 +22,7 @@ declare module angular.translate { interface IStorage { get(name: string): string; - set(name: string, value: string): void; + put(name: string, value: string): void; } interface IStaticFilesLoaderOptions { @@ -108,3 +108,11 @@ declare module angular.translate { useLoaderCache(cache?: any): ITranslateProvider; } } + +declare module angular { + interface IFilterService { + (name:'translate'): { + (translationId: string, interpolateParams?: any, interpolation?: string): string; + }; + } +} diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index 3211faee5c..41661d60d5 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -230,7 +230,7 @@ module UrlRouterProviderTests { // this allows you to configure custom behavior in between // location changes and route synchronization: $urlRouterProvider.deferIntercept(); - }).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService) => { + }).run(($rootScope: ng.IRootScopeService, $urlRouter: ng.ui.IUrlRouterService, UserService: ITestUserService, $urlMatcher: ng.ui.IUrlMatcher) => { $rootScope.$on('$locationChangeSuccess', e => { // UserService is an example service for managing user state if (UserService.isLoggedIn()) return; @@ -245,6 +245,18 @@ module UrlRouterProviderTests { }); // Configures $urlRouter's listener *after* your custom listener - $urlRouter.listen(); + var listen: Function = $urlRouter.listen(); + + var href: string; + href = $urlRouter.href($urlMatcher); + href = $urlRouter.href($urlMatcher, {}); + href = $urlRouter.href($urlMatcher, {}, {}); + + $urlRouter.update(); + $urlRouter.update(false); + + $urlRouter.push($urlMatcher); + $urlRouter.push($urlMatcher, {}); + $urlRouter.push($urlMatcher, {}, {}); }); } diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 014baf5ac4..a22b7d0da3 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -5,10 +5,27 @@ /// -// Support for AMD require +// Support for AMD require and CommonJS declare module 'angular-ui-router' { - var _: string; - export = _; + // Since angular-ui-router adds providers for a bunch of + // injectable dependencies, it doesn't really return any + // actual data except the plain string 'ui.router'. + // + // As such, I don't think anybody will ever use the actual + // default value of the module. So I've only included the + // the types. (@xogeny) + export type IState = angular.ui.IState; + export type IStateProvider = angular.ui.IStateProvider; + export type IUrlMatcher = angular.ui.IUrlMatcher; + export type IUrlRouterProvider = angular.ui.IUrlRouterProvider; + export type IStateOptions = angular.ui.IStateOptions; + export type IHrefOptions = angular.ui.IHrefOptions; + export type IStateService = angular.ui.IStateService; + export type IResolvedState = angular.ui.IResolvedState; + export type IStateParamsService = angular.ui.IStateParamsService; + export type IUrlRouterService = angular.ui.IUrlRouterService; + export type IUiViewScrollProvider = angular.ui.IUiViewScrollProvider; + export type IType = angular.ui.IType; } declare module angular.ui { @@ -283,7 +300,10 @@ declare module angular.ui { * */ sync(): void; - listen(): void; + listen(): Function; + href(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): string; + update(read?: boolean): void; + push(urlMatcher: IUrlMatcher, params?: IStateParamsService, options?: IHrefOptions): void; } interface IUiViewScrollProvider { diff --git a/angular-ui-tree/angular-ui-tree-tests.ts b/angular-ui-tree/angular-ui-tree-tests.ts index e66408814e..718fada2ce 100644 --- a/angular-ui-tree/angular-ui-tree-tests.ts +++ b/angular-ui-tree/angular-ui-tree-tests.ts @@ -11,3 +11,73 @@ var treeNode2: AngularUITree.ITreeNode = { nodes: [treeNode], title: "test2" }; + +// fake jquery node here so that we can pull a pretend +// angular scope element out of it +var dummyJQueryNode: ng.IAugmentedJQuery; +var fakeScope: (ng.IScope | AngularUITree.IParentTreeNodeScope) = dummyJQueryNode.scope(); + +( fakeScope).node = treeNode; + +var treeNodeScope: AngularUITree.ITreeNodeScope = fakeScope; + +( fakeScope).isParent = (nodeScope: AngularUITree.ITreeNodeScope) => { + return true; +}; + +var parentTreeNodeScope: AngularUITree.IParentTreeNodeScope = fakeScope; + +var eventSourceInfo: AngularUITree.IEventSourceInfo = { + cloneModel: {}, + nodeScope: treeNodeScope, + index: 0, + nodesScope: parentTreeNodeScope +}; + +var position: AngularUITree.IPosition = { + dirAx: 0, + dirX: 0, + dirY: 0, + distAxX: 0, + distAxY: 0, + distX: 0, + distY: 0, + lastDirX: 0, + lastDirY: 0, + lastX: 0, + lastY: 0, + moving: true, + nowX: 0, + nowY: 0, + offsetX: 0, + offsetY: 0, + startX: 0, + startY: 0 + +}; + +var eventInfo: AngularUITree.IEventInfo = { + source: eventSourceInfo, + dest: { + index: 0, + nodesScope: parentTreeNodeScope + }, + elements: {}, + pos: position +}; + +var acceptCallback: AngularUITree.IAcceptCallback = (source: AngularUITree.ITreeNodeScope, + destination: AngularUITree.ITreeNodeScope, + destinationIndex: number) => { + return false; +}; + +var droppedCallback: AngularUITree.IDroppedCallback = (eventInfo: AngularUITree.IEventInfo) => { + return; +}; + +var callbacks: AngularUITree.ICallbacks = { + accept: acceptCallback, + dragStart: droppedCallback, + dropped: droppedCallback +}; diff --git a/angular-ui-tree/angular-ui-tree.d.ts b/angular-ui-tree/angular-ui-tree.d.ts index 1017ac11cd..cfcb2b1087 100644 --- a/angular-ui-tree/angular-ui-tree.d.ts +++ b/angular-ui-tree/angular-ui-tree.d.ts @@ -3,7 +3,72 @@ // Definitions by: Calvin Fernandez // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module AngularUITree { + interface IEventSourceInfo { + cloneModel: any; + index: number; + nodeScope: ITreeNodeScope; + nodesScope: ITreeNodeScope; + } + + interface IPosition { + dirAx: number; + dirX: number; + dirY: number; + distAxX: number; + distAxY: number; + distX: number; + distY: number; + lastDirX: number; + lastDirY: number; + lastX: number; + lastY: number; + moving: boolean; + nowX: number; + nowY: number; + offsetX: number; + offsetY: number; + startX: number; + startY: number; + } + + interface IEventInfo { + dest: { + index: number; + nodesScope: IParentTreeNodeScope; + }; + elements: any; + pos: IPosition; + source: IEventSourceInfo; + } + + interface IAcceptCallback { + (source: ITreeNodeScope, destination: ITreeNodeScope, destinationIndex: number): boolean; + } + + interface IDroppedCallback { + (eventInfo: IEventInfo): void; + } + + interface ICallbacks { + accept: IAcceptCallback; + dragStart: IDroppedCallback; + dropped: IDroppedCallback; + } + + /** + * Internal representation of node in the UI + */ + interface ITreeNodeScope extends ng.IScope { + node: ITreeNode; + } + + interface IParentTreeNodeScope extends ITreeNodeScope { + isParent(nodeScope: ITreeNodeScope): boolean; + } + /** * Node in list */ diff --git a/angularjs/angular-resource-tests.ts b/angularjs/angular-resource-tests.ts index cfa7712cc2..fcf0bd0a96 100644 --- a/angularjs/angular-resource-tests.ts +++ b/angularjs/angular-resource-tests.ts @@ -89,6 +89,9 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () { var promise : angular.IPromise; var arrayPromise : angular.IPromise; +var json: { + [index: string]: any; +}; promise = resource.$delete(); promise = resource.$delete({ key: 'value' }); @@ -127,6 +130,8 @@ promise = resource.$save(function () { }); promise = resource.$save(function () { }, function () { }); promise = resource.$save({ key: 'value' }, function () { }, function () { }); +json = resource.toJSON(); + /////////////////////////////////////// // IResourceService /////////////////////////////////////// diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 76930196ba..1e82f31545 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -5,6 +5,10 @@ /// +declare module 'angular-resource' { + var _: string; + export = _; +} /////////////////////////////////////////////////////////////////////////////// // ngResource module (angular-resource.js) @@ -136,12 +140,15 @@ declare module angular.resource { /** the promise of the original server interaction that created this instance. **/ $promise : angular.IPromise; $resolved : boolean; + toJSON: () => { + [index: string]: any; + } } /** * Really just a regular Array object with $promise and $resolve attached to it */ - interface IResourceArray extends Array { + interface IResourceArray extends Array> { /** the promise of the original server interaction that created this collection. **/ $promise : angular.IPromise>; $resolved : boolean; diff --git a/angularjs/angular-route.d.ts b/angularjs/angular-route.d.ts index 662b2c11d3..eafdf714ce 100644 --- a/angularjs/angular-route.d.ts +++ b/angularjs/angular-route.d.ts @@ -35,6 +35,16 @@ declare module angular.route { // May not always be available. For instance, current will not be available // to a controller that was not initialized as a result of a route maching. current?: ICurrentRoute; + + /** + * Causes $route service to update the current URL, replacing current route parameters with those specified in newParams. + * Provided property names that match the route's path segment definitions will be interpolated into the + * location's path, while remaining properties will be treated as query params. + * + * @param newParams Object. mapping of URL parameter names to values + */ + updateParams(newParams:{[key:string]:string}): void; + } @@ -118,6 +128,12 @@ declare module angular.route { } interface IRouteProvider extends IServiceProvider { + /** + * Match routes without being case sensitive + * + * This option defaults to false. If the option is set to true, then the particular route can be matched without being case sensitive + */ + caseInsensitiveMatch?: boolean; /** * Sets route definition that will be used on route change when no other route definition is matched. * diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index a489141d54..97477e9a81 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -165,7 +165,7 @@ declare module angular { dot: number; codeName: string; }; - + /** * If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called. * @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with. @@ -181,6 +181,13 @@ declare module angular { animation(name: string, animationFactory: Function): IModule; animation(name: string, inlineAnnotatedFunction: any[]): IModule; animation(object: Object): IModule; + /** + * Use this method to register a component. + * + * @param name The name of the component. + * @param options A definition object passed into the component. + */ + component(name: string, options: IComponentOptions): IModule; /** * Use this method to register work which needs to be performed on module loading. * @@ -1620,6 +1627,29 @@ declare module angular { totalPendingRequests: number; } + /////////////////////////////////////////////////////////////////////////// + // Component + // 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/ + /////////////////////////////////////////////////////////////////////////// + + interface IComponentOptions { + bindings?: Object; + controller?: string | Function; + controllerAs?: string; + isolate?: boolean; + template?: string | IComponentTemplateFn; + templateUrl?: string | IComponentTemplateFn; + transclude?: boolean; + restrict?: string; + $canActivate?: Function; + $routeConfig?: Object; + } + + interface IComponentTemplateFn { + ( $element?: IAugmentedJQuery, $attrs?: IAttributes ): string; + } + /////////////////////////////////////////////////////////////////////////// // Directive // see http://docs.angularjs.org/api/ng.$compileProvider#directive diff --git a/angulartics/angulartics.d.ts b/angulartics/angulartics.d.ts index edb9aefb3d..fdcb409ca2 100644 --- a/angulartics/angulartics.d.ts +++ b/angulartics/angulartics.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angulartics v0.19.2 +// Type definitions for Angulartics v0.20.2 // Project: http://luisfarzati.github.io/angulartics/ // Definitions by: Steven Fan // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -21,6 +21,7 @@ declare module angulartics { interface IAnalyticsServiceProvider extends angular.IServiceProvider { virtualPageviews(value: boolean): void; + excludeRoutes(value: string[]): void; firstPageview(value: boolean): void; withBase(value: boolean): void; withAutoBase(value: boolean): void; diff --git a/api-error-handler/api-error-handler-tests.ts b/api-error-handler/api-error-handler-tests.ts index 83df91e862..fc92cf9a70 100644 --- a/api-error-handler/api-error-handler-tests.ts +++ b/api-error-handler/api-error-handler-tests.ts @@ -1,7 +1,7 @@ /// -import errorHandler = require('api-error-handler'); -import express = require('express'); +import * as errorHandler from 'api-error-handler'; +import * as express from 'express'; var api = express.Router(); api.get('/users/:userid', function (req, res, next) { @@ -9,3 +9,5 @@ api.get('/users/:userid', function (req, res, next) { }); api.use(errorHandler()); + +let res: errorHandler.Response; diff --git a/api-error-handler/api-error-handler.d.ts b/api-error-handler/api-error-handler.d.ts index 61a63825d9..90318acd00 100644 --- a/api-error-handler/api-error-handler.d.ts +++ b/api-error-handler/api-error-handler.d.ts @@ -6,7 +6,23 @@ /// declare module 'api-error-handler' { - import express = require('express'); + import * as express from 'express'; + + namespace apiErrorHandler { + + // Body response: the JSON returned by api-error-handler + // See https://github.com/expressjs/api-error-handler/blob/1.0.0/index.js + interface Response { + status: number; + stack?: string; + message: string; + + // Client errors + code?: any; + name?: string; + type?: any; + } + } function apiErrorHandler(options?: any): express.ErrorRequestHandler; diff --git a/arcgis-js-api/arcgis-js-api.d.ts b/arcgis-js-api/arcgis-js-api.d.ts index ba5e0fb9f4..88d68cb19f 100644 --- a/arcgis-js-api/arcgis-js-api.d.ts +++ b/arcgis-js-api/arcgis-js-api.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ArcGIS API for JavaScript v3.14 +// Type definitions for ArcGIS API for JavaScript v3.15 // Project: http://js.arcgis.com // Definitions by: Esri // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -146,7 +146,7 @@ declare module "esri" { /** Class attribute to set for the layer's node. */ className?: string; /** Lists which levels to draw. */ - displayLevels?: number; + displayLevels?: number[]; /** An array of objects that define areas where a tiled map service should not display tiles. */ exclusionAreas?: any[]; /** Id to assign to the layer. */ @@ -157,7 +157,7 @@ declare module "esri" { opacity?: number; /** Refresh interval of the layer in minutes. */ refreshInterval?: number; - /** When true, tile resampling is enabled. */ + /** The purpose of resampling is to enlarge the image and fill in at the levels where there are no tiles available. */ resampling?: boolean; /** Number of levels beyond the last level where tiles are available. */ resamplingTolerance?: number; @@ -215,6 +215,8 @@ declare module "esri" { opacity?: number; /** Specify subDomains where tiles are served to speed up tile retrieval (using subDomains gets around the browser limit of the max number of concurrent requests to a domain). */ subDomains?: string[]; + /** The URL template used to retrieve the tiles. */ + templateUrl?: string; /** Define the tile info for the layer including lods, rows, cols, origin and spatial reference. */ tileInfo?: TileInfo; /** Define additional tile server domains for the layer. */ @@ -307,19 +309,15 @@ declare module "esri" { export interface ClassedColorSliderOptions { /** Data map containing renderer information. */ breakInfos: any; - /** Classification method. */ + /** Indicates the classification method used to divide the range of values into bins. */ classificationMethod?: string; - /** Handles identified by their index values within the stops array. */ + /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Represents histogram data object. */ + /** Represents the histogram data object. */ histogram?: any; /** Width of the histogram in pixels. */ histogramWidth?: number; - /** Absolute maximum value of the slider. */ - maxValue?: number; - /** Absolute minimum value of the slider. */ - minValue?: number; - /** Normalization type. */ + /** Indicates how data values are normalized. */ normalizationType?: string; /** Handle identified by its index value within the stops array. */ primaryHandle?: number; @@ -333,61 +331,51 @@ declare module "esri" { showLabels?: boolean; /** Displays ticks on slider when true. */ showTicks?: boolean; - /** Represents statistics data object. */ + /** Represents the statistics data object. */ statistics?: any; } export interface ClassedSizeSliderOptions { - /** Data map containing renderer information. */ + /** The data map containing renderer information. */ breakInfos: any; - /** Classification method. */ + /** Optional: Indicates the classification method used to divide the range of values into bins. */ classificationMethod?: string; - /** Handles identified by their index values within the stops array. */ + /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Represents histogram data object. */ + /** Represents the histogram data object. */ histogram?: any; /** Width of histogram in pixels. */ histogramWidth?: number; - /** Absolute maximum value of the slider. */ - maxValue?: number; - /** Absolute minimum value of the slider. */ - minValue?: number; - /** Normalization type. */ + /** Indicates how data values are normalized. */ normalizationType?: string; - /** Handle identified by its index value within the stops array. */ + /** The handle identified by its index value within the stops array. */ primaryHandle?: number; /** Width of slider ramp in pixels. */ rampWidth?: number; /** Displays slider handles when true. */ showHandles?: boolean; - /** Displays the histogram when true. */ + /** Indicates whether to display the histogram. */ showHistogram?: boolean; /** Displays labels when true. */ showLabels?: boolean; /** Displays slider ticks when true. */ showTicks?: boolean; - /** Represents statistics data object. */ + /** Optional: Represents the statistics data object. */ statistics?: any; - /** Indicates whether to use a circle or line-based ClassedSizeSlider. */ - symbol?: any; } export interface ColorInfoSliderOptions { - /** Classification method. */ - classificationMethod?: string; - /** Data map containing renderer information. */ + /** The data map containing renderer information. */ colorInfo: any; /** Handles identified by their index values within the stops array. */ handles: number[]; - /** Represents histogram data object. */ + /** Optional: Represents the histogram data object. */ histogram?: any; /** Width of histogram in pixels. */ histogramWidth?: number; - /** Absolute maximum value of slider. */ + /** The absolute maximum value of the slider. */ maxValue?: number; - /** Absolute minimum value of slider. */ + /** The absolute minimum value of the slider. */ minValue?: number; - /** Normalization Type. */ - normalizationType?: string; - /** Handle identified by its index value within the stops array. */ + /** The handle identified by its index value within the stops array. */ primaryHandle?: number; /** Width of widget ramp in pixels. */ rampWidth?: number; @@ -397,13 +385,15 @@ declare module "esri" { showHistogram?: boolean; /** Displays labels when set to true. */ showLabels?: boolean; - /** Displays ticks when set to true. */ + /** Indicates whether to display percentage labels. */ + showRatioLabels?: boolean | string; + /** Displays tick marks when set to true. */ showTicks?: boolean; /** Displays transparent background when set to true. */ showTransparentBackground?: boolean; - /** Represents statistics data object. */ + /** Represents a statistics data object. */ statistics?: any; - /** Object containing additional options. */ + /** Additional options to customize slider. */ zoomOptions?: any; } export interface ColorPickerOptions { @@ -655,8 +645,6 @@ declare module "esri" { traffic?: boolean; /** The traffic layer used for real-time traffic. */ trafficLayer?: ArcGISDynamicMapServiceLayer; - /** An example of when to use this is when working with a proxied ArcGIS Online route service item with stored credentials. */ - travelModesServiceUrl?: string; } export interface DissolveBoundariesOptions { /** The URL to the GPServer used to execute an analysis job. */ @@ -718,7 +706,7 @@ declare module "esri" { /** Specifies whether users can add new vertices. */ allowAddVertices?: boolean; /** Specifies whether users can delete vertices. */ - allowDeletevertices?: boolean; + allowDeleteVertices?: boolean; /** Line symbol used to draw the guild lines, displayed when moving vertices. */ ghostLineSymbol?: LineSymbol; /** Marker symbol used to display the insertable vertices. */ @@ -859,8 +847,14 @@ declare module "esri" { cellNavigation?: boolean; /** Object defining the date options specifically for formatting date and time editors. */ dateOptions?: any; + /** Allows selection of a table's row via clicking a feature on the map. */ + enableLayerClick?: boolean; + /** Allows selection of a feature on a map via clicking row in the table. */ + enableLayerSelection?: boolean; /** The featureLayer that the table is associated with. */ featureLayer: FeatureLayer; + /** Reference to the 'Options' drop-down menu. */ + gridMenu?: any; /** Columns to hide by default using the dGrid ColumnHider extension. */ hiddenFields?: string[]; /** A reference to the Map. */ @@ -1173,8 +1167,12 @@ declare module "esri" { map: Map; /** Indicates whether to remove underscores from the layer title. */ removeUnderscores?: boolean; + /** Indicates whether to display a legend for the layer items. */ + showLegend?: boolean; + /** Indicates whether to display the opacity slider. */ + showOpacitySlider?: boolean; /** Indicates whether to show sublayers in the list of layers. */ - subLayers?: boolean; + showSubLayers?: boolean; /** The CSS class selector used to uniquely style the widget. */ theme?: string; /** Indicates whether to show the LayerList widget. */ @@ -1455,19 +1453,19 @@ declare module "esri" { export interface OpacitySliderOptions { /** Handles identified by their index values within the stops array. */ handles: number[]; - /** Represents histogram data object. */ + /** Represents the histogram data object. */ histogram?: any; /** Width of histogram in pixels. */ histogramWidth?: number; - /** Absolute maximum value of the slider. */ + /** The absolute maximum value of the slider. */ maxValue?: number; - /** Absolute minimum value of the slider. */ + /** The absolute minimum value of the slider. */ minValue?: number; - /** Data map containing renderer information. */ + /** The data map containing renderer information. */ opacityInfo: any; - /** Handle identified by its index value within the stops array. */ + /** The handle identified by its index value within the stops array. */ primaryHandle?: number; - /** Width of slider ramp in pixels. */ + /** Represents the width of the SVG ramp in pixels. */ rampWidth?: number; /** Displays slider handles when true. */ showHandles?: boolean; @@ -1479,9 +1477,9 @@ declare module "esri" { showTicks?: boolean; /** Displays the transparent background when true. */ showTransparentBackground?: boolean; - /** Represents statistics data object. */ + /** Represents a statistics data object. */ statistics?: any; - /** Additional options for slider customization. */ + /** Additional options to customize slider. */ zoomOptions?: any; } export interface OpenStreetMapLayerOptions { @@ -1699,7 +1697,7 @@ declare module "esri" { minimum: number; /** Bottom label for the slider. */ minLabel?: string; - /** **CHECK THIS: Is it num of dec places? - Accuracy of the data (related to rounding). */ + /** Accuracy of the data (related to rounding). */ precision?: number; /** Primary handle identified by its index value within the related infos array (color, size, break). */ primaryHandle?: number; @@ -1737,9 +1735,11 @@ declare module "esri" { activeSourceIndex?: number | string; /** Indicates whether to automatically add all the feature layers from the map. */ addLayersFromMap?: boolean; + /** This is the default value used as a hint for input text when searching on multiple sources. */ + allPlaceholder?: string; /** Indicates whether to automatically navigate to the selected result. */ autoNavigate?: boolean; - /** Indicates whether to automatically select the first result. */ + /** Indicates whether to automatically select the first geocoded result (not the first suggestion). */ autoSelect?: boolean; /** Indicates whether to enable an option to collapse/expand the search into a button. */ enableButtonMode?: boolean; @@ -1749,6 +1749,8 @@ declare module "esri" { enableInfoWindow?: boolean; /** Indicates whether to enable showing a label for the geometry.The default value is false. */ enableLabel?: boolean; + /** Indicates whether to display the option to search "All" sources. */ + enableSearchingAll?: boolean; /** Indicates whether to enable the menu for selecting different sources. */ enableSourcesMenu?: boolean; /** Indicates whether or not to enable suggest on the widget. */ @@ -1765,7 +1767,7 @@ declare module "esri" { infoTemplate?: InfoTemplate; /** The text symbol for the label graphic. */ labelSymbol?: TextSymbol; - /** The default distance specified in meters used to reverse geocode, (if not specified by source).The default value is 1500. */ + /** The default distance specified in meters used to reverse geocode, (if not specified by source). */ locationToAddressDistance?: number; /** Reference to the map. */ map?: Map; @@ -1791,23 +1793,19 @@ declare module "esri" { zoomScale?: number; } export interface SizeInfoSliderOptions { - /** Classification method. */ - classificationMethod?: string; /** Handles identified by their index values within the stops array. */ handles: number[]; - /** Represents histogram data object. */ + /** Represents the histogram data object. */ histogram?: any; /** Width of the histogram in pixels. */ histogramWidth?: number; - /** Absolute maximum value of the slider. */ + /** The absolute maximum value of the slider. */ maxValue?: number; - /** Absolute minimum value of the slider. */ + /** The absolute minimum value of the slider. */ minValue?: number; - /** Normalization type. */ - normalizationType?: string; - /** Handle identified by its index value within the stops array. */ + /** The handle identified by its index value within the stops array. */ primaryHandle?: number; - /** Width of slider ramp in pixels. */ + /** Represents the width of the SVG ramp in pixels. */ rampWidth?: number; /** Displays slider handles when true. */ showHandles?: boolean; @@ -1817,11 +1815,11 @@ declare module "esri" { showLabels?: boolean; /** Displays slider ticks when true. */ showTicks?: boolean; - /** Data map containing renderer information. */ + /** Defines the size of the symbol where feature size is proportional to data value. */ sizeInfo: any; - /** Represents statistics data object. */ + /** Represents the statistics data object. */ statistics?: any; - /** The symbol used with the widget. */ + /** The SimpleLineSymbol or SimpleMarkerSymbol used with the widget. */ symbol: Symbol; /** Additional options to customize slider. */ zoomOptions?: any; @@ -1969,10 +1967,12 @@ declare module "esri" { sumWithinLayer: FeatureLayer; } export interface SymbolStylerOptions { + /** Added at v. */ + portal?: string | any; /** Self response of Portal used as symbol provider. */ - portalSelf: string; + portalSelf?: any; /** URL to Portal used as symbol provider. */ - portalUrl: string; + portalUrl?: string; } export interface TemplatePickerOptions { /** Number of visible columns. */ @@ -2062,6 +2062,18 @@ declare module "esri" { /** A predefined style. */ style?: string; } + export interface VectorTileLayerOptions { + /** Lists which levels of the layer to draw. */ + displayLevels?: number[]; + /** Maximum visible scale for the layer. */ + maxScale?: number; + /** Minimum visible scale for the layer. */ + minScale?: number; + /** Initial opacity or transparency of layer. */ + opacity?: number; + /** Visibility of the layer. */ + visible?: boolean; + } export interface VisibleScaleRangeSliderOptions { /** Layer used to determine the suggested scale range and set the minScale, maxScale values. */ layer: FeatureLayer; @@ -2275,7 +2287,7 @@ declare module "esri/IdentityManager" { /** Dialog box widget used to challenge the user for their credentials when the application attempts to access a secure resource. */ dialog: any; /** - * When accessing secure resources via Oauth2 from ArcGIS.com or one of its sub-domains the IdentityManager redirects the user to the ArcGIS.com or Portal for ArcGIS sign-in page. + * When accessing secure resources via OAuth2 from ArcGIS.com or one of its sub-domains the IdentityManager redirects the user to the ArcGIS.com or Portal for ArcGIS sign-in page. * @param handlerFunction When called, the function passed to setOAuthRedirectionHandler receives an object containing the redirection properties. */ setOAuthRedirectionHandler(handlerFunction: Function): void; @@ -2391,7 +2403,7 @@ declare module "esri/IdentityManagerBase" { /** Return properties of this object in JSON. */ toJson(): any; /** Fired when a credential is created. */ - on(type: "credential-create", listener: (event: { target: IdentityManagerBase }) => void): esri.Handle; + on(type: "credential-create", listener: (event: { credential: Credential; target: IdentityManagerBase }) => void): esri.Handle; /** Fired when all credentials are destroyed. */ on(type: "credentials-destroy", listener: (event: { target: IdentityManagerBase }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; @@ -2675,7 +2687,7 @@ declare module "esri/arcgis/OAuthInfo" { minTimeUntilExpiration: number; /** Set to true to show the OAuth sign in page in a popup window. */ popup: boolean; - /** The relative page URL for the user to be sent to from the OAuth sign in page. */ + /** Applicable if working with the popup user-login workflow. */ popupCallbackUrl: string; /** The window features passed to window.open(). */ popupWindowFeatures: string; @@ -2886,7 +2898,7 @@ declare module "esri/arcgis/Portal" { /** The date the group was last modified. */ modified: Date; /** The username of the group's owner. */ - owner: Portal; + owner: string; /** The portal for the group. */ portal: Portal; /** A short summary that describes the group. */ @@ -3062,7 +3074,7 @@ declare module "esri/arcgis/Portal" { * Retrieve all the items in the specified folder. * @param folderId The id of the folder that contains the items to retrieve. */ - getItems(folderId: string): any; + getItems(folderId?: string): any; /** Get information about any notifications for the portal user. */ getNotifications(): any; /** Access the tag objects that have been created by the portal user. */ @@ -3087,6 +3099,11 @@ declare module "esri/arcgis/utils" { * @param itemId The itemId for a publicly shared ArcGIS.com item. */ getItem(itemId: string): any; + /** + * Can be used with LayerList widget to get the layers list to be passed into the constructor. + * @param createMapResponse The object created from the resolved promise returned by createMap(). + */ + getLayerList(createMapResponse: any): any[]; /** * Can be used with esri.dijit.Legend to get the layerInfos list to be passed into the Legend constructor. * @param createMapResponse Object returned by .createMap() in the .then() callback. @@ -3422,37 +3439,35 @@ declare module "esri/dijit/ClassedColorSlider" { /** A widget to assist with managing a renderer used for visualizing features by their class and color. */ class ClassedColorSlider extends RendererSlider { - /** Required */ + /** Required: The data map containing renderer information. */ breakInfos: any; - /** Optional */ + /** Optional: Indicates the classification method used to divide the range of values into bins. */ classificationMethod: string; /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Optional: Property representing histogram data object. */ + /** Optional: Represents the histogram data object. */ histogram: any; - /** Optional */ + /** Optional: The width of the histogram in pixels. */ histogramWidth: boolean; - /** Optional */ + /** Read Only. */ maxValue: number; - /** Optional */ + /** Read Only. */ minValue: number; - /** Optional */ + /** Optional: Indicates how data values are normalized. */ normalizationType: string; - /** Optional: Handle identified by its index value within the stops array. */ + /** Optional: The handle identified by its index value within the stops array. */ primaryHandle: number; - /** Optional */ + /** Optional: Width of the widget ramp in pixels. */ rampWidth: number; - /** Property for showing handles. */ + /** Optional: Indicates whether to display handles. */ showHandles: boolean; - /** Optional: Property for displaying the histogram. */ + /** Optional: Indicates whether to display the histogram. */ showHistogram: boolean; - /** Property for showing labels. */ + /** Optional: Indicates whether to display labels. */ showLabels: boolean; - /** Property for showing ticks. */ + /** Optional: Indicates whether to display tick marks. */ showTicks: boolean; - /** Property for displaying the transparent background. */ - showTransparentBackground: boolean; - /** Optional: Property representing statistics data object. */ + /** Optional: Represents the statistics data object. */ statistics: any; /** * Creates a new ClassedColorSlider widget. @@ -3464,7 +3479,7 @@ declare module "esri/dijit/ClassedColorSlider" { startup(): void; /** Fires when the ClassedColorSlider widget properties change. */ on(type: "change", listener: (event: { breakInfos: any; target: ClassedColorSlider }) => void): esri.Handle; - /** Fires when minValue or maxValue of ClassedColorSlider changes. */ + /** Fires when minValue or maxValue of the ClassedColorSlider changes. */ on(type: "data-value-change", listener: (event: { breakInfos: any; maxValue: number; minValue: number; target: ClassedColorSlider }) => void): esri.Handle; /** Fires when a ClassedColorSlider handle is moved. */ on(type: "handle-value-change", listener: (event: { breakInfos: any; target: ClassedColorSlider }) => void): esri.Handle; @@ -3479,35 +3494,35 @@ declare module "esri/dijit/ClassedSizeSlider" { /** A widget to assist with managing a renderer for visualizing features by varying classes and size. */ class ClassedSizeSlider extends RendererSlider { - /** Required. */ + /** Required: The data map containing renderer information. */ breakInfos: any; - /** Optional. */ + /** Optional: Indicates the classification method used to divide the range of values into bins. */ classificationMethod: string; - /** Required. */ + /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Optional. */ + /** Optional: Represents the histogram data object. */ histogram: any; - /** Optional. */ - histogramWidth: boolean; - /** Optional. */ + /** Optional: Width of histogram in pixels. */ + histogramWidth: number; + /** Read Only. */ maxValue: number; - /** Optional. */ + /** Read Only. */ minValue: number; - /** Optional. */ + /** Optional: Indicates how data values are normalized. */ normalizationType: string; - /** Optional. */ + /** Optional: Handle identified by its index value within the stops array. */ primaryHandle: number; - /** Optional */ + /** Optional: Width of the widget ramp in pixels. */ rampWidth: number; - /** Property for showing handles. */ + /** Optional: Indicates whether to display handles. */ showHandles: boolean; - /** Optional. */ + /** Optional: Indicates whether to display the histogram. */ showHistogram: boolean; - /** Property for showing labels. */ + /** Optional: Indicates whether to display labels. */ showLabels: boolean; - /** Property for showing ticks. */ + /** Optional: Indicates whether to display ticks marks. */ showTicks: boolean; - /** Optional. */ + /** Optional: Represents the statistics data object. */ statistics: any; /** * Creates a new ClassedSizeSlider widget within the provided DOM node srcNodeRef. @@ -3517,7 +3532,7 @@ declare module "esri/dijit/ClassedSizeSlider" { constructor(params: esri.ClassedSizeSliderOptions, srcNodeRef: Node | string); /** Fires when ClassedSizeSlider changes. */ on(type: "change", listener: (event: { breakInfos: any; target: ClassedSizeSlider }) => void): esri.Handle; - /** Fires when minValue or maxValue changes in ClassedSizeSlider. */ + /** Fires when minValue or maxValue of the ClassedSizeSlider changes. */ on(type: "data-value-change", listener: (event: { breakInfos: any; maxValue: number; minValue: number; target: ClassedSizeSlider }) => void): esri.Handle; /** Fires when a ClassedSizeSlider handle is moved. */ on(type: "handle-value-change", listener: (event: { breakInfos: any; target: ClassedSizeSlider }) => void): esri.Handle; @@ -3532,39 +3547,41 @@ declare module "esri/dijit/ColorInfoSlider" { /** A widget to assist with managing a renderer for visualizing features based upon colors. */ class ColorInfoSlider extends RendererSlider { - /** Optional */ + /** The classification method used for the ColorInfoSlider. */ classificationMethod: string; - /** Required: Example colorInfo: colorRenderer.renderer.visualVariables[0]. */ + /** Required: The data map containing renderer information. */ colorInfo: any; /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Optional: Property representing histogram data object. */ + /** Optional: Represents the histogram data object. */ histogram: any; - /** Optional */ - histogramWidth: boolean; - /** Optional */ + /** Optional: Width of histogram in pixels. */ + histogramWidth: number; + /** Optional: The absolute maximum value of the slider. */ maxValue: number; - /** Optional */ + /** Optional: The absolute minimum value of the slider. */ minValue: number; /** Optional */ normalizationType: string; - /** Optional: Handle identified by its index value within the stops array. */ + /** Optional: The handle identified by its index value within the stops array. */ primaryHandle: number; - /** Optional */ + /** Optional: Width of the widget ramp in pixels. */ rampWidth: number; - /** Property for showing handles. */ + /** Optional: Indicates whether to display handles. */ showHandles: boolean; - /** Optional: Property for displaying the histogram. */ + /** Optional: Indicates whether to display the histogram. */ showHistogram: boolean; - /** Property for showing labels. */ + /** Optional: Indicates whether to display handles. */ showLabels: boolean; - /** Property for showing ticks. */ + /** Indicates whether to display percentage labels. */ + showRatioLabels: boolean | string; + /** Optional: Indicates whether to display ticks marks. */ showTicks: boolean; - /** Property for displaying the transparent background. */ + /** Optional: Indicates whether to display a transparent background. */ showTransparentBackground: boolean; - /** Optional: Property representing statistics data object. */ + /** Optional: Represents a statistics data object. */ statistics: any; - /** Optional */ + /** Optional: Additional options to customize slider. */ zoomOptions: any; /** * Creates a new ColorInfoSlider widget within the provided DOM node srcNodeRef. @@ -3576,10 +3593,12 @@ declare module "esri/dijit/ColorInfoSlider" { startup(): void; /** Fires when ColorInfoSlider changes. */ on(type: "change", listener: (event: { colorInfo: any; target: ColorInfoSlider }) => void): esri.Handle; - /** Fires when minValue or maxValue of ColorInfoSlider changes. */ + /** Fires when minValue or maxValue of the ColorInfoSlider changes. */ on(type: "data-value-change", listener: (event: { colorInfo: any; maxValue: number; minValue: number; target: ColorInfoSlider }) => void): esri.Handle; /** Fires when a ColorInfoSlider handle is moved. */ - on(type: "handle-value-change", listener: (event: { target: ColorInfoSlider }) => void): esri.Handle; + on(type: "handle-value-change", listener: (event: { colorInfo: any; target: ColorInfoSlider }) => void): esri.Handle; + /** Fires when the zoom state changes. */ + on(type: "zoomed", listener: (event: { zoomed: boolean; target: ColorInfoSlider }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; } export = ColorInfoSlider; @@ -3765,6 +3784,8 @@ declare module "esri/dijit/ElevationProfile" { measureUnits: string; /** The polyline input geometry used to create the elevation profile. */ profileGeometry: Geometry; + /** The title of the resulting elevation profile. */ + title: string; /** * Create a new ElevationProfile widget using the given DOM node. * @param options See options table below for the full descriptions of the properties needed for this object. @@ -3781,6 +3802,8 @@ declare module "esri/dijit/ElevationProfile" { on(type: "clear-profile", listener: (event: { target: ElevationProfile }) => void): esri.Handle; /** Fires when the widget has fully loaded. */ on(type: "load", listener: (event: { target: ElevationProfile }) => void): esri.Handle; + /** Fires when the title of the elevation profile is changed */ + on(type: "title-changed", listener: (event: { target: ElevationProfile }) => void): esri.Handle; /** Fires when the elevation profile is updated. */ on(type: "update-profile", listener: (event: { profileResults: any; target: ElevationProfile }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; @@ -3793,7 +3816,7 @@ declare module "esri/dijit/FeatureTable" { import FeatureLayer = require("esri/layers/FeatureLayer"); import Map = require("esri/map"); - /** (Currently in beta) Creates an instance of the FeatureTable widget within the provided DOM node. */ + /** Creates an instance of the FeatureTable widget within the provided DOM node. */ class FeatureTable { /** An optional dGrid property. */ allowSelectAll: boolean; @@ -3805,10 +3828,16 @@ declare module "esri/dijit/FeatureTable" { dataStore: any; /** Object defining the date options specifically for formatting date and time editors. */ dateOptions: any; + /** Allows selection of a table's row via clicking a feature on the map. */ + enableLayerClick: boolean; + /** Allows selection of a feature on a map via clicking row in the table. */ + enableLayerSelection: boolean; /** The featureLayer that the table is associated with. */ featureLayer: FeatureLayer; /** Reference to the dGrid. */ grid: any; + /** Reference to the 'Options' drop-down menu. */ + gridMenu: any; /** Optional columns to hide by default using the dGrid ColumnHider extension. */ hiddenFields: string[]; /** A reference to the primary key used by the dataStore to differentiate columns. */ @@ -4004,15 +4033,15 @@ declare module "esri/dijit/HeatmapSlider" { import esri = require("esri"); import RendererSlider = require("esri/dijit/RendererSlider"); - /** A widget to assist in managing properties of a HeatmapRenderer. */ + /** A widget to assist in obtaining values for managing and setting properties on a HeatmapRenderer. */ class HeatmapSlider extends RendererSlider { /** Required. */ colorStops: any; /** Required. */ handles: number[]; - /** Optional. */ + /** Optional, absolute maximum value of the slider.NOTE: This value overrides statistics' max property. */ maxValue: number; - /** Optional. */ + /** Optional, absolute minimum value of the slider.NOTE: This value overrides statistics' min property. */ minValue: number; /** Optional */ rampWidth: number; @@ -4127,6 +4156,7 @@ declare module "esri/dijit/ImageServiceMeasure" { import SimpleFillSymbol = require("esri/symbols/SimpleFillSymbol"); import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); + import ImageServiceMeasureTool = require("esri/toolbars/ImageServiceMeasureTool"); /** This widget allows you to perform measurements on image services. */ class ImageServiceMeasure { @@ -4136,6 +4166,8 @@ declare module "esri/dijit/ImageServiceMeasure" { lineSymbol: SimpleLineSymbol; /** Symbol to be used when drawing a point. */ markerSymbol: SimpleMarkerSymbol; + /** The instance of ImageServiceMeasureTool associated with this widget. */ + measureToolbar: ImageServiceMeasureTool; /** * Creates an instance of the ImageServiceMeasure widget. * @param params An Object containing constructor options. @@ -4294,8 +4326,12 @@ declare module "esri/dijit/LayerList" { map: Map; /** Indicates whether to remove underscores from the layer title */ removeUnderscores: boolean; + /** Indicates whether to display a legend for the layer items. */ + showLegend: boolean; + /** Indicates whether to display the opacity slider. */ + showOpacitySlider: boolean; /** Indicates whether to show sublayers in the list of layers. */ - sublayers: boolean; + showSubLayers: boolean; /** CSS Class for uniquely styling the widget. */ theme: string; /** Indicates whether to show the widget. */ @@ -4314,7 +4350,7 @@ declare module "esri/dijit/LayerList" { startup(): void; /** Fired when the LayerList widget has fully loaded. */ on(type: "load", listener: (event: { target: LayerList }) => void): esri.Handle; - /** Fired when refresh is called on the LabelList widget. */ + /** Fired when refresh() is called on the widget. */ on(type: "refresh", listener: (event: { target: LayerList }) => void): esri.Handle; /** Fired when the layer is toggled on/off within the widget. */ on(type: "toggle", listener: (event: { layerIndex: number; subLayerIndex: number; visible: boolean; target: LayerList }) => void): esri.Handle; @@ -4622,33 +4658,35 @@ declare module "esri/dijit/OpacitySlider" { /** A widget to assist with managing opacity with a renderer. */ class OpacitySlider extends RendererSlider { - /** Required. */ + /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Optional. */ + /** Optional: Represents the histogram data object. */ histogram: any; - /** Optional: */ - histogramWidth: boolean; - /** Optional. */ + /** Optional: Width of histogram in pixels. */ + histogramWidth: number; + /** Optional: The absolute maximum value of the slider. */ maxValue: number; - /** Optional. */ + /** Optional: The absolute minimum value of the slider. */ minValue: number; - /** Required. */ + /** Required: The data map containing renderer information. */ opacityInfo: any; - /** Optional */ + /** Optional: The handle identified by its index value within the stops array. */ + primaryHandle: number; + /** Optional: Represents the width of the SVG ramp in pixels. */ rampWidth: number; - /** Property for showing handles. */ + /** Optional: Indicates whether to display slider handles. */ showHandles: boolean; - /** Optional. */ + /** Optional: Indicates whether to display the histogram. */ showHistogram: boolean; - /** Property for showing labels. */ + /** Optional: Indicates whether to display slider labels. */ showLabels: boolean; - /** Property for showing ticks. */ + /** Optional: Indicates whether to display slider tick marks. */ showTicks: boolean; - /** Property for displaying the transparent background. */ + /** Optional: Indicates whether to display the transparent background. */ showTransparentBackground: boolean; - /** Optional. */ + /** Optional: Represents a statistics data object. */ statistics: any; - /** Optional. */ + /** Optional: Additional options to customize slider. */ zoomOptions: any; /** * Creates a new OpacitySlider widget within the provided DOM node srcNodeRef. @@ -4658,10 +4696,12 @@ declare module "esri/dijit/OpacitySlider" { constructor(params: esri.OpacitySliderOptions, srcNodeRef: Node | string); /** Fires when OpacitySlider changes. */ on(type: "change", listener: (event: { opacityInfo: any; target: OpacitySlider }) => void): esri.Handle; - /** Fires when minValue or maxValue of OpacitySlider changes. */ + /** Fires when minValue or maxValue of the OpacitySlider changes. */ on(type: "data-value-change", listener: (event: { maxValue: number; minValue: number; opacityInfo: any; target: OpacitySlider }) => void): esri.Handle; /** Fires when an OpacitySlider handle is moved. */ on(type: "handle-value-change", listener: (event: { opacityInfo: any; target: OpacitySlider }) => void): esri.Handle; + /** Fires when the zoom state changes. */ + on(type: "zoomed", listener: (event: { zoomed: boolean; target: OpacitySlider }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; } export = OpacitySlider; @@ -4985,7 +5025,7 @@ declare module "esri/dijit/RendererSlider" { showLabels: boolean | string[]; /** Toggle for showing the horizontal line indicators from the center of the handle. */ showTicks: boolean; - /** Handle positions represented as numbers that fall between minimum and maximum. */ + /** Required: Handle positions represented as numbers that fall between minimum and maximum. */ values: number[]; /** * Creates a new RendererSlider widget. @@ -5044,10 +5084,14 @@ declare module "esri/dijit/Search" { activeSourceIndex: number; /** Indicates whether to automatically add all the feature layers from the map. */ addLayersFromMap: boolean; + /** This is the default value used as a hint for input text when searching on multiple sources. */ + allPlaceholder: string; /** Indicates whether to automatically navigate to the selected result. */ autoNavigate: boolean; - /** Indicates whether to automatically select and zoom to the first geocoded result. */ + /** Indicates whether to automatically select the first geocoded result. */ autoSelect: boolean; + /** (Read-only), the default source used for the Search widget. */ + defaultSource: any; /** Indicates whether to enable an option to collapse/expand the search into a button. */ enableButtonMode: boolean; /** Show the selected feature on the map using a default symbol determined by the source's geometry type. */ @@ -5056,6 +5100,8 @@ declare module "esri/dijit/Search" { enableInfoWindow: boolean; /** Indicates whether to enable showing a label for the geometry. */ enableLabel: boolean; + /** Indicates whether to display the option to search "All" sources. */ + enableSearchingAll: boolean; /** Indicates whether to enable the menu for selecting different sources. */ enableSourcesMenu: boolean; /** Enable suggestions for the widget. */ @@ -5150,8 +5196,8 @@ declare module "esri/dijit/Search" { /** Finalizes the creation of the Search widget. */ startup(): void; /** - * Performs a suggest() request on the active Locator. - * @param value The string value used to suggest() on an active Locator. + * Performs a suggest() request on the active Locator or feature layer. + * @param value The string value used to suggest() on an active locator or feature layer. */ suggest(value?: string): any; /** Fired when the widget's text input loses focus. */ @@ -5176,39 +5222,44 @@ declare module "esri/dijit/Search" { declare module "esri/dijit/SizeInfoSlider" { import esri = require("esri"); import RendererSlider = require("esri/dijit/RendererSlider"); + import SimpleMarkerSymbol = require("esri/symbols/SimpleMarkerSymbol"); + import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol"); + /** A widget to assist with managing size with a renderer. */ class SizeInfoSlider extends RendererSlider { - /** Optional. */ + /** Optional, the classification method used for the SizeInfoSlider. */ classificationMethod: string; - /** Required. */ + /** Required: Handles identified by their index values within the stops array. */ handles: number[]; - /** Optional. */ + /** Optional: Represents the histogram data object. */ histogram: any; - /** Optional. */ - histogramWidth: boolean; - /** Optional. */ + /** Optional: Width of the histogram in pixels. */ + histogramWidth: number; + /** Optional: The absolute maximum value of the slider. */ maxValue: number; - /** Optional. */ + /** Optional: The absolute minimum value of the slider. */ minValue: number; - /** Optional. */ + /** Optional, indicates how data values are normalized. */ normalizationType: string; - /** Optional. */ + /** Optional: The handle identified by its index value within the stops array. */ primaryHandle: number; - /** Optional */ + /** Optional: Represents the width of the SVG ramp in pixels. */ rampWidth: number; - /** Property for showing handles. */ + /** Optional: Indicates whether to display slider handles. */ showHandles: boolean; - /** Optional. */ + /** Optional: Indicates whether to display the histogram. */ showHistogram: boolean; - /** Property for showing labels. */ + /** Optional: Indicates whether to display the slider labels. */ showLabels: boolean; - /** Property for showing ticks. */ + /** Optional: Indicates whether to display the slider tick marks. */ showTicks: boolean; - /** Required. */ + /** Required: Defines the size of the symbol where feature size is proportional to data value. */ sizeInfo: any; - /** Optional. */ + /** Optional: Represents the statistics data object. */ statistics: any; - /** Optional. */ + /** Required: The SimpleLineSymbol or SimpleMarkerSymbol used with the widget. */ + symbol: SimpleMarkerSymbol | SimpleLineSymbol; + /** Optional: Additional options to customize slider. */ zoomOptions: any; /** * Creates a new SizeInfoSlider widget. @@ -5220,10 +5271,12 @@ declare module "esri/dijit/SizeInfoSlider" { startup(): void; /** Fires when the SizeInfoSlider properties change. */ on(type: "change", listener: (event: { sizeInfo: any; target: SizeInfoSlider }) => void): esri.Handle; - /** Fires when minValue or maxValue of SizeInfoSlider change. */ + /** Fires when minValue or maxValue of the SizeInfoSlider changes. */ on(type: "data-value-change", listener: (event: { maxValue: number; minValue: number; sizeInfo: any; target: SizeInfoSlider }) => void): esri.Handle; /** Fires when a SizeInfoSlider handle is moved. */ on(type: "handle-value-change", listener: (event: { sizeInfo: any; target: SizeInfoSlider }) => void): esri.Handle; + /** Fires when the zoom state changes. */ + on(type: "zoomed", listener: (event: { zoomed: boolean; target: SizeInfoSlider }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; } export = SizeInfoSlider; @@ -6730,7 +6783,7 @@ declare module "esri/dijit/geoenrichment/DataBrowser" { export = DataBrowser; } -declare module "esri/dijit/geoenrichment/InfoGraphic" { +declare module "esri/dijit/geoenrichment/Infographic" { import esri = require("esri"); import GeometryStudyArea = require("esri/tasks/geoenrichment/GeometryStudyArea"); import RingBuffer = require("esri/tasks/geoenrichment/RingBuffer"); @@ -7451,13 +7504,13 @@ declare module "esri/geometry/geometryEngine" { import SpatialReference = require("esri/SpatialReference"); import Point = require("esri/geometry/Point"); - /** (Currently in beta) A client-side geometry engine. */ + /** A client-side geometry engine. */ var geometryEngine: { /** * Creates planar (or Euclidean) buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distance(s). + * @param unit Measurement unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ buffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): Polygon | Polygon[]; @@ -7495,7 +7548,7 @@ declare module "esri/geometry/geometryEngine" { * Densify geometries by plotting points between existing vertices. * @param geometry The geometry to be densified. * @param maxSegmentLength The maximum segment length allowed. - * @param maxSegmentLengthUnit Unit for the maximum segment length. + * @param maxSegmentLengthUnit Measurement unit for maxSegmentLength. */ densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit: string | number): Geometry; /** @@ -7514,7 +7567,7 @@ declare module "esri/geometry/geometryEngine" { * Calculates the shortest planar distance between two geometries. * @param geometry1 First input geometry. * @param geometry2 Second input geometry. - * @param distanceUnit Units of the return value. + * @param distanceUnit Measurement unit of the return value. */ distance(geometry1: Geometry, geometry2: Geometry, distanceUnit: string | number): number; /** @@ -7545,27 +7598,34 @@ declare module "esri/geometry/geometryEngine" { * @param geometry The geometry to be generalized. * @param maxDeviation The maximum allowed deviation from the generalized geometry to the original geometry. * @param removeDegenerateParts When true, the degenerate parts of the geometry will be removed from the output (may be undesired for drawing). - * @param maxDeviationUnit A unit for maximum deviation. + * @param maxDeviationUnit Measurement unit for maxDeviation. */ generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: string | number): Geometry; /** * Calculates the area of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ geodesicArea(geometry: Geometry, unit: string | number): number; /** * Creates geodesic buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distance(s). + * @param unit Measurement unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ geodesicBuffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): Polygon | Polygon[]; + /** + * Returns a geodesically densified version of the input geometry. + * @param geometry A polyline or polygon geometry to densify. + * @param maxSegmentLength The maximum segment length allowed. + * @param maxSegmentLengthUnit Measurement unit for maxSegmentLength. + */ + geodesicDensify(geometry: Polyline | Polygon, maxSegmentLength: number, maxSegmentLengthUnit?: number): Geometry; /** * Calculates the length of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ geodesicLength(geometry: Geometry, unit: string | number): number; /** @@ -7609,7 +7669,7 @@ declare module "esri/geometry/geometryEngine" { * Creates offset version of the input geometry. * @param geometry The geometries to offset. * @param offsetDistance The offset distance for the Geometries. - * @param offsetUnit Unit for the offset. + * @param offsetUnit Measurement unit for the offset. * @param joinType The join type. * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. @@ -7624,13 +7684,13 @@ declare module "esri/geometry/geometryEngine" { /** * Calculates the area of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ planarArea(geometry: Geometry, unit: string | number): number; /** * Calculates the length of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ planarLength(geometry: Geometry, unit: string | number): number; /** @@ -7685,14 +7745,15 @@ declare module "esri/geometry/geometryEngineAsync" { import Polyline = require("esri/geometry/Polyline"); import SpatialReference = require("esri/SpatialReference"); import Point = require("esri/geometry/Point"); + import Polygon = require("esri/geometry/Polygon"); - /** (Currently in beta) A client-side asynchronous geometry engine. */ + /** A client-side asynchronous geometry engine. */ var geometryEngineAsync: { /** * Creates planar (or Euclidean) buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distance(s). + * @param unit Measurement unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ buffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): any; @@ -7730,7 +7791,7 @@ declare module "esri/geometry/geometryEngineAsync" { * Densify geometries by plotting points between existing vertices. * @param geometry The geometry to be densified. * @param maxSegmentLength The maximum segment length allowed. - * @param maxSegmentLengthUnit Defaults to the units of the input geometries. + * @param maxSegmentLengthUnit Measurement unit for maxSegmentLength. */ densify(geometry: Geometry, maxSegmentLength: number, maxSegmentLengthUnit: string | number): any; /** @@ -7749,7 +7810,7 @@ declare module "esri/geometry/geometryEngineAsync" { * Calculates the shortest planar distance between two geometries. * @param geometry1 First input geometry. * @param geometry2 Second input geometry. - * @param distanceUnit Units of the return value. + * @param distanceUnit Measurement unit of the return value. */ distance(geometry1: Geometry, geometry2: Geometry, distanceUnit: string | number): any; /** @@ -7780,27 +7841,34 @@ declare module "esri/geometry/geometryEngineAsync" { * @param geometry The geometry to be generalized. * @param maxDeviation The maximum allowed deviation from the generalized geometry to the original geometry. * @param removeDegenerateParts When true, the degenerate parts of the geometry will be removed from the output (may be undesired for drawing). - * @param maxDeviationUnit Defaults to the units of the input geometries. + * @param maxDeviationUnit Measurement unit for maxDeviation. */ generalize(geometry: Geometry, maxDeviation: number, removeDegenerateParts?: boolean, maxDeviationUnit?: string | number): any; /** * Calculates the area of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ geodesicArea(geometry: Geometry, unit: string | number): any; /** * Creates geodesic buffer polygons at a specified distance around the input geometries. * @param geometry The buffer input geometry. * @param distance The specified distance(s) for buffering. - * @param unit Unit for the distance(s). + * @param unit Measurement unit for the distance(s). * @param unionResults Whether the output geometries should be unioned into a single polygon. */ geodesicBuffer(geometry: Geometry | Geometry[], distance: number | number[], unit: string | number, unionResults?: boolean): any; + /** + * Resolves to a geodesically densified version of the input geometry. + * @param geometry A polyline or polygon geometry to densify. + * @param maxSegmentLength The maximum segment length allowed. + * @param maxSegmentLengthUnit Measurement unit for maxSegmentLength. + */ + geodesicDensify(geometry: Polyline | Polygon, maxSegmentLength: number, maxSegmentLengthUnit?: number): any; /** * Calculates the length of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ geodesicLength(geometry: Geometry, unit: string | number): any; /** @@ -7844,7 +7912,7 @@ declare module "esri/geometry/geometryEngineAsync" { * Creates offset version of the input geometry. * @param geometry The geometries to offset. * @param offsetDistance The offset distance for the Geometries. - * @param offsetUnit Unit for the offset. + * @param offsetUnit Measurement unit for the offset. * @param joinType The join type. * @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled. * @param flattenError Applicable to ROUND, flattenError determines the maximum distance of the resulting segments compared to the true circular arc. @@ -7859,13 +7927,13 @@ declare module "esri/geometry/geometryEngineAsync" { /** * Calculates the area of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ planarArea(geometry: Geometry, unit: string | number): any; /** * Calculates the length of the input geometry. * @param geometry The input geometry. - * @param unit Units of the return value. + * @param unit Measurement unit of the return value. */ planarLength(geometry: Geometry, unit: string | number): any; /** @@ -9219,7 +9287,7 @@ declare module "esri/layers/FeatureLayer" { */ setAutoGeneralize(enable: boolean): FeatureLayer; /** - * Set's the definition expression for the FeatureLayer. + * Sets the definition expression for the FeatureLayer. * @param expression The definition expression to apply. */ setDefinitionExpression(expression: string): FeatureLayer; @@ -9275,7 +9343,7 @@ declare module "esri/layers/FeatureLayer" { */ setScaleRange(minScale: number, maxScale: number): void; /** - * Set's the selection symbol for the feature layer. + * Sets the selection symbol for the feature layer. * @param symbol Symbol for the current selection. */ setSelectionSymbol(symbol: Symbol): FeatureLayer; @@ -9285,7 +9353,7 @@ declare module "esri/layers/FeatureLayer" { */ setShowLabels(showLabels: boolean): void; /** - * Set's the time definition for the feature layer. + * Sets the time definition for the feature layer. * @param definition The new time extent used to filter the layer. */ setTimeDefinition(definition: TimeExtent): FeatureLayer; @@ -9458,6 +9526,8 @@ declare module "esri/layers/GeoRSSLayer" { items: Graphic[]; /** The name of the layer. */ name: string; + /** The publicly accessible URL to a GeoRSS file. */ + url: string; /** * Creates a new GeoRSSLayer object. * @param url URL to the GeoRSS resource. @@ -9805,10 +9875,14 @@ declare module "esri/layers/LOD" { declare module "esri/layers/LabelClass" { import TextSymbol = require("esri/symbols/TextSymbol"); - /** LabelClass defines the styles of labels for ArcGISDynamicMapServiceLayer. */ + /** Use label classes to restrict labels to certain features or to specify different label fields, symbols, scale ranges, label priorities, and sets of label placement options for different groups of labels. */ class LabelClass { + /** An array of objects representing field information to label. */ + fieldInfos: any[]; /** Adjusts the formatting of labels. */ labelExpression: string; + /** Use this when working with FeatureLayer layer types. */ + labelExpressionInfo: any; /** The position of the label. */ labelPlacement: string; /** The maximum scale to show labels. */ @@ -9824,7 +9898,7 @@ declare module "esri/layers/LabelClass" { /** A where clause determining which features are labeled. */ where: string; /** - * Create a LabelClass, in order to be added to layerDrawingOption.labelingInfo. + * Creates a label class, used for formatting parameters, symbols, date, etc. * @param json Various options to configure this LabelClass. */ constructor(json?: Object); @@ -9840,7 +9914,7 @@ declare module "esri/layers/LabelLayer" { import UniqueValueRenderer = require("esri/renderers/UniqueValueRenderer"); import ClassBreaksRenderer = require("esri/renderers/ClassBreaksRenderer"); - /** The LabelLayer inherits from the graphics layer and can be used to display texts and symbols on map. */ + /** NOTE: Deprecated as of version 3.14, read below for additional information on the suggested method of labeling. */ class LabelLayer extends GraphicsLayer { /** * Creates a new Label layer. @@ -10248,6 +10322,8 @@ declare module "esri/layers/RasterLayer" { /** The RasterLayer is used to display image services. */ class RasterLayer extends Layer { + /** A function that takes a pixelData object as input, processes it, and returns it. */ + pixelFilter: Function; /** * Creates a new RasterLayer object. * @param url URL to the ArcGIS Server REST resource that represents a raster layer service. @@ -10262,6 +10338,11 @@ declare module "esri/layers/RasterLayer" { * @param doNotRefresh Use true to avoid refreshing the layer; false to refresh it. */ setImageFormat(imageFormat: string, doNotRefresh?: boolean): void; + /** + * Sets a pixelFilter on the layer. + * @param pixelFilter The function defining the PixelFilter to set on the layer. + */ + setPixelFilter(pixelFilter: Function): void; /** * Determines if the layer will update its content based on the map's current time extent. * @param use Use true to update the layer's content based on the map's current time extent. @@ -10495,16 +10576,55 @@ declare module "esri/layers/TimeInfo" { } declare module "esri/layers/TimeReference" { - /** TimeReference contains information about how the time was measured. */ + /** TimeReference contains read-only information about how the time was captured when the data was created. */ class TimeReference { - /** Indicates whether the time reference respects daylight savings time. */ + /** A read-only property that indicates whether the time reference takes into account daylight savings time. */ respectsDaylightSaving: boolean; - /** The time zone information associated with the time reference. */ + /** The time zone in which the data was captured. */ timeZone: string; } export = TimeReference; } +declare module "esri/layers/VectorTileLayer" { + import esri = require("esri"); + import Layer = require("esri/layers/layer"); + import Extent = require("esri/geometry/Extent"); + import SpatialReference = require("esri/SpatialReference"); + import TileInfo = require("esri/layers/TileInfo"); + + /** A VectorTileLayer accesses cached tiles of data and renders it in vector format. */ + class VectorTileLayer extends Layer { + /** The full extent of the layer. */ + fullExtent: Extent; + /** The initial extent of the layer. */ + initialExtent: Extent; + /** The spatial reference of the layer. */ + spatialReference: SpatialReference; + /** The style object of the service with fully qualified URLs for glyphs and sprite. */ + style: any; + /** Contains information about the tiling scheme for the layer. */ + tileInfo: TileInfo; + /** The URL to the vector tile service or style JSON that will be used to draw the layer. */ + url: string; + /** + * Create a new VectorTileLayer object. + * @param url The URL to the vector tile service or style JSON that will be used to draw the layer. + * @param options Optional parameters. + */ + constructor(url: string | any, options?: esri.VectorTileLayerOptions); + /** + * Changes the style properties used to render the layers. + * @param styleUrl A url to a JSON file containing the stylesheet information to render the layer. + */ + setStyle(styleUrl: string | any): void; + /** Fires when the style is changed on the layer. */ + on(type: "style-change", listener: (event: { style: any; target: VectorTileLayer }) => void): esri.Handle; + on(type: string, listener: (event: any) => void): esri.Handle; + } + export = VectorTileLayer; +} + declare module "esri/layers/WFSLayer" { import esri = require("esri"); import Field = require("esri/layers/Field"); @@ -10513,7 +10633,7 @@ declare module "esri/layers/WFSLayer" { import InfoTemplate = require("esri/InfoTemplate"); import Renderer = require("esri/renderers/Renderer"); - /** (Currently in beta)A layer for OGC Web Feature Services (WFS). */ + /** (Currently in beta) A layer for OGC Web Feature Services (WFS). */ class WFSLayer { /** An array of fields in the layer. */ fields: Field[]; @@ -11262,6 +11382,8 @@ declare module "esri/opsdashboard/DataSourceProxy" { id: string; /** Read-only: Indicates if the last query failed and the data source is in a broken state. */ isBroken: boolean; + /** Read-only: The mapWidgetId of the data source. */ + mapWidgetId: string; /** Read-only: The name of the data source. */ name: string; /** Read-only: The name of the object id field. */ @@ -11279,6 +11401,8 @@ declare module "esri/opsdashboard/DataSourceProxy" { * @param query The query object to apply. */ executeQuery(query: Query): any; + /** An object that contains service level metadata about whether or not the layer supports queries using statistics, order by fields, DISTINCT, pagination, query with distance, and returning queries with extents. */ + getAdvancedQueryCapabilities(): any; /** Retrieve the associated data source that supports selection. */ getAssociatedSelectionDataSourceProxy(): any; /** Get the associated popupInfo for the data source if any available. */ @@ -11334,8 +11458,8 @@ declare module "esri/opsdashboard/ExtensionBase" { static POLYLINE: any; /** Read-only: Indicates if the host application is the Windows Operations Dashboard. */ isNative: boolean; - /** Get the collection of data sources from the host application. */ - getDataSourceProxies(): any; + /** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */ + portalUrl: string; /** Get the collection of data sources from the host application. */ getDataSourceProxies(): any; /** Get the data source corresponding to the data source id from the host application. */ @@ -11386,6 +11510,8 @@ declare module "esri/opsdashboard/ExtensionConfigurationBase" { /** ExtensionConfigurationBase is a base class used by all the extension configuration proxies. */ class ExtensionConfigurationBase extends ExtensionBase { + /** The object that will store the Widget/MapTool/FeatureAction configuration. */ + config: any; /** Indicates that the configuration is ready to be persisted or not. */ readyToPersistConfig: boolean; } @@ -11467,10 +11593,10 @@ declare module "esri/opsdashboard/GraphicsLayerProxy" { */ addOrUpdateGraphic(graphic: Graphic): void; /** - * Update a graphic in the host graphics layer with a new version. - * @param graphic The graphic to update in the host graphics layer. + * Update graphics in the host graphics layer with a new version. + * @param graphics The graphics to update in the host graphics layer. */ - addOrUpdateGraphics(graphic: Graphic): void; + addOrUpdateGraphics(graphics: Graphic[]): void; /** Removes all the graphics from the host graphics layer. */ clear(): void; /** @@ -11625,8 +11751,6 @@ declare module "esri/opsdashboard/WidgetConfigurationProxy" { /** WidgetConfigurationProxy is a class used to provide the configuration user experience for an operations dashboard extension widget. */ class WidgetConfigurationProxy extends ExtensionConfigurationBase { - /** The object that will store the widget configuration. */ - config: any; /** * Called by the host application when the user has changed the selected data source in the data source selector. * @param dataSourceProxy The selected data source. @@ -11639,7 +11763,7 @@ declare module "esri/opsdashboard/WidgetConfigurationProxy" { */ getDataSourceConfig(dataSourceProxyOrDataSourceId: DataSourceProxy | string): any; /** - * Called by the host application when the user has changed the slected map widget in the map widget selector. + * Called by the host application when the user has changed the selected map widget in the map widget selector. * @param mapWidgetProxy The selected map widget. */ mapWidgetSelectionChanged(mapWidgetProxy: MapWidgetProxy): void; @@ -11897,7 +12021,7 @@ declare module "esri/renderers/BlendRenderer" { import esri = require("esri"); import Symbol = require("esri/symbols/Symbol"); - /** (Currently in beta) BlendRenderer allows you to easily identify a predominant attribute among two or more competing attributes in a feature. */ + /** (Currently in beta) BlendRenderer allows you to easily identify the predominant attribute among two or more competing attributes of a feature and visualizes the strength of that predominance using blended colors. */ class BlendRenderer { /** This determines how colors are blended together. */ blendMode: string; @@ -12129,7 +12253,7 @@ declare module "esri/renderers/Renderer" { import Color = require("esri/Color"); import Symbol = require("esri/symbols/Symbol"); - /** The base class for the renderers - SimpleRenderer, ClassBreaksRenderer, UniqueValueRenderer, DotDensityRenderer, ScaleDependentRenderer, and TemporalRenderer used with a GraphicsLayer and FeatureLayer. */ + /** The base class for the renderers - SimpleRenderer, ClassBreaksRenderer, UniqueValueRenderer, DotDensityRenderer, ScaleDependentRenderer, TemporalRenderer, HeatmapRenderer, and VectorFieldRenderer used with a GraphicsLayer and FeatureLayer. */ class Renderer { /** An object defining a color ramp used to render the layer. */ colorInfo: any; @@ -12188,11 +12312,14 @@ declare module "esri/renderers/Renderer" { * @param info An object with the same properties as rotationInfo. */ setRotationInfo(info: any): Renderer; - /** Set size info of the renderer to modify the symbol size based on data value. */ - setSizeInfo(): Renderer; + /** + * Set size info of the renderer to modify the symbol size based on data value. + * @param info An object with the same properties as sizeInfo. + */ + setSizeInfo(info: any): Renderer; /** * Sets the renderer with the specified visualVariables. - * @param visualParams The specified visualVariables. + * @param visualParams The specified visualVariables. */ setVisualVariables(visualParams: any[]): void; /** Converts object to its ArcGIS Server JSON representation. */ @@ -12503,6 +12630,11 @@ declare module "esri/renderers/smartMapping" { * @param params See the object specifications table below for the structure of the params object. */ createClassedSizeRenderer(params: any): any; + /** + * Creates an object defining a color ramp used to render a layer. + * @param params See the object specifications table below for the structure of the params object. + */ + createColorInfo(params: any): any; /** * Creates a renderer for visualizing features using colors. * @param params See the object specifications table below for the structure of the params object. @@ -12518,6 +12650,16 @@ declare module "esri/renderers/smartMapping" { * @param params See the object specifications table below for the structure of the params object. */ createOpacityInfo(params: any): any; + /** + * Creates a renderer for identifying features by their color. + * @param params See the Object Specifications table below for the structure of the params object. + */ + createPredominanceRenderer(params: any): any; + /** + * Defines the size of the symbol where feature size is proportional to data value. + * @param params See the object specifications table below for the structure of the params object. + */ + createSizeInfo(params: any): any; /** * Creates a renderer for visualizing features by varying their size based on data. * @param params See the object specifications table below for the structure of the params object. @@ -13113,6 +13255,10 @@ declare module "esri/symbols/TextSymbol" { decoration: string; /** Font for displaying text. */ font: Font; + /** The halo color used for the text symbol.Known limitations:IE 9 and below not supported.Sub-pixel halo (i.e. */ + haloColor: Color; + /** The size (in pixel units) used if setting a halo on a text symbol.Known limitations:IE 9 and below not supported.Sub-pixel halo (i.e. */ + haloSize: number; /** Horizontal alignment of the text with respect to the graphic. */ horizontalAlignment: string; /** Determines whether to adjust the spacing between characters in the text string. */ @@ -13164,6 +13310,16 @@ declare module "esri/symbols/TextSymbol" { * @param font Text font. */ setFont(font: Font): TextSymbol; + /** + * Sets a halo color for the text symbol.NOTE: Known limitations when working with the text symbol halo:IE 9 and below not supported.Sub-pixel halo (i.e. + * @param color The color used for the text symbol halo. + */ + setHaloColor(color: Color): TextSymbol; + /** + * Sets the size of the halo (in pixels) used for the text symbol.NOTE: Known limitations when working with the text symbol halo:IE 9 and below not supported.Sub-pixel halo (i.e. + * @param size The size (in pixels) of the text symbol halo. + */ + setHaloSize(size: number): TextSymbol; /** * Updates the horizontal alignment of the text symbol. * @param alignment Horizontal alignment of the text with respect to the graphic. @@ -13658,6 +13814,8 @@ declare module "esri/tasks/FindParameters" { contains: boolean; /** An array of DynamicLayerInfos used to change the layer ordering or redefine the map. */ dynamicLayerInfos: DynamicLayerInfo[]; + /** Specifies the number of decimal places for the geometries returned by the query operation. */ + geometryPrecision: number; /** Array of layer definition expressions that allows you to filter the features of individual layers. */ layerDefinitions: string[]; /** The layers to perform the find operation on. */ @@ -13731,26 +13889,26 @@ declare module "esri/tasks/FindTask" { declare module "esri/tasks/GPMessage" { /** Represents a message generated during the execution of a geoprocessing task. */ class GPMessage { - /** esriJobMessageTypeAbort */ + /** esriJobMessageTypeAbort - Indicates the job has aborted. */ static TYPE_ABORT: any; - /** esriGPMessageTypeEmpty */ + /** esriJobMessageTypeEmpty - Indicates the task returned an empty result. */ static TYPE_EMPTY: any; - /** esriGPMessageTypeError */ + /** esriJobMessageTypeError - Indicates an error was returned during the execution of the job. */ static TYPE_ERROR: any; - /** esriGPMessageTypeInformative */ + /** esriJobMessageTypeInformative - Indicates the message is informative. */ static TYPE_INFORMATIVE: any; - /** TBA */ + /** esriJobMessageTypeProcessDefinition */ static TYPE_PROCESS_DEFINITION: any; - /** TBA */ + /** esriJobMessageTypeProcessStart - Indicates the GP process has started. */ static TYPE_PROCESS_START: any; - /** TBA */ + /** esriJobMessageTypeProcessStop - Indicates the GP process has stopped. */ static TYPE_PROCESS_STOP: any; - /** esriGPMessageTypeWarning */ + /** esriJobMessageTypeWarning - Indicates the message is a warning. */ static TYPE_WARNING: any; /** A description of the geoprocessing message. */ description: string; /** The geoprocessing message type. */ - type: number; + type: string; } export = GPMessage; } @@ -14127,7 +14285,7 @@ declare module "esri/tasks/Geoprocessor" { * @param callback The function to call when the method has completed. * @param errback An error object is returned if an error occurs on the Server during task execution. */ - checkJobStatus(jobId: string, callback?: Function, errback?: Function): void; + checkJobStatus(jobId: string, callback?: Function, errback?: Function): any; /** * Sends a request to the server to execute a synchronous GP task. * @param inputParameters The inputParameters argument specifies the input parameters accepted by the task and their corresponding values. @@ -14187,7 +14345,7 @@ declare module "esri/tasks/Geoprocessor" { * @param statusCallback Checks the current status of the job. * @param errback An error object is returned if an error occurs on the Server during task execution. */ - submitJob(inputParameters: any, callback?: Function, statusCallback?: Function, errback?: Function): void; + submitJob(inputParameters: any, callback?: Function, statusCallback?: Function, errback?: Function): any; /** Fires when an error occurs when executing the task. */ on(type: "error", listener: (event: { error: Error; target: Geoprocessor }) => void): esri.Handle; /** Fires when a synchronous GP task is completed. */ @@ -14231,6 +14389,8 @@ declare module "esri/tasks/IdentifyParameters" { dynamicLayerInfos: DynamicLayerInfo[]; /** The geometry used to select features during Identify. */ geometry: Geometry; + /** Specifies the number of decimal places for the geometries returned by the query operation. */ + geometryPrecision: number; /** Height of the map currently being viewed in pixels. */ height: number; /** Array of layer definition expressions that allows you to filter the features of individual layers. */ @@ -14403,6 +14563,28 @@ declare module "esri/tasks/ImageServiceMeasureParameters" { /** Defines parameters for the ImageServiceMeasureTask. */ class ImageServiceMeasureParameters { + /** Calculates the area and perimeter of given geometry. */ + static OPERATION_AREA_PERIMETER: any; + /** Calculates the area and perimeter of the given geometry using the DEM defined by the service to refine the calculation. */ + static OPERATION_AREA_PERIMETER_3D: any; + /** Calculates the height of a structure by measuring from the base of the structure to the top of the structure. */ + static OPERATION_BASE_TOP: any; + /** Calculates the height of a structure by measuring from the base of the structure to the top of the structure's shadow on the ground. */ + static OPERATION_BASE_TOP_SHADOW: any; + /** Calculates the centroid of a given area. */ + static OPERATION_CENTROID: any; + /** Calculates the centroid of a given area, using the DEM defined by the service to refine the calculation. */ + static OPERATION_CENTROID_3D: any; + /** Calculates the distance and azimuth angle between two points. */ + static OPERATION_DISTANCE_ANGLE: any; + /** Calculates the distance and azimuth angle between two points using the DEM defined by the service to refine the calculation. */ + static OPERATION_DISTANCE_ANGLE_3D: any; + /** Measures the location of a given point. */ + static OPERATION_POINT: any; + /** Measures the location of a given point, using the DEM defined by the service to refine the calculation. */ + static OPERATION_POINT_3D: any; + /** Calculates the height of a structure by measuring from the top of the structure to the top of the structure's shadow on the ground. */ + static OPERATION_TOP_TOP_SHADOW: any; /** The angular unit in which directions of line segments will be calculated. */ angularUnit: string; /** The area unit in which areas of polygons will be calculated. */ @@ -14613,6 +14795,8 @@ declare module "esri/tasks/ParameterValue" { class ParameterValue { /** Specifies the type of data for the parameter. */ dataType: string; + /** The name of the output parameter as defined by the geoprocessing task in the Services Directory. */ + paramName: string; /** The value of the parameter. */ value: any; } @@ -14707,7 +14891,7 @@ declare module "esri/tasks/ProjectParameters" { geometries: Geometry[]; /** The spatial reference to which you are projecting the geometries. */ outSR: SpatialReference; - /** The well-known id {wkid:number} or well-known text {wkt:string} or for the datum transfomation to be applied on the projected geometries. */ + /** The well-known id {wkid:number} or well-known text {wkt:string} or for the datum transformation to be applied on the projected geometries. */ transformation: any; /** Indicates whether to transform forward or not. */ transformForward: boolean; @@ -15331,6 +15515,8 @@ declare module "esri/tasks/datareviewer/BatchValidationTask" { executeJob(parameters: BatchValidationParameters): any; /** Retrieves all adhoc jobs from the server and returns an array of BatchValidationJob with the information. */ getAdhocJobsList(): any; + /** Returns an array of custom field names defined in a Reviewer workspace. */ + getCustomFieldNames(): any; /** * Fetches Batch Validation Job details. * @param jobId Job Id of the batch validation job. @@ -15373,19 +15559,21 @@ declare module "esri/tasks/datareviewer/BatchValidationTask" { /** Fires when the executeJob method is complete. */ on(type: "execute-job", listener: (event: { jobId: string; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getAdhocJobsList method is complete. */ - on(type: "get-adhoc-jobs-list", listener: (event: { adhocJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + on(type: "get-adhoc-jobs-list", listener: (event: { adhocJobs: BatchValidationJob[]; target: BatchValidationTask }) => void): esri.Handle; + /** Fires when the getCustomFieldNames method is complete. */ + on(type: "get-custom-field-names", listener: (event: { customFieldNames: string[]; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getJobDetails method is complete. */ on(type: "get-job-details", listener: (event: { jobDetails: BatchValidationJob; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getJobExecutionDetails method is complete. */ on(type: "get-job-execution-details", listener: (event: { jobInfo: BatchValidationJobInfo; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getJobIds method is complete. */ - on(type: "get-job-ids", listener: (event: { adhocJobs: any[]; scheduledJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + on(type: "get-job-ids", listener: (event: { adhocJobs: string[]; scheduledJobs: string[]; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getLifecycleStatusStrings method is complete. */ - on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: BatchValidationTask }) => void): esri.Handle; + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: string[]; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getReviewerSessions method is complete. */ - on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: BatchValidationTask }) => void): esri.Handle; + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: ReviewerSession[]; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the getScheduledJobsList method is complete. */ - on(type: "get-scheduled-jobs-list", listener: (event: { scheduledJobs: any[]; target: BatchValidationTask }) => void): esri.Handle; + on(type: "get-scheduled-jobs-list", listener: (event: { scheduledJobs: BatchValidationJob[]; target: BatchValidationTask }) => void): esri.Handle; /** Fires when the scheduleJob method is complete. */ on(type: "schedule-job", listener: (event: { jobId: string; target: BatchValidationTask }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; @@ -15435,6 +15623,8 @@ declare module "esri/tasks/datareviewer/DashboardTask" { * @param sessionOptions Session properties to be used to create the session. */ createReviewerSession(sessionName: string, sessionOptions: SessionOptions): any; + /** Returns an array of custom field names defined in a Reviewer workspace. */ + getCustomFieldNames(): any; /** Requests Dashboard results field names. */ getDashboardFieldNames(): any; /** @@ -15453,14 +15643,16 @@ declare module "esri/tasks/datareviewer/DashboardTask" { on(type: "create-reviewer-sessions", listener: (event: { reviewerSession: ReviewerSession; target: DashboardTask }) => void): esri.Handle; /** Fires when an error occurs during a DashboardTask method execution. */ on(type: "error", listener: (event: { error: Error; target: DashboardTask }) => void): esri.Handle; + /** Fires when the getCustomFieldNames method is complete. */ + on(type: "get-custom-field-names", listener: (event: { customFieldNames: string[]; target: DashboardTask }) => void): esri.Handle; /** Fires when the getDashboardFieldNames method is complete. */ - on(type: "get-dashboard-field-names", listener: (event: { fieldNames: any[]; target: DashboardTask }) => void): esri.Handle; + on(type: "get-dashboard-field-names", listener: (event: { fieldNames: string[]; target: DashboardTask }) => void): esri.Handle; /** Fires when the getDashboardResults method is complete. */ on(type: "get-dashboard-results", listener: (event: { dashboardResult: DashboardResult; target: DashboardTask }) => void): esri.Handle; /** Fires when the getLifecycleStatusStrings method is complete. */ - on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: DashboardTask }) => void): esri.Handle; + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: string[]; target: DashboardTask }) => void): esri.Handle; /** Fires when the getReviewerSessions method is complete. */ - on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: DashboardTask }) => void): esri.Handle; + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: ReviewerSession[]; target: DashboardTask }) => void): esri.Handle; on(type: string, listener: (event: any) => void): esri.Handle; } export = DashboardTask; @@ -15542,8 +15734,8 @@ declare module "esri/tasks/datareviewer/ReviewerFilters" { } declare module "esri/tasks/datareviewer/ReviewerLifecycle" { - /** The ReviewerLifecycle class specifies constant values for all lifecycle status and lifecycle phase strings within the Reviewer quality control workflow. */ - class ReviewerLifecycle { + /** The ReviewerLifecycle object specifies constant values for all lifecycle status and lifecycle phase strings within the Reviewer quality control workflow. */ + var ReviewerLifecycle: { /** Acceptable lifecycleStatus code = 4 belongs to Verification Phase. */ ACCEPTABLE: number; /** Code for Correction Phase. */ @@ -15600,7 +15792,7 @@ declare module "esri/tasks/datareviewer/ReviewerLifecycle" { * @param lifecycleStatus The lifecycle status code. */ toLifecycleStatusString(lifecycleStatus: number): string; - } + }; export = ReviewerLifecycle; } @@ -15614,6 +15806,7 @@ declare module "esri/tasks/datareviewer/ReviewerResultsTask" { import Geometry = require("esri/geometry/Geometry"); import ReviewerSession = require("esri/tasks/datareviewer/ReviewerSession"); import FeatureSet = require("esri/tasks/FeatureSet"); + import FeatureEditResult = require("esri/layers/FeatureEditResult"); /** ReviewerResults allows access to the reviewer workspace. */ class ReviewerResultsTask { @@ -15633,6 +15826,8 @@ declare module "esri/tasks/datareviewer/ReviewerResultsTask" { * @param batchRunIds Array of batchRunIds used to get batch run details. */ getBatchRunDetails(batchRunIds: any[]): any; + /** Returns an array of custom field names defined in a Reviewer workspace. */ + getCustomFieldNames(): any; /** * Utility operation that returns a where clause given a set of input filters. * @param filters An instance of ReviewerFilters used to create a layer definition. @@ -15646,8 +15841,10 @@ declare module "esri/tasks/datareviewer/ReviewerResultsTask" { * @param filters Instance of ReviewerFilters used to query reviewer results. */ getResults(getResultsQueryParameters: GetResultsQueryParameters, filters?: ReviewerFilters): any; + /** Retrieves a list of field names that can be used to fetch or query results from reviewer workspace. */ + getResultsFieldNames(): string[]; /** Extracts the MapServer url from the full ArcGIS Data Reviewer for Server SOE url. */ - getReviewerMapServerUrl(): any; + getReviewerMapServerUrl(): string; /** Returns an array of sessions in a Reviewer workspace. */ getReviewerSessions(): any; /** @@ -15676,16 +15873,18 @@ declare module "esri/tasks/datareviewer/ReviewerResultsTask" { on(type: "error", listener: (event: { error: Error; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the getBatchRunDetails method is complete. */ on(type: "get-batch-run-details", listener: (event: { featureSet: FeatureSet; target: ReviewerResultsTask }) => void): esri.Handle; + /** Fires when the getCustomFieldNames method is complete. */ + on(type: "get-custom-field-names", listener: (event: { customFieldNames: string[]; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the getLayerDefinition method is complete. */ on(type: "get-layer-definition", listener: (event: { whereClause: string; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the getLifecycleStatusStrings method is complete. */ - on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + on(type: "get-lifecycle-status-strings", listener: (event: { lifecycleStatusStrings: string[]; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the getResults method is complete. */ on(type: "get-results", listener: (event: { featureSet: FeatureSet; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the getReviewerSessions method is complete. */ - on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + on(type: "get-reviewer-sessions", listener: (event: { reviewerSessions: ReviewerSession[]; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the updateLifecycleStatus method is complete. */ - on(type: "update-lifecycle-status", listener: (event: { featureEditResults: any[]; target: ReviewerResultsTask }) => void): esri.Handle; + on(type: "update-lifecycle-status", listener: (event: { featureEditResults: FeatureEditResult[]; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the writeFeatureAsResult method is complete. */ on(type: "write-feature-as-result", listener: (event: { success: boolean; target: ReviewerResultsTask }) => void): esri.Handle; /** Fires when the writeResult method is complete. */ diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index bef269dbcb..3269103ab1 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -72,6 +72,8 @@ interface Auth0LockStatic { hide(callback: () => void): void; logout(callback: () => void): void; + + getClient(): Auth0Static; } declare var Auth0Lock: Auth0LockStatic; diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index b2e1149fb6..1548bd06f0 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -51,6 +51,8 @@ interface Auth0UserProfile { user_id: string; /** Represents one or more Identities that may be associated with the User. */ identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; } /** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ diff --git a/aws-sdk/aws-sdk-tests.ts.tscparams b/aws-sdk/aws-sdk-tests.ts.tscparams deleted file mode 100644 index 70401a77ee..0000000000 --- a/aws-sdk/aws-sdk-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny --module commonjs --target es5 \ No newline at end of file diff --git a/babylonjs/babylon-tests.ts b/babylonjs/babylon-tests.ts new file mode 100644 index 0000000000..142d3840f5 --- /dev/null +++ b/babylonjs/babylon-tests.ts @@ -0,0 +1 @@ +/// diff --git a/babylonjs/babylon.d.ts b/babylonjs/babylon.d.ts new file mode 100644 index 0000000000..1cc835442c --- /dev/null +++ b/babylonjs/babylon.d.ts @@ -0,0 +1,6327 @@ +// Type definitions for BabylonJS v2.2 +// Project: http://www.babylonjs.com/ +// Definitions by: David Catuhe +// Definitions: https://github.com/borisyankov/babylonjs + + +declare module BABYLON { + class _DepthCullingState { + private _isDepthTestDirty; + private _isDepthMaskDirty; + private _isDepthFuncDirty; + private _isCullFaceDirty; + private _isCullDirty; + private _isZOffsetDirty; + private _depthTest; + private _depthMask; + private _depthFunc; + private _cull; + private _cullFace; + private _zOffset; + isDirty: boolean; + zOffset: number; + cullFace: number; + cull: boolean; + depthFunc: number; + depthMask: boolean; + depthTest: boolean; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } + class _AlphaState { + private _isAlphaBlendDirty; + private _isBlendFunctionParametersDirty; + private _alphaBlend; + private _blendFunctionParameters; + isDirty: boolean; + alphaBlend: boolean; + setAlphaBlendFunctionParameters(value0: number, value1: number, value2: number, value3: number): void; + reset(): void; + apply(gl: WebGLRenderingContext): void; + } + class EngineCapabilities { + maxTexturesImageUnits: number; + maxTextureSize: number; + maxCubemapTextureSize: number; + maxRenderTextureSize: number; + standardDerivatives: boolean; + s3tc: any; + textureFloat: boolean; + textureAnisotropicFilterExtension: any; + maxAnisotropy: number; + instancedArrays: any; + uintIndices: boolean; + highPrecisionShaderSupported: boolean; + } + /** + * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio. + */ + class Engine { + private static _ALPHA_DISABLE; + private static _ALPHA_ADD; + private static _ALPHA_COMBINE; + private static _ALPHA_SUBTRACT; + private static _ALPHA_MULTIPLY; + private static _ALPHA_MAXIMIZED; + private static _ALPHA_ONEONE; + private static _DELAYLOADSTATE_NONE; + private static _DELAYLOADSTATE_LOADED; + private static _DELAYLOADSTATE_LOADING; + private static _DELAYLOADSTATE_NOTLOADED; + private static _TEXTUREFORMAT_ALPHA; + private static _TEXTUREFORMAT_LUMINANCE; + private static _TEXTUREFORMAT_LUMINANCE_ALPHA; + private static _TEXTUREFORMAT_RGB; + private static _TEXTUREFORMAT_RGBA; + private static _TEXTURETYPE_UNSIGNED_INT; + private static _TEXTURETYPE_FLOAT; + static ALPHA_DISABLE: number; + static ALPHA_ONEONE: number; + static ALPHA_ADD: number; + static ALPHA_COMBINE: number; + static ALPHA_SUBTRACT: number; + static ALPHA_MULTIPLY: number; + static ALPHA_MAXIMIZED: number; + static DELAYLOADSTATE_NONE: number; + static DELAYLOADSTATE_LOADED: number; + static DELAYLOADSTATE_LOADING: number; + static DELAYLOADSTATE_NOTLOADED: number; + static TEXTUREFORMAT_ALPHA: number; + static TEXTUREFORMAT_LUMINANCE: number; + static TEXTUREFORMAT_LUMINANCE_ALPHA: number; + static TEXTUREFORMAT_RGB: number; + static TEXTUREFORMAT_RGBA: number; + static TEXTURETYPE_UNSIGNED_INT: number; + static TEXTURETYPE_FLOAT: number; + static Version: string; + static Epsilon: number; + static CollisionsEpsilon: number; + static CodeRepository: string; + static ShadersRepository: string; + isFullscreen: boolean; + isPointerLock: boolean; + cullBackFaces: boolean; + renderEvenInBackground: boolean; + enableOfflineSupport: boolean; + scenes: Scene[]; + _gl: WebGLRenderingContext; + private _renderingCanvas; + private _windowIsBackground; + static audioEngine: AudioEngine; + private _onBlur; + private _onFocus; + private _onFullscreenChange; + private _onPointerLockChange; + private _hardwareScalingLevel; + private _caps; + private _pointerLockRequested; + private _alphaTest; + private _resizeLoadingUI; + private _loadingDiv; + private _loadingTextDiv; + private _loadingDivBackgroundColor; + private _drawCalls; + private _glVersion; + private _glRenderer; + private _glVendor; + private _videoTextureSupported; + private _renderingQueueLaunched; + private _activeRenderLoops; + private fpsRange; + private previousFramesDuration; + private fps; + private deltaTime; + private _depthCullingState; + private _alphaState; + private _alphaMode; + private _loadedTexturesCache; + _activeTexturesCache: BaseTexture[]; + private _currentEffect; + private _compiledEffects; + private _vertexAttribArrays; + private _cachedViewport; + private _cachedVertexBuffers; + private _cachedIndexBuffer; + private _cachedEffectForVertexBuffers; + private _currentRenderTarget; + private _uintIndicesCurrentlySet; + private _workingCanvas; + private _workingContext; + /** + * @constructor + * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering + * @param {boolean} [antialias] - enable antialias + * @param options - further options to be sent to the getContext function + */ + constructor(canvas: HTMLCanvasElement, antialias?: boolean, options?: any); + private _prepareWorkingCanvas(); + getGlInfo(): { + vendor: string; + renderer: string; + version: string; + }; + getAspectRatio(camera: Camera): number; + getRenderWidth(): number; + getRenderHeight(): number; + getRenderingCanvas(): HTMLCanvasElement; + getRenderingCanvasClientRect(): ClientRect; + setHardwareScalingLevel(level: number): void; + getHardwareScalingLevel(): number; + getLoadedTexturesCache(): WebGLTexture[]; + getCaps(): EngineCapabilities; + drawCalls: number; + resetDrawCalls(): void; + setDepthFunctionToGreater(): void; + setDepthFunctionToGreaterOrEqual(): void; + setDepthFunctionToLess(): void; + setDepthFunctionToLessOrEqual(): void; + /** + * stop executing a render loop function and remove it from the execution array + * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed. + */ + stopRenderLoop(renderFunction?: () => void): void; + _renderLoop(): void; + /** + * Register and execute a render loop. The engine can have more than one render function. + * @param {Function} renderFunction - the function to continuesly execute starting the next render loop. + * @example + * engine.runRenderLoop(function () { + * scene.render() + * }) + */ + runRenderLoop(renderFunction: () => void): void; + /** + * Toggle full screen mode. + * @param {boolean} requestPointerLock - should a pointer lock be requested from the user + */ + switchFullscreen(requestPointerLock: boolean): void; + clear(color: any, backBuffer: boolean, depthStencil: boolean): void; + /** + * Set the WebGL's viewport + * @param {BABYLON.Viewport} viewport - the viewport element to be used. + * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used. + * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used. + */ + setViewport(viewport: Viewport, requiredWidth?: number, requiredHeight?: number): void; + setDirectViewport(x: number, y: number, width: number, height: number): void; + beginFrame(): void; + endFrame(): void; + /** + * resize the view according to the canvas' size. + * @example + * window.addEventListener("resize", function () { + * engine.resize(); + * }); + */ + resize(): void; + /** + * force a specific size of the canvas + * @param {number} width - the new canvas' width + * @param {number} height - the new canvas' height + */ + setSize(width: number, height: number): void; + bindFramebuffer(texture: WebGLTexture): void; + unBindFramebuffer(texture: WebGLTexture): void; + flushFramebuffer(): void; + restoreDefaultFramebuffer(): void; + private _resetVertexBufferBinding(); + createVertexBuffer(vertices: number[]): WebGLBuffer; + createDynamicVertexBuffer(capacity: number): WebGLBuffer; + updateDynamicVertexBuffer(vertexBuffer: WebGLBuffer, vertices: any, offset?: number): void; + private _resetIndexBufferBinding(); + createIndexBuffer(indices: number[]): WebGLBuffer; + bindBuffers(vertexBuffer: WebGLBuffer, indexBuffer: WebGLBuffer, vertexDeclaration: number[], vertexStrideSize: number, effect: Effect): void; + bindMultiBuffers(vertexBuffers: VertexBuffer[], indexBuffer: WebGLBuffer, effect: Effect): void; + _releaseBuffer(buffer: WebGLBuffer): boolean; + createInstancesBuffer(capacity: number): WebGLBuffer; + deleteInstancesBuffer(buffer: WebGLBuffer): void; + updateAndBindInstancesBuffer(instancesBuffer: WebGLBuffer, data: Float32Array, offsetLocations: number[]): void; + unBindInstancesBuffer(instancesBuffer: WebGLBuffer, offsetLocations: number[]): void; + applyStates(): void; + draw(useTriangles: boolean, indexStart: number, indexCount: number, instancesCount?: number): void; + drawPointClouds(verticesStart: number, verticesCount: number, instancesCount?: number): void; + _releaseEffect(effect: Effect): void; + createEffect(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], defines: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + createEffectForParticles(fragmentName: string, uniformsNames?: string[], samplers?: string[], defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void): Effect; + createShaderProgram(vertexCode: string, fragmentCode: string, defines: string): WebGLProgram; + getUniforms(shaderProgram: WebGLProgram, uniformsNames: string[]): WebGLUniformLocation[]; + getAttributes(shaderProgram: WebGLProgram, attributesNames: string[]): number[]; + enableEffect(effect: Effect): void; + setArray(uniform: WebGLUniformLocation, array: number[]): void; + setArray2(uniform: WebGLUniformLocation, array: number[]): void; + setArray3(uniform: WebGLUniformLocation, array: number[]): void; + setArray4(uniform: WebGLUniformLocation, array: number[]): void; + setMatrices(uniform: WebGLUniformLocation, matrices: Float32Array): void; + setMatrix(uniform: WebGLUniformLocation, matrix: Matrix): void; + setMatrix3x3(uniform: WebGLUniformLocation, matrix: Float32Array): void; + setMatrix2x2(uniform: WebGLUniformLocation, matrix: Float32Array): void; + setFloat(uniform: WebGLUniformLocation, value: number): void; + setFloat2(uniform: WebGLUniformLocation, x: number, y: number): void; + setFloat3(uniform: WebGLUniformLocation, x: number, y: number, z: number): void; + setBool(uniform: WebGLUniformLocation, bool: number): void; + setFloat4(uniform: WebGLUniformLocation, x: number, y: number, z: number, w: number): void; + setColor3(uniform: WebGLUniformLocation, color3: Color3): void; + setColor4(uniform: WebGLUniformLocation, color3: Color3, alpha: number): void; + setState(culling: boolean, zOffset?: number, force?: boolean): void; + setDepthBuffer(enable: boolean): void; + getDepthWrite(): boolean; + setDepthWrite(enable: boolean): void; + setColorWrite(enable: boolean): void; + setAlphaMode(mode: number): void; + getAlphaMode(): number; + setAlphaTesting(enable: boolean): void; + getAlphaTesting(): boolean; + wipeCaches(): void; + setSamplingMode(texture: WebGLTexture, samplingMode: number): void; + createTexture(url: string, noMipmap: boolean, invertY: boolean, scene: Scene, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any): WebGLTexture; + updateRawTexture(texture: WebGLTexture, data: ArrayBufferView, format: number, invertY: boolean, compression?: string): void; + createRawTexture(data: ArrayBufferView, width: number, height: number, format: number, generateMipMaps: boolean, invertY: boolean, samplingMode: number, compression?: string): WebGLTexture; + createDynamicTexture(width: number, height: number, generateMipMaps: boolean, samplingMode: number, forceExponantOfTwo?: boolean): WebGLTexture; + updateTextureSamplingMode(samplingMode: number, texture: WebGLTexture): void; + updateDynamicTexture(texture: WebGLTexture, canvas: HTMLCanvasElement, invertY: boolean): void; + updateVideoTexture(texture: WebGLTexture, video: HTMLVideoElement, invertY: boolean): void; + createRenderTargetTexture(size: any, options: any): WebGLTexture; + createCubeTexture(rootUrl: string, scene: Scene, extensions: string[], noMipmap?: boolean): WebGLTexture; + _releaseTexture(texture: WebGLTexture): void; + bindSamplers(effect: Effect): void; + _bindTexture(channel: number, texture: WebGLTexture): void; + setTextureFromPostProcess(channel: number, postProcess: PostProcess): void; + setTexture(channel: number, texture: BaseTexture): void; + _setAnisotropicLevel(key: number, texture: BaseTexture): void; + readPixels(x: number, y: number, width: number, height: number): Uint8Array; + dispose(): void; + displayLoadingUI(): void; + loadingUIText: string; + loadingUIBackgroundColor: string; + hideLoadingUI(): void; + getFps(): number; + getDeltaTime(): number; + private _measureFps(); + static isSupported(): boolean; + } +} + +interface Window { + mozIndexedDB(func: any): any; + webkitIndexedDB(func: any): any; + IDBTransaction(func: any): any; + webkitIDBTransaction(func: any): any; + msIDBTransaction(func: any): any; + IDBKeyRange(func: any): any; + webkitIDBKeyRange(func: any): any; + msIDBKeyRange(func: any): any; + webkitURL: HTMLURL; + webkitRequestAnimationFrame(func: any): any; + mozRequestAnimationFrame(func: any): any; + oRequestAnimationFrame(func: any): any; + WebGLRenderingContext: WebGLRenderingContext; + MSGesture: MSGesture; + CANNON: any; + SIMD: any; + AudioContext: AudioContext; + webkitAudioContext: AudioContext; +} +interface HTMLURL { + createObjectURL(param1: any, param2?: any): any; +} +interface Document { + exitFullscreen(): void; + webkitCancelFullScreen(): void; + mozCancelFullScreen(): void; + msCancelFullScreen(): void; + mozFullScreen: boolean; + msIsFullScreen: boolean; + fullscreen: boolean; + mozPointerLockElement: HTMLElement; + msPointerLockElement: HTMLElement; + webkitPointerLockElement: HTMLElement; +} +interface HTMLCanvasElement { + requestPointerLock(): void; + msRequestPointerLock(): void; + mozRequestPointerLock(): void; + webkitRequestPointerLock(): void; +} +interface CanvasRenderingContext2D { + imageSmoothingEnabled: boolean; + mozImageSmoothingEnabled: boolean; + oImageSmoothingEnabled: boolean; + webkitImageSmoothingEnabled: boolean; +} +interface WebGLTexture { + isReady: boolean; + isCube: boolean; + url: string; + noMipmap: boolean; + samplingMode: number; + references: number; + generateMipMaps: boolean; + _size: number; + _baseWidth: number; + _baseHeight: number; + _width: number; + _height: number; + _workingCanvas: HTMLCanvasElement; + _workingContext: CanvasRenderingContext2D; + _framebuffer: WebGLFramebuffer; + _depthBuffer: WebGLRenderbuffer; + _cachedCoordinatesMode: number; + _cachedWrapU: number; + _cachedWrapV: number; + _isDisabled: boolean; +} +interface WebGLBuffer { + references: number; + capacity: number; + is32Bits: boolean; +} +interface MouseEvent { + mozMovementX: number; + mozMovementY: number; + webkitMovementX: number; + webkitMovementY: number; + msMovementX: number; + msMovementY: number; +} +interface MSStyleCSSProperties { + webkitTransform: string; + webkitTransition: string; +} +interface Navigator { + getVRDevices: () => any; + mozGetVRDevices: (any: any) => any; + isCocoonJS: boolean; +} +interface Screen { + orientation: string; + mozOrientation: string; +} + +declare module BABYLON { + /** + * Node is the basic class for all scene objects (Mesh, Light Camera). + */ + class Node { + parent: Node; + name: string; + id: string; + uniqueId: number; + state: string; + animations: Animation[]; + onReady: (node: Node) => void; + private _childrenFlag; + private _isEnabled; + private _isReady; + _currentRenderId: number; + private _parentRenderId; + _waitingParentId: string; + private _scene; + _cache: any; + /** + * @constructor + * @param {string} name - the name and id to be given to this node + * @param {BABYLON.Scene} the scene this node will be added to + */ + constructor(name: string, scene: Scene); + getScene(): Scene; + getEngine(): Engine; + getWorldMatrix(): Matrix; + _initCache(): void; + updateCache(force?: boolean): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronized(): boolean; + _markSyncedWithParent(): void; + isSynchronizedWithParent(): boolean; + isSynchronized(updateCache?: boolean): boolean; + hasNewParent(update?: boolean): boolean; + /** + * Is this node ready to be used/rendered + * @return {boolean} is it ready + */ + isReady(): boolean; + /** + * Is this node enabled. + * If the node has a parent and is enabled, the parent will be inspected as well. + * @return {boolean} whether this node (and its parent) is enabled. + * @see setEnabled + */ + isEnabled(): boolean; + /** + * Set the enabled state of this node. + * @param {boolean} value - the new enabled state + * @see isEnabled + */ + setEnabled(value: boolean): void; + /** + * Is this node a descendant of the given node. + * The function will iterate up the hierarchy until the ancestor was found or no more parents defined. + * @param {BABYLON.Node} ancestor - The parent node to inspect + * @see parent + */ + isDescendantOf(ancestor: Node): boolean; + _getDescendants(list: Node[], results: Node[]): void; + /** + * Will return all nodes that have this node as parent. + * @return {BABYLON.Node[]} all children nodes of all types. + */ + getDescendants(): Node[]; + _setReady(state: boolean): void; + } +} + +declare module BABYLON { + interface IDisposable { + dispose(): void; + } + /** + * Represents a scene to be rendered by the engine. + * @see http://doc.babylonjs.com/page.php?p=21911 + */ + class Scene { + private static _FOGMODE_NONE; + private static _FOGMODE_EXP; + private static _FOGMODE_EXP2; + private static _FOGMODE_LINEAR; + static MinDeltaTime: number; + static MaxDeltaTime: number; + static FOGMODE_NONE: number; + static FOGMODE_EXP: number; + static FOGMODE_EXP2: number; + static FOGMODE_LINEAR: number; + autoClear: boolean; + clearColor: any; + ambientColor: Color3; + /** + * A function to be executed before rendering this scene + * @type {Function} + */ + beforeRender: () => void; + /** + * A function to be executed after rendering this scene + * @type {Function} + */ + afterRender: () => void; + /** + * A function to be executed when this scene is disposed. + * @type {Function} + */ + onDispose: () => void; + beforeCameraRender: (camera: Camera) => void; + afterCameraRender: (camera: Camera) => void; + forceWireframe: boolean; + forcePointsCloud: boolean; + forceShowBoundingBoxes: boolean; + clipPlane: Plane; + animationsEnabled: boolean; + private _onPointerMove; + private _onPointerDown; + private _onPointerUp; + onPointerDown: (evt: PointerEvent, pickInfo: PickingInfo) => void; + onPointerUp: (evt: PointerEvent, pickInfo: PickingInfo) => void; + cameraToUseForPointers: Camera; + private _pointerX; + private _pointerY; + private _meshUnderPointer; + private _onKeyDown; + private _onKeyUp; + /** + * is fog enabled on this scene. + * @type {boolean} + */ + fogEnabled: boolean; + fogMode: number; + fogColor: Color3; + fogDensity: number; + fogStart: number; + fogEnd: number; + /** + * is shadow enabled on this scene. + * @type {boolean} + */ + shadowsEnabled: boolean; + /** + * is light enabled on this scene. + * @type {boolean} + */ + lightsEnabled: boolean; + /** + * All of the lights added to this scene. + * @see BABYLON.Light + * @type {BABYLON.Light[]} + */ + lights: Light[]; + onNewLightAdded: (newLight?: Light, positionInArray?: number, scene?: Scene) => void; + onLightRemoved: (removedLight?: Light) => void; + /** + * All of the cameras added to this scene. + * @see BABYLON.Camera + * @type {BABYLON.Camera[]} + */ + cameras: Camera[]; + onNewCameraAdded: (newCamera?: Camera, positionInArray?: number, scene?: Scene) => void; + onCameraRemoved: (removedCamera?: Camera) => void; + activeCameras: Camera[]; + activeCamera: Camera; + /** + * All of the (abstract) meshes added to this scene. + * @see BABYLON.AbstractMesh + * @type {BABYLON.AbstractMesh[]} + */ + meshes: AbstractMesh[]; + onNewMeshAdded: (newMesh?: AbstractMesh, positionInArray?: number, scene?: Scene) => void; + onMeshRemoved: (removedMesh?: AbstractMesh) => void; + private _geometries; + onGeometryAdded: (newGeometry?: Geometry) => void; + onGeometryRemoved: (removedGeometry?: Geometry) => void; + materials: Material[]; + multiMaterials: MultiMaterial[]; + defaultMaterial: StandardMaterial; + texturesEnabled: boolean; + textures: BaseTexture[]; + particlesEnabled: boolean; + particleSystems: ParticleSystem[]; + spritesEnabled: boolean; + spriteManagers: SpriteManager[]; + layers: Layer[]; + skeletonsEnabled: boolean; + skeletons: Skeleton[]; + lensFlaresEnabled: boolean; + lensFlareSystems: LensFlareSystem[]; + collisionsEnabled: boolean; + private _workerCollisions; + collisionCoordinator: ICollisionCoordinator; + gravity: Vector3; + postProcessesEnabled: boolean; + postProcessManager: PostProcessManager; + postProcessRenderPipelineManager: PostProcessRenderPipelineManager; + renderTargetsEnabled: boolean; + dumpNextRenderTargets: boolean; + customRenderTargets: RenderTargetTexture[]; + useDelayedTextureLoading: boolean; + importedMeshesFiles: String[]; + database: any; + /** + * This scene's action manager + * @type {BABYLON.ActionManager} + */ + actionManager: ActionManager; + _actionManagers: ActionManager[]; + private _meshesForIntersections; + proceduralTexturesEnabled: boolean; + _proceduralTextures: ProceduralTexture[]; + mainSoundTrack: SoundTrack; + soundTracks: SoundTrack[]; + private _audioEnabled; + private _headphone; + simplificationQueue: SimplificationQueue; + private _engine; + private _totalVertices; + _activeIndices: number; + _activeParticles: number; + private _lastFrameDuration; + private _evaluateActiveMeshesDuration; + private _renderTargetsDuration; + _particlesDuration: number; + private _renderDuration; + _spritesDuration: number; + private _animationRatio; + private _animationStartDate; + _cachedMaterial: Material; + private _renderId; + private _executeWhenReadyTimeoutId; + _toBeDisposed: SmartArray; + private _onReadyCallbacks; + private _pendingData; + private _onBeforeRenderCallbacks; + private _onAfterRenderCallbacks; + private _activeMeshes; + private _processedMaterials; + private _renderTargets; + _activeParticleSystems: SmartArray; + private _activeSkeletons; + private _softwareSkinnedMeshes; + _activeBones: number; + private _renderingManager; + private _physicsEngine; + _activeAnimatables: Animatable[]; + private _transformMatrix; + private _pickWithRayInverseMatrix; + private _edgesRenderers; + private _boundingBoxRenderer; + private _outlineRenderer; + private _viewMatrix; + private _projectionMatrix; + private _frustumPlanes; + private _selectionOctree; + private _pointerOverMesh; + private _debugLayer; + private _depthRenderer; + private _uniqueIdCounter; + /** + * @constructor + * @param {BABYLON.Engine} engine - the engine to be used to render this scene. + */ + constructor(engine: Engine); + debugLayer: DebugLayer; + workerCollisions: boolean; + SelectionOctree: Octree; + /** + * The mesh that is currently under the pointer. + * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none. + */ + meshUnderPointer: AbstractMesh; + /** + * Current on-screen X position of the pointer + * @return {number} X position of the pointer + */ + pointerX: number; + /** + * Current on-screen Y position of the pointer + * @return {number} Y position of the pointer + */ + pointerY: number; + getCachedMaterial(): Material; + getBoundingBoxRenderer(): BoundingBoxRenderer; + getOutlineRenderer(): OutlineRenderer; + getEngine(): Engine; + getTotalVertices(): number; + getActiveIndices(): number; + getActiveParticles(): number; + getActiveBones(): number; + getLastFrameDuration(): number; + getEvaluateActiveMeshesDuration(): number; + getActiveMeshes(): SmartArray; + getRenderTargetsDuration(): number; + getRenderDuration(): number; + getParticlesDuration(): number; + getSpritesDuration(): number; + getAnimationRatio(): number; + getRenderId(): number; + incrementRenderId(): void; + private _updatePointerPosition(evt); + attachControl(): void; + detachControl(): void; + isReady(): boolean; + resetCachedMaterial(): void; + registerBeforeRender(func: () => void): void; + unregisterBeforeRender(func: () => void): void; + registerAfterRender(func: () => void): void; + unregisterAfterRender(func: () => void): void; + _addPendingData(data: any): void; + _removePendingData(data: any): void; + getWaitingItemsCount(): number; + /** + * Registers a function to be executed when the scene is ready. + * @param {Function} func - the function to be executed. + */ + executeWhenReady(func: () => void): void; + _checkIsReady(): void; + /** + * Will start the animation sequence of a given target + * @param target - the target + * @param {number} from - from which frame should animation start + * @param {number} to - till which frame should animation run. + * @param {boolean} [loop] - should the animation loop + * @param {number} [speedRatio] - the speed in which to run the animation + * @param {Function} [onAnimationEnd] function to be executed when the animation ended. + * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params. + * @return {BABYLON.Animatable} the animatable object created for this animation + * @see BABYLON.Animatable + * @see http://doc.babylonjs.com/page.php?p=22081 + */ + beginAnimation(target: any, from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void, animatable?: Animatable): Animatable; + beginDirectAnimation(target: any, animations: Animation[], from: number, to: number, loop?: boolean, speedRatio?: number, onAnimationEnd?: () => void): Animatable; + getAnimatableByTarget(target: any): Animatable; + /** + * Will stop the animation of the given target + * @param target - the target + * @see beginAnimation + */ + stopAnimation(target: any): void; + private _animate(); + getViewMatrix(): Matrix; + getProjectionMatrix(): Matrix; + getTransformMatrix(): Matrix; + setTransformMatrix(view: Matrix, projection: Matrix): void; + addMesh(newMesh: AbstractMesh): void; + removeMesh(toRemove: AbstractMesh): number; + removeLight(toRemove: Light): number; + removeCamera(toRemove: Camera): number; + addLight(newLight: Light): void; + addCamera(newCamera: Camera): void; + /** + * sets the active camera of the scene using its ID + * @param {string} id - the camera's ID + * @return {BABYLON.Camera|null} the new active camera or null if none found. + * @see activeCamera + */ + setActiveCameraByID(id: string): Camera; + /** + * sets the active camera of the scene using its name + * @param {string} name - the camera's name + * @return {BABYLON.Camera|null} the new active camera or null if none found. + * @see activeCamera + */ + setActiveCameraByName(name: string): Camera; + /** + * get a material using its id + * @param {string} the material's ID + * @return {BABYLON.Material|null} the material or null if none found. + */ + getMaterialByID(id: string): Material; + /** + * get a material using its name + * @param {string} the material's name + * @return {BABYLON.Material|null} the material or null if none found. + */ + getMaterialByName(name: string): Material; + getLensFlareSystemByName(name: string): LensFlareSystem; + getCameraByID(id: string): Camera; + getCameraByUniqueID(uniqueId: number): Camera; + /** + * get a camera using its name + * @param {string} the camera's name + * @return {BABYLON.Camera|null} the camera or null if none found. + */ + getCameraByName(name: string): Camera; + /** + * get a light node using its name + * @param {string} the light's name + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByName(name: string): Light; + /** + * get a light node using its ID + * @param {string} the light's id + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByID(id: string): Light; + /** + * get a light node using its scene-generated unique ID + * @param {number} the light's unique id + * @return {BABYLON.Light|null} the light or null if none found. + */ + getLightByUniqueID(uniqueId: number): Light; + /** + * get a geometry using its ID + * @param {string} the geometry's id + * @return {BABYLON.Geometry|null} the geometry or null if none found. + */ + getGeometryByID(id: string): Geometry; + /** + * add a new geometry to this scene. + * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene. + * @param {boolean} [force] - force addition, even if a geometry with this ID already exists + * @return {boolean} was the geometry added or not + */ + pushGeometry(geometry: Geometry, force?: boolean): boolean; + /** + * Removes an existing geometry + * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene. + * @return {boolean} was the geometry removed or not + */ + removeGeometry(geometry: Geometry): boolean; + getGeometries(): Geometry[]; + /** + * Get the first added mesh found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getMeshByID(id: string): AbstractMesh; + /** + * Get a mesh with its auto-generated unique id + * @param {number} uniqueId - the unique id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getMeshByUniqueID(uniqueId: number): AbstractMesh; + /** + * Get a the last added mesh found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all. + */ + getLastMeshByID(id: string): AbstractMesh; + /** + * Get a the last added node (Mesh, Camera, Light) found of a given ID + * @param {string} id - the id to search for + * @return {BABYLON.Node|null} the node found or null if not found at all. + */ + getLastEntryByID(id: string): Node; + getNodeByID(id: string): Node; + getNodeByName(name: string): Node; + getMeshByName(name: string): AbstractMesh; + getSoundByName(name: string): Sound; + getLastSkeletonByID(id: string): Skeleton; + getSkeletonById(id: string): Skeleton; + getSkeletonByName(name: string): Skeleton; + isActiveMesh(mesh: Mesh): boolean; + private _evaluateSubMesh(subMesh, mesh); + private _evaluateActiveMeshes(); + private _activeMesh(mesh); + updateTransformMatrix(force?: boolean): void; + private _renderForCamera(camera); + private _processSubCameras(camera); + private _checkIntersections(); + render(): void; + private _updateAudioParameters(); + audioEnabled: boolean; + private _disableAudio(); + private _enableAudio(); + headphone: boolean; + private _switchAudioModeForHeadphones(); + private _switchAudioModeForNormalSpeakers(); + enableDepthRenderer(): DepthRenderer; + disableDepthRenderer(): void; + dispose(): void; + disposeSounds(): void; + getWorldExtends(): { + min: Vector3; + max: Vector3; + }; + createOrUpdateSelectionOctree(maxCapacity?: number, maxDepth?: number): Octree; + createPickingRay(x: number, y: number, world: Matrix, camera: Camera): Ray; + private _internalPick(rayFunction, predicate, fastCheck?); + pick(x: number, y: number, predicate?: (mesh: AbstractMesh) => boolean, fastCheck?: boolean, camera?: Camera): PickingInfo; + pickWithRay(ray: Ray, predicate: (mesh: Mesh) => boolean, fastCheck?: boolean): PickingInfo; + setPointerOverMesh(mesh: AbstractMesh): void; + getPointerOverMesh(): AbstractMesh; + getPhysicsEngine(): PhysicsEngine; + enablePhysics(gravity: Vector3, plugin?: IPhysicsEnginePlugin): boolean; + disablePhysicsEngine(): void; + isPhysicsEnabled(): boolean; + setGravity(gravity: Vector3): void; + createCompoundImpostor(parts: any, options: PhysicsBodyCreationOptions): any; + deleteCompoundImpostor(compound: any): void; + createDefaultCameraOrLight(): void; + private _getByTags(list, tagsQuery, forEach?); + getMeshesByTags(tagsQuery: string, forEach?: (mesh: AbstractMesh) => void): Mesh[]; + getCamerasByTags(tagsQuery: string, forEach?: (camera: Camera) => void): Camera[]; + getLightsByTags(tagsQuery: string, forEach?: (light: Light) => void): Light[]; + getMaterialByTags(tagsQuery: string, forEach?: (material: Material) => void): Material[]; + } +} + +declare module BABYLON { + class Action { + triggerOptions: any; + trigger: number; + _actionManager: ActionManager; + private _nextActiveAction; + private _child; + private _condition; + private _triggerParameter; + constructor(triggerOptions: any, condition?: Condition); + _prepare(): void; + getTriggerParameter(): any; + _executeCurrent(evt: ActionEvent): void; + execute(evt: ActionEvent): void; + then(action: Action): Action; + _getProperty(propertyPath: string): string; + _getEffectiveTarget(target: any, propertyPath: string): any; + } +} + +declare module BABYLON { + /** + * ActionEvent is the event beint sent when an action is triggered. + */ + class ActionEvent { + source: AbstractMesh; + pointerX: number; + pointerY: number; + meshUnderPointer: AbstractMesh; + sourceEvent: any; + additionalData: any; + /** + * @constructor + * @param source The mesh that triggered the action. + * @param pointerX the X mouse cursor position at the time of the event + * @param pointerY the Y mouse cursor position at the time of the event + * @param meshUnderPointer The mesh that is currently pointed at (can be null) + * @param sourceEvent the original (browser) event that triggered the ActionEvent + */ + constructor(source: AbstractMesh, pointerX: number, pointerY: number, meshUnderPointer: AbstractMesh, sourceEvent?: any, additionalData?: any); + /** + * Helper function to auto-create an ActionEvent from a source mesh. + * @param source the source mesh that triggered the event + * @param evt {Event} The original (browser) event + */ + static CreateNew(source: AbstractMesh, evt?: Event, additionalData?: any): ActionEvent; + /** + * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew + * @param scene the scene where the event occurred + * @param evt {Event} The original (browser) event + */ + static CreateNewFromScene(scene: Scene, evt: Event): ActionEvent; + } + /** + * Action Manager manages all events to be triggered on a given mesh or the global scene. + * A single scene can have many Action Managers to handle predefined actions on specific meshes. + */ + class ActionManager { + private static _NothingTrigger; + private static _OnPickTrigger; + private static _OnLeftPickTrigger; + private static _OnRightPickTrigger; + private static _OnCenterPickTrigger; + private static _OnPointerOverTrigger; + private static _OnPointerOutTrigger; + private static _OnEveryFrameTrigger; + private static _OnIntersectionEnterTrigger; + private static _OnIntersectionExitTrigger; + private static _OnKeyDownTrigger; + private static _OnKeyUpTrigger; + private static _OnPickUpTrigger; + static NothingTrigger: number; + static OnPickTrigger: number; + static OnLeftPickTrigger: number; + static OnRightPickTrigger: number; + static OnCenterPickTrigger: number; + static OnPointerOverTrigger: number; + static OnPointerOutTrigger: number; + static OnEveryFrameTrigger: number; + static OnIntersectionEnterTrigger: number; + static OnIntersectionExitTrigger: number; + static OnKeyDownTrigger: number; + static OnKeyUpTrigger: number; + static OnPickUpTrigger: number; + actions: Action[]; + private _scene; + constructor(scene: Scene); + dispose(): void; + getScene(): Scene; + /** + * Does this action manager handles actions of any of the given triggers + * @param {number[]} triggers - the triggers to be tested + * @return {boolean} whether one (or more) of the triggers is handeled + */ + hasSpecificTriggers(triggers: number[]): boolean; + /** + * Does this action manager handles actions of a given trigger + * @param {number} trigger - the trigger to be tested + * @return {boolean} whether the trigger is handeled + */ + hasSpecificTrigger(trigger: number): boolean; + /** + * Does this action manager has pointer triggers + * @return {boolean} whether or not it has pointer triggers + */ + hasPointerTriggers: boolean; + /** + * Does this action manager has pick triggers + * @return {boolean} whether or not it has pick triggers + */ + hasPickTriggers: boolean; + /** + * Registers an action to this action manager + * @param {BABYLON.Action} action - the action to be registered + * @return {BABYLON.Action} the action amended (prepared) after registration + */ + registerAction(action: Action): Action; + /** + * Process a specific trigger + * @param {number} trigger - the trigger to process + * @param evt {BABYLON.ActionEvent} the event details to be processed + */ + processTrigger(trigger: number, evt: ActionEvent): void; + _getEffectiveTarget(target: any, propertyPath: string): any; + _getProperty(propertyPath: string): string; + } +} + +declare module BABYLON { + class Condition { + _actionManager: ActionManager; + _evaluationId: number; + _currentResult: boolean; + constructor(actionManager: ActionManager); + isValid(): boolean; + _getProperty(propertyPath: string): string; + _getEffectiveTarget(target: any, propertyPath: string): any; + } + class ValueCondition extends Condition { + propertyPath: string; + value: any; + operator: number; + private static _IsEqual; + private static _IsDifferent; + private static _IsGreater; + private static _IsLesser; + static IsEqual: number; + static IsDifferent: number; + static IsGreater: number; + static IsLesser: number; + _actionManager: ActionManager; + private _target; + private _property; + constructor(actionManager: ActionManager, target: any, propertyPath: string, value: any, operator?: number); + isValid(): boolean; + } + class PredicateCondition extends Condition { + predicate: () => boolean; + _actionManager: ActionManager; + constructor(actionManager: ActionManager, predicate: () => boolean); + isValid(): boolean; + } + class StateCondition extends Condition { + value: string; + _actionManager: ActionManager; + private _target; + constructor(actionManager: ActionManager, target: any, value: string); + isValid(): boolean; + } +} + +declare module BABYLON { + class SwitchBooleanAction extends Action { + propertyPath: string; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, condition?: Condition); + _prepare(): void; + execute(): void; + } + class SetStateAction extends Action { + value: string; + private _target; + constructor(triggerOptions: any, target: any, value: string, condition?: Condition); + execute(): void; + } + class SetValueAction extends Action { + propertyPath: string; + value: any; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class IncrementValueAction extends Action { + propertyPath: string; + value: any; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class PlayAnimationAction extends Action { + from: number; + to: number; + loop: boolean; + private _target; + constructor(triggerOptions: any, target: any, from: number, to: number, loop?: boolean, condition?: Condition); + _prepare(): void; + execute(): void; + } + class StopAnimationAction extends Action { + private _target; + constructor(triggerOptions: any, target: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class DoNothingAction extends Action { + constructor(triggerOptions?: any, condition?: Condition); + execute(): void; + } + class CombineAction extends Action { + children: Action[]; + constructor(triggerOptions: any, children: Action[], condition?: Condition); + _prepare(): void; + execute(evt: ActionEvent): void; + } + class ExecuteCodeAction extends Action { + func: (evt: ActionEvent) => void; + constructor(triggerOptions: any, func: (evt: ActionEvent) => void, condition?: Condition); + execute(evt: ActionEvent): void; + } + class SetParentAction extends Action { + private _parent; + private _target; + constructor(triggerOptions: any, target: any, parent: any, condition?: Condition); + _prepare(): void; + execute(): void; + } + class PlaySoundAction extends Action { + private _sound; + constructor(triggerOptions: any, sound: Sound, condition?: Condition); + _prepare(): void; + execute(): void; + } + class StopSoundAction extends Action { + private _sound; + constructor(triggerOptions: any, sound: Sound, condition?: Condition); + _prepare(): void; + execute(): void; + } +} + +declare module BABYLON { + class InterpolateValueAction extends Action { + propertyPath: string; + value: any; + duration: number; + stopOtherAnimations: boolean; + private _target; + private _property; + constructor(triggerOptions: any, target: any, propertyPath: string, value: any, duration?: number, condition?: Condition, stopOtherAnimations?: boolean); + _prepare(): void; + execute(): void; + } +} + +declare module BABYLON { + class Animatable { + target: any; + fromFrame: number; + toFrame: number; + loopAnimation: boolean; + speedRatio: number; + onAnimationEnd: any; + private _localDelayOffset; + private _pausedDelay; + private _animations; + private _paused; + private _scene; + animationStarted: boolean; + constructor(scene: Scene, target: any, fromFrame?: number, toFrame?: number, loopAnimation?: boolean, speedRatio?: number, onAnimationEnd?: any, animations?: any); + appendAnimations(target: any, animations: Animation[]): void; + getAnimationByTargetProperty(property: string): Animation; + reset(): void; + pause(): void; + restart(): void; + stop(): void; + _animate(delay: number): boolean; + } +} + +declare module BABYLON { + class Animation { + name: string; + targetProperty: string; + framePerSecond: number; + dataType: number; + loopMode: number; + private _keys; + private _offsetsCache; + private _highLimitsCache; + private _stopped; + _target: any; + private _easingFunction; + targetPropertyPath: string[]; + currentFrame: number; + allowMatricesInterpolation: boolean; + static CreateAndStartAnimation(name: string, mesh: AbstractMesh, targetProperty: string, framePerSecond: number, totalFrame: number, from: any, to: any, loopMode?: number, easingFunction?: EasingFunction): Animatable; + constructor(name: string, targetProperty: string, framePerSecond: number, dataType: number, loopMode?: number); + reset(): void; + isStopped(): boolean; + getKeys(): any[]; + getEasingFunction(): IEasingFunction; + setEasingFunction(easingFunction: EasingFunction): void; + floatInterpolateFunction(startValue: number, endValue: number, gradient: number): number; + quaternionInterpolateFunction(startValue: Quaternion, endValue: Quaternion, gradient: number): Quaternion; + vector3InterpolateFunction(startValue: Vector3, endValue: Vector3, gradient: number): Vector3; + vector2InterpolateFunction(startValue: Vector2, endValue: Vector2, gradient: number): Vector2; + color3InterpolateFunction(startValue: Color3, endValue: Color3, gradient: number): Color3; + matrixInterpolateFunction(startValue: Matrix, endValue: Matrix, gradient: number): Matrix; + clone(): Animation; + setKeys(values: Array): void; + private _getKeyValue(value); + private _interpolate(currentFrame, repeatCount, loopMode, offsetValue?, highLimitValue?); + animate(delay: number, from: number, to: number, loop: boolean, speedRatio: number): boolean; + private static _ANIMATIONTYPE_FLOAT; + private static _ANIMATIONTYPE_VECTOR3; + private static _ANIMATIONTYPE_QUATERNION; + private static _ANIMATIONTYPE_MATRIX; + private static _ANIMATIONTYPE_COLOR3; + private static _ANIMATIONTYPE_VECTOR2; + private static _ANIMATIONLOOPMODE_RELATIVE; + private static _ANIMATIONLOOPMODE_CYCLE; + private static _ANIMATIONLOOPMODE_CONSTANT; + static ANIMATIONTYPE_FLOAT: number; + static ANIMATIONTYPE_VECTOR3: number; + static ANIMATIONTYPE_VECTOR2: number; + static ANIMATIONTYPE_QUATERNION: number; + static ANIMATIONTYPE_MATRIX: number; + static ANIMATIONTYPE_COLOR3: number; + static ANIMATIONLOOPMODE_RELATIVE: number; + static ANIMATIONLOOPMODE_CYCLE: number; + static ANIMATIONLOOPMODE_CONSTANT: number; + } +} + +declare module BABYLON { + interface IEasingFunction { + ease(gradient: number): number; + } + class EasingFunction implements IEasingFunction { + private static _EASINGMODE_EASEIN; + private static _EASINGMODE_EASEOUT; + private static _EASINGMODE_EASEINOUT; + static EASINGMODE_EASEIN: number; + static EASINGMODE_EASEOUT: number; + static EASINGMODE_EASEINOUT: number; + private _easingMode; + setEasingMode(easingMode: number): void; + getEasingMode(): number; + easeInCore(gradient: number): number; + ease(gradient: number): number; + } + class CircleEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class BackEase extends EasingFunction implements IEasingFunction { + amplitude: number; + constructor(amplitude?: number); + easeInCore(gradient: number): number; + } + class BounceEase extends EasingFunction implements IEasingFunction { + bounces: number; + bounciness: number; + constructor(bounces?: number, bounciness?: number); + easeInCore(gradient: number): number; + } + class CubicEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class ElasticEase extends EasingFunction implements IEasingFunction { + oscillations: number; + springiness: number; + constructor(oscillations?: number, springiness?: number); + easeInCore(gradient: number): number; + } + class ExponentialEase extends EasingFunction implements IEasingFunction { + exponent: number; + constructor(exponent?: number); + easeInCore(gradient: number): number; + } + class PowerEase extends EasingFunction implements IEasingFunction { + power: number; + constructor(power?: number); + easeInCore(gradient: number): number; + } + class QuadraticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class QuarticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class QuinticEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class SineEase extends EasingFunction implements IEasingFunction { + easeInCore(gradient: number): number; + } + class BezierCurveEase extends EasingFunction implements IEasingFunction { + x1: number; + y1: number; + x2: number; + y2: number; + constructor(x1?: number, y1?: number, x2?: number, y2?: number); + easeInCore(gradient: number): number; + } +} + +declare module BABYLON { + class Analyser { + SMOOTHING: number; + FFT_SIZE: number; + BARGRAPHAMPLITUDE: number; + DEBUGCANVASPOS: { + x: number; + y: number; + }; + DEBUGCANVASSIZE: { + width: number; + height: number; + }; + private _byteFreqs; + private _byteTime; + private _floatFreqs; + private _webAudioAnalyser; + private _debugCanvas; + private _debugCanvasContext; + private _scene; + private _registerFunc; + private _audioEngine; + constructor(scene: Scene); + getFrequencyBinCount(): number; + getByteFrequencyData(): Uint8Array; + getByteTimeDomainData(): Uint8Array; + getFloatFrequencyData(): Uint8Array; + drawDebugCanvas(): void; + stopDebugCanvas(): void; + connectAudioNodes(inputAudioNode: AudioNode, outputAudioNode: AudioNode): void; + dispose(): void; + } +} + +declare module BABYLON { + class AudioEngine { + private _audioContext; + private _audioContextInitialized; + canUseWebAudio: boolean; + masterGain: GainNode; + private _connectedAnalyser; + WarnedWebAudioUnsupported: boolean; + audioContext: AudioContext; + constructor(); + private _initializeAudioContext(); + dispose(): void; + getGlobalVolume(): number; + setGlobalVolume(newVolume: number): void; + connectToAnalyser(analyser: Analyser): void; + } +} + +declare module BABYLON { + class Sound { + name: string; + autoplay: boolean; + loop: boolean; + useCustomAttenuation: boolean; + soundTrackId: number; + spatialSound: boolean; + refDistance: number; + rolloffFactor: number; + maxDistance: number; + distanceModel: string; + private _panningModel; + onended: () => any; + private _playbackRate; + private _startTime; + private _startOffset; + private _position; + private _localDirection; + private _volume; + private _isLoaded; + private _isReadyToPlay; + isPlaying: boolean; + isPaused: boolean; + private _isDirectional; + private _readyToPlayCallback; + private _audioBuffer; + private _soundSource; + private _soundPanner; + private _soundGain; + private _inputAudioNode; + private _ouputAudioNode; + private _coneInnerAngle; + private _coneOuterAngle; + private _coneOuterGain; + private _scene; + private _connectedMesh; + private _customAttenuationFunction; + private _registerFunc; + private _isOutputConnected; + /** + * Create a sound and attach it to a scene + * @param name Name of your sound + * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer + * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played + * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel + */ + constructor(name: string, urlOrArrayBuffer: any, scene: Scene, readyToPlayCallback?: () => void, options?: any); + dispose(): void; + private _soundLoaded(audioData); + setAudioBuffer(audioBuffer: AudioBuffer): void; + updateOptions(options: any): void; + private _createSpatialParameters(); + private _updateSpatialParameters(); + switchPanningModelToHRTF(): void; + switchPanningModelToEqualPower(): void; + private _switchPanningModel(); + connectToSoundTrackAudioNode(soundTrackAudioNode: AudioNode): void; + /** + * Transform this sound into a directional source + * @param coneInnerAngle Size of the inner cone in degree + * @param coneOuterAngle Size of the outer cone in degree + * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) + */ + setDirectionalCone(coneInnerAngle: number, coneOuterAngle: number, coneOuterGain: number): void; + setPosition(newPosition: Vector3): void; + setLocalDirectionToMesh(newLocalDirection: Vector3): void; + private _updateDirection(); + updateDistanceFromListener(): void; + setAttenuationFunction(callback: (currentVolume: number, currentDistance: number, maxDistance: number, refDistance: number, rolloffFactor: number) => number): void; + /** + * Play the sound + * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. + */ + play(time?: number): void; + private _onended(); + /** + * Stop the sound + * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. + */ + stop(time?: number): void; + pause(): void; + setVolume(newVolume: number, time?: number): void; + setPlaybackRate(newPlaybackRate: number): void; + getVolume(): number; + attachToMesh(meshToConnectTo: AbstractMesh): void; + private _onRegisterAfterWorldMatrixUpdate(connectedMesh); + } +} + +declare module BABYLON { + class SoundTrack { + private _audioEngine; + private _outputAudioNode; + private _inputAudioNode; + private _trackConvolver; + private _scene; + id: number; + soundCollection: Array; + private _isMainTrack; + private _connectedAnalyser; + constructor(scene: Scene, options?: any); + dispose(): void; + AddSound(sound: Sound): void; + RemoveSound(sound: Sound): void; + setVolume(newVolume: number): void; + switchPanningModelToHRTF(): void; + switchPanningModelToEqualPower(): void; + connectToAnalyser(analyser: Analyser): void; + } +} + +declare module BABYLON { + class Bone extends Node { + name: string; + children: Bone[]; + animations: Animation[]; + private _skeleton; + private _matrix; + private _baseMatrix; + private _worldTransform; + private _absoluteTransform; + private _invertedAbsoluteTransform; + private _parent; + constructor(name: string, skeleton: Skeleton, parentBone: Bone, matrix: Matrix); + getParent(): Bone; + getLocalMatrix(): Matrix; + getBaseMatrix(): Matrix; + getWorldMatrix(): Matrix; + getInvertedAbsoluteTransform(): Matrix; + getAbsoluteMatrix(): Matrix; + updateMatrix(matrix: Matrix): void; + private _updateDifferenceMatrix(); + markAsDirty(): void; + } +} + +declare module BABYLON { + class Skeleton { + name: string; + id: string; + bones: Bone[]; + private _scene; + private _isDirty; + private _transformMatrices; + private _animatables; + private _identity; + constructor(name: string, id: string, scene: Scene); + getTransformMatrices(): Float32Array; + getScene(): Scene; + _markAsDirty(): void; + prepare(): void; + getAnimatables(): IAnimatable[]; + clone(name: string, id: string): Skeleton; + } +} + +declare module BABYLON { + class ArcRotateCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + target: any; + inertialAlphaOffset: number; + inertialBetaOffset: number; + inertialRadiusOffset: number; + lowerAlphaLimit: any; + upperAlphaLimit: any; + lowerBetaLimit: number; + upperBetaLimit: number; + lowerRadiusLimit: any; + upperRadiusLimit: any; + angularSensibilityX: number; + angularSensibilityY: number; + wheelPrecision: number; + pinchPrecision: number; + panningSensibility: number; + inertialPanningX: number; + inertialPanningY: number; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + zoomOnFactor: number; + targetScreenOffset: Vector2; + pinchInwards: boolean; + allowUpsideDown: boolean; + private _keys; + _viewMatrix: Matrix; + private _attachedElement; + private _onContextMenu; + private _onPointerDown; + private _onPointerUp; + private _onPointerMove; + private _wheel; + private _onMouseMove; + private _onKeyDown; + private _onKeyUp; + private _onLostFocus; + _reset: () => void; + private _onGestureStart; + private _onGesture; + private _MSGestureHandler; + private _localDirection; + private _transformedDirection; + private _isRightClick; + private _isCtrlPushed; + onCollide: (collidedMesh: AbstractMesh) => void; + checkCollisions: boolean; + collisionRadius: Vector3; + private _collider; + private _previousPosition; + private _collisionVelocity; + private _newPosition; + private _previousAlpha; + private _previousBeta; + private _previousRadius; + private _collisionTriggered; + angularSensibility: number; + constructor(name: string, alpha: number, beta: number, radius: number, target: any, scene: Scene); + _getTargetPosition(): Vector3; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronizedViewMatrix(): boolean; + attachControl(element: HTMLElement, noPreventDefault?: boolean, useCtrlForPanning?: boolean): void; + detachControl(element: HTMLElement): void; + _checkInputs(): void; + private _checkLimits(); + setPosition(position: Vector3): void; + setTarget(target: Vector3): void; + _getViewMatrix(): Matrix; + private _onCollisionPositionChange; + zoomOn(meshes?: AbstractMesh[], doNotUpdateMaxZ?: boolean): void; + focusOn(meshesOrMinMaxVectorAndDistance: any, doNotUpdateMaxZ?: boolean): void; + /** + * @override + * Override Camera.createRigCamera + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras(): void; + } +} + +declare module BABYLON { + class VRCameraMetrics { + hResolution: number; + vResolution: number; + hScreenSize: number; + vScreenSize: number; + vScreenCenter: number; + eyeToScreenDistance: number; + lensSeparationDistance: number; + interpupillaryDistance: number; + distortionK: number[]; + chromaAbCorrection: number[]; + postProcessScaleFactor: number; + lensCenterOffset: number; + compensateDistorsion: boolean; + aspectRatio: number; + aspectRatioFov: number; + leftHMatrix: Matrix; + rightHMatrix: Matrix; + leftPreViewMatrix: Matrix; + rightPreViewMatrix: Matrix; + static GetDefault(): VRCameraMetrics; + } + class Camera extends Node { + position: Vector3; + private static _PERSPECTIVE_CAMERA; + private static _ORTHOGRAPHIC_CAMERA; + private static _FOVMODE_VERTICAL_FIXED; + private static _FOVMODE_HORIZONTAL_FIXED; + private static _RIG_MODE_NONE; + private static _RIG_MODE_STEREOSCOPIC_ANAGLYPH; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL; + private static _RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; + private static _RIG_MODE_STEREOSCOPIC_OVERUNDER; + private static _RIG_MODE_VR; + static PERSPECTIVE_CAMERA: number; + static ORTHOGRAPHIC_CAMERA: number; + static FOVMODE_VERTICAL_FIXED: number; + static FOVMODE_HORIZONTAL_FIXED: number; + static RIG_MODE_NONE: number; + static RIG_MODE_STEREOSCOPIC_ANAGLYPH: number; + static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL: number; + static RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED: number; + static RIG_MODE_STEREOSCOPIC_OVERUNDER: number; + static RIG_MODE_VR: number; + upVector: Vector3; + orthoLeft: any; + orthoRight: any; + orthoBottom: any; + orthoTop: any; + fov: number; + minZ: number; + maxZ: number; + inertia: number; + mode: number; + isIntermediate: boolean; + viewport: Viewport; + layerMask: number; + fovMode: number; + cameraRigMode: number; + _cameraRigParams: any; + _rigCameras: Camera[]; + private _computedViewMatrix; + _projectionMatrix: Matrix; + private _worldMatrix; + _postProcesses: PostProcess[]; + _postProcessesTakenIndices: any[]; + _activeMeshes: SmartArray; + private _globalPosition; + constructor(name: string, position: Vector3, scene: Scene); + globalPosition: Vector3; + getActiveMeshes(): SmartArray; + isActiveMesh(mesh: Mesh): boolean; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _updateFromScene(): void; + _isSynchronized(): boolean; + _isSynchronizedViewMatrix(): boolean; + _isSynchronizedProjectionMatrix(): boolean; + attachControl(element: HTMLElement): void; + detachControl(element: HTMLElement): void; + _update(): void; + _checkInputs(): void; + attachPostProcess(postProcess: PostProcess, insertAt?: number): number; + detachPostProcess(postProcess: PostProcess, atIndices?: any): number[]; + getWorldMatrix(): Matrix; + _getViewMatrix(): Matrix; + getViewMatrix(force?: boolean): Matrix; + _computeViewMatrix(force?: boolean): Matrix; + getProjectionMatrix(force?: boolean): Matrix; + dispose(): void; + setCameraRigMode(mode: number, rigParams: any): void; + private _getVRProjectionMatrix(); + setCameraRigParameter(name: string, value: any): void; + /** + * May needs to be overridden by children so sub has required properties to be copied + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * May needs to be overridden by children + */ + _updateRigCameras(): void; + } +} + +declare module BABYLON { + class DeviceOrientationCamera extends FreeCamera { + private _offsetX; + private _offsetY; + private _orientationGamma; + private _orientationBeta; + private _initialOrientationGamma; + private _initialOrientationBeta; + private _attachedCanvas; + private _orientationChanged; + angularSensibility: number; + moveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; + detachControl(canvas: HTMLCanvasElement): void; + _checkInputs(): void; + } +} + +declare module BABYLON { + class FollowCamera extends TargetCamera { + radius: number; + rotationOffset: number; + heightOffset: number; + cameraAcceleration: number; + maxCameraSpeed: number; + target: AbstractMesh; + constructor(name: string, position: Vector3, scene: Scene); + private getRadians(degrees); + private follow(cameraTarget); + _checkInputs(): void; + } + class ArcFollowCamera extends TargetCamera { + alpha: number; + beta: number; + radius: number; + target: AbstractMesh; + private _cartesianCoordinates; + constructor(name: string, alpha: number, beta: number, radius: number, target: AbstractMesh, scene: Scene); + private follow(); + _checkInputs(): void; + } +} + +declare module BABYLON { + class FreeCamera extends TargetCamera { + ellipsoid: Vector3; + keysUp: number[]; + keysDown: number[]; + keysLeft: number[]; + keysRight: number[]; + checkCollisions: boolean; + applyGravity: boolean; + angularSensibility: number; + onCollide: (collidedMesh: AbstractMesh) => void; + private _keys; + private _collider; + private _needMoveForGravity; + private _oldPosition; + private _diffPosition; + private _newPosition; + private _attachedElement; + private _localDirection; + private _transformedDirection; + private _onMouseDown; + private _onMouseUp; + private _onMouseOut; + private _onMouseMove; + private _onKeyDown; + private _onKeyUp; + _onLostFocus: (e: FocusEvent) => any; + _waitingLockedTargetId: string; + constructor(name: string, position: Vector3, scene: Scene); + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + _collideWithWorld(velocity: Vector3): void; + private _onCollisionPositionChange; + _checkInputs(): void; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + } +} + +declare module BABYLON { + class GamepadCamera extends FreeCamera { + private _gamepad; + private _gamepads; + angularSensibility: number; + moveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + private _onNewGameConnected(gamepad); + _checkInputs(): void; + dispose(): void; + } +} + +declare module BABYLON { + class AnaglyphFreeCamera extends FreeCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); + } + class AnaglyphArcRotateCamera extends ArcRotateCamera { + constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, scene: Scene); + } + class AnaglyphGamepadCamera extends GamepadCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, scene: Scene); + } + class StereoscopicFreeCamera extends FreeCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } + class StereoscopicArcRotateCamera extends ArcRotateCamera { + constructor(name: string, alpha: number, beta: number, radius: number, target: any, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } + class StereoscopicGamepadCamera extends GamepadCamera { + constructor(name: string, position: Vector3, interaxialDistance: number, isSideBySide: boolean, scene: Scene); + } +} + +declare module BABYLON { + class TargetCamera extends Camera { + cameraDirection: Vector3; + cameraRotation: Vector2; + rotation: Vector3; + speed: number; + noRotationConstraint: boolean; + lockedTarget: any; + _currentTarget: Vector3; + _viewMatrix: Matrix; + _camMatrix: Matrix; + _cameraTransformMatrix: Matrix; + _cameraRotationMatrix: Matrix; + private _rigCamTransformMatrix; + _referencePoint: Vector3; + _transformedReferencePoint: Vector3; + _lookAtTemp: Matrix; + _tempMatrix: Matrix; + _reset: () => void; + _waitingLockedTargetId: string; + constructor(name: string, position: Vector3, scene: Scene); + getFrontPosition(distance: number): Vector3; + _getLockedTargetPosition(): Vector3; + _initCache(): void; + _updateCache(ignoreParentClass?: boolean): void; + _isSynchronizedViewMatrix(): boolean; + _computeLocalCameraSpeed(): number; + setTarget(target: Vector3): void; + getTarget(): Vector3; + _decideIfNeedsToMove(): boolean; + _updatePosition(): void; + _checkInputs(): void; + _getViewMatrix(): Matrix; + _getVRViewMatrix(): Matrix; + /** + * @override + * Override Camera.createRigCamera + */ + createRigCamera(name: string, cameraIndex: number): Camera; + /** + * @override + * Override Camera._updateRigCameras + */ + _updateRigCameras(): void; + private _getRigCamPosition(halfSpace, result); + } +} + +declare module BABYLON { + class TouchCamera extends FreeCamera { + private _offsetX; + private _offsetY; + private _pointerCount; + private _pointerPressed; + private _attachedCanvas; + private _onPointerDown; + private _onPointerUp; + private _onPointerMove; + angularSensibility: number; + moveSensibility: number; + constructor(name: string, position: Vector3, scene: Scene); + attachControl(canvas: HTMLCanvasElement, noPreventDefault: boolean): void; + detachControl(canvas: HTMLCanvasElement): void; + _checkInputs(): void; + } +} + +declare module BABYLON { + class VirtualJoysticksCamera extends FreeCamera { + private _leftjoystick; + private _rightjoystick; + constructor(name: string, position: Vector3, scene: Scene); + getLeftJoystick(): VirtualJoystick; + getRightJoystick(): VirtualJoystick; + _checkInputs(): void; + dispose(): void; + } +} + +declare module BABYLON { + class Collider { + radius: Vector3; + retry: number; + velocity: Vector3; + basePoint: Vector3; + epsilon: number; + collisionFound: boolean; + velocityWorldLength: number; + basePointWorld: Vector3; + velocityWorld: Vector3; + normalizedVelocity: Vector3; + initialVelocity: Vector3; + initialPosition: Vector3; + nearestDistance: number; + intersectionPoint: Vector3; + collidedMesh: AbstractMesh; + private _collisionPoint; + private _planeIntersectionPoint; + private _tempVector; + private _tempVector2; + private _tempVector3; + private _tempVector4; + private _edge; + private _baseToVertex; + private _destinationPoint; + private _slidePlaneNormal; + private _displacementVector; + _initialize(source: Vector3, dir: Vector3, e: number): void; + _checkPointInTriangle(point: Vector3, pa: Vector3, pb: Vector3, pc: Vector3, n: Vector3): boolean; + _canDoCollision(sphereCenter: Vector3, sphereRadius: number, vecMin: Vector3, vecMax: Vector3): boolean; + _testTriangle(faceIndex: number, trianglePlaneArray: Array, p1: Vector3, p2: Vector3, p3: Vector3, hasMaterial: boolean): void; + _collide(trianglePlaneArray: Array, pts: Vector3[], indices: number[], indexStart: number, indexEnd: number, decal: number, hasMaterial: boolean): void; + _getResponse(pos: Vector3, vel: Vector3): void; + } +} + +declare module BABYLON { + var CollisionWorker: string; + interface ICollisionCoordinator { + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): any; + onMeshUpdated(mesh: AbstractMesh): any; + onMeshRemoved(mesh: AbstractMesh): any; + onGeometryAdded(geometry: Geometry): any; + onGeometryUpdated(geometry: Geometry): any; + onGeometryDeleted(geometry: Geometry): any; + } + interface SerializedMesh { + id: string; + name: string; + uniqueId: number; + geometryId: string; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + worldMatrixFromCache: any; + subMeshes: Array; + checkCollisions: boolean; + } + interface SerializedSubMesh { + position: number; + verticesStart: number; + verticesCount: number; + indexStart: number; + indexCount: number; + hasMaterial: boolean; + sphereCenter: Array; + sphereRadius: number; + boxMinimum: Array; + boxMaximum: Array; + } + interface SerializedGeometry { + id: string; + positions: Float32Array; + indices: Int32Array; + normals: Float32Array; + } + interface BabylonMessage { + taskType: WorkerTaskType; + payload: InitPayload | CollidePayload | UpdatePayload; + } + interface SerializedColliderToWorker { + position: Array; + velocity: Array; + radius: Array; + } + enum WorkerTaskType { + INIT = 0, + UPDATE = 1, + COLLIDE = 2, + } + interface WorkerReply { + error: WorkerReplyType; + taskType: WorkerTaskType; + payload?: any; + } + interface CollisionReplyPayload { + newPosition: Array; + collisionId: number; + collidedMeshUniqueId: number; + } + interface InitPayload { + } + interface CollidePayload { + collisionId: number; + collider: SerializedColliderToWorker; + maximumRetry: number; + excludedMeshUniqueId?: number; + } + interface UpdatePayload { + updatedMeshes: { + [n: number]: SerializedMesh; + }; + updatedGeometries: { + [s: string]: SerializedGeometry; + }; + removedMeshes: Array; + removedGeometries: Array; + } + enum WorkerReplyType { + SUCCESS = 0, + UNKNOWN_ERROR = 1, + } + class CollisionCoordinatorWorker implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _collisionsCallbackArray; + private _init; + private _runningUpdated; + private _runningCollisionTask; + private _worker; + private _addUpdateMeshesList; + private _addUpdateGeometriesList; + private _toRemoveMeshesArray; + private _toRemoveGeometryArray; + constructor(); + static SerializeMesh: (mesh: AbstractMesh) => SerializedMesh; + static SerializeGeometry: (geometry: Geometry) => SerializedGeometry; + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated: (mesh: AbstractMesh) => void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated: (geometry: Geometry) => void; + onGeometryDeleted(geometry: Geometry): void; + private _afterRender; + private _onMessageFromWorker; + } + class CollisionCoordinatorLegacy implements ICollisionCoordinator { + private _scene; + private _scaledPosition; + private _scaledVelocity; + private _finalPosition; + getNewPosition(position: Vector3, velocity: Vector3, collider: Collider, maximumRetry: number, excludedMesh: AbstractMesh, onNewPosition: (collisionIndex: number, newPosition: Vector3, collidedMesh?: AbstractMesh) => void, collisionIndex: number): void; + init(scene: Scene): void; + destroy(): void; + onMeshAdded(mesh: AbstractMesh): void; + onMeshUpdated(mesh: AbstractMesh): void; + onMeshRemoved(mesh: AbstractMesh): void; + onGeometryAdded(geometry: Geometry): void; + onGeometryUpdated(geometry: Geometry): void; + onGeometryDeleted(geometry: Geometry): void; + private _collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh?); + } +} + +declare module BABYLON { + var WorkerIncluded: boolean; + class CollisionCache { + private _meshes; + private _geometries; + getMeshes(): { + [n: number]: SerializedMesh; + }; + getGeometries(): { + [s: number]: SerializedGeometry; + }; + getMesh(id: any): SerializedMesh; + addMesh(mesh: SerializedMesh): void; + getGeometry(id: string): SerializedGeometry; + addGeometry(geometry: SerializedGeometry): void; + } + class CollideWorker { + collider: Collider; + private _collisionCache; + private finalPosition; + private collisionsScalingMatrix; + private collisionTranformationMatrix; + constructor(collider: Collider, _collisionCache: CollisionCache, finalPosition: Vector3); + collideWithWorld(position: Vector3, velocity: Vector3, maximumRetry: number, excludedMeshUniqueId?: number): void; + private checkCollision(mesh); + private processCollisionsForSubMeshes(transformMatrix, mesh); + private collideForSubMesh(subMesh, transformMatrix, meshGeometry); + private checkSubmeshCollision(subMesh); + } + interface ICollisionDetector { + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } + class CollisionDetectorTransferable implements ICollisionDetector { + private _collisionCache; + onInit(payload: InitPayload): void; + onUpdate(payload: UpdatePayload): void; + onCollision(payload: CollidePayload): void; + } +} + +declare module BABYLON { + class IntersectionInfo { + bu: number; + bv: number; + distance: number; + faceId: number; + subMeshId: number; + constructor(bu: number, bv: number, distance: number); + } + class PickingInfo { + hit: boolean; + distance: number; + pickedPoint: Vector3; + pickedMesh: AbstractMesh; + bu: number; + bv: number; + faceId: number; + subMeshId: number; + getNormal(useWorldCoordinates?: boolean, useVerticesNormals?: boolean): Vector3; + getTextureCoordinates(): Vector2; + } +} + +declare module BABYLON { + class BoundingBox { + minimum: Vector3; + maximum: Vector3; + vectors: Vector3[]; + center: Vector3; + extendSize: Vector3; + directions: Vector3[]; + vectorsWorld: Vector3[]; + minimumWorld: Vector3; + maximumWorld: Vector3; + private _worldMatrix; + constructor(minimum: Vector3, maximum: Vector3); + getWorldMatrix(): Matrix; + _update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + intersectsPoint(point: Vector3): boolean; + intersectsSphere(sphere: BoundingSphere): boolean; + intersectsMinMax(min: Vector3, max: Vector3): boolean; + static Intersects(box0: BoundingBox, box1: BoundingBox): boolean; + static IntersectsSphere(minPoint: Vector3, maxPoint: Vector3, sphereCenter: Vector3, sphereRadius: number): boolean; + static IsCompletelyInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; + static IsInFrustum(boundingVectors: Vector3[], frustumPlanes: Plane[]): boolean; + } +} + +declare module BABYLON { + class BoundingInfo { + minimum: Vector3; + maximum: Vector3; + boundingBox: BoundingBox; + boundingSphere: BoundingSphere; + constructor(minimum: Vector3, maximum: Vector3); + _update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(frustumPlanes: Plane[]): boolean; + _checkCollision(collider: Collider): boolean; + intersectsPoint(point: Vector3): boolean; + intersects(boundingInfo: BoundingInfo, precise: boolean): boolean; + } +} + +declare module BABYLON { + class BoundingSphere { + minimum: Vector3; + maximum: Vector3; + center: Vector3; + radius: number; + centerWorld: Vector3; + radiusWorld: number; + private _tempRadiusVector; + constructor(minimum: Vector3, maximum: Vector3); + _update(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + intersectsPoint(point: Vector3): boolean; + static Intersects(sphere0: BoundingSphere, sphere1: BoundingSphere): boolean; + } +} + +declare module BABYLON { + class DebugLayer { + private _scene; + private _camera; + private _transformationMatrix; + private _enabled; + private _labelsEnabled; + private _displayStatistics; + private _displayTree; + private _displayLogs; + private _globalDiv; + private _statsDiv; + private _statsSubsetDiv; + private _optionsDiv; + private _optionsSubsetDiv; + private _logDiv; + private _logSubsetDiv; + private _treeDiv; + private _treeSubsetDiv; + private _drawingCanvas; + private _drawingContext; + private _syncPositions; + private _syncData; + private _syncUI; + private _onCanvasClick; + private _clickPosition; + private _ratio; + private _identityMatrix; + private _showUI; + private _needToRefreshMeshesTree; + shouldDisplayLabel: (node: Node) => boolean; + shouldDisplayAxis: (mesh: Mesh) => boolean; + axisRatio: number; + accentColor: string; + customStatsFunction: () => string; + constructor(scene: Scene); + private _refreshMeshesTreeContent(); + private _renderSingleAxis(zero, unit, unitText, label, color); + private _renderAxis(projectedPosition, mesh, globalViewport); + private _renderLabel(text, projectedPosition, labelOffset, onClick, getFillStyle); + private _isClickInsideRect(x, y, width, height); + isVisible(): boolean; + hide(): void; + show(showUI?: boolean, camera?: Camera): void; + private _clearLabels(); + private _generateheader(root, text); + private _generateTexBox(root, title, color); + private _generateAdvancedCheckBox(root, leftTitle, rightTitle, initialState, task, tag?); + private _generateCheckBox(root, title, initialState, task, tag?); + private _generateButton(root, title, task, tag?); + private _generateRadio(root, title, name, initialState, task, tag?); + private _generateDOMelements(); + private _displayStats(); + } +} + +declare module BABYLON { + class Layer { + name: string; + texture: Texture; + isBackground: boolean; + color: Color4; + onDispose: () => void; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _effect; + constructor(name: string, imgUrl: string, scene: Scene, isBackground?: boolean, color?: Color4); + render(): void; + dispose(): void; + } +} + +declare module BABYLON { + class LensFlare { + size: number; + position: number; + color: Color3; + texture: Texture; + private _system; + constructor(size: number, position: number, color: any, imgUrl: string, system: LensFlareSystem); + dispose: () => void; + } +} + +declare module BABYLON { + class LensFlareSystem { + name: string; + lensFlares: LensFlare[]; + borderLimit: number; + meshesSelectionPredicate: (mesh: Mesh) => boolean; + layerMask: number; + private _scene; + private _emitter; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _effect; + private _positionX; + private _positionY; + private _isEnabled; + constructor(name: string, emitter: any, scene: Scene); + isEnabled: boolean; + getScene(): Scene; + getEmitter(): any; + setEmitter(newEmitter: any): void; + getEmitterPosition(): Vector3; + computeEffectivePosition(globalViewport: Viewport): boolean; + _isVisible(): boolean; + render(): boolean; + dispose(): void; + } +} + +declare module BABYLON { + class DirectionalLight extends Light implements IShadowLight { + direction: Vector3; + position: Vector3; + private _transformedDirection; + transformedPosition: Vector3; + private _worldMatrix; + shadowOrthoScale: number; + constructor(name: string, direction: Vector3, scene: Scene); + getAbsolutePosition(): Vector3; + setDirectionToTarget(target: Vector3): Vector3; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + computeTransformedPosition(): boolean; + transferToEffect(effect: Effect, directionUniformName: string): void; + _getWorldMatrix(): Matrix; + } +} + +declare module BABYLON { + class HemisphericLight extends Light { + direction: Vector3; + groundColor: Color3; + private _worldMatrix; + constructor(name: string, direction: Vector3, scene: Scene); + setDirectionToTarget(target: Vector3): Vector3; + getShadowGenerator(): ShadowGenerator; + transferToEffect(effect: Effect, directionUniformName: string, groundColorUniformName: string): void; + _getWorldMatrix(): Matrix; + } +} + +declare module BABYLON { + interface IShadowLight { + position: Vector3; + direction: Vector3; + transformedPosition: Vector3; + name: string; + computeTransformedPosition(): boolean; + getScene(): Scene; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + _shadowGenerator: ShadowGenerator; + } + class Light extends Node { + diffuse: Color3; + specular: Color3; + intensity: number; + range: number; + includeOnlyWithLayerMask: number; + includedOnlyMeshes: AbstractMesh[]; + excludedMeshes: AbstractMesh[]; + excludeWithLayerMask: number; + _shadowGenerator: ShadowGenerator; + private _parentedWorldMatrix; + _excludedMeshesIds: string[]; + _includedOnlyMeshesIds: string[]; + constructor(name: string, scene: Scene); + getShadowGenerator(): ShadowGenerator; + getAbsolutePosition(): Vector3; + transferToEffect(effect: Effect, uniformName0?: string, uniformName1?: string): void; + _getWorldMatrix(): Matrix; + canAffectMesh(mesh: AbstractMesh): boolean; + getWorldMatrix(): Matrix; + dispose(): void; + } +} + +declare module BABYLON { + class PointLight extends Light { + position: Vector3; + private _worldMatrix; + private _transformedPosition; + constructor(name: string, position: Vector3, scene: Scene); + getAbsolutePosition(): Vector3; + transferToEffect(effect: Effect, positionUniformName: string): void; + getShadowGenerator(): ShadowGenerator; + _getWorldMatrix(): Matrix; + } +} + +declare module BABYLON { + class SpotLight extends Light implements IShadowLight { + position: Vector3; + direction: Vector3; + angle: number; + exponent: number; + transformedPosition: Vector3; + private _transformedDirection; + private _worldMatrix; + constructor(name: string, position: Vector3, direction: Vector3, angle: number, exponent: number, scene: Scene); + getAbsolutePosition(): Vector3; + setShadowProjectionMatrix(matrix: Matrix, viewMatrix: Matrix, renderList: Array): void; + supportsVSM(): boolean; + needRefreshPerFrame(): boolean; + setDirectionToTarget(target: Vector3): Vector3; + computeTransformedPosition(): boolean; + transferToEffect(effect: Effect, positionUniformName: string, directionUniformName: string): void; + _getWorldMatrix(): Matrix; + } +} + +declare module BABYLON { + interface ISceneLoaderPlugin { + extensions: string; + importMesh: (meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => boolean; + load: (scene: Scene, data: string, rootUrl: string) => boolean; + } + class SceneLoader { + private static _ForceFullSceneLoadingForIncremental; + private static _ShowLoadingScreen; + static ForceFullSceneLoadingForIncremental: boolean; + static ShowLoadingScreen: boolean; + private static _registeredPlugins; + private static _getPluginForFilename(sceneFilename); + static RegisterPlugin(plugin: ISceneLoaderPlugin): void; + static ImportMesh(meshesNames: any, rootUrl: string, sceneFilename: string, scene: Scene, onsuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, progressCallBack?: () => void, onerror?: (scene: Scene, e: any) => void): void; + /** + * Load a scene + * @param rootUrl a string that defines the root url for scene and resources + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene + * @param engine is the instance of BABYLON.Engine to use to create the scene + */ + static Load(rootUrl: string, sceneFilename: any, engine: Engine, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; + /** + * Append a scene + * @param rootUrl a string that defines the root url for scene and resources + * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene + * @param scene is the instance of BABYLON.Scene to append to + */ + static Append(rootUrl: string, sceneFilename: any, scene: Scene, onsuccess?: (scene: Scene) => void, progressCallBack?: any, onerror?: (scene: Scene) => void): void; + } +} + +declare module BABYLON { + class EffectFallbacks { + private _defines; + private _currentRank; + private _maxRank; + addFallback(rank: number, define: string): void; + isMoreFallbacks: boolean; + reduce(currentDefines: string): string; + } + class Effect { + name: any; + defines: string; + onCompiled: (effect: Effect) => void; + onError: (effect: Effect, errors: string) => void; + onBind: (effect: Effect) => void; + private _engine; + private _uniformsNames; + private _samplers; + private _isReady; + private _compilationError; + private _attributesNames; + private _attributes; + private _uniforms; + _key: string; + private _program; + private _valueCache; + constructor(baseName: any, attributesNames: string[], uniformsNames: string[], samplers: string[], engine: any, defines?: string, fallbacks?: EffectFallbacks, onCompiled?: (effect: Effect) => void, onError?: (effect: Effect, errors: string) => void); + isReady(): boolean; + getProgram(): WebGLProgram; + getAttributesNames(): string[]; + getAttributeLocation(index: number): number; + getAttributeLocationByName(name: string): number; + getAttributesCount(): number; + getUniformIndex(uniformName: string): number; + getUniform(uniformName: string): WebGLUniformLocation; + getSamplers(): string[]; + getCompilationError(): string; + _loadVertexShader(vertex: any, callback: (data: any) => void): void; + _loadFragmentShader(fragment: any, callback: (data: any) => void): void; + private _prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks?); + _bindTexture(channel: string, texture: WebGLTexture): void; + setTexture(channel: string, texture: BaseTexture): void; + setTextureFromPostProcess(channel: string, postProcess: PostProcess): void; + _cacheFloat2(uniformName: string, x: number, y: number): void; + _cacheFloat3(uniformName: string, x: number, y: number, z: number): void; + _cacheFloat4(uniformName: string, x: number, y: number, z: number, w: number): void; + setArray(uniformName: string, array: number[]): Effect; + setArray2(uniformName: string, array: number[]): Effect; + setArray3(uniformName: string, array: number[]): Effect; + setArray4(uniformName: string, array: number[]): Effect; + setMatrices(uniformName: string, matrices: Float32Array): Effect; + setMatrix(uniformName: string, matrix: Matrix): Effect; + setMatrix3x3(uniformName: string, matrix: Float32Array): Effect; + setMatrix2x2(uniformname: string, matrix: Float32Array): Effect; + setFloat(uniformName: string, value: number): Effect; + setBool(uniformName: string, bool: boolean): Effect; + setVector2(uniformName: string, vector2: Vector2): Effect; + setFloat2(uniformName: string, x: number, y: number): Effect; + setVector3(uniformName: string, vector3: Vector3): Effect; + setFloat3(uniformName: string, x: number, y: number, z: number): Effect; + setVector4(uniformName: string, vector4: Vector4): Effect; + setFloat4(uniformName: string, x: number, y: number, z: number, w: number): Effect; + setColor3(uniformName: string, color3: Color3): Effect; + setColor4(uniformName: string, color3: Color3, alpha: number): Effect; + static ShadersStore: {}; + } +} + +declare module BABYLON { + class Material { + name: string; + private static _TriangleFillMode; + private static _WireFrameFillMode; + private static _PointFillMode; + static TriangleFillMode: number; + static WireFrameFillMode: number; + static PointFillMode: number; + id: string; + checkReadyOnEveryCall: boolean; + checkReadyOnlyOnce: boolean; + state: string; + alpha: number; + backFaceCulling: boolean; + onCompiled: (effect: Effect) => void; + onError: (effect: Effect, errors: string) => void; + onDispose: () => void; + onBind: (material: Material, mesh: Mesh) => void; + getRenderTargetTextures: () => SmartArray; + alphaMode: number; + disableDepthWrite: boolean; + _effect: Effect; + _wasPreviouslyReady: boolean; + private _scene; + private _fillMode; + private _cachedDepthWriteState; + pointSize: number; + zOffset: number; + wireframe: boolean; + pointsCloud: boolean; + fillMode: number; + constructor(name: string, scene: Scene, doNotAdd?: boolean); + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + getEffect(): Effect; + getScene(): Scene; + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + getAlphaTestTexture(): BaseTexture; + trackCreation(onCompiled: (effect: Effect) => void, onError: (effect: Effect, errors: string) => void): void; + _preBind(): void; + bind(world: Matrix, mesh?: Mesh): void; + bindOnlyWorldMatrix(world: Matrix): void; + unbind(): void; + clone(name: string): Material; + dispose(forceDisposeEffect?: boolean): void; + } +} + +declare module BABYLON { + class MultiMaterial extends Material { + subMaterials: Material[]; + constructor(name: string, scene: Scene); + getSubMaterial(index: any): Material; + isReady(mesh?: AbstractMesh): boolean; + clone(name: string): MultiMaterial; + } +} + +declare module BABYLON { + class ShaderMaterial extends Material { + private _shaderPath; + private _options; + private _textures; + private _floats; + private _floatsArrays; + private _colors3; + private _colors4; + private _vectors2; + private _vectors3; + private _vectors4; + private _matrices; + private _matrices3x3; + private _matrices2x2; + private _cachedWorldViewMatrix; + private _renderId; + constructor(name: string, scene: Scene, shaderPath: any, options: any); + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + private _checkUniform(uniformName); + setTexture(name: string, texture: Texture): ShaderMaterial; + setFloat(name: string, value: number): ShaderMaterial; + setFloats(name: string, value: number[]): ShaderMaterial; + setColor3(name: string, value: Color3): ShaderMaterial; + setColor4(name: string, value: Color4): ShaderMaterial; + setVector2(name: string, value: Vector2): ShaderMaterial; + setVector3(name: string, value: Vector3): ShaderMaterial; + setVector4(name: string, value: Vector4): ShaderMaterial; + setMatrix(name: string, value: Matrix): ShaderMaterial; + setMatrix3x3(name: string, value: Float32Array): ShaderMaterial; + setMatrix2x2(name: string, value: Float32Array): ShaderMaterial; + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + bindOnlyWorldMatrix(world: Matrix): void; + bind(world: Matrix, mesh?: Mesh): void; + clone(name: string): ShaderMaterial; + dispose(forceDisposeEffect?: boolean): void; + } +} + +declare module BABYLON { + class FresnelParameters { + isEnabled: boolean; + leftColor: Color3; + rightColor: Color3; + bias: number; + power: number; + } + class StandardMaterial extends Material { + diffuseTexture: BaseTexture; + ambientTexture: BaseTexture; + opacityTexture: BaseTexture; + reflectionTexture: BaseTexture; + emissiveTexture: BaseTexture; + specularTexture: BaseTexture; + bumpTexture: BaseTexture; + ambientColor: Color3; + diffuseColor: Color3; + specularColor: Color3; + specularPower: number; + emissiveColor: Color3; + useAlphaFromDiffuseTexture: boolean; + useEmissiveAsIllumination: boolean; + useReflectionFresnelFromSpecular: boolean; + useSpecularOverAlpha: boolean; + fogEnabled: boolean; + roughness: number; + diffuseFresnelParameters: FresnelParameters; + opacityFresnelParameters: FresnelParameters; + reflectionFresnelParameters: FresnelParameters; + emissiveFresnelParameters: FresnelParameters; + useGlossinessFromSpecularMapAlpha: boolean; + private _renderTargets; + private _worldViewProjectionMatrix; + private _globalAmbientColor; + private _scaledDiffuse; + private _scaledSpecular; + private _renderId; + private _defines; + private _cachedDefines; + constructor(name: string, scene: Scene); + needAlphaBlending(): boolean; + needAlphaTesting(): boolean; + private _shouldUseAlphaFromDiffuseTexture(); + getAlphaTestTexture(): BaseTexture; + isReady(mesh?: AbstractMesh, useInstances?: boolean): boolean; + unbind(): void; + bindOnlyWorldMatrix(world: Matrix): void; + bind(world: Matrix, mesh?: Mesh): void; + getAnimatables(): IAnimatable[]; + dispose(forceDisposeEffect?: boolean): void; + clone(name: string): StandardMaterial; + static DiffuseTextureEnabled: boolean; + static AmbientTextureEnabled: boolean; + static OpacityTextureEnabled: boolean; + static ReflectionTextureEnabled: boolean; + static EmissiveTextureEnabled: boolean; + static SpecularTextureEnabled: boolean; + static BumpTextureEnabled: boolean; + static FresnelEnabled: boolean; + } +} + +declare module BABYLON { + class Color3 { + r: number; + g: number; + b: number; + constructor(r?: number, g?: number, b?: number); + toString(): string; + toArray(array: number[], index?: number): Color3; + toColor4(alpha?: number): Color4; + asArray(): number[]; + toLuminance(): number; + multiply(otherColor: Color3): Color3; + multiplyToRef(otherColor: Color3, result: Color3): Color3; + equals(otherColor: Color3): boolean; + equalsFloats(r: number, g: number, b: number): boolean; + scale(scale: number): Color3; + scaleToRef(scale: number, result: Color3): Color3; + add(otherColor: Color3): Color3; + addToRef(otherColor: Color3, result: Color3): Color3; + subtract(otherColor: Color3): Color3; + subtractToRef(otherColor: Color3, result: Color3): Color3; + clone(): Color3; + copyFrom(source: Color3): Color3; + copyFromFloats(r: number, g: number, b: number): Color3; + toHexString(): string; + static FromHexString(hex: string): Color3; + static FromArray(array: number[], offset?: number): Color3; + static FromInts(r: number, g: number, b: number): Color3; + static Lerp(start: Color3, end: Color3, amount: number): Color3; + static Red(): Color3; + static Green(): Color3; + static Blue(): Color3; + static Black(): Color3; + static White(): Color3; + static Purple(): Color3; + static Magenta(): Color3; + static Yellow(): Color3; + static Gray(): Color3; + } + class Color4 { + r: number; + g: number; + b: number; + a: number; + constructor(r: number, g: number, b: number, a: number); + addInPlace(right: any): Color4; + asArray(): number[]; + toArray(array: number[], index?: number): Color4; + add(right: Color4): Color4; + subtract(right: Color4): Color4; + subtractToRef(right: Color4, result: Color4): Color4; + scale(scale: number): Color4; + scaleToRef(scale: number, result: Color4): Color4; + toString(): string; + clone(): Color4; + copyFrom(source: Color4): Color4; + toHexString(): string; + static FromHexString(hex: string): Color4; + static Lerp(left: Color4, right: Color4, amount: number): Color4; + static LerpToRef(left: Color4, right: Color4, amount: number, result: Color4): void; + static FromArray(array: number[], offset?: number): Color4; + static FromInts(r: number, g: number, b: number, a: number): Color4; + } + class Vector2 { + x: number; + y: number; + constructor(x: number, y: number); + toString(): string; + toArray(array: number[], index?: number): Vector2; + asArray(): number[]; + copyFrom(source: Vector2): Vector2; + copyFromFloats(x: number, y: number): Vector2; + add(otherVector: Vector2): Vector2; + addVector3(otherVector: Vector3): Vector2; + subtract(otherVector: Vector2): Vector2; + subtractInPlace(otherVector: Vector2): Vector2; + multiplyInPlace(otherVector: Vector2): Vector2; + multiply(otherVector: Vector2): Vector2; + multiplyToRef(otherVector: Vector2, result: Vector2): Vector2; + multiplyByFloats(x: number, y: number): Vector2; + divide(otherVector: Vector2): Vector2; + divideToRef(otherVector: Vector2, result: Vector2): Vector2; + negate(): Vector2; + scaleInPlace(scale: number): Vector2; + scale(scale: number): Vector2; + equals(otherVector: Vector2): boolean; + equalsWithEpsilon(otherVector: Vector2, epsilon?: number): boolean; + length(): number; + lengthSquared(): number; + normalize(): Vector2; + clone(): Vector2; + static Zero(): Vector2; + static FromArray(array: number[], offset?: number): Vector2; + static FromArrayToRef(array: number[], offset: number, result: Vector2): void; + static CatmullRom(value1: Vector2, value2: Vector2, value3: Vector2, value4: Vector2, amount: number): Vector2; + static Clamp(value: Vector2, min: Vector2, max: Vector2): Vector2; + static Hermite(value1: Vector2, tangent1: Vector2, value2: Vector2, tangent2: Vector2, amount: number): Vector2; + static Lerp(start: Vector2, end: Vector2, amount: number): Vector2; + static Dot(left: Vector2, right: Vector2): number; + static Normalize(vector: Vector2): Vector2; + static Minimize(left: Vector2, right: Vector2): Vector2; + static Maximize(left: Vector2, right: Vector2): Vector2; + static Transform(vector: Vector2, transformation: Matrix): Vector2; + static Distance(value1: Vector2, value2: Vector2): number; + static DistanceSquared(value1: Vector2, value2: Vector2): number; + } + class Vector3 { + x: number; + y: number; + z: number; + constructor(x: number, y: number, z: number); + toString(): string; + asArray(): number[]; + toArray(array: number[], index?: number): Vector3; + toQuaternion(): Quaternion; + addInPlace(otherVector: Vector3): Vector3; + add(otherVector: Vector3): Vector3; + addToRef(otherVector: Vector3, result: Vector3): Vector3; + subtractInPlace(otherVector: Vector3): Vector3; + subtract(otherVector: Vector3): Vector3; + subtractToRef(otherVector: Vector3, result: Vector3): Vector3; + subtractFromFloats(x: number, y: number, z: number): Vector3; + subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3; + negate(): Vector3; + scaleInPlace(scale: number): Vector3; + scale(scale: number): Vector3; + scaleToRef(scale: number, result: Vector3): void; + equals(otherVector: Vector3): boolean; + equalsWithEpsilon(otherVector: Vector3, epsilon?: number): boolean; + equalsToFloats(x: number, y: number, z: number): boolean; + multiplyInPlace(otherVector: Vector3): Vector3; + multiply(otherVector: Vector3): Vector3; + multiplyToRef(otherVector: Vector3, result: Vector3): Vector3; + multiplyByFloats(x: number, y: number, z: number): Vector3; + divide(otherVector: Vector3): Vector3; + divideToRef(otherVector: Vector3, result: Vector3): Vector3; + MinimizeInPlace(other: Vector3): Vector3; + MaximizeInPlace(other: Vector3): Vector3; + length(): number; + lengthSquared(): number; + normalize(): Vector3; + clone(): Vector3; + copyFrom(source: Vector3): Vector3; + copyFromFloats(x: number, y: number, z: number): Vector3; + static GetClipFactor(vector0: Vector3, vector1: Vector3, axis: Vector3, size: any): number; + static FromArray(array: number[], offset?: number): Vector3; + static FromFloatArray(array: Float32Array, offset?: number): Vector3; + static FromArrayToRef(array: number[], offset: number, result: Vector3): void; + static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector3): void; + static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void; + static Zero(): Vector3; + static Up(): Vector3; + static TransformCoordinates(vector: Vector3, transformation: Matrix): Vector3; + static TransformCoordinatesToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformCoordinatesFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + static TransformCoordinatesToRefSIMD(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformCoordinatesFromFloatsToRefSIMD(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + static TransformNormal(vector: Vector3, transformation: Matrix): Vector3; + static TransformNormalToRef(vector: Vector3, transformation: Matrix, result: Vector3): void; + static TransformNormalFromFloatsToRef(x: number, y: number, z: number, transformation: Matrix, result: Vector3): void; + static CatmullRom(value1: Vector3, value2: Vector3, value3: Vector3, value4: Vector3, amount: number): Vector3; + static Clamp(value: Vector3, min: Vector3, max: Vector3): Vector3; + static Hermite(value1: Vector3, tangent1: Vector3, value2: Vector3, tangent2: Vector3, amount: number): Vector3; + static Lerp(start: Vector3, end: Vector3, amount: number): Vector3; + static Dot(left: Vector3, right: Vector3): number; + static Cross(left: Vector3, right: Vector3): Vector3; + static CrossToRef(left: Vector3, right: Vector3, result: Vector3): void; + static Normalize(vector: Vector3): Vector3; + static NormalizeToRef(vector: Vector3, result: Vector3): void; + static Project(vector: Vector3, world: Matrix, transform: Matrix, viewport: Viewport): Vector3; + static UnprojectFromTransform(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, transform: Matrix): Vector3; + static Unproject(source: Vector3, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Vector3; + static Minimize(left: Vector3, right: Vector3): Vector3; + static Maximize(left: Vector3, right: Vector3): Vector3; + static Distance(value1: Vector3, value2: Vector3): number; + static DistanceSquared(value1: Vector3, value2: Vector3): number; + static Center(value1: Vector3, value2: Vector3): Vector3; + /** + * Given three orthogonal left-handed oriented Vector3 axis in space (target system), + * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply + * to something in order to rotate it from its local system to the given target system. + */ + static RotationFromAxis(axis1: Vector3, axis2: Vector3, axis3: Vector3): Vector3; + /** + * The same than RotationFromAxis but updates the passed ref Vector3 parameter. + */ + static RotationFromAxisToRef(axis1: Vector3, axis2: Vector3, axis3: Vector3, ref: Vector3): void; + } + class Vector4 { + x: number; + y: number; + z: number; + w: number; + constructor(x: number, y: number, z: number, w: number); + toString(): string; + asArray(): number[]; + toArray(array: number[], index?: number): Vector4; + addInPlace(otherVector: Vector4): Vector4; + add(otherVector: Vector4): Vector4; + addToRef(otherVector: Vector4, result: Vector4): Vector4; + subtractInPlace(otherVector: Vector4): Vector4; + subtract(otherVector: Vector4): Vector4; + subtractToRef(otherVector: Vector4, result: Vector4): Vector4; + subtractFromFloats(x: number, y: number, z: number, w: number): Vector4; + subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4; + negate(): Vector4; + scaleInPlace(scale: number): Vector4; + scale(scale: number): Vector4; + scaleToRef(scale: number, result: Vector4): void; + equals(otherVector: Vector4): boolean; + equalsWithEpsilon(otherVector: Vector4, epsilon?: number): boolean; + equalsToFloats(x: number, y: number, z: number, w: number): boolean; + multiplyInPlace(otherVector: Vector4): Vector4; + multiply(otherVector: Vector4): Vector4; + multiplyToRef(otherVector: Vector4, result: Vector4): Vector4; + multiplyByFloats(x: number, y: number, z: number, w: number): Vector4; + divide(otherVector: Vector4): Vector4; + divideToRef(otherVector: Vector4, result: Vector4): Vector4; + MinimizeInPlace(other: Vector4): Vector4; + MaximizeInPlace(other: Vector4): Vector4; + length(): number; + lengthSquared(): number; + normalize(): Vector4; + clone(): Vector4; + copyFrom(source: Vector4): Vector4; + copyFromFloats(x: number, y: number, z: number, w: number): Vector4; + static FromArray(array: number[], offset?: number): Vector4; + static FromArrayToRef(array: number[], offset: number, result: Vector4): void; + static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector4): void; + static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void; + static Zero(): Vector4; + static Normalize(vector: Vector4): Vector4; + static NormalizeToRef(vector: Vector4, result: Vector4): void; + static Minimize(left: Vector4, right: Vector4): Vector4; + static Maximize(left: Vector4, right: Vector4): Vector4; + static Distance(value1: Vector4, value2: Vector4): number; + static DistanceSquared(value1: Vector4, value2: Vector4): number; + static Center(value1: Vector4, value2: Vector4): Vector4; + } + class Quaternion { + x: number; + y: number; + z: number; + w: number; + constructor(x?: number, y?: number, z?: number, w?: number); + toString(): string; + asArray(): number[]; + equals(otherQuaternion: Quaternion): boolean; + clone(): Quaternion; + copyFrom(other: Quaternion): Quaternion; + copyFromFloats(x: number, y: number, z: number, w: number): Quaternion; + add(other: Quaternion): Quaternion; + subtract(other: Quaternion): Quaternion; + scale(value: number): Quaternion; + multiply(q1: Quaternion): Quaternion; + multiplyToRef(q1: Quaternion, result: Quaternion): Quaternion; + length(): number; + normalize(): Quaternion; + toEulerAngles(): Vector3; + toEulerAnglesToRef(result: Vector3): Quaternion; + toRotationMatrix(result: Matrix): Quaternion; + fromRotationMatrix(matrix: Matrix): Quaternion; + static FromRotationMatrix(matrix: Matrix): Quaternion; + static FromRotationMatrixToRef(matrix: Matrix, result: Quaternion): void; + static Inverse(q: Quaternion): Quaternion; + static Identity(): Quaternion; + static RotationAxis(axis: Vector3, angle: number): Quaternion; + static FromArray(array: number[], offset?: number): Quaternion; + static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Quaternion; + static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Quaternion): void; + static RotationAlphaBetaGamma(alpha: number, beta: number, gamma: number): Quaternion; + static RotationAlphaBetaGammaToRef(alpha: number, beta: number, gamma: number, result: Quaternion): void; + static Slerp(left: Quaternion, right: Quaternion, amount: number): Quaternion; + } + class Matrix { + private static _tempQuaternion; + private static _xAxis; + private static _yAxis; + private static _zAxis; + m: Float32Array; + isIdentity(): boolean; + determinant(): number; + toArray(): Float32Array; + asArray(): Float32Array; + invert(): Matrix; + reset(): Matrix; + add(other: Matrix): Matrix; + addToRef(other: Matrix, result: Matrix): Matrix; + addToSelf(other: Matrix): Matrix; + invertToRef(other: Matrix): Matrix; + invertToRefSIMD(other: Matrix): Matrix; + setTranslation(vector3: Vector3): Matrix; + multiply(other: Matrix): Matrix; + copyFrom(other: Matrix): Matrix; + copyToArray(array: Float32Array, offset?: number): Matrix; + multiplyToRef(other: Matrix, result: Matrix): Matrix; + multiplyToArray(other: Matrix, result: Float32Array, offset: number): Matrix; + multiplyToArraySIMD(other: Matrix, result: Matrix, offset?: number): void; + equals(value: Matrix): boolean; + clone(): Matrix; + decompose(scale: Vector3, rotation: Quaternion, translation: Vector3): boolean; + static FromArray(array: number[], offset?: number): Matrix; + static FromArrayToRef(array: number[], offset: number, result: Matrix): void; + static FromFloat32ArrayToRefScaled(array: Float32Array, offset: number, scale: number, result: Matrix): void; + static FromValuesToRef(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number, result: Matrix): void; + static FromValues(initialM11: number, initialM12: number, initialM13: number, initialM14: number, initialM21: number, initialM22: number, initialM23: number, initialM24: number, initialM31: number, initialM32: number, initialM33: number, initialM34: number, initialM41: number, initialM42: number, initialM43: number, initialM44: number): Matrix; + static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix; + static Identity(): Matrix; + static IdentityToRef(result: Matrix): void; + static Zero(): Matrix; + static RotationX(angle: number): Matrix; + static Invert(source: Matrix): Matrix; + static RotationXToRef(angle: number, result: Matrix): void; + static RotationY(angle: number): Matrix; + static RotationYToRef(angle: number, result: Matrix): void; + static RotationZ(angle: number): Matrix; + static RotationZToRef(angle: number, result: Matrix): void; + static RotationAxis(axis: Vector3, angle: number): Matrix; + static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix; + static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void; + static Scaling(x: number, y: number, z: number): Matrix; + static ScalingToRef(x: number, y: number, z: number, result: Matrix): void; + static Translation(x: number, y: number, z: number): Matrix; + static TranslationToRef(x: number, y: number, z: number, result: Matrix): void; + static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix; + static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void; + static LookAtLHToRefSIMD(eyeRef: Vector3, targetRef: Vector3, upRef: Vector3, result: Matrix): void; + static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix; + static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void; + static OrthoOffCenterLH(left: number, right: number, bottom: number, top: number, znear: number, zfar: number): Matrix; + static OrthoOffCenterLHToRef(left: number, right: any, bottom: number, top: number, znear: number, zfar: number, result: Matrix): void; + static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix; + static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix; + static PerspectiveFovLHToRef(fov: number, aspect: number, znear: number, zfar: number, result: Matrix, fovMode?: number): void; + static GetFinalMatrix(viewport: Viewport, world: Matrix, view: Matrix, projection: Matrix, zmin: number, zmax: number): Matrix; + static GetAsMatrix2x2(matrix: Matrix): Float32Array; + static GetAsMatrix3x3(matrix: Matrix): Float32Array; + static Transpose(matrix: Matrix): Matrix; + static Reflection(plane: Plane): Matrix; + static ReflectionToRef(plane: Plane, result: Matrix): void; + } + class Plane { + normal: Vector3; + d: number; + constructor(a: number, b: number, c: number, d: number); + asArray(): number[]; + clone(): Plane; + normalize(): Plane; + transform(transformation: Matrix): Plane; + dotCoordinate(point: any): number; + copyFromPoints(point1: Vector3, point2: Vector3, point3: Vector3): Plane; + isFrontFacingTo(direction: Vector3, epsilon: number): boolean; + signedDistanceTo(point: Vector3): number; + static FromArray(array: number[]): Plane; + static FromPoints(point1: any, point2: any, point3: any): Plane; + static FromPositionAndNormal(origin: Vector3, normal: Vector3): Plane; + static SignedDistanceToPlaneFromPositionAndNormal(origin: Vector3, normal: Vector3, point: Vector3): number; + } + class Viewport { + x: number; + y: number; + width: number; + height: number; + constructor(x: number, y: number, width: number, height: number); + toGlobal(engine: any): Viewport; + } + class Frustum { + static GetPlanes(transform: Matrix): Plane[]; + static GetPlanesToRef(transform: Matrix, frustumPlanes: Plane[]): void; + } + class Ray { + origin: Vector3; + direction: Vector3; + length: number; + private _edge1; + private _edge2; + private _pvec; + private _tvec; + private _qvec; + constructor(origin: Vector3, direction: Vector3, length?: number); + intersectsBoxMinMax(minimum: Vector3, maximum: Vector3): boolean; + intersectsBox(box: BoundingBox): boolean; + intersectsSphere(sphere: any): boolean; + intersectsTriangle(vertex0: Vector3, vertex1: Vector3, vertex2: Vector3): IntersectionInfo; + static CreateNew(x: number, y: number, viewportWidth: number, viewportHeight: number, world: Matrix, view: Matrix, projection: Matrix): Ray; + /** + * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be + * transformed to the given world matrix. + * @param origin The origin point + * @param end The end point + * @param world a matrix to transform the ray to. Default is the identity matrix. + */ + static CreateNewFromTo(origin: Vector3, end: Vector3, world?: Matrix): Ray; + static Transform(ray: Ray, matrix: Matrix): Ray; + } + enum Space { + LOCAL = 0, + WORLD = 1, + } + class Axis { + static X: Vector3; + static Y: Vector3; + static Z: Vector3; + } + class BezierCurve { + static interpolate(t: number, x1: number, y1: number, x2: number, y2: number): number; + } + enum Orientation { + CW = 0, + CCW = 1, + } + class Angle { + private _radians; + constructor(radians: number); + degrees: () => number; + radians: () => number; + static BetweenTwoPoints(a: Vector2, b: Vector2): Angle; + static FromRadians(radians: number): Angle; + static FromDegrees(degrees: number): Angle; + } + class Arc2 { + startPoint: Vector2; + midPoint: Vector2; + endPoint: Vector2; + centerPoint: Vector2; + radius: number; + angle: Angle; + startAngle: Angle; + orientation: Orientation; + constructor(startPoint: Vector2, midPoint: Vector2, endPoint: Vector2); + } + class PathCursor { + private path; + private _onchange; + value: number; + animations: Animation[]; + constructor(path: Path2); + getPoint(): Vector3; + moveAhead(step?: number): PathCursor; + moveBack(step?: number): PathCursor; + move(step: number): PathCursor; + private ensureLimits(); + private markAsDirty(propertyName); + private raiseOnChange(); + onchange(f: (cursor: PathCursor) => void): PathCursor; + } + class Path2 { + private _points; + private _length; + closed: boolean; + constructor(x: number, y: number); + addLineTo(x: number, y: number): Path2; + addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments?: number): Path2; + close(): Path2; + length(): number; + getPoints(): Vector2[]; + getPointAtLengthPosition(normalizedLengthPosition: number): Vector2; + static StartingAt(x: number, y: number): Path2; + } + class Path3D { + path: Vector3[]; + private _curve; + private _distances; + private _tangents; + private _normals; + private _binormals; + private _raw; + /** + * new Path3D(path, normal, raw) + * path : an array of Vector3, the curve axis of the Path3D + * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal. + * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed. + */ + constructor(path: Vector3[], firstNormal?: Vector3, raw?: boolean); + getCurve(): Vector3[]; + getTangents(): Vector3[]; + getNormals(): Vector3[]; + getBinormals(): Vector3[]; + getDistances(): number[]; + update(path: Vector3[], firstNormal?: Vector3): Path3D; + private _compute(firstNormal); + private _getFirstNonNullVector(index); + private _getLastNonNullVector(index); + private _normalVector(v0, vt, va); + } + class Curve3 { + private _points; + private _length; + static CreateQuadraticBezier(v0: Vector3, v1: Vector3, v2: Vector3, nbPoints: number): Curve3; + static CreateCubicBezier(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3, nbPoints: number): Curve3; + static CreateHermiteSpline(p1: Vector3, t1: Vector3, p2: Vector3, t2: Vector3, nbPoints: number): Curve3; + constructor(points: Vector3[]); + getPoints(): Vector3[]; + length(): number; + continue(curve: Curve3): Curve3; + private _computeLength(path); + } + class PositionNormalVertex { + position: Vector3; + normal: Vector3; + constructor(position?: Vector3, normal?: Vector3); + clone(): PositionNormalVertex; + } + class PositionNormalTextureVertex { + position: Vector3; + normal: Vector3; + uv: Vector2; + constructor(position?: Vector3, normal?: Vector3, uv?: Vector2); + clone(): PositionNormalTextureVertex; + } + class SIMDHelper { + private static _isEnabled; + static IsEnabled: boolean; + static DisableSIMD(): void; + static EnableSIMD(): void; + } +} + +declare module BABYLON { + class AbstractMesh extends Node implements IDisposable { + private static _BILLBOARDMODE_NONE; + private static _BILLBOARDMODE_X; + private static _BILLBOARDMODE_Y; + private static _BILLBOARDMODE_Z; + private static _BILLBOARDMODE_ALL; + static BILLBOARDMODE_NONE: number; + static BILLBOARDMODE_X: number; + static BILLBOARDMODE_Y: number; + static BILLBOARDMODE_Z: number; + static BILLBOARDMODE_ALL: number; + definedFacingForward: boolean; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Quaternion; + scaling: Vector3; + billboardMode: number; + visibility: number; + alphaIndex: number; + infiniteDistance: boolean; + isVisible: boolean; + isPickable: boolean; + showBoundingBox: boolean; + showSubMeshesBoundingBox: boolean; + onDispose: any; + isBlocker: boolean; + skeleton: Skeleton; + renderingGroupId: number; + material: Material; + receiveShadows: boolean; + actionManager: ActionManager; + renderOutline: boolean; + outlineColor: Color3; + outlineWidth: number; + renderOverlay: boolean; + overlayColor: Color3; + overlayAlpha: number; + hasVertexAlpha: boolean; + useVertexColors: boolean; + applyFog: boolean; + computeBonesUsingShaders: boolean; + useOctreeForRenderingSelection: boolean; + useOctreeForPicking: boolean; + useOctreeForCollisions: boolean; + layerMask: number; + alwaysSelectAsActiveMesh: boolean; + _physicImpostor: number; + _physicsMass: number; + _physicsFriction: number; + _physicRestitution: number; + private _checkCollisions; + ellipsoid: Vector3; + ellipsoidOffset: Vector3; + private _collider; + private _oldPositionForCollisions; + private _diffPositionForCollisions; + private _newPositionForCollisions; + onCollide: (collidedMesh: AbstractMesh) => void; + private _meshToBoneReferal; + edgesWidth: number; + edgesColor: Color4; + _edgesRenderer: EdgesRenderer; + private _localScaling; + private _localRotation; + private _localTranslation; + private _localBillboard; + private _localPivotScaling; + private _localPivotScalingRotation; + private _localMeshReferalTransform; + private _localWorld; + _worldMatrix: Matrix; + private _rotateYByPI; + private _absolutePosition; + private _collisionsTransformMatrix; + private _collisionsScalingMatrix; + _positions: Vector3[]; + private _isDirty; + _masterMesh: AbstractMesh; + _boundingInfo: BoundingInfo; + private _pivotMatrix; + _isDisposed: boolean; + _renderId: number; + subMeshes: SubMesh[]; + _submeshesOctree: Octree; + _intersectionsInProgress: AbstractMesh[]; + private _onAfterWorldMatrixUpdate; + private _isWorldMatrixFrozen; + _waitingActions: any; + _waitingFreezeWorldMatrix: boolean; + constructor(name: string, scene: Scene); + disableEdgesRendering(): void; + enableEdgesRendering(epsilon?: number, checkVerticesInsteadOfIndices?: boolean): void; + isBlocked: boolean; + getLOD(camera: Camera): AbstractMesh; + getTotalVertices(): number; + getIndices(): number[]; + getVerticesData(kind: string): number[]; + isVerticesDataPresent(kind: string): boolean; + getBoundingInfo(): BoundingInfo; + useBones: boolean; + _preActivate(): void; + _activate(renderId: number): void; + getWorldMatrix(): Matrix; + worldMatrixFromCache: Matrix; + absolutePosition: Vector3; + freezeWorldMatrix(): void; + unfreezeWorldMatrix(): void; + isWorldMatrixFrozen: boolean; + rotate(axis: Vector3, amount: number, space: Space): void; + translate(axis: Vector3, distance: number, space: Space): void; + getAbsolutePosition(): Vector3; + setAbsolutePosition(absolutePosition: Vector3): void; + /** + * Perform relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward. + * @param {number} amountRight + * @param {number} amountUp + * @param {number} amountForward + */ + movePOV(amountRight: number, amountUp: number, amountForward: number): void; + /** + * Calculate relative position change from the point of view of behind the front of the mesh. + * This is performed taking into account the meshes current rotation, so you do not have to care. + * Supports definition of mesh facing forward or backward. + * @param {number} amountRight + * @param {number} amountUp + * @param {number} amountForward + */ + calcMovePOV(amountRight: number, amountUp: number, amountForward: number): Vector3; + /** + * Perform relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param {number} flipBack + * @param {number} twirlClockwise + * @param {number} tiltRight + */ + rotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): void; + /** + * Calculate relative rotation change from the point of view of behind the front of the mesh. + * Supports definition of mesh facing forward or backward. + * @param {number} flipBack + * @param {number} twirlClockwise + * @param {number} tiltRight + */ + calcRotatePOV(flipBack: number, twirlClockwise: number, tiltRight: number): Vector3; + setPivotMatrix(matrix: Matrix): void; + getPivotMatrix(): Matrix; + _isSynchronized(): boolean; + _initCache(): void; + markAsDirty(property: string): void; + _updateBoundingInfo(): void; + _updateSubMeshesBoundingInfo(matrix: Matrix): void; + computeWorldMatrix(force?: boolean): Matrix; + /** + * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated + * @param func: callback function to add + */ + registerAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; + unregisterAfterWorldMatrixUpdate(func: (mesh: AbstractMesh) => void): void; + setPositionWithLocalVector(vector3: Vector3): void; + getPositionExpressedInLocalSpace(): Vector3; + locallyTranslate(vector3: Vector3): void; + lookAt(targetPoint: Vector3, yawCor: number, pitchCor: number, rollCor: number): void; + attachToBone(bone: Bone, affectedMesh: AbstractMesh): void; + detachFromBone(): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + isCompletelyInFrustum(camera?: Camera): boolean; + intersectsMesh(mesh: AbstractMesh, precise?: boolean): boolean; + intersectsPoint(point: Vector3): boolean; + setPhysicsState(impostor?: any, options?: PhysicsBodyCreationOptions): any; + getPhysicsImpostor(): number; + getPhysicsMass(): number; + getPhysicsFriction(): number; + getPhysicsRestitution(): number; + getPositionInCameraSpace(camera?: Camera): Vector3; + getDistanceToCamera(camera?: Camera): number; + applyImpulse(force: Vector3, contactPoint: Vector3): void; + setPhysicsLinkWith(otherMesh: Mesh, pivot1: Vector3, pivot2: Vector3, options?: any): void; + updatePhysicsBodyPosition(): void; + checkCollisions: boolean; + moveWithCollisions(velocity: Vector3): void; + private _onCollisionPositionChange; + /** + * This function will create an octree to help select the right submeshes for rendering, picking and collisions + * Please note that you must have a decent number of submeshes to get performance improvements when using octree + */ + createOrUpdateSubmeshesOctree(maxCapacity?: number, maxDepth?: number): Octree; + _collideForSubMesh(subMesh: SubMesh, transformMatrix: Matrix, collider: Collider): void; + _processCollisionsForSubMeshes(collider: Collider, transformMatrix: Matrix): void; + _checkCollision(collider: Collider): void; + _generatePointsArray(): boolean; + intersects(ray: Ray, fastCheck?: boolean): PickingInfo; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): AbstractMesh; + releaseSubMeshes(): void; + dispose(doNotRecurse?: boolean): void; + } +} + +declare module BABYLON { + class CSG { + private polygons; + matrix: Matrix; + position: Vector3; + rotation: Vector3; + rotationQuaternion: Quaternion; + scaling: Vector3; + static FromMesh(mesh: Mesh): CSG; + private static FromPolygons(polygons); + clone(): CSG; + private toPolygons(); + union(csg: CSG): CSG; + unionInPlace(csg: CSG): void; + subtract(csg: CSG): CSG; + subtractInPlace(csg: CSG): void; + intersect(csg: CSG): CSG; + intersectInPlace(csg: CSG): void; + inverse(): CSG; + inverseInPlace(): void; + copyTransformAttributes(csg: CSG): CSG; + buildMeshGeometry(name: string, scene: Scene, keepSubMeshes: boolean): Mesh; + toMesh(name: string, material: Material, scene: Scene, keepSubMeshes: boolean): Mesh; + } +} + +declare module BABYLON { + class Geometry implements IGetSetVerticesData { + id: string; + delayLoadState: number; + delayLoadingFile: string; + onGeometryUpdated: (geometry: Geometry, kind?: string) => void; + private _scene; + private _engine; + private _meshes; + private _totalVertices; + private _indices; + private _vertexBuffers; + private _isDisposed; + _delayInfo: any; + private _indexBuffer; + _boundingInfo: BoundingInfo; + _delayLoadingFunction: (any: any, geometry: Geometry) => void; + constructor(id: string, scene: Scene, vertexData?: VertexData, updatable?: boolean, mesh?: Mesh); + getScene(): Scene; + getEngine(): Engine; + isReady(): boolean; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: number[], updatable?: boolean, stride?: number): void; + updateVerticesDataDirectly(kind: string, data: Float32Array, offset: number): void; + updateVerticesData(kind: string, data: number[], updateExtends?: boolean): void; + getTotalVertices(): number; + getVerticesData(kind: string, copyWhenShared?: boolean): number[]; + getVertexBuffer(kind: string): VertexBuffer; + getVertexBuffers(): VertexBuffer[]; + isVerticesDataPresent(kind: string): boolean; + getVerticesDataKinds(): string[]; + setIndices(indices: number[], totalVertices?: number): void; + getTotalIndices(): number; + getIndices(copyWhenShared?: boolean): number[]; + getIndexBuffer(): any; + releaseForMesh(mesh: Mesh, shouldDispose?: boolean): void; + applyToMesh(mesh: Mesh): void; + private _applyToMesh(mesh); + private notifyUpdate(kind?); + load(scene: Scene, onLoaded?: () => void): void; + isDisposed(): boolean; + dispose(): void; + copy(id: string): Geometry; + static ExtractFromMesh(mesh: Mesh, id: string): Geometry; + static RandomId(): string; + } + module Geometry.Primitives { + class _Primitive extends Geometry { + private _beingRegenerated; + private _canBeRegenerated; + constructor(id: string, scene: Scene, vertexData?: VertexData, canBeRegenerated?: boolean, mesh?: Mesh); + canBeRegenerated(): boolean; + regenerate(): void; + asNewGeometry(id: string): Geometry; + setAllVerticesData(vertexData: VertexData, updatable?: boolean): void; + setVerticesData(kind: string, data: number[], updatable?: boolean): void; + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Ribbon extends _Primitive { + pathArray: Vector3[][]; + closeArray: boolean; + closePath: boolean; + offset: number; + side: number; + constructor(id: string, scene: Scene, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Box extends _Primitive { + size: number; + side: number; + constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Sphere extends _Primitive { + segments: number; + diameter: number; + side: number; + constructor(id: string, scene: Scene, segments: number, diameter: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Cylinder extends _Primitive { + height: number; + diameterTop: number; + diameterBottom: number; + tessellation: number; + subdivisions: number; + side: number; + constructor(id: string, scene: Scene, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions?: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Torus extends _Primitive { + diameter: number; + thickness: number; + tessellation: number; + side: number; + constructor(id: string, scene: Scene, diameter: number, thickness: number, tessellation: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Ground extends _Primitive { + width: number; + height: number; + subdivisions: number; + constructor(id: string, scene: Scene, width: number, height: number, subdivisions: number, canBeRegenerated?: boolean, mesh?: Mesh); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class TiledGround extends _Primitive { + xmin: number; + zmin: number; + xmax: number; + zmax: number; + subdivisions: { + w: number; + h: number; + }; + precision: { + w: number; + h: number; + }; + constructor(id: string, scene: Scene, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, canBeRegenerated?: boolean, mesh?: Mesh); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class Plane extends _Primitive { + size: number; + side: number; + constructor(id: string, scene: Scene, size: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + class TorusKnot extends _Primitive { + radius: number; + tube: number; + radialSegments: number; + tubularSegments: number; + p: number; + q: number; + side: number; + constructor(id: string, scene: Scene, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, canBeRegenerated?: boolean, mesh?: Mesh, side?: number); + _regenerateVertexData(): VertexData; + copy(id: string): Geometry; + } + } +} + +declare module BABYLON { + class GroundMesh extends Mesh { + generateOctree: boolean; + private _worldInverse; + _subdivisions: number; + constructor(name: string, scene: Scene); + subdivisions: number; + optimize(chunksCount: number, octreeBlocksSize?: number): void; + getHeightAtCoordinates(x: number, z: number): number; + } +} + +declare module BABYLON { + /** + * Creates an instance based on a source mesh. + */ + class InstancedMesh extends AbstractMesh { + private _sourceMesh; + private _currentLOD; + constructor(name: string, source: Mesh); + receiveShadows: boolean; + material: Material; + visibility: number; + skeleton: Skeleton; + getTotalVertices(): number; + sourceMesh: Mesh; + getVerticesData(kind: string): number[]; + isVerticesDataPresent(kind: string): boolean; + getIndices(): number[]; + _positions: Vector3[]; + refreshBoundingInfo(): void; + _preActivate(): void; + _activate(renderId: number): void; + getLOD(camera: Camera): AbstractMesh; + _syncSubMeshes(): void; + _generatePointsArray(): boolean; + clone(name: string, newParent: Node, doNotCloneChildren?: boolean): InstancedMesh; + dispose(doNotRecurse?: boolean): void; + } +} + +declare module BABYLON { + class LinesMesh extends Mesh { + color: Color3; + alpha: number; + private _colorShader; + constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); + material: Material; + isPickable: boolean; + checkCollisions: boolean; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; + intersects(ray: Ray, fastCheck?: boolean): any; + dispose(doNotRecurse?: boolean): void; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): LinesMesh; + } +} + +declare module BABYLON { + class _InstancesBatch { + mustReturn: boolean; + visibleInstances: InstancedMesh[][]; + renderSelf: boolean[]; + } + class Mesh extends AbstractMesh implements IGetSetVerticesData { + static _FRONTSIDE: number; + static _BACKSIDE: number; + static _DOUBLESIDE: number; + static _DEFAULTSIDE: number; + static _NO_CAP: number; + static _CAP_START: number; + static _CAP_END: number; + static _CAP_ALL: number; + static FRONTSIDE: number; + static BACKSIDE: number; + static DOUBLESIDE: number; + static DEFAULTSIDE: number; + static NO_CAP: number; + static CAP_START: number; + static CAP_END: number; + static CAP_ALL: number; + delayLoadState: number; + instances: InstancedMesh[]; + delayLoadingFile: string; + _binaryInfo: any; + private _LODLevels; + onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Mesh) => void; + _geometry: Geometry; + private _onBeforeRenderCallbacks; + private _onAfterRenderCallbacks; + _delayInfo: any; + _delayLoadingFunction: (any: any, mesh: Mesh) => void; + _visibleInstances: any; + private _renderIdForInstances; + private _batchCache; + private _worldMatricesInstancesBuffer; + private _worldMatricesInstancesArray; + private _instancesBufferSize; + _shouldGenerateFlatShading: boolean; + private _preActivateId; + private _sideOrientation; + private _areNormalsFrozen; + private _sourcePositions; + private _sourceNormals; + /** + * @constructor + * @param {string} name - The value used by scene.getMeshByName() to do a lookup. + * @param {Scene} scene - The scene to add this mesh to. + * @param {Node} parent - The parent of this mesh, if it has one + * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned. + * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False. + * When false, achieved by calling a clone(), also passing False. + * This will make creation of children, recursive. + */ + constructor(name: string, scene: Scene, parent?: Node, source?: Mesh, doNotCloneChildren?: boolean); + hasLODLevels: boolean; + private _sortLODLevels(); + /** + * Add a mesh as LOD level triggered at the given distance. + * @param {number} distance - the distance from the center of the object to show this level + * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level + * @return {BABYLON.Mesh} this mesh (for chaining) + */ + addLODLevel(distance: number, mesh: Mesh): Mesh; + getLODLevelAtDistance(distance: number): Mesh; + /** + * Remove a mesh from the LOD array + * @param {BABYLON.Mesh} mesh - the mesh to be removed. + * @return {BABYLON.Mesh} this mesh (for chaining) + */ + removeLODLevel(mesh: Mesh): Mesh; + getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh; + geometry: Geometry; + getTotalVertices(): number; + getVerticesData(kind: string, copyWhenShared?: boolean): number[]; + getVertexBuffer(kind: any): VertexBuffer; + isVerticesDataPresent(kind: string): boolean; + getVerticesDataKinds(): string[]; + getTotalIndices(): number; + getIndices(copyWhenShared?: boolean): number[]; + isBlocked: boolean; + isReady(): boolean; + isDisposed(): boolean; + sideOrientation: number; + areNormalsFrozen: boolean; + /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ + freezeNormals(): void; + /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */ + unfreezeNormals(): void; + _preActivate(): void; + _registerInstanceForRenderId(instance: InstancedMesh, renderId: number): void; + refreshBoundingInfo(): void; + _createGlobalSubMesh(): SubMesh; + subdivide(count: number): void; + setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void; + updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void; + updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void; + updateMeshPositions(positionFunction: any, computeNormals?: boolean): void; + makeGeometryUnique(): void; + setIndices(indices: number[], totalVertices?: number): void; + _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void; + _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void; + registerBeforeRender(func: (mesh: AbstractMesh) => void): void; + unregisterBeforeRender(func: (mesh: AbstractMesh) => void): void; + registerAfterRender(func: (mesh: AbstractMesh) => void): void; + unregisterAfterRender(func: (mesh: AbstractMesh) => void): void; + _getInstancesRenderList(subMeshId: number): _InstancesBatch; + _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void; + _processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix) => void): void; + render(subMesh: SubMesh, enableAlphaMode: boolean): void; + getEmittedParticleSystems(): ParticleSystem[]; + getHierarchyEmittedParticleSystems(): ParticleSystem[]; + getChildren(): Node[]; + _checkDelayState(): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + setMaterialByID(id: string): void; + getAnimatables(): IAnimatable[]; + bakeTransformIntoVertices(transform: Matrix): void; + bakeCurrentTransformIntoVertices(): void; + _resetPointsArrayCache(): void; + _generatePointsArray(): boolean; + clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh; + dispose(doNotRecurse?: boolean): void; + applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void; + applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void; + convertToFlatShadedMesh(): void; + flipFaces(flipNormals?: boolean): void; + createInstance(name: string): InstancedMesh; + synchronizeInstances(): void; + /** + * Simplify the mesh according to the given array of settings. + * Function will return immediately and will simplify async. + * @param settings a collection of simplification settings. + * @param parallelProcessing should all levels calculate parallel or one after the other. + * @param type the type of simplification to run. + * @param successCallback optional success callback to be called after the simplification finished processing all settings. + */ + simplify(settings: Array, parallelProcessing?: boolean, simplificationType?: SimplificationType, successCallback?: (mesh?: Mesh, submeshIndex?: number) => void): void; + /** + * Optimization of the mesh's indices, in case a mesh has duplicated vertices. + * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes. + * This should be used together with the simplification to avoid disappearing triangles. + * @param successCallback an optional success callback to be called after the optimization finished. + */ + optimizeIndices(successCallback?: (mesh?: Mesh) => void): void; + static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene: Scene, updatable?: boolean, sideOrientation?: number, ribbonInstance?: Mesh): Mesh; + static CreateDisc(name: string, radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateBox(name: string, options: { + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateSphere(name: string, options: { + segments?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: any): Mesh; + static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any, sideOrientation?: number): Mesh; + static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean, linesInstance?: LinesMesh): LinesMesh; + static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene: Scene, updatable?: boolean, linesInstance?: LinesMesh): LinesMesh; + static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, extrudedInstance?: Mesh): Mesh; + static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: any, rotationFunction: any, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, extrudedInstance?: Mesh): Mesh; + private static _ExtrudeShapeGeneric(name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance); + static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh; + static CreatePlane(name: string, options: { + width?: number; + height?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: Scene): Mesh; + static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh; + static CreateGround(name: string, options: { + width?: number; + height?: number; + subdivisions?: number; + sideOrientation?: number; + updatable?: boolean; + }, scene: any): Mesh; + static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { + w: number; + h: number; + }, precision: { + w: number; + h: number; + }, scene: Scene, updatable?: boolean): Mesh; + static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void): GroundMesh; + static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: { + (i: number, distance: number): number; + }, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, tubeInstance?: Mesh): Mesh; + static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle?: number): Mesh; + /** + * Update the vertex buffers by applying transformation from the bones + * @param {skeleton} skeleton to apply + */ + applySkeleton(skeleton: Skeleton): Mesh; + static MinMax(meshes: AbstractMesh[]): { + min: Vector3; + max: Vector3; + }; + static Center(meshesOrMinMaxVector: any): Vector3; + /** + * Merge the array of meshes into a single mesh for performance reasons. + * @param {Array} meshes - The vertices source. They should all be of the same material. Entries can empty + * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes + * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true. + * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class. + */ + static MergeMeshes(meshes: Array, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh): Mesh; + } +} + +declare module BABYLON { + interface IGetSetVerticesData { + isVerticesDataPresent(kind: string): boolean; + getVerticesData(kind: string, copyWhenShared?: boolean): number[]; + getIndices(copyWhenShared?: boolean): number[]; + setVerticesData(kind: string, data: number[], updatable?: boolean): void; + updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void; + setIndices(indices: number[]): void; + } + class VertexData { + positions: number[]; + normals: number[]; + uvs: number[]; + uvs2: number[]; + uvs3: number[]; + uvs4: number[]; + uvs5: number[]; + uvs6: number[]; + colors: number[]; + matricesIndices: number[]; + matricesWeights: number[]; + indices: number[]; + set(data: number[], kind: string): void; + applyToMesh(mesh: Mesh, updatable?: boolean): void; + applyToGeometry(geometry: Geometry, updatable?: boolean): void; + updateMesh(mesh: Mesh, updateExtends?: boolean, makeItUnique?: boolean): void; + updateGeometry(geometry: Geometry, updateExtends?: boolean, makeItUnique?: boolean): void; + private _applyTo(meshOrGeometry, updatable?); + private _update(meshOrGeometry, updateExtends?, makeItUnique?); + transform(matrix: Matrix): void; + merge(other: VertexData): void; + static ExtractFromMesh(mesh: Mesh, copyWhenShared?: boolean): VertexData; + static ExtractFromGeometry(geometry: Geometry, copyWhenShared?: boolean): VertexData; + private static _ExtractFrom(meshOrGeometry, copyWhenShared?); + static CreateRibbon(pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, sideOrientation?: number): VertexData; + static CreateBox(options: { + width?: number; + height?: number; + depth?: number; + faceUV?: Vector4[]; + faceColors?: Color4[]; + sideOrientation?: number; + }): VertexData; + static CreateBox(size: number, sideOrientation?: number): VertexData; + static CreateSphere(options: { + segments?: number; + diameterX?: number; + diameterY?: number; + diameterZ?: number; + sideOrientation?: number; + }): VertexData; + static CreateSphere(segments: number, diameter?: number, sideOrientation?: number): VertexData; + static CreateCylinder(height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions?: number, sideOrientation?: number): VertexData; + static CreateTorus(diameter: any, thickness: any, tessellation: any, sideOrientation?: number): VertexData; + static CreateLines(points: Vector3[]): VertexData; + static CreateDashedLines(points: Vector3[], dashSize: number, gapSize: number, dashNb: number): VertexData; + static CreateGround(options: { + width?: number; + height?: number; + subdivisions?: number; + sideOrientation?: number; + }): VertexData; + static CreateGround(width: number, height: number, subdivisions?: number): VertexData; + static CreateTiledGround(xmin: number, zmin: number, xmax: number, zmax: number, subdivisions?: { + w: number; + h: number; + }, precision?: { + w: number; + h: number; + }): VertexData; + static CreateGroundFromHeightMap(width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, buffer: Uint8Array, bufferWidth: number, bufferHeight: number): VertexData; + static CreatePlane(options: { + width?: number; + height?: number; + sideOrientation?: number; + }): VertexData; + static CreatePlane(size: number, sideOrientation?: number): VertexData; + static CreateDisc(radius: number, tessellation: number, sideOrientation?: number): VertexData; + static CreateTorusKnot(radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, sideOrientation?: number): VertexData; + /** + * @param {any} - positions (number[] or Float32Array) + * @param {any} - indices (number[] or Uint16Array) + * @param {any} - normals (number[] or Float32Array) + */ + static ComputeNormals(positions: any, indices: any, normals: any): void; + private static _ComputeSides(sideOrientation, positions, indices, normals, uvs); + } +} + +declare module BABYLON.Internals { + class MeshLODLevel { + distance: number; + mesh: Mesh; + constructor(distance: number, mesh: Mesh); + } +} + +declare module BABYLON { + /** + * A simplifier interface for future simplification implementations. + */ + interface ISimplifier { + /** + * Simplification of a given mesh according to the given settings. + * Since this requires computation, it is assumed that the function runs async. + * @param settings The settings of the simplification, including quality and distance + * @param successCallback A callback that will be called after the mesh was simplified. + * @param errorCallback in case of an error, this callback will be called. optional. + */ + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMeshes: Mesh) => void, errorCallback?: () => void): void; + } + /** + * Expected simplification settings. + * Quality should be between 0 and 1 (1 being 100%, 0 being 0%); + */ + interface ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh?: boolean; + } + class SimplificationSettings implements ISimplificationSettings { + quality: number; + distance: number; + optimizeMesh: boolean; + constructor(quality: number, distance: number, optimizeMesh?: boolean); + } + interface ISimplificationTask { + settings: Array; + simplificationType: SimplificationType; + mesh: Mesh; + successCallback?: () => void; + parallelProcessing: boolean; + } + class SimplificationQueue { + private _simplificationArray; + running: any; + constructor(); + addTask(task: ISimplificationTask): void; + executeNext(): void; + runSimplification(task: ISimplificationTask): void; + private getSimplifier(task); + } + /** + * The implemented types of simplification. + * At the moment only Quadratic Error Decimation is implemented. + */ + enum SimplificationType { + QUADRATIC = 0, + } + class DecimationTriangle { + vertices: Array; + normal: Vector3; + error: Array; + deleted: boolean; + isDirty: boolean; + borderFactor: number; + deletePending: boolean; + originalOffset: number; + constructor(vertices: Array); + } + class DecimationVertex { + position: Vector3; + id: any; + q: QuadraticMatrix; + isBorder: boolean; + triangleStart: number; + triangleCount: number; + originalOffsets: Array; + constructor(position: Vector3, id: any); + updatePosition(newPosition: Vector3): void; + } + class QuadraticMatrix { + data: Array; + constructor(data?: Array); + det(a11: any, a12: any, a13: any, a21: any, a22: any, a23: any, a31: any, a32: any, a33: any): number; + addInPlace(matrix: QuadraticMatrix): void; + addArrayInPlace(data: Array): void; + add(matrix: QuadraticMatrix): QuadraticMatrix; + static FromData(a: number, b: number, c: number, d: number): QuadraticMatrix; + static DataFromNumbers(a: number, b: number, c: number, d: number): number[]; + } + class Reference { + vertexId: number; + triangleId: number; + constructor(vertexId: number, triangleId: number); + } + /** + * An implementation of the Quadratic Error simplification algorithm. + * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf + * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS + * @author RaananW + */ + class QuadraticErrorSimplification implements ISimplifier { + private _mesh; + private triangles; + private vertices; + private references; + private initialized; + private _reconstructedMesh; + syncIterations: number; + aggressiveness: number; + decimationIterations: number; + boundingBoxEpsilon: number; + constructor(_mesh: Mesh); + simplify(settings: ISimplificationSettings, successCallback: (simplifiedMesh: Mesh) => void): void; + private isTriangleOnBoundingBox(triangle); + private runDecimation(settings, submeshIndex, successCallback); + private initWithMesh(submeshIndex, callback, optimizeMesh?); + private init(callback); + private reconstructMesh(submeshIndex); + private initDecimatedMesh(); + private isFlipped(vertex1, vertex2, point, deletedArray, borderFactor, delTr); + private updateTriangles(origVertex, vertex, deletedArray, deletedTriangles); + private identifyBorder(); + private updateMesh(identifyBorders?); + private vertexError(q, point); + private calculateError(vertex1, vertex2, pointResult?, normalResult?, uvResult?, colorResult?); + } +} + +declare module BABYLON { + class Polygon { + static Rectangle(xmin: number, ymin: number, xmax: number, ymax: number): Vector2[]; + static Circle(radius: number, cx?: number, cy?: number, numberOfSides?: number): Vector2[]; + static Parse(input: string): Vector2[]; + static StartingAt(x: number, y: number): Path2; + } + class PolygonMeshBuilder { + private _swctx; + private _points; + private _outlinepoints; + private _holes; + private _name; + private _scene; + constructor(name: string, contours: Path2, scene: Scene); + constructor(name: string, contours: Vector2[], scene: Scene); + addHole(hole: Vector2[]): PolygonMeshBuilder; + build(updatable?: boolean, depth?: number): Mesh; + private addSide(positions, normals, uvs, indices, bounds, points, depth, flip); + } +} + +declare module BABYLON { + class SubMesh { + materialIndex: number; + verticesStart: number; + verticesCount: number; + indexStart: any; + indexCount: number; + linesIndexCount: number; + private _mesh; + private _renderingMesh; + private _boundingInfo; + private _linesIndexBuffer; + _lastColliderWorldVertices: Vector3[]; + _trianglePlanes: Plane[]; + _lastColliderTransformMatrix: Matrix; + _renderId: number; + _alphaIndex: number; + _distanceToCamera: number; + _id: number; + constructor(materialIndex: number, verticesStart: number, verticesCount: number, indexStart: any, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh, createBoundingBox?: boolean); + getBoundingInfo(): BoundingInfo; + getMesh(): AbstractMesh; + getRenderingMesh(): Mesh; + getMaterial(): Material; + refreshBoundingInfo(): void; + _checkCollision(collider: Collider): boolean; + updateBoundingInfo(world: Matrix): void; + isInFrustum(frustumPlanes: Plane[]): boolean; + render(enableAlphaMode: boolean): void; + getLinesIndexBuffer(indices: number[], engine: any): WebGLBuffer; + canIntersects(ray: Ray): boolean; + intersects(ray: Ray, positions: Vector3[], indices: number[], fastCheck?: boolean): IntersectionInfo; + clone(newMesh: AbstractMesh, newRenderingMesh?: Mesh): SubMesh; + dispose(): void; + static CreateFromIndices(materialIndex: number, startIndex: number, indexCount: number, mesh: AbstractMesh, renderingMesh?: Mesh): SubMesh; + } +} + +declare module BABYLON { + class VertexBuffer { + private _mesh; + private _engine; + private _buffer; + private _data; + private _updatable; + private _kind; + private _strideSize; + constructor(engine: any, data: number[], kind: string, updatable: boolean, postponeInternalCreation?: boolean, stride?: number); + isUpdatable(): boolean; + getData(): number[]; + getBuffer(): WebGLBuffer; + getStrideSize(): number; + create(data?: number[]): void; + update(data: number[]): void; + updateDirectly(data: Float32Array, offset: number): void; + dispose(): void; + private static _PositionKind; + private static _NormalKind; + private static _UVKind; + private static _UV2Kind; + private static _UV3Kind; + private static _UV4Kind; + private static _UV5Kind; + private static _UV6Kind; + private static _ColorKind; + private static _MatricesIndicesKind; + private static _MatricesWeightsKind; + static PositionKind: string; + static NormalKind: string; + static UVKind: string; + static UV2Kind: string; + static UV3Kind: string; + static UV4Kind: string; + static UV5Kind: string; + static UV6Kind: string; + static ColorKind: string; + static MatricesIndicesKind: string; + static MatricesWeightsKind: string; + } +} + +declare module BABYLON { + class Particle { + position: Vector3; + direction: Vector3; + color: Color4; + colorStep: Color4; + lifeTime: number; + age: number; + size: number; + angle: number; + angularSpeed: number; + copyTo(other: Particle): void; + } +} + +declare module BABYLON { + class ParticleSystem implements IDisposable { + name: string; + static BLENDMODE_ONEONE: number; + static BLENDMODE_STANDARD: number; + id: string; + renderingGroupId: number; + emitter: any; + emitRate: number; + manualEmitCount: number; + updateSpeed: number; + targetStopDuration: number; + disposeOnStop: boolean; + minEmitPower: number; + maxEmitPower: number; + minLifeTime: number; + maxLifeTime: number; + minSize: number; + maxSize: number; + minAngularSpeed: number; + maxAngularSpeed: number; + particleTexture: Texture; + layerMask: number; + onDispose: () => void; + updateFunction: (particles: Particle[]) => void; + blendMode: number; + forceDepthWrite: boolean; + gravity: Vector3; + direction1: Vector3; + direction2: Vector3; + minEmitBox: Vector3; + maxEmitBox: Vector3; + color1: Color4; + color2: Color4; + colorDead: Color4; + textureMask: Color4; + startDirectionFunction: (emitPower: number, worldMatrix: Matrix, directionToUpdate: Vector3) => void; + startPositionFunction: (worldMatrix: Matrix, positionToUpdate: Vector3) => void; + private particles; + private _capacity; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _stockParticles; + private _newPartsExcess; + private _vertexBuffer; + private _indexBuffer; + private _vertices; + private _effect; + private _customEffect; + private _cachedDefines; + private _scaledColorStep; + private _colorDiff; + private _scaledDirection; + private _scaledGravity; + private _currentRenderId; + private _alive; + private _started; + private _stopped; + private _actualFrame; + private _scaledUpdateSpeed; + constructor(name: string, capacity: number, scene: Scene, customEffect?: Effect); + recycleParticle(particle: Particle): void; + getCapacity(): number; + isAlive(): boolean; + isStarted(): boolean; + start(): void; + stop(): void; + _appendParticleVertex(index: number, particle: Particle, offsetX: number, offsetY: number): void; + private _update(newParticles); + private _getEffect(); + animate(): void; + render(): number; + dispose(): void; + clone(name: string, newEmitter: any): ParticleSystem; + } +} + +declare module BABYLON { + interface IPhysicsEnginePlugin { + initialize(iterations?: number): any; + setGravity(gravity: Vector3): void; + runOneStep(delta: number): void; + registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + unregisterMesh(mesh: AbstractMesh): any; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + dispose(): void; + isSupported(): boolean; + updateBodyPosition(mesh: AbstractMesh): void; + } + interface PhysicsBodyCreationOptions { + mass: number; + friction: number; + restitution: number; + } + interface PhysicsCompoundBodyPart { + mesh: Mesh; + impostor: number; + } + class PhysicsEngine { + gravity: Vector3; + private _currentPlugin; + constructor(plugin?: IPhysicsEnginePlugin); + _initialize(gravity?: Vector3): void; + _runOneStep(delta: number): void; + _setGravity(gravity: Vector3): void; + _registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + _registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + _unregisterMesh(mesh: AbstractMesh): void; + _applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + _createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + _updateBodyPosition(mesh: AbstractMesh): void; + dispose(): void; + isSupported(): boolean; + static NoImpostor: number; + static SphereImpostor: number; + static BoxImpostor: number; + static PlaneImpostor: number; + static MeshImpostor: number; + static CapsuleImpostor: number; + static ConeImpostor: number; + static CylinderImpostor: number; + static ConvexHullImpostor: number; + static Epsilon: number; + } +} + +declare module BABYLON { + class BoundingBoxRenderer { + frontColor: Color3; + backColor: Color3; + showBackLines: boolean; + renderList: SmartArray; + private _scene; + private _colorShader; + private _vb; + private _ib; + constructor(scene: Scene); + private _prepareRessources(); + reset(): void; + render(): void; + dispose(): void; + } +} + +declare module BABYLON { + class DepthRenderer { + private _scene; + private _depthMap; + private _effect; + private _viewMatrix; + private _projectionMatrix; + private _transformMatrix; + private _worldViewProjection; + private _cachedDefines; + constructor(scene: Scene, type?: number); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + getDepthMap(): RenderTargetTexture; + dispose(): void; + } +} + +declare module BABYLON { + class EdgesRenderer { + private _source; + private _linesPositions; + private _linesNormals; + private _linesIndices; + private _epsilon; + private _indicesCount; + private _lineShader; + private _vb0; + private _vb1; + private _ib; + private _buffers; + private _checkVerticesInsteadOfIndices; + constructor(source: AbstractMesh, epsilon?: number, checkVerticesInsteadOfIndices?: boolean); + private _prepareRessources(); + dispose(): void; + private _processEdgeForAdjacencies(pa, pb, p0, p1, p2); + private _processEdgeForAdjacenciesWithVertices(pa, pb, p0, p1, p2); + private _checkEdge(faceIndex, edge, faceNormals, p0, p1); + _generateEdgesLines(): void; + render(): void; + } +} + +declare module BABYLON { + class OutlineRenderer { + private _scene; + private _effect; + private _cachedDefines; + constructor(scene: Scene); + render(subMesh: SubMesh, batch: _InstancesBatch, useOverlay?: boolean): void; + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + } +} + +declare module BABYLON { + class RenderingGroup { + index: number; + private _scene; + private _opaqueSubMeshes; + private _transparentSubMeshes; + private _alphaTestSubMeshes; + private _activeVertices; + constructor(index: number, scene: Scene); + render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void): boolean; + prepare(): void; + dispatch(subMesh: SubMesh): void; + } +} + +declare module BABYLON { + class RenderingManager { + static MAX_RENDERINGGROUPS: number; + private _scene; + private _renderingGroups; + private _depthBufferAlreadyCleaned; + constructor(scene: Scene); + private _renderParticles(index, activeMeshes); + private _renderSprites(index); + private _clearDepthBuffer(); + render(customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray) => void, activeMeshes: AbstractMesh[], renderParticles: boolean, renderSprites: boolean): void; + reset(): void; + dispatch(subMesh: SubMesh): void; + } +} + +declare module BABYLON { + class AnaglyphPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class BlackAndWhitePostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class BlurPostProcess extends PostProcess { + direction: Vector2; + blurWidth: number; + constructor(name: string, direction: Vector2, blurWidth: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class ColorCorrectionPostProcess extends PostProcess { + private _colorTableTexture; + constructor(name: string, colorTableUrl: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class ConvolutionPostProcess extends PostProcess { + kernel: number[]; + constructor(name: string, kernel: number[], ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + static EdgeDetect0Kernel: number[]; + static EdgeDetect1Kernel: number[]; + static EdgeDetect2Kernel: number[]; + static SharpenKernel: number[]; + static EmbossKernel: number[]; + static GaussianKernel: number[]; + } +} + +declare module BABYLON { + class DisplayPassPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class FilterPostProcess extends PostProcess { + kernelMatrix: Matrix; + constructor(name: string, kernelMatrix: Matrix, ratio: number, camera?: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class FxaaPostProcess extends PostProcess { + texelWidth: number; + texelHeight: number; + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class HDRRenderingPipeline extends PostProcessRenderPipeline implements IDisposable { + /** + * Public members + */ + /** + * Gaussian blur coefficient + * @type {number} + */ + gaussCoeff: number; + /** + * Gaussian blur mean + * @type {number} + */ + gaussMean: number; + /** + * Gaussian blur standard deviation + * @type {number} + */ + gaussStandDev: number; + /** + * Exposure, controls the overall intensity of the pipeline + * @type {number} + */ + exposure: number; + /** + * Minimum luminance that the post-process can output. Luminance is >= 0 + * @type {number} + */ + minimumLuminance: number; + /** + * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance + * @type {number} + */ + maximumLuminance: number; + /** + * Increase rate for luminance: eye adaptation speed to dark + * @type {number} + */ + luminanceIncreaserate: number; + /** + * Decrease rate for luminance: eye adaptation speed to bright + * @type {number} + */ + luminanceDecreaseRate: number; + /** + * Minimum luminance needed to compute HDR + * @type {number} + */ + brightThreshold: number; + /** + * Private members + */ + private _guassianBlurHPostProcess; + private _guassianBlurVPostProcess; + private _brightPassPostProcess; + private _textureAdderPostProcess; + private _downSampleX4PostProcess; + private _originalPostProcess; + private _hdrPostProcess; + private _hdrCurrentLuminance; + private _hdrOutputLuminance; + static LUM_STEPS: number; + private _downSamplePostProcesses; + private _scene; + private _needUpdate; + /** + * @constructor + * @param {string} name - The rendering pipeline name + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null. + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, scene: Scene, ratio: number, originalPostProcess?: PostProcess, cameras?: Camera[]); + /** + * Tells the pipeline to update its post-processes + */ + update(): void; + /** + * Returns the current calculated luminance + */ + getCurrentLuminance(): number; + /** + * Returns the currently drawn luminance + */ + getOutputLuminance(): number; + /** + * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras + */ + dispose(): void; + /** + * Creates the HDR post-process and computes the luminance adaptation + */ + private _createHDRPostProcess(scene, ratio); + /** + * Texture Adder post-process + */ + private _createTextureAdderPostProcess(scene, ratio); + /** + * Down sample X4 post-process + */ + private _createDownSampleX4PostProcess(scene, ratio); + /** + * Bright pass post-process + */ + private _createBrightPassPostProcess(scene, ratio); + /** + * Luminance generator. Creates the luminance post-process and down sample post-processes + */ + private _createLuminanceGeneratorPostProcess(scene); + /** + * Gaussian blur post-processes. Horizontal and Vertical + */ + private _createGaussianBlurPostProcess(scene, ratio); + } +} + +declare module BABYLON { + class LensRenderingPipeline extends PostProcessRenderPipeline { + /** + * The chromatic aberration PostProcess id in the pipeline + * @type {string} + */ + LensChromaticAberrationEffect: string; + /** + * The highlights enhancing PostProcess id in the pipeline + * @type {string} + */ + HighlightsEnhancingEffect: string; + /** + * The depth-of-field PostProcess id in the pipeline + * @type {string} + */ + LensDepthOfFieldEffect: string; + private _scene; + private _depthTexture; + private _grainTexture; + private _chromaticAberrationPostProcess; + private _highlightsPostProcess; + private _depthOfFieldPostProcess; + private _edgeBlur; + private _grainAmount; + private _chromaticAberration; + private _distortion; + private _highlightsGain; + private _highlightsThreshold; + private _dofDistance; + private _dofAperture; + private _dofDarken; + private _dofPentagon; + private _blurNoise; + /** + * @constructor + * + * Effect parameters are as follow: + * { + * chromatic_aberration: number; // from 0 to x (1 for realism) + * edge_blur: number; // from 0 to x (1 for realism) + * distortion: number; // from 0 to x (1 for realism) + * grain_amount: number; // from 0 to 1 + * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise + * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default) + * dof_aperture: number; // depth-of-field: focus blur bias (default: 1) + * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default) + * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect + * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default) + * dof_threshold: number; // depth-of-field: highlights threshold (default: 1) + * blur_noise: boolean; // add a little bit of noise to the blur (default: true) + * } + * Note: if an effect parameter is unset, effect is disabled + * + * @param {string} name - The rendering pipeline name + * @param {object} parameters - An object containing all parameters (see above) + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, parameters: any, scene: Scene, ratio?: number, cameras?: Camera[]); + setEdgeBlur(amount: number): void; + disableEdgeBlur(): void; + setGrainAmount(amount: number): void; + disableGrain(): void; + setChromaticAberration(amount: number): void; + disableChromaticAberration(): void; + setEdgeDistortion(amount: number): void; + disableEdgeDistortion(): void; + setFocusDistance(amount: number): void; + disableDepthOfField(): void; + setAperture(amount: number): void; + setDarkenOutOfFocus(amount: number): void; + enablePentagonBokeh(): void; + disablePentagonBokeh(): void; + enableNoiseBlur(): void; + disableNoiseBlur(): void; + setHighlightsGain(amount: number): void; + setHighlightsThreshold(amount: number): void; + disableHighlights(): void; + /** + * Removes the internal pipeline assets and detaches the pipeline from the scene cameras + */ + dispose(disableDepthRender?: boolean): void; + private _createChromaticAberrationPostProcess(ratio); + private _createHighlightsPostProcess(ratio); + private _createDepthOfFieldPostProcess(ratio); + private _createGrainTexture(); + } +} + +declare module BABYLON { + class PassPostProcess extends PostProcess { + constructor(name: string, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + } +} + +declare module BABYLON { + class PostProcess { + name: string; + onApply: (effect: Effect) => void; + onBeforeRender: (effect: Effect) => void; + onAfterRender: (effect: Effect) => void; + onSizeChanged: () => void; + onActivate: (camera: Camera) => void; + width: number; + height: number; + renderTargetSamplingMode: number; + clearColor: Color4; + private _camera; + private _scene; + private _engine; + private _renderRatio; + private _reusable; + private _textureType; + _textures: SmartArray; + _currentRenderTextureInd: number; + private _effect; + constructor(name: string, fragmentUrl: string, parameters: string[], samplers: string[], ratio: number | any, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean, defines?: string, textureType?: number); + isReusable(): boolean; + activate(camera: Camera, sourceTexture?: WebGLTexture): void; + apply(): Effect; + dispose(camera?: Camera): void; + } +} + +declare module BABYLON { + class PostProcessManager { + private _scene; + private _indexBuffer; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + constructor(scene: Scene); + private _prepareBuffers(); + _prepareFrame(sourceTexture?: WebGLTexture): boolean; + directRender(postProcesses: PostProcess[], targetTexture?: WebGLTexture): void; + _finalizeFrame(doNotPresent?: boolean, targetTexture?: WebGLTexture, postProcesses?: PostProcess[]): void; + dispose(): void; + } +} + +declare module BABYLON { + class RefractionPostProcess extends PostProcess { + color: Color3; + depth: number; + colorLevel: number; + private _refRexture; + constructor(name: string, refractionTextureUrl: string, color: Color3, depth: number, colorLevel: number, ratio: number, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean); + dispose(camera: Camera): void; + } +} + +declare module BABYLON { + class SSAORenderingPipeline extends PostProcessRenderPipeline { + /** + * The PassPostProcess id in the pipeline that contains the original scene color + * @type {string} + */ + SSAOOriginalSceneColorEffect: string; + /** + * The SSAO PostProcess id in the pipeline + * @type {string} + */ + SSAORenderEffect: string; + /** + * The horizontal blur PostProcess id in the pipeline + * @type {string} + */ + SSAOBlurHRenderEffect: string; + /** + * The vertical blur PostProcess id in the pipeline + * @type {string} + */ + SSAOBlurVRenderEffect: string; + /** + * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect) + * @type {string} + */ + SSAOCombineRenderEffect: string; + /** + * The output strength of the SSAO post-process. Default value is 1.0. + * @type {number} + */ + totalStrength: number; + /** + * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002 + * @type {number} + */ + radius: number; + /** + * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel + * Must not be equal to fallOff and superior to fallOff. + * Default value is 0.0075 + * @type {number} + */ + area: number; + /** + * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel + * Must not be equal to area and inferior to area. + * Default value is 0.0002 + * @type {number} + */ + fallOff: number; + private _scene; + private _depthTexture; + private _randomTexture; + private _originalColorPostProcess; + private _ssaoPostProcess; + private _blurHPostProcess; + private _blurVPostProcess; + private _ssaoCombinePostProcess; + private _firstUpdate; + /** + * @constructor + * @param {string} name - The rendering pipeline name + * @param {BABYLON.Scene} scene - The scene linked to this pipeline + * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 } + * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to + */ + constructor(name: string, scene: Scene, ratio: any, cameras?: Camera[]); + /** + * Returns the horizontal blur PostProcess + * @return {BABYLON.BlurPostProcess} The horizontal blur post-process + */ + getBlurHPostProcess(): BlurPostProcess; + /** + * Returns the vertical blur PostProcess + * @return {BABYLON.BlurPostProcess} The vertical blur post-process + */ + getBlurVPostProcess(): BlurPostProcess; + /** + * Removes the internal pipeline assets and detatches the pipeline from the scene cameras + */ + dispose(disableDepthRender?: boolean): void; + private _createSSAOPostProcess(ratio); + private _createSSAOCombinePostProcess(ratio); + private _createRandomTexture(); + } +} + +declare module BABYLON { + class StereoscopicInterlacePostProcess extends PostProcess { + private _stepSize; + constructor(name: string, camB: Camera, postProcessA: PostProcess, isStereoscopicHoriz: boolean, samplingMode?: number); + } +} + +declare module BABYLON { + enum TonemappingOperator { + Hable = 0, + Reinhard = 1, + HejiDawson = 2, + Photographic = 3, + } + class TonemapPostProcess extends PostProcess { + private _operator; + private _exposureAdjustment; + constructor(name: string, operator: TonemappingOperator, exposureAdjustment: number, camera: Camera, samplingMode?: number, engine?: Engine, textureFormat?: number); + } +} + +declare module BABYLON { + class VolumetricLightScatteringPostProcess extends PostProcess { + private _volumetricLightScatteringPass; + private _volumetricLightScatteringRTT; + private _viewPort; + private _screenCoordinates; + private _cachedDefines; + private _customMeshPosition; + /** + * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false) + * @type {boolean} + */ + useCustomMeshPosition: boolean; + /** + * If the post-process should inverse the light scattering direction + * @type {boolean} + */ + invert: boolean; + /** + * The internal mesh used by the post-process + * @type {boolean} + */ + mesh: Mesh; + /** + * Set to true to use the diffuseColor instead of the diffuseTexture + * @type {boolean} + */ + useDiffuseColor: boolean; + /** + * Array containing the excluded meshes not rendered in the internal pass + */ + excludedMeshes: AbstractMesh[]; + /** + * Controls the overall intensity of the post-process + * @type {number} + */ + exposure: number; + /** + * Dissipates each sample's contribution in range [0, 1] + * @type {number} + */ + decay: number; + /** + * Controls the overall intensity of each sample + * @type {number} + */ + weight: number; + /** + * Controls the density of each sample + * @type {number} + */ + density: number; + /** + * @constructor + * @param {string} name - The post-process name + * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5) + * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to + * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering + * @param {number} samples - The post-process quality, default 100 + * @param {number} samplingMode - The post-process filtering mode + * @param {BABYLON.Engine} engine - The babylon engine + * @param {boolean} reusable - If the post-process is reusable + * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided + */ + constructor(name: string, ratio: any, camera: Camera, mesh?: Mesh, samples?: number, samplingMode?: number, engine?: Engine, reusable?: boolean, scene?: Scene); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + /** + * Sets the new light position for light scattering effect + * @param {BABYLON.Vector3} The new custom light position + */ + setCustomMeshPosition(position: Vector3): void; + /** + * Returns the light position for light scattering effect + * @return {BABYLON.Vector3} The custom light position + */ + getCustomMeshPosition(): Vector3; + /** + * Disposes the internal assets and detaches the post-process from the camera + */ + dispose(camera: Camera): void; + /** + * Returns the render target texture used by the post-process + * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process + */ + getPass(): RenderTargetTexture; + private _meshExcluded(mesh); + private _createPass(scene, ratio); + private _updateMeshScreenCoordinates(scene); + /** + * Creates a default mesh for the Volumeric Light Scattering post-process + * @param {string} The mesh name + * @param {BABYLON.Scene} The scene where to create the mesh + * @return {BABYLON.Mesh} the default mesh + */ + static CreateDefaultMesh(name: string, scene: Scene): Mesh; + } +} + +declare module BABYLON { + class VRDistortionCorrectionPostProcess extends PostProcess { + aspectRatio: number; + private _isRightEye; + private _distortionFactors; + private _postProcessScaleFactor; + private _lensCenterOffset; + private _scaleIn; + private _scaleFactor; + private _lensCenter; + constructor(name: string, camera: Camera, isRightEye: boolean, vrMetrics: VRCameraMetrics); + } +} + +declare module BABYLON { + class Sprite { + name: string; + position: Vector3; + color: Color4; + width: number; + height: number; + angle: number; + cellIndex: number; + invertU: number; + invertV: number; + disposeWhenFinishedAnimating: boolean; + animations: Animation[]; + private _animationStarted; + private _loopAnimation; + private _fromIndex; + private _toIndex; + private _delay; + private _direction; + private _frameCount; + private _manager; + private _time; + size: number; + constructor(name: string, manager: SpriteManager); + playAnimation(from: number, to: number, loop: boolean, delay: number): void; + stopAnimation(): void; + _animate(deltaTime: number): void; + dispose(): void; + } +} + +declare module BABYLON { + class SpriteManager { + name: string; + cellSize: number; + sprites: Sprite[]; + renderingGroupId: number; + layerMask: number; + onDispose: () => void; + fogEnabled: boolean; + private _capacity; + private _spriteTexture; + private _epsilon; + private _scene; + private _vertexDeclaration; + private _vertexStrideSize; + private _vertexBuffer; + private _indexBuffer; + private _vertices; + private _effectBase; + private _effectFog; + constructor(name: string, imgUrl: string, capacity: number, cellSize: number, scene: Scene, epsilon?: number, samplingMode?: number); + private _appendSpriteVertex(index, sprite, offsetX, offsetY, rowSize); + render(): void; + dispose(): void; + } +} + +declare module BABYLON.Internals { + class AndOrNotEvaluator { + static Eval(query: string, evaluateCallback: (val: any) => boolean): boolean; + private static _HandleParenthesisContent(parenthesisContent, evaluateCallback); + private static _SimplifyNegation(booleanString); + } +} + +declare module BABYLON { + interface IAssetTask { + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + run(scene: Scene, onSuccess: () => void, onError: () => void): any; + } + class MeshAssetTask implements IAssetTask { + name: string; + meshesNames: any; + rootUrl: string; + sceneFilename: string; + loadedMeshes: Array; + loadedParticleSystems: Array; + loadedSkeletons: Array; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + constructor(name: string, meshesNames: any, rootUrl: string, sceneFilename: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class TextFileAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + text: string; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class BinaryFileAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + data: ArrayBuffer; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class ImageAssetTask implements IAssetTask { + name: string; + url: string; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + image: HTMLImageElement; + constructor(name: string, url: string); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class TextureAssetTask implements IAssetTask { + name: string; + url: string; + noMipmap: boolean; + invertY: boolean; + samplingMode: number; + onSuccess: (task: IAssetTask) => void; + onError: (task: IAssetTask) => void; + isCompleted: boolean; + texture: Texture; + constructor(name: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number); + run(scene: Scene, onSuccess: () => void, onError: () => void): void; + } + class AssetsManager { + private _tasks; + private _scene; + private _waitingTasksCount; + onFinish: (tasks: IAssetTask[]) => void; + onTaskSuccess: (task: IAssetTask) => void; + onTaskError: (task: IAssetTask) => void; + useDefaultLoadingScreen: boolean; + constructor(scene: Scene); + addMeshTask(taskName: string, meshesNames: any, rootUrl: string, sceneFilename: string): IAssetTask; + addTextFileTask(taskName: string, url: string): IAssetTask; + addBinaryFileTask(taskName: string, url: string): IAssetTask; + addImageTask(taskName: string, url: string): IAssetTask; + addTextureTask(taskName: string, url: string, noMipmap?: boolean, invertY?: boolean, samplingMode?: number): IAssetTask; + private _decreaseWaitingTasksCount(); + private _runTask(task); + reset(): AssetsManager; + load(): AssetsManager; + } +} + +declare module BABYLON { + class Database { + private callbackManifestChecked; + private currentSceneUrl; + private db; + private enableSceneOffline; + private enableTexturesOffline; + private manifestVersionFound; + private mustUpdateRessources; + private hasReachedQuota; + private isSupported; + private idbFactory; + static IsUASupportingBlobStorage: boolean; + static IDBStorageEnabled: boolean; + constructor(urlToScene: string, callbackManifestChecked: (checked: boolean) => any); + static parseURL: (url: string) => string; + static ReturnFullUrlLocation: (url: string) => string; + checkManifestFile(): void; + openAsync(successCallback: any, errorCallback: any): void; + loadImageFromDB(url: string, image: HTMLImageElement): void; + private _loadImageFromDBAsync(url, image, notInDBCallback); + private _saveImageIntoDBAsync(url, image); + private _checkVersionFromDB(url, versionLoaded); + private _loadVersionFromDBAsync(url, callback, updateInDBCallback); + private _saveVersionIntoDBAsync(url, callback); + private loadFileFromDB(url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer?); + private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?); + private _saveFileIntoDBAsync(url, callback, progressCallback, useArrayBuffer?); + } +} + +declare module BABYLON { + class FilesInput { + private _engine; + private _currentScene; + private _canvas; + private _sceneLoadedCallback; + private _progressCallback; + private _additionnalRenderLoopLogicCallback; + private _textureLoadingCallback; + private _startingProcessingFilesCallback; + private _elementToMonitor; + static FilesTextures: any[]; + static FilesToLoad: any[]; + private _sceneFileToLoad; + private _filesToLoad; + constructor(p_engine: Engine, p_scene: Scene, p_canvas: HTMLCanvasElement, p_sceneLoadedCallback: any, p_progressCallback: any, p_additionnalRenderLoopLogicCallback: any, p_textureLoadingCallback: any, p_startingProcessingFilesCallback: any); + monitorElementForDragNDrop(p_elementToMonitor: HTMLElement): void; + private renderFunction(); + private drag(e); + private drop(eventDrop); + loadFiles(event: any): void; + reload(): void; + } +} + +declare module BABYLON { + class Gamepads { + private babylonGamepads; + private oneGamepadConnected; + private isMonitoring; + private gamepadEventSupported; + private gamepadSupportAvailable; + private _callbackGamepadConnected; + private buttonADataURL; + private static gamepadDOMInfo; + constructor(ongamedpadconnected: (gamepad: Gamepad) => void); + private _insertGamepadDOMInstructions(); + private _insertGamepadDOMNotSupported(); + dispose(): void; + private _onGamepadConnected(evt); + private _addNewGamepad(gamepad); + private _onGamepadDisconnected(evt); + private _startMonitoringGamepads(); + private _stopMonitoringGamepads(); + private _checkGamepadsStatus(); + private _updateGamepadObjects(); + } + class StickValues { + x: any; + y: any; + constructor(x: any, y: any); + } + class Gamepad { + id: string; + index: number; + browserGamepad: any; + private _leftStick; + private _rightStick; + private _onleftstickchanged; + private _onrightstickchanged; + constructor(id: string, index: number, browserGamepad: any); + onleftstickchanged(callback: (values: StickValues) => void): void; + onrightstickchanged(callback: (values: StickValues) => void): void; + leftStick: StickValues; + rightStick: StickValues; + update(): void; + } + class GenericPad extends Gamepad { + id: string; + index: number; + gamepad: any; + private _buttons; + private _onbuttondown; + private _onbuttonup; + onbuttondown(callback: (buttonPressed: number) => void): void; + onbuttonup(callback: (buttonReleased: number) => void): void; + constructor(id: string, index: number, gamepad: any); + private _setButtonValue(newValue, currentValue, buttonIndex); + update(): void; + } + enum Xbox360Button { + A = 0, + B = 1, + X = 2, + Y = 3, + Start = 4, + Back = 5, + LB = 6, + RB = 7, + LeftStick = 8, + RightStick = 9, + } + enum Xbox360Dpad { + Up = 0, + Down = 1, + Left = 2, + Right = 3, + } + class Xbox360Pad extends Gamepad { + private _leftTrigger; + private _rightTrigger; + private _onlefttriggerchanged; + private _onrighttriggerchanged; + private _onbuttondown; + private _onbuttonup; + private _ondpaddown; + private _ondpadup; + private _buttonA; + private _buttonB; + private _buttonX; + private _buttonY; + private _buttonBack; + private _buttonStart; + private _buttonLB; + private _buttonRB; + private _buttonLeftStick; + private _buttonRightStick; + private _dPadUp; + private _dPadDown; + private _dPadLeft; + private _dPadRight; + onlefttriggerchanged(callback: (value: number) => void): void; + onrighttriggerchanged(callback: (value: number) => void): void; + leftTrigger: number; + rightTrigger: number; + onbuttondown(callback: (buttonPressed: Xbox360Button) => void): void; + onbuttonup(callback: (buttonReleased: Xbox360Button) => void): void; + ondpaddown(callback: (dPadPressed: Xbox360Dpad) => void): void; + ondpadup(callback: (dPadReleased: Xbox360Dpad) => void): void; + private _setButtonValue(newValue, currentValue, buttonType); + private _setDPadValue(newValue, currentValue, buttonType); + buttonA: number; + buttonB: number; + buttonX: number; + buttonY: number; + buttonStart: number; + buttonBack: number; + buttonLB: number; + buttonRB: number; + buttonLeftStick: number; + buttonRightStick: number; + dPadUp: number; + dPadDown: number; + dPadLeft: number; + dPadRight: number; + update(): void; + } +} +interface Navigator { + getGamepads(func?: any): any; + webkitGetGamepads(func?: any): any; + msGetGamepads(func?: any): any; + webkitGamepads(func?: any): any; +} + +declare module BABYLON { + class SceneOptimization { + priority: number; + apply: (scene: Scene) => boolean; + constructor(priority?: number); + } + class TextureOptimization extends SceneOptimization { + priority: number; + maximumSize: number; + constructor(priority?: number, maximumSize?: number); + apply: (scene: Scene) => boolean; + } + class HardwareScalingOptimization extends SceneOptimization { + priority: number; + maximumScale: number; + private _currentScale; + constructor(priority?: number, maximumScale?: number); + apply: (scene: Scene) => boolean; + } + class ShadowsOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class PostProcessesOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class LensFlaresOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class ParticlesOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class RenderTargetsOptimization extends SceneOptimization { + apply: (scene: Scene) => boolean; + } + class MergeMeshesOptimization extends SceneOptimization { + static _UpdateSelectionTree: boolean; + static UpdateSelectionTree: boolean; + private _canBeMerged; + apply: (scene: Scene, updateSelectionTree?: boolean) => boolean; + } + class SceneOptimizerOptions { + targetFrameRate: number; + trackerDuration: number; + optimizations: SceneOptimization[]; + constructor(targetFrameRate?: number, trackerDuration?: number); + static LowDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + static ModerateDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + static HighDegradationAllowed(targetFrameRate?: number): SceneOptimizerOptions; + } + class SceneOptimizer { + static _CheckCurrentState(scene: Scene, options: SceneOptimizerOptions, currentPriorityLevel: number, onSuccess?: () => void, onFailure?: () => void): void; + static OptimizeAsync(scene: Scene, options?: SceneOptimizerOptions, onSuccess?: () => void, onFailure?: () => void): void; + } +} + +declare module BABYLON { + class SceneSerializer { + static Serialize(scene: Scene): any; + static SerializeMesh(toSerialize: any, withParents?: boolean, withChildren?: boolean): any; + } +} + +declare module BABYLON { + class SmartArray { + data: Array; + length: number; + private _id; + private _duplicateId; + constructor(capacity: number); + push(value: any): void; + pushNoDuplicate(value: any): void; + sort(compareFn: any): void; + reset(): void; + concat(array: any): void; + concatWithNoDuplicate(array: any): void; + indexOf(value: any): number; + private static _GlobalId; + } +} + +declare module BABYLON { + class SmartCollection { + count: number; + items: any; + private _keys; + private _initialCapacity; + constructor(capacity?: number); + add(key: any, item: any): number; + remove(key: any): number; + removeItemOfIndex(index: number): number; + indexOf(key: any): number; + item(key: any): any; + getAllKeys(): any[]; + getKeyByIndex(index: number): any; + getItemByIndex(index: number): any; + empty(): void; + forEach(block: (item: any) => void): void; + } +} + +declare module BABYLON { + class Tags { + static EnableFor(obj: any): void; + static DisableFor(obj: any): void; + static HasTags(obj: any): boolean; + static GetTags(obj: any): any; + static AddTagsTo(obj: any, tagsString: string): void; + static _AddTagTo(obj: any, tag: string): void; + static RemoveTagsFrom(obj: any, tagsString: string): void; + static _RemoveTagFrom(obj: any, tag: string): void; + static MatchesQuery(obj: any, tagsQuery: string): boolean; + } +} + +declare module BABYLON.Internals { + interface DDSInfo { + width: number; + height: number; + mipmapCount: number; + isFourCC: boolean; + isRGB: boolean; + isLuminance: boolean; + isCube: boolean; + } + class DDSTools { + static GetDDSInfo(arrayBuffer: any): DDSInfo; + private static GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + private static GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer); + static UploadDDSLevels(gl: WebGLRenderingContext, ext: any, arrayBuffer: any, info: DDSInfo, loadMipmaps: boolean, faces: number): void; + } +} + +declare module BABYLON.Internals { + class TGATools { + private static _TYPE_NO_DATA; + private static _TYPE_INDEXED; + private static _TYPE_RGB; + private static _TYPE_GREY; + private static _TYPE_RLE_INDEXED; + private static _TYPE_RLE_RGB; + private static _TYPE_RLE_GREY; + private static _ORIGIN_MASK; + private static _ORIGIN_SHIFT; + private static _ORIGIN_BL; + private static _ORIGIN_BR; + private static _ORIGIN_UL; + private static _ORIGIN_UR; + static GetTGAHeader(data: Uint8Array): any; + static UploadContent(gl: WebGLRenderingContext, data: Uint8Array): void; + static _getImageData8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData24bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageData32bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageDataGrey8bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + static _getImageDataGrey16bits(header: any, palettes: Uint8Array, pixel_data: Uint8Array, y_start: number, y_step: number, y_end: number, x_start: number, x_step: number, x_end: number): Uint8Array; + } +} + +declare module BABYLON { + interface IAnimatable { + animations: Array; + } + interface ISize { + width: number; + height: number; + } + class Tools { + static BaseUrl: string; + static ToHex(i: number): string; + static SetImmediate(action: () => void): void; + static IsExponantOfTwo(value: number): boolean; + static GetExponantOfTwo(value: number, max: number): number; + static GetFilename(path: string): string; + static GetDOMTextContent(element: HTMLElement): string; + static ToDegrees(angle: number): number; + static ToRadians(angle: number): number; + static ExtractMinAndMaxIndexed(positions: number[], indices: number[], indexStart: number, indexCount: number): { + minimum: Vector3; + maximum: Vector3; + }; + static ExtractMinAndMax(positions: number[], start: number, count: number): { + minimum: Vector3; + maximum: Vector3; + }; + static MakeArray(obj: any, allowsNullUndefined?: boolean): Array; + static GetPointerPrefix(): string; + static QueueNewFrame(func: any): void; + static RequestFullscreen(element: any): void; + static ExitFullscreen(): void; + static CleanUrl(url: string): string; + static LoadImage(url: string, onload: any, onerror: any, database: any): HTMLImageElement; + static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?: any, useArrayBuffer?: boolean, onError?: () => void): void; + static ReadFileAsDataURL(fileToLoad: any, callback: any, progressCallback: any): void; + static ReadFile(fileToLoad: any, callback: any, progressCallBack: any, useArrayBuffer?: boolean): void; + static Clamp(value: number, min?: number, max?: number): number; + static Sign(value: number): number; + static Format(value: number, decimals?: number): string; + static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void; + static WithinEpsilon(a: number, b: number, epsilon?: number): boolean; + static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void; + static IsEmpty(obj: any): boolean; + static RegisterTopRootEvents(events: { + name: string; + handler: EventListener; + }[]): void; + static UnregisterTopRootEvents(events: { + name: string; + handler: EventListener; + }[]): void; + static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: String) => void): void; + static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: String) => void): void; + static ValidateXHRData(xhr: XMLHttpRequest, dataType?: number): boolean; + private static _NoneLogLevel; + private static _MessageLogLevel; + private static _WarningLogLevel; + private static _ErrorLogLevel; + private static _LogCache; + static errorsCount: number; + static OnNewCacheEntry: (entry: string) => void; + static NoneLogLevel: number; + static MessageLogLevel: number; + static WarningLogLevel: number; + static ErrorLogLevel: number; + static AllLogLevel: number; + private static _AddLogEntry(entry); + private static _FormatMessage(message); + static Log: (message: string) => void; + private static _LogDisabled(message); + private static _LogEnabled(message); + static Warn: (message: string) => void; + private static _WarnDisabled(message); + private static _WarnEnabled(message); + static Error: (message: string) => void; + private static _ErrorDisabled(message); + private static _ErrorEnabled(message); + static LogCache: string; + static ClearLogCache(): void; + static LogLevels: number; + private static _PerformanceNoneLogLevel; + private static _PerformanceUserMarkLogLevel; + private static _PerformanceConsoleLogLevel; + private static _performance; + static PerformanceNoneLogLevel: number; + static PerformanceUserMarkLogLevel: number; + static PerformanceConsoleLogLevel: number; + static PerformanceLogLevel: number; + static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void; + static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void; + static _StartUserMark(counterName: string, condition?: boolean): void; + static _EndUserMark(counterName: string, condition?: boolean): void; + static _StartPerformanceConsole(counterName: string, condition?: boolean): void; + static _EndPerformanceConsole(counterName: string, condition?: boolean): void; + static StartPerformanceCounter: (counterName: string, condition?: boolean) => void; + static EndPerformanceCounter: (counterName: string, condition?: boolean) => void; + static Now: number; + static GetFps(): number; + } + /** + * An implementation of a loop for asynchronous functions. + */ + class AsyncLoop { + iterations: number; + private _fn; + private _successCallback; + index: number; + private _done; + /** + * Constroctor. + * @param iterations the number of iterations. + * @param _fn the function to run each iteration + * @param _successCallback the callback that will be called upon succesful execution + * @param offset starting offset. + */ + constructor(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number); + /** + * Execute the next iteration. Must be called after the last iteration was finished. + */ + executeNext(): void; + /** + * Break the loop and run the success callback. + */ + breakLoop(): void; + /** + * Helper function + */ + static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset?: number): AsyncLoop; + /** + * A for-loop that will run a given number of iterations synchronous and the rest async. + * @param iterations total number of iterations + * @param syncedIterations number of synchronous iterations in each async iteration. + * @param fn the function to call each iteration. + * @param callback a success call back that will be called when iterating stops. + * @param breakFunction a break condition (optional) + * @param timeout timeout settings for the setTimeout function. default - 0. + * @constructor + */ + static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout?: number): void; + } +} + +declare module BABYLON { + enum JoystickAxis { + X = 0, + Y = 1, + Z = 2, + } + class VirtualJoystick { + reverseLeftRight: boolean; + reverseUpDown: boolean; + deltaPosition: Vector3; + pressed: boolean; + private static _globalJoystickIndex; + private static vjCanvas; + private static vjCanvasContext; + private static vjCanvasWidth; + private static vjCanvasHeight; + private static halfWidth; + private static halfHeight; + private _action; + private _axisTargetedByLeftAndRight; + private _axisTargetedByUpAndDown; + private _joystickSensibility; + private _inversedSensibility; + private _rotationSpeed; + private _inverseRotationSpeed; + private _rotateOnAxisRelativeToMesh; + private _joystickPointerID; + private _joystickColor; + private _joystickPointerPos; + private _joystickPreviousPointerPos; + private _joystickPointerStartPos; + private _deltaJoystickVector; + private _leftJoystick; + private _joystickIndex; + private _touches; + private _onPointerDownHandlerRef; + private _onPointerMoveHandlerRef; + private _onPointerUpHandlerRef; + private _onPointerOutHandlerRef; + private _onResize; + constructor(leftJoystick?: boolean); + setJoystickSensibility(newJoystickSensibility: number): void; + private _onPointerDown(e); + private _onPointerMove(e); + private _onPointerUp(e); + /** + * Change the color of the virtual joystick + * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000") + */ + setJoystickColor(newColor: string): void; + setActionOnTouch(action: () => any): void; + setAxisForLeftRight(axis: JoystickAxis): void; + setAxisForUpDown(axis: JoystickAxis): void; + private _clearCanvas(); + private _drawVirtualJoystick(); + releaseCanvas(): void; + } +} + +declare module BABYLON { + class VRDeviceOrientationFreeCamera extends FreeCamera { + _alpha: number; + _beta: number; + _gamma: number; + private _offsetOrientation; + private _deviceOrientationHandler; + constructor(name: string, position: Vector3, scene: Scene, compensateDistorsion?: boolean); + _onOrientationEvent(evt: DeviceOrientationEvent): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + } +} + +declare var HMDVRDevice: any; +declare var PositionSensorVRDevice: any; +declare module BABYLON { + class WebVRFreeCamera extends FreeCamera { + _hmdDevice: any; + _sensorDevice: any; + _cacheState: any; + _cacheQuaternion: Quaternion; + _cacheRotation: Vector3; + _vrEnabled: boolean; + constructor(name: string, position: Vector3, scene: Scene, compensateDistorsion?: boolean); + private _getWebVRDevices(devices); + _checkInputs(): void; + attachControl(element: HTMLElement, noPreventDefault?: boolean): void; + detachControl(element: HTMLElement): void; + } +} + +declare module BABYLON { + interface IOctreeContainer { + blocks: Array>; + } + class Octree { + maxDepth: number; + blocks: Array>; + dynamicContent: T[]; + private _maxBlockCapacity; + private _selectionContent; + private _creationFunc; + constructor(creationFunc: (entry: T, block: OctreeBlock) => void, maxBlockCapacity?: number, maxDepth?: number); + update(worldMin: Vector3, worldMax: Vector3, entries: T[]): void; + addMesh(entry: T): void; + select(frustumPlanes: Plane[], allowDuplicate?: boolean): SmartArray; + intersects(sphereCenter: Vector3, sphereRadius: number, allowDuplicate?: boolean): SmartArray; + intersectsRay(ray: Ray): SmartArray; + static _CreateBlocks(worldMin: Vector3, worldMax: Vector3, entries: T[], maxBlockCapacity: number, currentDepth: number, maxDepth: number, target: IOctreeContainer, creationFunc: (entry: T, block: OctreeBlock) => void): void; + static CreationFuncForMeshes: (entry: AbstractMesh, block: OctreeBlock) => void; + static CreationFuncForSubMeshes: (entry: SubMesh, block: OctreeBlock) => void; + } +} + +declare module BABYLON { + class OctreeBlock { + entries: T[]; + blocks: Array>; + private _depth; + private _maxDepth; + private _capacity; + private _minPoint; + private _maxPoint; + private _boundingVectors; + private _creationFunc; + constructor(minPoint: Vector3, maxPoint: Vector3, capacity: number, depth: number, maxDepth: number, creationFunc: (entry: T, block: OctreeBlock) => void); + capacity: number; + minPoint: Vector3; + maxPoint: Vector3; + addEntry(entry: T): void; + addEntries(entries: T[]): void; + select(frustumPlanes: Plane[], selection: SmartArray, allowDuplicate?: boolean): void; + intersects(sphereCenter: Vector3, sphereRadius: number, selection: SmartArray, allowDuplicate?: boolean): void; + intersectsRay(ray: Ray, selection: SmartArray): void; + createInnerBlocks(): void; + } +} + +declare module BABYLON { + class ShadowGenerator { + private static _FILTER_NONE; + private static _FILTER_VARIANCESHADOWMAP; + private static _FILTER_POISSONSAMPLING; + private static _FILTER_BLURVARIANCESHADOWMAP; + static FILTER_NONE: number; + static FILTER_VARIANCESHADOWMAP: number; + static FILTER_POISSONSAMPLING: number; + static FILTER_BLURVARIANCESHADOWMAP: number; + private _filter; + blurScale: number; + private _blurBoxOffset; + private _bias; + private _lightDirection; + bias: number; + blurBoxOffset: number; + filter: number; + useVarianceShadowMap: boolean; + usePoissonSampling: boolean; + useBlurVarianceShadowMap: boolean; + private _light; + private _scene; + private _shadowMap; + private _shadowMap2; + private _darkness; + private _transparencyShadow; + private _effect; + private _viewMatrix; + private _projectionMatrix; + private _transformMatrix; + private _worldViewProjection; + private _cachedPosition; + private _cachedDirection; + private _cachedDefines; + private _currentRenderID; + private _downSamplePostprocess; + private _boxBlurPostprocess; + private _mapSize; + constructor(mapSize: number, light: IShadowLight); + isReady(subMesh: SubMesh, useInstances: boolean): boolean; + getShadowMap(): RenderTargetTexture; + getShadowMapForRendering(): RenderTargetTexture; + getLight(): IShadowLight; + getTransformMatrix(): Matrix; + getDarkness(): number; + setDarkness(darkness: number): void; + setTransparencyShadow(hasShadow: boolean): void; + private _packHalf(depth); + dispose(): void; + } +} + +declare module BABYLON.Internals { +} + +declare module BABYLON { + class BaseTexture { + name: string; + delayLoadState: number; + hasAlpha: boolean; + getAlphaFromRGB: boolean; + level: number; + isCube: boolean; + isRenderTarget: boolean; + animations: Animation[]; + onDispose: () => void; + coordinatesIndex: number; + coordinatesMode: number; + wrapU: number; + wrapV: number; + uScale: number; + vScale: number; + anisotropicFilteringLevel: number; + _cachedAnisotropicFilteringLevel: number; + private _scene; + _texture: WebGLTexture; + constructor(scene: Scene); + getScene(): Scene; + getTextureMatrix(): Matrix; + getReflectionTextureMatrix(): Matrix; + getInternalTexture(): WebGLTexture; + isReady(): boolean; + getSize(): ISize; + getBaseSize(): ISize; + scale(ratio: number): void; + canRescale: boolean; + _removeFromCache(url: string, noMipmap: boolean): void; + _getFromCache(url: string, noMipmap: boolean, sampling?: number): WebGLTexture; + delayLoad(): void; + releaseInternalTexture(): void; + clone(): BaseTexture; + dispose(): void; + } +} + +declare module BABYLON { + class CubeTexture extends BaseTexture { + url: string; + coordinatesMode: number; + private _noMipmap; + private _extensions; + private _textureMatrix; + constructor(rootUrl: string, scene: Scene, extensions?: string[], noMipmap?: boolean); + clone(): CubeTexture; + delayLoad(): void; + getReflectionTextureMatrix(): Matrix; + } +} + +declare module BABYLON { + class DynamicTexture extends Texture { + private _generateMipMaps; + private _canvas; + private _context; + constructor(name: string, options: any, scene: Scene, generateMipMaps: boolean, samplingMode?: number); + canRescale: boolean; + scale(ratio: number): void; + getContext(): CanvasRenderingContext2D; + clear(): void; + update(invertY?: boolean): void; + drawText(text: string, x: number, y: number, font: string, color: string, clearColor: string, invertY?: boolean, update?: boolean): void; + clone(): DynamicTexture; + } +} + +declare module BABYLON { + class MirrorTexture extends RenderTargetTexture { + mirrorPlane: Plane; + private _transformMatrix; + private _mirrorMatrix; + private _savedViewMatrix; + constructor(name: string, size: number, scene: Scene, generateMipMaps?: boolean); + clone(): MirrorTexture; + } +} + +declare module BABYLON { + class RawTexture extends Texture { + format: number; + constructor(data: ArrayBufferView, width: number, height: number, format: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); + update(data: ArrayBufferView): void; + static CreateLuminanceTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateLuminanceAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateAlphaTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateRGBTexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + static CreateRGBATexture(data: ArrayBufferView, width: number, height: number, scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number): RawTexture; + } +} + +declare module BABYLON { + class RenderTargetTexture extends Texture { + renderList: AbstractMesh[]; + renderParticles: boolean; + renderSprites: boolean; + coordinatesMode: number; + onBeforeRender: () => void; + onAfterRender: () => void; + onAfterUnbind: () => void; + onClear: (engine: Engine) => void; + activeCamera: Camera; + customRenderFunction: (opaqueSubMeshes: SmartArray, transparentSubMeshes: SmartArray, alphaTestSubMeshes: SmartArray, beforeTransparents?: () => void) => void; + private _size; + _generateMipMaps: boolean; + private _renderingManager; + _waitingRenderList: string[]; + private _doNotChangeAspectRatio; + private _currentRefreshId; + private _refreshRate; + constructor(name: string, size: any, scene: Scene, generateMipMaps?: boolean, doNotChangeAspectRatio?: boolean, type?: number); + resetRefreshCounter(): void; + refreshRate: number; + _shouldRender(): boolean; + isReady(): boolean; + getRenderSize(): number; + canRescale: boolean; + scale(ratio: number): void; + resize(size: any, generateMipMaps?: boolean): void; + render(useCameraPostProcess?: boolean, dumpForDebug?: boolean): void; + clone(): RenderTargetTexture; + } +} + +declare module BABYLON { + class Texture extends BaseTexture { + static NEAREST_SAMPLINGMODE: number; + static BILINEAR_SAMPLINGMODE: number; + static TRILINEAR_SAMPLINGMODE: number; + static EXPLICIT_MODE: number; + static SPHERICAL_MODE: number; + static PLANAR_MODE: number; + static CUBIC_MODE: number; + static PROJECTION_MODE: number; + static SKYBOX_MODE: number; + static CLAMP_ADDRESSMODE: number; + static WRAP_ADDRESSMODE: number; + static MIRROR_ADDRESSMODE: number; + url: string; + uOffset: number; + vOffset: number; + uScale: number; + vScale: number; + uAng: number; + vAng: number; + wAng: number; + private _noMipmap; + _invertY: boolean; + private _rowGenerationMatrix; + private _cachedTextureMatrix; + private _projectionModeMatrix; + private _t0; + private _t1; + private _t2; + private _cachedUOffset; + private _cachedVOffset; + private _cachedUScale; + private _cachedVScale; + private _cachedUAng; + private _cachedVAng; + private _cachedWAng; + private _cachedCoordinatesMode; + _samplingMode: number; + private _buffer; + private _deleteBuffer; + constructor(url: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void, buffer?: any, deleteBuffer?: boolean); + delayLoad(): void; + updateSamplingMode(samplingMode: number): void; + private _prepareRowForTextureGeneration(x, y, z, t); + getTextureMatrix(): Matrix; + getReflectionTextureMatrix(): Matrix; + clone(): Texture; + static CreateFromBase64String(data: string, name: string, scene: Scene, noMipmap?: boolean, invertY?: boolean, samplingMode?: number, onLoad?: () => void, onError?: () => void): Texture; + } +} + +declare module BABYLON { + class VideoTexture extends Texture { + video: HTMLVideoElement; + private _autoLaunch; + private _lastUpdate; + constructor(name: string, urls: string[], scene: Scene, generateMipMaps?: boolean, invertY?: boolean, samplingMode?: number); + update(): boolean; + } +} + +declare module BABYLON { + class CannonJSPlugin implements IPhysicsEnginePlugin { + checkWithEpsilon: (value: number) => number; + private _world; + private _registeredMeshes; + private _physicsMaterials; + initialize(iterations?: number): void; + private _checkWithEpsilon(value); + runOneStep(delta: number): void; + setGravity(gravity: Vector3): void; + registerMesh(mesh: AbstractMesh, impostor: number, options?: PhysicsBodyCreationOptions): any; + private _createSphere(radius, mesh, options?); + private _createBox(x, y, z, mesh, options?); + private _createPlane(mesh, options?); + private _createConvexPolyhedron(rawVerts, rawFaces, mesh, options?); + private _addMaterial(friction, restitution); + private _createRigidBodyFromShape(shape, mesh, mass, friction, restitution); + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + private _unbindBody(body); + unregisterMesh(mesh: AbstractMesh): void; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + updateBodyPosition: (mesh: AbstractMesh) => void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3): boolean; + dispose(): void; + isSupported(): boolean; + } +} + +declare module BABYLON { + class OimoJSPlugin implements IPhysicsEnginePlugin { + private _world; + private _registeredMeshes; + private _checkWithEpsilon(value); + initialize(iterations?: number): void; + setGravity(gravity: Vector3): void; + registerMesh(mesh: AbstractMesh, impostor: number, options: PhysicsBodyCreationOptions): any; + registerMeshesAsCompound(parts: PhysicsCompoundBodyPart[], options: PhysicsBodyCreationOptions): any; + private _createBodyAsCompound(part, options, initialMesh); + unregisterMesh(mesh: AbstractMesh): void; + private _unbindBody(body); + /** + * Update the body position according to the mesh position + * @param mesh + */ + updateBodyPosition: (mesh: AbstractMesh) => void; + applyImpulse(mesh: AbstractMesh, force: Vector3, contactPoint: Vector3): void; + createLink(mesh1: AbstractMesh, mesh2: AbstractMesh, pivot1: Vector3, pivot2: Vector3, options?: any): boolean; + dispose(): void; + isSupported(): boolean; + private _getLastShape(body); + runOneStep(time: number): void; + } +} + +declare module BABYLON { + class PostProcessRenderEffect { + private _engine; + private _postProcesses; + private _getPostProcess; + private _singleInstance; + private _cameras; + private _indicesForCamera; + private _renderPasses; + private _renderEffectAsPasses; + _name: string; + applyParameters: (postProcess: PostProcess) => void; + constructor(engine: Engine, name: string, getPostProcess: () => PostProcess, singleInstance?: boolean); + _update(): void; + addPass(renderPass: PostProcessRenderPass): void; + removePass(renderPass: PostProcessRenderPass): void; + addRenderEffectAsPass(renderEffect: PostProcessRenderEffect): void; + getPass(passName: string): void; + emptyPasses(): void; + _attachCameras(cameras: Camera): any; + _attachCameras(cameras: Camera[]): any; + _detachCameras(cameras: Camera): any; + _detachCameras(cameras: Camera[]): any; + _enable(cameras: Camera): any; + _enable(cameras: Camera[]): any; + _disable(cameras: Camera): any; + _disable(cameras: Camera[]): any; + getPostProcess(camera?: Camera): PostProcess; + private _linkParameters(); + private _linkTextures(effect); + } +} + +declare module BABYLON { + class PostProcessRenderPass { + private _enabled; + private _renderList; + private _renderTexture; + private _scene; + private _refCount; + _name: string; + constructor(scene: Scene, name: string, size: number, renderList: Mesh[], beforeRender: () => void, afterRender: () => void); + _incRefCount(): number; + _decRefCount(): number; + _update(): void; + setRenderList(renderList: Mesh[]): void; + getRenderTexture(): RenderTargetTexture; + } +} + +declare module BABYLON { + class PostProcessRenderPipeline { + private _engine; + private _renderEffects; + private _renderEffectsForIsolatedPass; + private _cameras; + _name: string; + private static PASS_EFFECT_NAME; + private static PASS_SAMPLER_NAME; + constructor(engine: Engine, name: string); + addEffect(renderEffect: PostProcessRenderEffect): void; + _enableEffect(renderEffectName: string, cameras: Camera): any; + _enableEffect(renderEffectName: string, cameras: Camera[]): any; + _disableEffect(renderEffectName: string, cameras: Camera): any; + _disableEffect(renderEffectName: string, cameras: Camera[]): any; + _attachCameras(cameras: Camera, unique: boolean): any; + _attachCameras(cameras: Camera[], unique: boolean): any; + _detachCameras(cameras: Camera): any; + _detachCameras(cameras: Camera[]): any; + _enableDisplayOnlyPass(passName: any, cameras: Camera): any; + _enableDisplayOnlyPass(passName: any, cameras: Camera[]): any; + _disableDisplayOnlyPass(cameras: Camera): any; + _disableDisplayOnlyPass(cameras: Camera[]): any; + _update(): void; + } +} + +declare module BABYLON { + class PostProcessRenderPipelineManager { + private _renderPipelines; + constructor(); + addPipeline(renderPipeline: PostProcessRenderPipeline): void; + attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera, unique?: boolean): any; + attachCamerasToRenderPipeline(renderPipelineName: string, cameras: Camera[], unique?: boolean): any; + detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera): any; + detachCamerasFromRenderPipeline(renderPipelineName: string, cameras: Camera[]): any; + enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; + enableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; + disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera): any; + disableEffectInPipeline(renderPipelineName: string, renderEffectName: string, cameras: Camera[]): any; + enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera): any; + enableDisplayOnlyPassInPipeline(renderPipelineName: string, passName: string, cameras: Camera[]): any; + disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera): any; + disableDisplayOnlyPassInPipeline(renderPipelineName: string, cameras: Camera[]): any; + update(): void; + } +} + +declare module BABYLON { + class CustomProceduralTexture extends ProceduralTexture { + private _animate; + private _time; + private _config; + private _texturePath; + constructor(name: string, texturePath: any, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + private loadJson(jsonUrl); + isReady(): boolean; + render(useCameraPostProcess?: boolean): void; + updateTextures(): void; + updateShaderUniforms(): void; + animate: boolean; + } +} + +declare module BABYLON { + class ProceduralTexture extends Texture { + private _size; + _generateMipMaps: boolean; + isEnabled: boolean; + private _doNotChangeAspectRatio; + private _currentRefreshId; + private _refreshRate; + private _vertexBuffer; + private _indexBuffer; + private _effect; + private _vertexDeclaration; + private _vertexStrideSize; + private _uniforms; + private _samplers; + private _fragment; + _textures: Texture[]; + private _floats; + private _floatsArrays; + private _colors3; + private _colors4; + private _vectors2; + private _vectors3; + private _matrices; + private _fallbackTexture; + private _fallbackTextureUsed; + constructor(name: string, size: any, fragment: any, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + reset(): void; + isReady(): boolean; + resetRefreshCounter(): void; + setFragment(fragment: any): void; + refreshRate: number; + _shouldRender(): boolean; + getRenderSize(): number; + resize(size: any, generateMipMaps: any): void; + private _checkUniform(uniformName); + setTexture(name: string, texture: Texture): ProceduralTexture; + setFloat(name: string, value: number): ProceduralTexture; + setFloats(name: string, value: number[]): ProceduralTexture; + setColor3(name: string, value: Color3): ProceduralTexture; + setColor4(name: string, value: Color4): ProceduralTexture; + setVector2(name: string, value: Vector2): ProceduralTexture; + setVector3(name: string, value: Vector3): ProceduralTexture; + setMatrix(name: string, value: Matrix): ProceduralTexture; + render(useCameraPostProcess?: boolean): void; + clone(): ProceduralTexture; + dispose(): void; + } +} + +declare module BABYLON { + class WoodProceduralTexture extends ProceduralTexture { + private _ampScale; + private _woodColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + ampScale: number; + woodColor: Color3; + } + class FireProceduralTexture extends ProceduralTexture { + private _time; + private _speed; + private _autoGenerateTime; + private _fireColors; + private _alphaThreshold; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + render(useCameraPostProcess?: boolean): void; + static PurpleFireColors: Color3[]; + static GreenFireColors: Color3[]; + static RedFireColors: Color3[]; + static BlueFireColors: Color3[]; + fireColors: Color3[]; + time: number; + speed: Vector2; + alphaThreshold: number; + } + class CloudProceduralTexture extends ProceduralTexture { + private _skyColor; + private _cloudColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + skyColor: Color4; + cloudColor: Color4; + } + class GrassProceduralTexture extends ProceduralTexture { + private _grassColors; + private _herb1; + private _herb2; + private _herb3; + private _groundColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + grassColors: Color3[]; + groundColor: Color3; + } + class RoadProceduralTexture extends ProceduralTexture { + private _roadColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + roadColor: Color3; + } + class BrickProceduralTexture extends ProceduralTexture { + private _numberOfBricksHeight; + private _numberOfBricksWidth; + private _jointColor; + private _brickColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + numberOfBricksHeight: number; + numberOfBricksWidth: number; + jointColor: Color3; + brickColor: Color3; + } + class MarbleProceduralTexture extends ProceduralTexture { + private _numberOfTilesHeight; + private _numberOfTilesWidth; + private _amplitude; + private _marbleColor; + private _jointColor; + constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean); + updateShaderUniforms(): void; + numberOfTilesHeight: number; + numberOfTilesWidth: number; + jointColor: Color3; + marbleColor: Color3; + } +} diff --git a/backbone.localstorage/backbone.localstorage-tests.ts b/backbone.localstorage/backbone.localstorage-tests.ts new file mode 100644 index 0000000000..0d44897a80 --- /dev/null +++ b/backbone.localstorage/backbone.localstorage-tests.ts @@ -0,0 +1,6 @@ +/// + +var store: Store = new Store('testStore'); +store.findAll(); + +store.save(); diff --git a/backbone.localstorage/backbone.localstorage.d.ts b/backbone.localstorage/backbone.localstorage.d.ts new file mode 100644 index 0000000000..122c475876 --- /dev/null +++ b/backbone.localstorage/backbone.localstorage.d.ts @@ -0,0 +1,51 @@ +// Type definitions for backbone.localStorage 1.0.0 +// Project: https://github.com/jeromegn/Backbone.localStorage +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Backbone { + interface Serializer { + serialize(item: any): any; + deserialize(data: any): any; + } + + class LocalStorage { + name: string; + serializer: Serializer; + records: string[]; + + constructor(name: string, serializer?: Serializer); + + save(): void; + + // Add a model, giving it a (hopefully)-unique GUID, if it doesn't already + // have an id of it's own. + create(model: any): any; + + // Update a model by replacing its copy in `this.data`. + update(model: any): any; + + // Retrieve a model from `this.data` by id. + find(model: any): any; + + // Return the array of all models currently in storage. + findAll(): any; + + // Delete a model from `this.data`, returning it. + destroy(model: T): T; + + localStorage(): any; + + // Clear localStorage for specific collection. + _clear(): void; + + _storageSize(): number; + + _itemName(id: any): string; + } +} + +import Store = Backbone.LocalStorage; + diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts index 764aa83d75..c16e1a59e3 100644 --- a/backbone/backbone-global.d.ts +++ b/backbone/backbone-global.d.ts @@ -43,6 +43,7 @@ declare module Backbone { interface PersistenceOptions { url?: string; + data?: any; beforeSend?: (jqxhr: JQueryXHR) => void; success?: (modelOrCollection?: any, response?: any, options?: any) => void; error?: (modelOrCollection?: any, jqxhr?: JQueryXHR, options?: any) => void; diff --git a/bcrypt-nodejs/bcrypt-nodejs-tests.ts b/bcrypt-nodejs/bcrypt-nodejs-tests.ts new file mode 100644 index 0000000000..2a151c1c7e --- /dev/null +++ b/bcrypt-nodejs/bcrypt-nodejs-tests.ts @@ -0,0 +1,30 @@ +/// + +import bCrypt = require("bcrypt-nodejs"); + +function test_sync() { + var salt1 = bCrypt.genSaltSync(); + var salt2 = bCrypt.genSaltSync(8); + + var hash1 = bCrypt.hashSync('super secret'); + var hash2 = bCrypt.hashSync('super secret', salt1); + + var compare1 = bCrypt.compareSync('super secret', hash1); + + var rounds1 = bCrypt.getRounds(hash2); +} + +function test_async() { + var cbString = (error: Error, result: string) => {}; + var cbVoid = () => {}; + var cbBoolean = (error: Error, result: boolean) => {}; + + bCrypt.genSalt(8, cbString); + + var salt = bCrypt.genSaltSync(); + bCrypt.hash('super secret', salt, cbString); + bCrypt.hash('super secret', salt, cbVoid, cbString); + + var hash = bCrypt.hashSync('super secret'); + bCrypt.compare('super secret', hash, cbBoolean); +} \ No newline at end of file diff --git a/bcrypt-nodejs/bcrypt-nodejs.d.ts b/bcrypt-nodejs/bcrypt-nodejs.d.ts new file mode 100644 index 0000000000..32b735d68f --- /dev/null +++ b/bcrypt-nodejs/bcrypt-nodejs.d.ts @@ -0,0 +1,68 @@ +// Type definitions for bcrypt-nodejs +// Project: https://github.com/shaneGirish/bcrypt-nodejs +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "bcrypt-nodejs" { + /** + * Generate a salt synchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @return Generated salt + */ + export function genSaltSync(rounds?: number): string; + + /** + * Generate a salt asynchronously + * @param rounds Number of rounds to process the data for (default - 10) + * @param callback Callback with error and resulting salt, to be fired once the salt has been generated + */ + export function genSalt(rounds: number, callback: (error: Error, result: string) => void): void; + + /** + * Generate a hash synchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption (default - new salt generated with 10 rounds) + * @return Generated hash + */ + export function hashSync(data: string, salt?: string): string; + + /** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ + export function hash(data: string, salt: string, callback: (error: Error, result: string) => void): void; + + /** + * Generate a hash asynchronously + * @param data Data to be encrypted + * @param salt Salt to be used in encryption + * @param progressCallback Callback to be fired multiple times during the hash calculation to signify progress + * @param callback Callback with error and hashed result, to be fired once the data has been encrypted + */ + export function hash(data: string, salt: string, progressCallback: () => void, callback: (error: Error, result: string) => void): void; + + /** + * Compares data with a hash synchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @return true if matching, false otherwise + */ + export function compareSync(data: string, hash: string): boolean; + + /** + * Compares data with a hash asynchronously + * @param data Data to be compared + * @param hash Hash to be compared to + * @param callback Callback with error and match result, to be fired once the data has been compared + */ + export function compare(data: string, hash: string, callback: (error: Error, result: boolean) => void): void; + + /** + * Get number of rounds used for hash + * @param hash Hash from which the number of rounds used should be extracted + * @return number of rounds used to encrypt a given hash + */ + export function getRounds(hash: string): number; +} diff --git a/bcryptjs/bcryptjs-tests.ts b/bcryptjs/bcryptjs-tests.ts new file mode 100644 index 0000000000..acfc48e439 --- /dev/null +++ b/bcryptjs/bcryptjs-tests.ts @@ -0,0 +1,54 @@ +/// + +import bcryptjs = require("bcryptjs"); + +let str: string; +let num: number; +let bool: boolean; + +str = bcryptjs.genSaltSync(); +str = bcryptjs.genSaltSync(10); + +bcryptjs.genSalt((err: Error, salt: string) => { + str = salt; +}); +bcryptjs.genSalt(10, (err: Error, salt: string) => { + str = salt; +}); + +str = bcryptjs.hashSync("string"); +str = bcryptjs.hashSync("string", 10); +str = bcryptjs.hashSync("string", "salt"); + +bcryptjs.hash("string", 10, (err: Error, hash: string) => { + str = hash; +}); +bcryptjs.hash("string", 10, (err: Error, hash: string) => { + str = hash; +}, (percent: number) => { + num = percent; +}); + +bcryptjs.hash("string", "salt", (err: Error, hash: string) => { + str = hash; +}); +bcryptjs.hash("string", "salt", (err: Error, hash: string) => { + str = hash; +}, (percent: number) => { + num = percent; +}); + +bool = bcryptjs.compareSync("string1", "string2"); + +bcryptjs.compare("string1", "string2", (err: Error, success: boolean) => { + bool = success; +}); +bcryptjs.compare("string1", "string2", (err: Error, success: boolean) => { + bool = success; +}, (percent: number) => { + num = percent; +}); + +num = bcryptjs.getRounds("string"); + +str = bcryptjs.getSalt("string"); diff --git a/bcryptjs/bcryptjs.d.ts b/bcryptjs/bcryptjs.d.ts new file mode 100644 index 0000000000..3d3128d022 --- /dev/null +++ b/bcryptjs/bcryptjs.d.ts @@ -0,0 +1,82 @@ +// Type definitions for bcryptjs v2.3.0 +// Project: https://github.com/dcodeIO/bcrypt.js +// Definitions by: Joshua Filby +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bcryptjs" { + + /** + * Sets the pseudo random number generator to use as a fallback if neither node's crypto module nor the Web Crypto API is available. + * Please note: It is highly important that the PRNG used is cryptographically secure and that it is seeded properly! + * @param random Function taking the number of bytes to generate as its sole argument, returning the corresponding array of cryptographically secure random byte values. + */ + export function setRandomFallback(random: (random: number) => number[]): void; + + /** + * Synchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @return Resulting salt + */ + export function genSaltSync(rounds?: number): string; + + /** + * Asynchronously generates a salt. + * @param callback Callback receiving the error, if any, and the resulting salt + */ + export function genSalt(callback: (err: Error, salt: string) => void): void; + + /** + * Asynchronously generates a salt. + * @param rounds Number of rounds to use, defaults to 10 if omitted + * @param callback Callback receiving the error, if any, and the resulting salt + */ + export function genSalt(rounds: number, callback: (err: Error, salt: string) => void): void; + + /** + * Synchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use, default to 10 + * @return Resulting hash + */ + export function hashSync(s: string, salt?: number | string): string; + + /** + * Asynchronously generates a hash for the given string. + * @param s String to hash + * @param salt Salt length to generate or salt to use + * @param callback Callback receiving the error, if any, and the resulting hash + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ + export function hash(s: string, salt: number | string, callback: (err: Error, hash: string) => void, progressCallback?: (percent: number) => void): void; + + /** + * Synchronously tests a string against a hash. + * @param s String to compare + * @param hash Hash to test against + * @return true if matching, otherwise false + */ + export function compareSync(s: string, hash: string): boolean; + + /** + * Asynchronously compares the given data against the given hash. + * @param s Data to compare + * @param hash Data to be compared to + * @param callback Callback receiving the error, if any, otherwise the result + * @param progressCallback Callback successively called with the percentage of rounds completed (0.0 - 1.0), maximally once per MAX_EXECUTION_TIME = 100 ms. + */ + export function compare(s: string, hash: string, callback: (err: Error, success: boolean) => void, progressCallback?: (percent: number) => void): void; + + /** + * Gets the number of rounds used to encrypt the specified hash. + * @param hash Hash to extract the used number of rounds from + * @return Number of rounds used + */ + export function getRounds(hash: string): number; + + /** + * Gets the salt portion from a hash. Does not validate the hash. + * @param hash Hash to extract the salt from + * @return Extracted salt part + */ + export function getSalt(hash: string): string; +} diff --git a/bezier-easing/bezier-easing-tests.ts b/bezier-easing/bezier-easing-tests.ts new file mode 100644 index 0000000000..eab1fb4f15 --- /dev/null +++ b/bezier-easing/bezier-easing-tests.ts @@ -0,0 +1,21 @@ +/// + +function test_create_from_array() { + let easing: BezierEasing = BezierEasing([0, 0, 1, 0.5]); +} + +function test_create_from_params() { + let easing: BezierEasing = BezierEasing(0, 0, 1, 0.5); +} + +function test_create_from_builtins() { + let easing: BezierEasing = BezierEasing.css['ease-in']; +} + +function test_methods() { + let easing: BezierEasing = BezierEasing.css['ease-in']; + let easedRatio: number = easing.get(0.5); + let points: Array = easing.getPoints(); + let stringified: string = easing.toString(); + let asCSS: string = easing.toCSS(); +} diff --git a/bezier-easing/bezier-easing.d.ts b/bezier-easing/bezier-easing.d.ts new file mode 100644 index 0000000000..695368e7af --- /dev/null +++ b/bezier-easing/bezier-easing.d.ts @@ -0,0 +1,24 @@ +// Type definitions for bezier-easing +// Project: https://github.com/gre/bezier-easing +// Definitions by: brian ridley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare interface BezierEasing { + get(ratio: number): number; + getPoints(): Array; + toString(): string; + toCSS(): string; +} + +declare function BezierEasing(points: Array): BezierEasing; +declare function BezierEasing(a: number, b: number, c: number, d: number): BezierEasing; + +declare namespace BezierEasing { + let css: { + 'ease': BezierEasing, + 'linear': BezierEasing, + 'ease-in': BezierEasing, + 'ease-out': BezierEasing, + 'ease-in-out': BezierEasing + }; +} diff --git a/big.js/big.js.d.ts b/big.js/big.js.d.ts index d4ca239e36..2ad360a564 100644 --- a/big.js/big.js.d.ts +++ b/big.js/big.js.d.ts @@ -200,4 +200,9 @@ declare module BigJsLibrary { } } +declare module "big.js" { + var bigjs : BigJsLibrary.BigJS; + export = bigjs; +} + declare var Big: BigJsLibrary.BigJS; diff --git a/blue-tape/blue-tape-tests.ts b/blue-tape/blue-tape-tests.ts new file mode 100644 index 0000000000..a01675a1c5 --- /dev/null +++ b/blue-tape/blue-tape-tests.ts @@ -0,0 +1,170 @@ +/// +/// +/// + +import tape = require('blue-tape'); +import P = require('bluebird'); + +var name: string; +var cb: tape.TestCase; +var opts: tape.TestOptions; +var t: tape.Test; + +tape(cb); +tape(name, cb); +tape(opts, cb); +tape(name, opts, cb); + +tape(name, (test: tape.Test) => { + t = test; +}); + +tape.skip(name, cb); +tape.only(name, cb); + + +var sopts: tape.StreamOptions; +var rs: NodeJS.ReadableStream; +rs = tape.createStream(); +rs = tape.createStream(sopts); + + +var htest: typeof tape; +htest = tape.createHarness(); + + +tape(name, (test: tape.Test) => { + var num: number; + var ms: number; + var value: any; + var actual: any; + var expected: any; + var err: any; + var fn = function() {}; + var msg: string; + + var exceptionExpected: RegExp | (() => void); + + test.plan(num); + test.end(); + test.end(err); + + test.fail(msg); + test.pass(msg); + test.timeoutAfter(ms); + test.skip(msg); + + test.ok(value); + test.ok(value, msg); + test.true(value); + test.true(value, msg); + test.assert(value); + test.assert(value, msg); + + test.notOk(value); + test.notOk(value, msg); + test.false(value); + test.false(value, msg); + test.notok(value); + test.notok(value, msg); + + test.error(err, msg); + test.ifError(err, msg); + test.ifErr(err, msg); + test.iferror(err, msg); + + test.equal(actual, expected); + test.equal(actual, expected, msg); + test.equals(actual, expected); + test.equals(actual, expected, msg); + test.isEqual(actual, expected); + test.isEqual(actual, expected, msg); + test.is(actual, expected); + test.is(actual, expected, msg); + test.strictEqual(actual, expected); + test.strictEqual(actual, expected, msg); + test.strictEquals(actual, expected); + test.strictEquals(actual, expected, msg); + + test.notEqual(actual, expected); + test.notEqual(actual, expected, msg); + test.notEquals(actual, expected); + test.notEquals(actual, expected, msg); + test.notStrictEqual(actual, expected); + test.notStrictEqual(actual, expected, msg); + test.notStrictEquals(actual, expected); + test.notStrictEquals(actual, expected, msg); + test.isNotEqual(actual, expected); + test.isNotEqual(actual, expected, msg); + test.isNot(actual, expected); + test.isNot(actual, expected, msg); + test.not(actual, expected); + test.not(actual, expected, msg); + test.doesNotEqual(actual, expected); + test.doesNotEqual(actual, expected, msg); + test.isInequal(actual, expected); + test.isInequal(actual, expected, msg); + + test.deepEqual(actual, expected); + test.deepEqual(actual, expected, msg); + test.deepEquals(actual, expected); + test.deepEquals(actual, expected, msg); + test.isEquivalent(actual, expected); + test.isEquivalent(actual, expected, msg); + test.same(actual, expected); + test.same(actual, expected, msg); + + test.notDeepEqual(actual, expected); + test.notDeepEqual(actual, expected, msg); + test.notEquivalent(actual, expected); + test.notEquivalent(actual, expected, msg); + test.notDeeply(actual, expected); + test.notDeeply(actual, expected, msg); + test.notSame(actual, expected); + test.notSame(actual, expected, msg); + test.isNotDeepEqual(actual, expected); + test.isNotDeepEqual(actual, expected, msg); + test.isNotDeeply(actual, expected); + test.isNotDeeply(actual, expected, msg); + test.isNotEquivalent(actual, expected); + test.isNotEquivalent(actual, expected, msg); + test.isInequivalent(actual, expected); + test.isInequivalent(actual, expected, msg); + + test.deepLooseEqual(actual, expected); + test.deepLooseEqual(actual, expected, msg); + test.looseEqual(actual, expected); + test.looseEqual(actual, expected, msg); + test.looseEquals(actual, expected); + test.looseEquals(actual, expected, msg); + + test.notDeepLooseEqual(actual, expected); + test.notDeepLooseEqual(actual, expected, msg); + test.notLooseEqual(actual, expected); + test.notLooseEqual(actual, expected, msg); + test.notLooseEquals(actual, expected); + test.notLooseEquals(actual, expected, msg); + + test.throws(fn); + test.throws(fn, msg); + test.throws(fn, exceptionExpected); + test.throws(fn, exceptionExpected, msg); + + test.doesNotThrow(fn); + test.doesNotThrow(fn, msg); + test.doesNotThrow(fn, exceptionExpected); + test.doesNotThrow(fn, exceptionExpected, msg); + + test.test(name, (st) => { + t = st; + }); + + test.comment(msg); +}); + +tape('simple delay', (test) => P.delay(1)); + +tape('nested tests with promises', function(test) { + test.test('delay1', () => P.delay(1) ); + test.test('delay2', () => P.delay(1) ); +}); diff --git a/blue-tape/blue-tape.d.ts b/blue-tape/blue-tape.d.ts new file mode 100644 index 0000000000..50bf0aab8d --- /dev/null +++ b/blue-tape/blue-tape.d.ts @@ -0,0 +1,12 @@ +// Type definitions for blue-tape v0.1.11 +// Project: https://github.com/spion/blue-tape +// Definitions by: Haoqun Jiang +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module 'blue-tape' { + import tape = require('tape'); + export = tape; +} diff --git a/bluebird/bluebird-1.0.d.ts b/bluebird/bluebird-1.0.d.ts index db9dd0dd24..b8287e57cc 100644 --- a/bluebird/bluebird-1.0.d.ts +++ b/bluebird/bluebird-1.0.d.ts @@ -394,7 +394,7 @@ declare class Promise implements Promise.Thenable { * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. */ // TODO how to model promisifyAll? - static promisifyAll(target: Object): Object; + static promisifyAll(target: Object): any; /** * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index bd4f46fc45..b1829c52ed 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -85,15 +85,15 @@ var bazProm: Promise; // - - - - - - - - - - - - - - - - - -var numThen: Promise.Thenable; -var strThen: Promise.Thenable; -var anyThen: Promise.Thenable; -var boolThen: Promise.Thenable; -var objThen: Promise.Thenable; -var voidThen: Promise.Thenable; +var numThen: PromiseLike; +var strThen: PromiseLike; +var anyThen: PromiseLike; +var boolThen: PromiseLike; +var objThen: PromiseLike; +var voidThen: PromiseLike; -var fooThen: Promise.Thenable; -var barThen: Promise.Thenable; +var fooThen: PromiseLike; +var barThen: PromiseLike; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -106,12 +106,12 @@ var barArrProm: Promise; // - - - - - - - - - - - - - - - - - -var numArrThen: Promise.Thenable; -var strArrThen: Promise.Thenable; -var anyArrThen: Promise.Thenable; +var numArrThen: PromiseLike; +var strArrThen: PromiseLike; +var anyArrThen: PromiseLike; -var fooArrThen: Promise.Thenable; -var barArrThen: Promise.Thenable; +var fooArrThen: PromiseLike; +var barArrThen: PromiseLike; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -124,18 +124,18 @@ var barPromArr: Promise[]; // - - - - - - - - - - - - - - - - - -var numThenArr: Promise.Thenable[]; -var strThenArr: Promise.Thenable[]; -var anyThenArr: Promise.Thenable[]; +var numThenArr: PromiseLike[]; +var strThenArr: PromiseLike[]; +var anyThenArr: PromiseLike[]; -var fooThenArr: Promise.Thenable[]; -var barThenArr: Promise.Thenable[]; +var fooThenArr: PromiseLike[]; +var barThenArr: PromiseLike[]; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // booya! -var fooThenArrThen: Promise.Thenable[]>; -var barThenArrThen: Promise.Thenable[]>; +var fooThenArrThen: PromiseLike[]>; +var barThenArrThen: PromiseLike[]>; var fooResolver: Promise.Resolver; var barResolver: Promise.Resolver; @@ -607,19 +607,19 @@ Promise.all([fooProm, barProm, fooProm]).then(result => { //TODO fix collection inference -barArrProm = fooProm.map((item: Foo, index: number, arrayLength: number) => { +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { return bar; }); -barArrProm = fooProm.map((item: Foo) => { +barArrProm = fooArrProm.map((item: Foo) => { return bar; }); -barArrProm = fooProm.map((item: Foo, index: number, arrayLength: number) => { +barArrProm = fooArrProm.map((item: Foo, index: number, arrayLength: number) => { return bar; }, { concurrency: 1 }); -barArrProm = fooProm.map((item: Foo) => { +barArrProm = fooArrProm.map((item: Foo) => { return bar; }, { concurrency: 1 @@ -627,10 +627,20 @@ barArrProm = fooProm.map((item: Foo) => { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -barProm = fooProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { +barArrProm = fooArrProm.mapSeries((item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = fooArrProm.mapSeries((item: Foo) => { + return bar; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +barProm = fooArrProm.reduce((memo: Bar, item: Foo, index: number, arrayLength: number) => { return memo; }); -barProm = fooProm.reduce((memo: Bar, item: Foo) => { +barProm = fooArrProm.reduce((memo: Bar, item: Foo) => { return memo; }, bar); @@ -756,6 +766,13 @@ func = Promise.promisify(f, obj); obj = Promise.promisifyAll(obj); anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback)); anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromNode(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromNode(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); + +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback)); +anyProm = Promise.fromCallback(callback => nodeCallbackFunc(callback), {multiArgs : true}); +anyProm = Promise.fromCallback(callback => nodeCallbackFuncErrorOnly(callback), {multiArgs : true}); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -1008,6 +1025,81 @@ barArrProm = Promise.map(fooArr, (item: Foo, index: number, arrayLength: number) concurrency: 1 }); +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// mapSeries() + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArrThen + +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArrThen + +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArrThen, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooThenArr + +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooThenArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + +// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + +// fooArr + +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo) => { + return barThen; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return bar; +}); +barArrProm = Promise.mapSeries(fooArr, (item: Foo, index: number, arrayLength: number) => { + return barThen; +}); + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // reduce() diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 9b55578efd..023eab7aa2 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -1,6 +1,6 @@ // Type definitions for bluebird 2.0.0 // Project: https://github.com/petkaantonov/bluebird -// Definitions by: Bart van der Schoor +// Definitions by: Bart van der Schoor , falsandtru // Definitions: https://github.com/borisyankov/DefinitelyTyped // ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts @@ -16,737 +16,767 @@ // TODO verify support to have no return statement in handlers to get a Promise (more overloads?) -declare class Promise implements Promise.Thenable, Promise.Inspection { - /** - * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. - */ - constructor(callback: (resolve: (thenableOrResult?: R | Promise.Thenable) => void, reject: (error: any) => void) => void); - - /** - * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. - */ - then(onFulfill: (value: R) => U|Promise.Thenable, onReject?: (error: any) => U|Promise.Thenable, onProgress?: (note: any) => any): Promise; - then(onFulfill: (value: R) => U|Promise.Thenable, onReject?: (error: any) => void|Promise.Thenable, onProgress?: (note: any) => any): Promise; - - /** - * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(onReject?: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - caught(onReject?: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - - catch(onReject?: (error: any) => U|Promise.Thenable): Promise; - caught(onReject?: (error: any) => U|Promise.Thenable): Promise; - - /** - * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. - * - * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. - * - * Alias `.caught();` for compatibility with earlier ECMAScript version. - */ - catch(predicate: (error: any) => boolean, onReject: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - - catch(predicate: (error: any) => boolean, onReject: (error: any) => U|Promise.Thenable): Promise; - caught(predicate: (error: any) => boolean, onReject: (error: any) => U|Promise.Thenable): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - caught(ErrorClass: Function, onReject: (error: any) => R|Promise.Thenable|void|Promise.Thenable): Promise; - - catch(ErrorClass: Function, onReject: (error: any) => U|Promise.Thenable): Promise; - caught(ErrorClass: Function, onReject: (error: any) => U|Promise.Thenable): Promise; - - - /** - * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. - */ - error(onReject: (reason: any) => Promise.Thenable): Promise; - error(onReject: (reason: any) => U): Promise; - - /** - * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. - * - * Alias `.lastly();` for compatibility with earlier ECMAScript version. - */ - finally(handler: () => Promise.Thenable): Promise; - finally(handler: () => U): Promise; - - lastly(handler: () => Promise.Thenable): Promise; - lastly(handler: () => U): Promise; - - /** - * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. - */ - bind(thisArg: any): Promise; - - /** - * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. - */ - done(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; - done(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; - done(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): void; - done(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; - - /** - * Like `.finally()`, but not called for rejections. - */ - tap(onFulFill: (value: R) => Promise.Thenable): Promise; - tap(onFulfill: (value: R) => U): Promise; - - /** - * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. - */ - progressed(handler: (note: any) => any): Promise; - - /** - * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - delay(ms: number): Promise; - - /** - * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. - * - * You may specify a custom error message with the `message` parameter. - */ - timeout(ms: number, message?: string): Promise; - - /** - * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. - * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. - */ - nodeify(callback: (err: any, value?: R) => void, options?: Promise.SpreadOption): Promise; - nodeify(...sink: any[]): void; - - /** - * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. - */ - cancellable(): Promise; - - /** - * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. - * - * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. - * - * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. - * - * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. - */ - // TODO what to do with this? - cancel(reason?: any): Promise; - - /** - * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. - */ - fork(onFulfilled: (value: R) => Promise.Thenable, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => Promise.Thenable, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - fork(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable, onProgress?: (note: any) => any): Promise; - fork(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; - - /** - * Create an uncancellable promise based on this promise. - */ - uncancellable(): Promise; - - /** - * See if this promise can be cancelled. - */ - isCancellable(): boolean; - - /** - * See if this `promise` has been fulfilled. - */ - isFulfilled(): boolean; - - /** - * See if this `promise` has been rejected. - */ - isRejected(): boolean; - - /** - * See if this `promise` is still defer. - */ - isPending(): boolean; - - /** - * See if this `promise` is resolved -> either fulfilled or rejected. - */ - isResolved(): boolean; - - /** - * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. - * - * throws `TypeError` - */ - value(): R; - - /** - * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. - * - * throws `TypeError` - */ - reason(): any; - - /** - * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. - */ - inspect(): Promise.Inspection; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName].call(obj, arg...); - * }); - * - */ - call(propertyName: string, ...args: any[]): Promise; - - /** - * This is a convenience method for doing: - * - * - * promise.then(function(obj){ - * return obj[propertyName]; - * }); - * - */ - // TODO find way to fix get() - // get(propertyName: string): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * return value; - * }); - * - * - * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` - * - * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. - */ - return(): Promise; - thenReturn(): Promise; - return(value: U): Promise; - thenReturn(value: U): Promise; - - /** - * Convenience method for: - * - * - * .then(function() { - * throw reason; - * }); - * - * Same limitations apply as with `.return()`. - * - * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. - */ - throw(reason: Error): Promise; - thenThrow(reason: Error): Promise; - - /** - * Convert to String. - */ - toString(): string; - - /** - * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. - */ - toJSON(): Object; - - /** - * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. - */ - // TODO how to model instance.spread()? like Q? - spread(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; - /* - // TODO or something like this? - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => Promise.Thenable, onReject?: (reason: any) => U): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable): Promise; - spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; - */ - /** - * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - all(): Promise; - - /** - * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO how to model instance.props()? - props(): Promise; - - /** - * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - settle(): Promise[]>; - - /** - * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - any(): Promise; - - /** - * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - some(count: number): Promise; - - /** - * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - race(): Promise; - - /** - * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - map(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - map(mapper: (item: Q, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; - - /** - * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - // TODO type inference from array-resolving promise? - filter(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - filter(filterer: (item: U, index: number, arrayLength: number) => boolean, options?: Promise.ConcurrencyOption): Promise; - - /** - * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. - */ - each(iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable): Promise; - - /** - * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. - * - * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. - * - * Alias for `attempt();` for compatibility with earlier ECMAScript version. - */ - static try(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - static try(fn: () => R, args?: any[], ctx?: any): Promise; - - static attempt(fn: () => Promise.Thenable, args?: any[], ctx?: any): Promise; - static attempt(fn: () => R, args?: any[], ctx?: any): Promise; - - /** - * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. - * This method is convenient when a function can sometimes return synchronously or throw synchronously. - */ - static method(fn: Function): Function; - - /** - * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. - */ - static resolve(): Promise; - static resolve(value: Promise.Thenable): Promise; - static resolve(value: R): Promise; - - /** - * Create a promise that is rejected with the given `reason`. - */ - static reject(reason: any): Promise; - static reject(reason: any): Promise; - - /** - * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). - */ - static defer(): Promise.Resolver; - - /** - * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. - */ - static cast(value: Promise.Thenable): Promise; - static cast(value: R): Promise; - - /** - * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. - */ - static bind(thisArg: any): Promise; - - /** - * See if `value` is a trusted Promise. - */ - static is(value: any): boolean; - - /** - * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. - */ - static longStackTraces(): void; - - /** - * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. - */ - // TODO enable more overloads - static delay(value: Promise.Thenable, ms: number): Promise; - static delay(value: R, ms: number): Promise; - static delay(ms: number): Promise; - - /** - * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. - * - * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. - * - * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. - */ - static promisify(func: (callback: (err:any, result: T) => void) => void, receiver?: any): () => Promise; - static promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; - static promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; - static promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; - static promisify(nodeFunction: Function, receiver?: any): Function; - - /** - * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. - * - * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. - */ - // TODO how to model promisifyAll? - static promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): Object; - - - /** - * Returns a promise that is resolved by a node style callback function. - */ - static fromNode(resolver: (callback: (err: any, result?: any) => void) => void): Promise; - - /** - * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix coroutine GeneratorFunction - static coroutine(generatorFunction: Function): Function; - - /** - * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. - */ - // TODO fix spawn GeneratorFunction - static spawn(generatorFunction: Function): Promise; - - /** - * This is relevant to browser environments with no module loader. - * - * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. - */ - static noConflict(): typeof Promise; - - /** - * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. - * - * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. - */ - static onPossiblyUnhandledRejection(handler: (reason: any) => any): void; - - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. - */ - // TODO enable more overloads - // promise of array with promises of value - static all(values: Promise.Thenable[]>): Promise; - // promise of array with values - static all(values: Promise.Thenable): Promise; - // array with promises of value - static all(values: Promise.Thenable[]): Promise; +declare var Promise: PromiseConstructor; + +interface PromiseConstructor { + /** + * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. + */ + new (callback: (resolve: (thenableOrResult?: T | PromiseLike) => void, reject: (error: any) => void) => void): Promise; + + // Ideally, we'd define e.g. "export class RangeError extends Error {}", + // but as Error is defined as an interface (not a class), TypeScript doesn't + // allow extending Error, only implementing it. + // However, if we want to catch() only a specific error type, we need to pass + // a constructor function to it. So, as a workaround, we define them here as such. + RangeError(): RangeError; + CancellationError(): Promise.CancellationError; + TimeoutError(): Promise.TimeoutError; + TypeError(): Promise.TypeError; + RejectionError(): Promise.RejectionError; + OperationalError(): Promise.OperationalError; + + /** + * Changes how bluebird schedules calls a-synchronously. + * + * @param scheduler Should be a function that asynchronously schedules + * the calling of the passed in function + */ + setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; + + /** + * Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise. + * + * Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call. + * + * Alias for `attempt();` for compatibility with earlier ECMAScript version. + */ + try(fn: () => PromiseLike, args?: any[], ctx?: any): Promise; + try(fn: () => T, args?: any[], ctx?: any): Promise; + + attempt(fn: () => PromiseLike, args?: any[], ctx?: any): Promise; + attempt(fn: () => T, args?: any[], ctx?: any): Promise; + + /** + * Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function. + * This method is convenient when a function can sometimes return synchronously or throw synchronously. + */ + method(fn: Function): Function; + + /** + * Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state. + */ + resolve(): Promise; + resolve(value: PromiseLike): Promise; + resolve(value: T): Promise; + + /** + * Create a promise that is rejected with the given `reason`. + */ + reject(reason: any): Promise; + reject(reason: any): Promise; + + /** + * Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution). + */ + defer(): Promise.Resolver; + + /** + * Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable. + */ + cast(value: PromiseLike): Promise; + cast(value: T): Promise; + + /** + * Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`. + */ + bind(thisArg: any): Promise; + + /** + * See if `value` is a trusted Promise. + */ + is(value: any): boolean; + + /** + * Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency. + */ + longStackTraces(): void; + + /** + * Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise. + */ + // TODO enable more overloads + delay(value: PromiseLike, ms: number): Promise; + delay(value: T, ms: number): Promise; + delay(ms: number): Promise; + + /** + * Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument. + * + * If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them. + * + * If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`. + */ + promisify(func: (callback: (err: any, result: T) => void) => void, receiver?: any): () => Promise; + promisify(func: (arg1: A1, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1) => Promise; + promisify(func: (arg1: A1, arg2: A2, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4) => Promise; + promisify(func: (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5, callback: (err: any, result: T) => void) => void, receiver?: any): (arg1: A1, arg2: A2, arg3: A3, arg4: A4, arg5: A5) => Promise; + promisify(nodeFunction: Function, receiver?: any): Function; + + /** + * Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object. + * + * Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method. + */ + // TODO how to model promisifyAll? + promisifyAll(target: Object, options?: Promise.PromisifyAllOptions): any; + + + /** + * Returns a promise that is resolved by a node style callback function. + */ + fromNode(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + fromCallback(resolver: (callback: (err: any, result?: any) => void) => void, options? : {multiArgs? : boolean}): Promise; + + /** + * Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix coroutine GeneratorFunction + coroutine(generatorFunction: Function): Function; + + /** + * Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch. + */ + // TODO fix spawn GeneratorFunction + spawn(generatorFunction: Function): Promise; + + /** + * This is relevant to browser environments with no module loader. + * + * Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else. + */ + noConflict(): typeof Promise; + + /** + * Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers. + * + * Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections. + */ + onPossiblyUnhandledRejection(handler: (reason: any) => any): void; + + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason. + */ + // TODO enable more overloads + // promise of array with promises of value + all(values: PromiseLike[]>): Promise; + // promise of array with values + all(values: PromiseLike): Promise; + // array with promises of value + all(values: PromiseLike[]): Promise; // array with promises of different types - static all(values: [Promise.Thenable, Promise.Thenable]): Promise<[T1, T2]>; - static all(values: [Promise.Thenable, Promise.Thenable, Promise.Thenable]): Promise<[T1, T2, T3]>; - static all(values: [Promise.Thenable, Promise.Thenable, Promise.Thenable, Promise.Thenable]): Promise<[T1, T2, T3, T4]>; - static all(values: [Promise.Thenable, Promise.Thenable, Promise.Thenable, Promise.Thenable, Promise.Thenable]): Promise<[T1, T2, T3, T4, T5]>; - // array with values - static all(values: R[]): Promise; + all(values: [PromiseLike, PromiseLike]): Promise<[T1, T2]>; + all(values: [PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3]>; + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4]>; + all(values: [PromiseLike, PromiseLike, PromiseLike, PromiseLike, PromiseLike]): Promise<[T1, T2, T3, T4, T5]>; + // array with values + all(values: T[]): Promise; - /** - * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. - * - * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. - * - * *The original object is not modified.* - */ - // TODO verify this is correct - // trusted promise for object - static props(object: Promise): Promise; - // object - static props(object: Object): Promise; + /** + * Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason. + * + * If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties. + * + * *The original object is not modified.* + */ + // TODO verify this is correct + // trusted promise for object + props(object: Promise): Promise; + // object + props(object: Object): Promise; - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. - * - * *original: The array is not modified. The input array sparsity is retained in the resulting array.* - */ - // promise of array with promises of value - static settle(values: Promise.Thenable[]>): Promise[]>; - // promise of array with values - static settle(values: Promise.Thenable): Promise[]>; - // array with promises of value - static settle(values: Promise.Thenable[]): Promise[]>; - // array with values - static settle(values: R[]): Promise[]>; + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array. + * + * *original: The array is not modified. The input array sparsity is retained in the resulting array.* + */ + // promise of array with promises of value + settle(values: PromiseLike[]>): Promise[]>; + // promise of array with values + settle(values: PromiseLike): Promise[]>; + // array with promises of value + settle(values: PromiseLike[]): Promise[]>; + // array with values + settle(values: T[]): Promise[]>; - /** - * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. - */ - // promise of array with promises of value - static any(values: Promise.Thenable[]>): Promise; - // promise of array with values - static any(values: Promise.Thenable): Promise; - // array with promises of value - static any(values: Promise.Thenable[]): Promise; - // array with values - static any(values: R[]): Promise; + /** + * Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly. + */ + // promise of array with promises of value + any(values: PromiseLike[]>): Promise; + // promise of array with values + any(values: PromiseLike): Promise; + // array with promises of value + any(values: PromiseLike[]): Promise; + // array with values + any(values: T[]): Promise; - /** - * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. - * - * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. - */ - // promise of array with promises of value - static race(values: Promise.Thenable[]>): Promise; - // promise of array with values - static race(values: Promise.Thenable): Promise; - // array with promises of value - static race(values: Promise.Thenable[]): Promise; - // array with values - static race(values: R[]): Promise; + /** + * Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value. + * + * **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending. + */ + // promise of array with promises of value + race(values: PromiseLike[]>): Promise; + // promise of array with values + race(values: PromiseLike): Promise; + // array with promises of value + race(values: PromiseLike[]): Promise; + // array with values + race(values: T[]): Promise; - /** - * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. - * - * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - static some(values: Promise.Thenable[]>, count: number): Promise; - // promise of array with values - static some(values: Promise.Thenable, count: number): Promise; - // array with promises of value - static some(values: Promise.Thenable[], count: number): Promise; - // array with values - static some(values: R[], count: number): Promise; + /** + * Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution. + * + * If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + some(values: PromiseLike[]>, count: number): Promise; + // promise of array with values + some(values: PromiseLike, count: number): Promise; + // array with promises of value + some(values: PromiseLike[], count: number): Promise; + // array with values + some(values: T[], count: number): Promise; - /** - * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. - */ - // variadic array with promises of value - static join(...values: Promise.Thenable[]): Promise; - // variadic array with values - static join(...values: R[]): Promise; + /** + * Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments. + */ + // variadic array with promises of value + join(...values: PromiseLike[]): Promise; + // variadic array with values + join(...values: T[]): Promise; - /** - * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. - * - * *The original array is not modified.* - */ - // promise of array with promises of value - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - static map(values: Promise.Thenable[]>, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; + /** + * Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + map(values: PromiseLike[]>, mapper: (item: T, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; - // promise of array with values - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - static map(values: Promise.Thenable, mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; + // promise of array with values + map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + map(values: PromiseLike, mapper: (item: T, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; - // array with promises of value - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - static map(values: Promise.Thenable[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; + // array with promises of value + map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + map(values: PromiseLike[], mapper: (item: T, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; - // array with values - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable, options?: Promise.ConcurrencyOption): Promise; - static map(values: R[], mapper: (item: R, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; + // array with values + map(values: T[], mapper: (item: T, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + map(values: T[], mapper: (item: T, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; - /** - * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - * - * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* - */ - // promise of array with promises of value - static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + /** + * Similar to `map` with concurrency set to 1 but guaranteed to execute in sequential order + * + * If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well. + * + * *The original array is not modified.* + */ + // promise of array with promises of value + mapSeries(values: PromiseLike[]>, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - // promise of array with values - static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + // promise of array with values + mapSeries(values: PromiseLike, mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with promises of value - static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: Promise.Thenable[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + // array with promises of value + mapSeries(values: PromiseLike[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; - // array with values - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable, initialValue?: U): Promise; - static reduce(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise; + // array with values + mapSeries(values: R[], mapper: (item: R, index: number, arrayLength: number) => U | PromiseLike): Promise; + - /** - * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. - * - * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. - * - * *The original array is not modified. - */ - // promise of array with promises of value - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; - static filter(values: Promise.Thenable[]>, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + /** + * Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + * + * *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.* + */ + // promise of array with promises of value + reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => PromiseLike, initialValue?: U): Promise; + reduce(values: PromiseLike[]>, reducer: (total: U, current: T, index: number, arrayLength: number) => U, initialValue?: U): Promise; - // promise of array with values - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; - static filter(values: Promise.Thenable, filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + // promise of array with values + reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => PromiseLike, initialValue?: U): Promise; + reduce(values: PromiseLike, reducer: (total: U, current: T, index: number, arrayLength: number) => U, initialValue?: U): Promise; - // array with promises of value - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; - static filter(values: Promise.Thenable[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + // array with promises of value + reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => PromiseLike, initialValue?: U): Promise; + reduce(values: PromiseLike[], reducer: (total: U, current: T, index: number, arrayLength: number) => U, initialValue?: U): Promise; - // array with values - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable, option?: Promise.ConcurrencyOption): Promise; - static filter(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + // array with values + reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => PromiseLike, initialValue?: U): Promise; + reduce(values: T[], reducer: (total: U, current: T, index: number, arrayLength: number) => U, initialValue?: U): Promise; - /** - * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. - * - * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. - */ - // promise of array with promises of value - static each(values: Promise.Thenable[]>, iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable): Promise; - // array with promises of value - static each(values: Promise.Thenable[], iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable): Promise; - // array with values OR promise of array with values - static each(values: R[] | Promise.Thenable, iterator: (item: R, index: number, arrayLength: number) => U | Promise.Thenable): Promise; + /** + * Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well. + * + * The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result. + * + * *The original array is not modified. + */ + // promise of array with promises of value + filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => PromiseLike, option?: Promise.ConcurrencyOption): Promise; + filter(values: PromiseLike[]>, filterer: (item: T, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + + // promise of array with values + filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => PromiseLike, option?: Promise.ConcurrencyOption): Promise; + filter(values: PromiseLike, filterer: (item: T, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + + // array with promises of value + filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => PromiseLike, option?: Promise.ConcurrencyOption): Promise; + filter(values: PromiseLike[], filterer: (item: T, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + + // array with values + filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => PromiseLike, option?: Promise.ConcurrencyOption): Promise; + filter(values: T[], filterer: (item: T, index: number, arrayLength: number) => boolean, option?: Promise.ConcurrencyOption): Promise; + + /** + * Iterate over an array, or a promise of an array, which contains promises (or a mix of promises and values) with the given iterator function with the signature (item, index, value) where item is the resolved value of a respective promise in the input array. Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well. + * + * Resolves to the original array unmodified, this method is meant to be used for side effects. If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration. + */ + // promise of array with promises of value + each(values: PromiseLike[]>, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with promises of value + each(values: PromiseLike[], iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; + // array with values OR promise of array with values + each(values: T[] | PromiseLike, iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; } -declare module Promise { - export interface RangeError extends Error { - } - export interface CancellationError extends Error { - } - export interface TimeoutError extends Error { - } - export interface TypeError extends Error { - } - export interface RejectionError extends Error { - } - export interface OperationalError extends Error { - } +interface Promise extends PromiseLike, Promise.Inspection { + /** + * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. + */ + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => U | PromiseLike, onProgress?: (note: any) => any): Promise; + then(onFulfill: (value: T) => U | PromiseLike, onReject?: (error: any) => void | PromiseLike, onProgress?: (note: any) => any): Promise; - export interface ConcurrencyOption { - concurrency: number; - } - export interface SpreadOption { - spread: boolean; - } - export interface PromisifyAllOptions { - suffix?: string; - filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; - // The promisifier gets a reference to the original method and should return a function which returns a promise - promisifier?: (originalMethod: Function) => () => Thenable ; - } + /** + * This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(onReject?: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - // Ideally, we'd define e.g. "export class RangeError extends Error {}", - // but as Error is defined as an interface (not a class), TypeScript doesn't - // allow extending Error, only implementing it. - // However, if we want to catch() only a specific error type, we need to pass - // a constructor function to it. So, as a workaround, we define them here as such. - export function RangeError(): RangeError; - export function CancellationError(): CancellationError; - export function TimeoutError(): TimeoutError; - export function TypeError(): TypeError; - export function RejectionError(): RejectionError; - export function OperationalError(): OperationalError; + catch(onReject?: (error: any) => U | PromiseLike): Promise; + caught(onReject?: (error: any) => U | PromiseLike): Promise; - export interface Thenable { - then(onFulfilled: (value: R) => U|Thenable, onRejected?: (error: any) => U|Thenable): Thenable; - then(onFulfilled: (value: R) => U|Thenable, onRejected?: (error: any) => void|Thenable): Thenable; - } + /** + * This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called. + * + * This method also supports predicate-based filters. If you pass a predicate function instead of an error constructor, the predicate will receive the error as an argument. The return result of the predicate will be used determine whether the error handler should be called. + * + * Alias `.caught();` for compatibility with earlier ECMAScript version. + */ + catch(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - export interface Resolver { - /** - * Returns a reference to the controlled promise that can be passed to clients. - */ - promise: Promise; + catch(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; + caught(predicate: (error: any) => boolean, onReject: (error: any) => U | PromiseLike): Promise; - /** - * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. - */ - resolve(value: R): void; - resolve(): void; + catch(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => T | PromiseLike | void | PromiseLike): Promise; - /** - * Reject the underlying promise with `reason` as the rejection reason. - */ - reject(reason: any): void; + catch(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; + caught(ErrorClass: Function, onReject: (error: any) => U | PromiseLike): Promise; - /** - * Progress the underlying promise with `value` as the progression value. - */ - progress(value: any): void; - /** - * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. - * - * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. - */ - // TODO specify resolver callback - callback: (err: any, value: R, ...values: R[]) => void; - } + /** + * Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections. + */ + error(onReject: (reason: any) => PromiseLike): Promise; + error(onReject: (reason: any) => U): Promise; - export interface Inspection { - /** - * See if the underlying promise was fulfilled at the creation time of this inspection object. - */ - isFulfilled(): boolean; + /** + * Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler. + * + * Alias `.lastly();` for compatibility with earlier ECMAScript version. + */ + finally(handler: () => PromiseLike): Promise; + finally(handler: () => U): Promise; - /** - * See if the underlying promise was rejected at the creation time of this inspection object. - */ - isRejected(): boolean; + lastly(handler: () => PromiseLike): Promise; + lastly(handler: () => U): Promise; - /** - * See if the underlying promise was defer at the creation time of this inspection object. - */ - isPending(): boolean; + /** + * Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise. + */ + bind(thisArg: any): Promise; - /** - * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. - * - * throws `TypeError` - */ - value(): R; + /** + * Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error. + */ + done(onFulfilled: (value: T) => PromiseLike, onRejected: (error: any) => PromiseLike, onProgress?: (note: any) => any): void; + done(onFulfilled: (value: T) => PromiseLike, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; + done(onFulfilled: (value: T) => U, onRejected: (error: any) => PromiseLike, onProgress?: (note: any) => any): void; + done(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): void; - /** - * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. - * - * throws `TypeError` - */ - reason(): any; - } + /** + * Like `.finally()`, but not called for rejections. + */ + tap(onFulFill: (value: T) => PromiseLike): Promise; + tap(onFulfill: (value: T) => U): Promise; - /** - * Changes how bluebird schedules calls a-synchronously. - * - * @param scheduler Should be a function that asynchronously schedules - * the calling of the passed in function - */ - export function setScheduler(scheduler: (callback: (...args: any[]) => void) => void): void; + /** + * Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise. + */ + progressed(handler: (note: any) => any): Promise; + + /** + * Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + delay(ms: number): Promise; + + /** + * Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance. + * + * You may specify a custom error message with the `message` parameter. + */ + timeout(ms: number, message?: string): Promise; + + /** + * Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success. + * Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything. + */ + nodeify(callback: (err: any, value?: T) => void, options?: Promise.SpreadOption): Promise; + nodeify(...sink: any[]): Promise; + + /** + * Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise. + */ + cancellable(): Promise; + + /** + * Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending. + * + * That ancestor will then be rejected with a `CancellationError` (get a reference from `Promise.CancellationError`) object as the rejection reason. + * + * In a promise rejection handler you may check for a cancellation by seeing if the reason object has `.name === "Cancel"`. + * + * Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable. + */ + // TODO what to do with this? + cancel(reason?: any): Promise; + + /** + * Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors. + */ + fork(onFulfilled: (value: T) => PromiseLike, onRejected: (error: any) => PromiseLike, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: T) => PromiseLike, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + fork(onFulfilled: (value: T) => U, onRejected: (error: any) => PromiseLike, onProgress?: (note: any) => any): Promise; + fork(onFulfilled?: (value: T) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise; + + /** + * Create an uncancellable promise based on this promise. + */ + uncancellable(): Promise; + + /** + * See if this promise can be cancelled. + */ + isCancellable(): boolean; + + /** + * See if this `promise` has been fulfilled. + */ + isFulfilled(): boolean; + + /** + * See if this `promise` has been rejected. + */ + isRejected(): boolean; + + /** + * See if this `promise` is still defer. + */ + isPending(): boolean; + + /** + * See if this `promise` is resolved -> either fulfilled or rejected. + */ + isResolved(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise isn't fulfilled yet. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise isn't rejected yet. + * + * throws `TypeError` + */ + reason(): any; + + /** + * Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`. + */ + inspect(): Promise.Inspection; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName].call(obj, arg...); + * }); + * + */ + call(propertyName: string, ...args: any[]): Promise; + + /** + * This is a convenience method for doing: + * + * + * promise.then(function(obj){ + * return obj[propertyName]; + * }); + * + */ + // TODO find way to fix get() + // get(propertyName: string): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * return value; + * }); + * + * + * in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()` + * + * Alias `.thenReturn();` for compatibility with earlier ECMAScript version. + */ + return(): Promise; + thenReturn(): Promise; + return(value: U): Promise; + thenReturn(value: U): Promise; + + /** + * Convenience method for: + * + * + * .then(function() { + * throw reason; + * }); + * + * Same limitations apply as with `.return()`. + * + * Alias `.thenThrow();` for compatibility with earlier ECMAScript version. + */ + throw(reason: Error): Promise; + thenThrow(reason: Error): Promise; + + /** + * Convert to String. + */ + toString(): string; + + /** + * This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`. + */ + toJSON(): Object; + + /** + * Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers. + */ + // TODO how to model instance.spread()? like Q? + spread(onFulfill: Function, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: Function, onReject?: (reason: any) => U): Promise; + /* + // TODO or something like this? + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => PromiseLike, onReject?: (reason: any) => U): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => PromiseLike): Promise; + spread(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise; + */ + /** + * Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + all(): Promise; + + /** + * Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO how to model instance.props()? + props(): Promise; + + /** + * Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + settle(): Promise[]>; + + /** + * Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + any(): Promise; + + /** + * Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + some(count: number): Promise; + + /** + * Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + race(): Promise; + + /** + * Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + map(mapper: (item: Q, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + map(mapper: (item: Q, index: number, arrayLength: number) => U, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as `Promise.mapSeries(thisPromise, mapper)`. + */ + // TODO type inference from array-resolving promise? + mapSeries(mapper: (item: Q, index: number, arrayLength: number) => U | PromiseLike): Promise; + + /** + * Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => PromiseLike, initialValue?: U): Promise; + reduce(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise; + + /** + * Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + // TODO type inference from array-resolving promise? + filter(filterer: (item: U, index: number, arrayLength: number) => PromiseLike, options?: Promise.ConcurrencyOption): Promise; + filter(filterer: (item: U, index: number, arrayLength: number) => boolean, options?: Promise.ConcurrencyOption): Promise; + + /** + * Same as calling ``Promise.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too. + */ + each(iterator: (item: T, index: number, arrayLength: number) => U | PromiseLike): Promise; +} + +/** + * Don't use variable namespace such as variables, functions, and classes. + * If you use this namespace, it will conflict in es6. + */ +declare namespace Promise { + export interface RangeError extends Error { + } + export interface CancellationError extends Error { + } + export interface TimeoutError extends Error { + } + export interface TypeError extends Error { + } + export interface RejectionError extends Error { + } + export interface OperationalError extends Error { + } + + export interface ConcurrencyOption { + concurrency: number; + } + export interface SpreadOption { + spread: boolean; + } + export interface PromisifyAllOptions { + suffix?: string; + filter?: (name: string, func: Function, target?: any, passesDefaultFilter?: boolean) => boolean; + // The promisifier gets a reference to the original method and should return a function which returns a promise + promisifier?: (originalMethod: Function) => () => PromiseLike; + } + + export interface Resolver { + /** + * Returns a reference to the controlled promise that can be passed to clients. + */ + promise: Promise; + + /** + * Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state. + */ + resolve(value: T): void; + resolve(): void; + + /** + * Reject the underlying promise with `reason` as the rejection reason. + */ + reject(reason: any): void; + + /** + * Progress the underlying promise with `value` as the progression value. + */ + progress(value: any): void; + + /** + * Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions. + * + * If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values. + */ + // TODO specify resolver callback + callback: (err: any, value: T, ...values: T[]) => void; + } + + export interface Inspection { + /** + * See if the underlying promise was fulfilled at the creation time of this inspection object. + */ + isFulfilled(): boolean; + + /** + * See if the underlying promise was rejected at the creation time of this inspection object. + */ + isRejected(): boolean; + + /** + * See if the underlying promise was defer at the creation time of this inspection object. + */ + isPending(): boolean; + + /** + * Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object. + * + * throws `TypeError` + */ + value(): T; + + /** + * Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object. + * + * throws `TypeError` + */ + reason(): any; + } } declare module 'bluebird' { - export = Promise; + export = Promise; } diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts index 67580dae5f..42faf0909e 100644 --- a/bookshelf/bookshelf-tests.ts +++ b/bookshelf/bookshelf-tests.ts @@ -97,4 +97,3 @@ class Photo extends bookshelf.Model { return this.morphTo('imageable', Site, Post); } } - diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts index 0da1ce2d68..e0278df261 100644 --- a/bookshelf/bookshelf.d.ts +++ b/bookshelf/bookshelf.d.ts @@ -11,7 +11,7 @@ declare module 'bookshelf' { import knex = require('knex'); import Promise = require('bluebird'); import Lodash = require('lodash'); - + interface Bookshelf extends Bookshelf.Events { VERSION : string; knex : knex; @@ -20,9 +20,9 @@ declare module 'bookshelf' { transaction(callback : (transaction : knex.Transaction) => T) : Promise; } - + function Bookshelf(knex : knex) : Bookshelf; - + namespace Bookshelf { abstract class Events { on(event? : string, callback? : EventFunction, context? : any) : void; @@ -31,20 +31,20 @@ declare module 'bookshelf' { triggerThen(name : string, ...args : any[]) : Promise; once(event : string, callback : EventFunction, context? : any) : void; } - + interface IModelBase { /** Should be declared as a getter instead of a plain property. */ hasTimestamps? : boolean|string[]; /** Should be declared as a getter instead of a plain property. Should be required, but cannot have abstract properties yet. */ tableName? : string; } - + abstract class ModelBase> extends Events> implements IModelBase { /** If overriding, must use a getter instead of a plain property. */ idAttribute : string; - + constructor(attributes? : any, options? : ModelOptions); - + clear() : T; clone() : T; escape(attribute : string) : string; @@ -63,7 +63,7 @@ declare module 'bookshelf' { timestamp(options? : TimestampOptions) : any; toJSON(options? : SerializeOptions) : any; unset(attribute : string) : T; - + // lodash methods invert() : R; keys() : string[]; @@ -74,7 +74,7 @@ declare module 'bookshelf' { pick(...attributes : string[]) : R; values() : any[]; } - + class Model> extends ModelBase { static collection>(models? : T[], options? : CollectionOptions) : Collection; static count(column? : string, options? : SyncOptions) : Promise; @@ -83,7 +83,7 @@ declare module 'bookshelf' { static fetchAll>() : Promise>; /** @deprecated should use `new` objects instead. */ static forge(attributes? : any, options? : ModelOptions) : T; - + 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; @@ -109,7 +109,7 @@ declare module 'bookshelf' { where(properties : {[key : string] : any}) : T; where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T; } - + abstract class CollectionBase> extends Events { add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection; at(index : number) : T; @@ -133,7 +133,7 @@ declare module 'bookshelf' { toJSON(options? : SerializeOptions) : any; unshift(model : any, options? : CollectionAddOptions) : void; where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection; - + // lodash methods all(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : boolean; all(predicate? : R) : boolean; @@ -200,13 +200,13 @@ declare module 'bookshelf' { toArray() : T[]; without(...values : any[]) : T[]; } - + class Collection> extends CollectionBase { /** @deprecated use Typescript classes */ static extend(prototypeProperties? : any, classProperties? : any) : Function; /** @deprecated should use `new` objects instead. */ static forge(attributes? : any, options? : ModelOptions) : T; - + attach(ids : any[], options? : SyncOptions) : Promise>; count(column? : string, options? : SyncOptions) : Promise; create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise; @@ -222,92 +222,92 @@ declare module 'bookshelf' { updatePivot(attributes : any, options? : PivotOptions) : Promise; withPivot(columns : string[]) : Collection; } - + interface ModelOptions { tableName? : string; hasTimestamps? : boolean; parse? : boolean; } - + interface LoadOptions extends SyncOptions { withRelated: string|any|any[]; } - + interface FetchOptions extends SyncOptions { require? : boolean; columns? : string|string[]; withRelated? : string|any|any[]; } - + interface FetchAllOptions extends SyncOptions { require? : boolean; } - + interface SaveOptions extends SyncOptions { method? : string; defaults? : string; patch? : boolean; require? : boolean; } - + interface SerializeOptions { shallow? : boolean; omitPivot? : boolean; } - + interface SetOptions { unset? : boolean; } - + interface TimestampOptions { method? : string; } - + interface SyncOptions { transacting? : knex.Transaction; debug? : boolean; } - + interface CollectionOptions { comparator? : boolean|string|((a : T, b : T) => number); } - + interface CollectionAddOptions extends EventOptions { at? : number; merge? : boolean; } - + interface CollectionFetchOptions { require? : boolean; withRelated? : string|string[]; } - + interface CollectionFetchOneOptions { require? : boolean; columns? : string|string[]; } - + interface CollectionSetOptions extends EventOptions { add? : boolean; remove? : boolean; merge?: boolean; } - + interface PivotOptions { query? : Function|any; require? : boolean; } - + interface EventOptions { silent? : boolean; } - + interface EventFunction { (model: T, attrs: any, options: any) : Promise|void; } - + interface CollectionCreateOptions extends ModelOptions, SyncOptions, CollectionAddOptions, SaveOptions {} } - + export = Bookshelf; } diff --git a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts index fb0b1b3899..bd8a3ff54e 100644 --- a/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts +++ b/bootstrap.v3.datetimepicker/bootstrap.v3.datetimepicker.d.ts @@ -54,6 +54,8 @@ declare module BootstrapV3DatetimePicker { showTodayButton?: boolean; viewMode?: string; inline?: boolean; + toolbarPlacement?: string; + showClear?: boolean; } interface Datetimepicker { diff --git a/breeze/breeze.d.ts b/breeze/breeze.d.ts index 2a60df6d84..1cc587c2f2 100644 --- a/breeze/breeze.d.ts +++ b/breeze/breeze.d.ts @@ -392,6 +392,7 @@ declare module breeze { constructor(config?: EntityManagerOptions); constructor(config?: string); + acceptChanges(): void; addEntity(entity: Entity): Entity; attachEntity(entity: Entity, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity; clear(): void; diff --git a/bull/bull-tests.ts.tscparams b/bull/bull-tests.ts.tscparams new file mode 100644 index 0000000000..6641df12d4 --- /dev/null +++ b/bull/bull-tests.ts.tscparams @@ -0,0 +1 @@ +--target es5 --noImplicitAny --module commonjs diff --git a/bull/bull-tests.tsx b/bull/bull-tests.tsx new file mode 100644 index 0000000000..bd25efc0c9 --- /dev/null +++ b/bull/bull-tests.tsx @@ -0,0 +1,102 @@ +/** + * Created by Bruno Grieder + */ + +/// + + +import * as Queue from "bull" + +var videoQueue = Queue( 'video transcoding', 6379, '127.0.0.1' ); +var audioQueue = Queue( 'audio transcoding', 6379, '127.0.0.1' ); +var imageQueue = Queue( 'image transcoding', 6379, '127.0.0.1' ); + +videoQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => { + + // job.data contains the custom data passed when the job was created + // job.jobId contains id of this job. + + // transcode video asynchronously and report progress + job.progress( 42 ); + + // call done when finished + done(); + + // or give a error if error + done( Error( 'error transcoding' ) ); + + // or pass it a result + done( null, { framerate: 29.5 /* etc... */ } ); + + // If the job throws an unhandled exception it is also handled correctly + throw (Error( 'some unexpected error' )); +} ); + +audioQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => { + // transcode audio asynchronously and report progress + job.progress( 42 ); + + // call done when finished + done(); + + // or give a error if error + done( Error( 'error transcoding' ) ); + + // or pass it a result + done( null, { samplerate: 48000 /* etc... */ } ); + + // If the job throws an unhandled exception it is also handled correctly + throw (Error( 'some unexpected error' )); +} ); + +imageQueue.process( ( job: Queue.Job, done: Queue.DoneCallback ) => { + // transcode image asynchronously and report progress + job.progress( 42 ); + + // call done when finished + done(); + + // or give a error if error + done( Error( 'error transcoding' ) ); + + // or pass it a result + done( null, { width: 1280, height: 720 /* etc... */ } ); + + // If the job throws an unhandled exception it is also handled correctly + throw (Error( 'some unexpected error' )); +} ); + +videoQueue.add( { video: 'http://example.com/video1.mov' } ); +audioQueue.add( { audio: 'http://example.com/audio1.mp3' } ); +imageQueue.add( { image: 'http://example.com/image1.tiff' } ); + + +////////////////////////////////////////////////////////////////////////////////// +// +// Using Promises +// +////////////////////////////////////////////////////////////////////////////////// + +const fetchVideo = ( url: string ): Promise => { return null } +const transcodeVideo = ( data: any ): Promise => { return null } + +interface VideoJob extends Queue.Job { + data: {url: string} +} + + +videoQueue.process( ( job: VideoJob ) => { // don't forget to remove the done callback! + // Simply return a promise + return fetchVideo( job.data.url ).then( transcodeVideo ); + + // Handles promise rejection + return Promise.reject( new Error( 'error transcoding' ) ); + + // Passes the value the promise is resolved with to the "completed" event + return Promise.resolve( { framerate: 29.5 /* etc... */ } ); + + // If the job throws an unhandled exception it is also handled correctly + throw new Error( 'some unexpected error' ); + // same as + return Promise.reject( new Error( 'some unexpected error' ) ); +} ); diff --git a/bull/bull.d.ts b/bull/bull.d.ts new file mode 100644 index 0000000000..b867c11235 --- /dev/null +++ b/bull/bull.d.ts @@ -0,0 +1,311 @@ +// Type definitions for bull 0.7.0 +// Project: https://github.com/OptimalBits/bull +// Definitions by: Bruno Grieder +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + + +declare module "bull" { + + import * as Redis from "redis"; + + /** + * This is the Queue constructor. + * It creates a new Queue that is persisted in Redis. + * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. + */ + function Bull(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): Bull.Queue; + + module Bull { + + export interface DoneCallback { + (error?: Error, value?: any): void + } + + export interface Job { + + id: string + + /** + * The custom data passed when the job was created + */ + data: Object; + + /** + * Report progress on a job + */ + progress(value: any): Promise; + + /** + * Removes a Job from the queue from all the lists where it may be included. + * @returns {Promise} A promise that resolves when the job is removed. + */ + remove(): Promise; + + /** + * Rerun a Job that has failed. + * @returns {Promise} A promise that resolves when the job is scheduled for retry. + */ + retry(): Promise; + } + + export interface Backoff { + + /** + * Backoff type, which can be either `fixed` or `exponential` + */ + type: string + + /** + * Backoff delay, in milliseconds + */ + delay: number; + } + + export interface AddOptions { + /** + * An amount of miliseconds to wait until this job can be processed. + * Note that for accurate delays, both server and clients should have their clocks synchronized + */ + delay?: number; + + /** + * A number of attempts to retry if the job fails [optional] + */ + attempts?: number; + + /** + * Backoff setting for automatic retries if the job fails + */ + backoff?: number | Backoff + + /** + * A boolean which, if true, adds the job to the right + * of the queue instead of the left (default false) + */ + lifo?: boolean; + + /** + * The number of milliseconds after which the job should be fail with a timeout error + */ + timeout?: number; + } + + export interface Queue { + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + * + * concurrency: Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; + * results, as a second argument to the "completed" event. + */ + process(callback: (job: Job, done: DoneCallback) => void): void; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + * + * concurrency: Bull will then call you handler in parallel respecting this max number. + */ + process(concurrency: number, callback: (job: Job) => void): Promise; + + /** + * Defines a processing function for the jobs placed into a given Queue. + * + * The callback is called everytime a job is placed in the queue. + * It is passed an instance of the job as first argument. + * + * A promise must be returned to signal job completion. + * If the promise is rejected, the error will be passed as a second argument to the "failed" event. + * If it is resolved, its value will be the "completed" event's second argument. + */ + process(callback: (job: Job) => void): Promise; + + // process(callback: (job: Job, done?: DoneCallback) => void): Promise; + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: Object, opts?: AddOptions): Promise; + + /** + * Returns a promise that resolves when the queue is paused. + * The pause is global, meaning that all workers in all queue instances for a given queue will be paused. + * A paused queue will not process new jobs until resumed, + * but current jobs being processed will continue until they are finalized. + * + * Pausing a queue that is already paused does nothing. + */ + pause(): Promise; + + /** + * Returns a promise that resolves when the queue is resumed after being paused. + * The resume is global, meaning that all workers in all queue instances for a given queue will be resumed. + * + * Resuming a queue that is not paused does nothing. + */ + resume(): Promise; + + /** + * Returns a promise that returns the number of jobs in the queue, waiting or paused. + * Since there may be other processes adding or processing jobs, this value may be true only for a very small amount of time. + */ + count(): Promise; + + /** + * Empties a queue deleting all the input lists and associated jobs. + */ + empty(): Promise; + + /** + * Closes the underlying redis client. Use this to perform a graceful shutdown. + * + * `close` can be called from anywhere, with one caveat: + * if called from within a job handler the queue won't close until after the job has been processed + */ + close(): Promise; + + /** + * Returns a promise that will return the job instance associated with the jobId parameter. + * If the specified job cannot be located, the promise callback parameter will be set to null. + */ + getJob(jobId: string): Promise; + + /** + * Tells the queue remove all jobs created outside of a grace period in milliseconds. + * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + */ + clean(gracePeriod: number, jobsState?: string): Promise; + + /** + * Listens to queue events + * 'ready', 'error', 'activ', 'progress', 'completed', 'failed', 'paused', 'resumed', 'cleaned' + */ + on(eventName: string, callback: EventCallback): void; + } + + interface EventCallback { + (...args: any[]): void + } + + interface ReadyEventCallback extends EventCallback { + (): void; + } + + interface ErrorEventCallback extends EventCallback { + (error: Error): void; + } + + interface JobPromise { + /** + * Abort this job + */ + cancel(): void + } + + interface ActiveEventCallback extends EventCallback { + (job: Job, jobPromise: JobPromise): void; + } + + interface ProgressEventCallback extends EventCallback { + (job: Job, progress: any): void; + } + + interface CompletedEventCallback extends EventCallback { + (job: Job, result: Object): void; + } + + interface FailedEventCallback extends EventCallback { + (job: Job, error: Error): void; + } + + interface PausedEventCallback extends EventCallback { + (): void; + } + + interface ResumedEventCallback extends EventCallback { + (job?: Job): void; + } + + /** + * @see clean() for details + */ + interface CleanedEventCallback extends EventCallback { + (jobs: Job[], type: string): void; + } + } + + export = Bull; +} + +declare module "bull/lib/priority-queue" { + + import * as Bull from "bull"; + import * as Redis from "redis"; + + /** + * This is the Queue constructor of priority queue. + * + * It works same a normal queue, with same function and parameters. + * The only difference is that the Queue#add() allow an options opts.priority + * that could take ["low", "normal", "medium", "hight", "critical"]. If no options provider, "normal" will be taken. + * + * The priority queue will process more often highter priority jobs than lower. + */ + function PQueue(queueName: string, redisPort: number, redisHost: string, redisOpt?: Redis.ClientOpts): PQueue.PriorityQueue; + + module PQueue { + + export interface AddOptions extends Bull.AddOptions { + + /** + * "low", "normal", "medium", "high", "critical" + */ + priority?: string; + } + + + export interface PriorityQueue extends Bull.Queue { + + /** + * Creates a new job and adds it to the queue. + * If the queue is empty the job will be executed directly, + * otherwise it will be placed in the queue and executed as soon as possible. + */ + add(data: Object, opts?: PQueue.AddOptions): Promise; + + } + } + + export = PQueue; +} diff --git a/chai-string/chai-string-tests.ts b/chai-string/chai-string-tests.ts new file mode 100644 index 0000000000..f5380b0768 --- /dev/null +++ b/chai-string/chai-string-tests.ts @@ -0,0 +1,128 @@ +/// +/// +/// + +var should = chai.should(); +var assert = chai.assert; +var expect = chai.expect; + +var chai_string = require('chai-string'); +chai.use(chai_string); + +describe('chai-string', function() { + + describe('#startsWith', function() { + + it('check that', function() { + var obj = { foo: 'hello world' }; + expect(obj).to.have.property('foo').that.startsWith('hello'); + }); + + }); + + describe('#startWith', function() { + + it('should return true', function() { + var str = 'abcdef', + prefix = 'abc'; + str.should.startWith(prefix); + }); + + it('should return false', function() { + var str = 'abcdef', + prefix = 'cba'; + str.should.not.startWith(prefix); + }); + + }); + + describe('#endWith', function() { + + it('should return true', function() { + var str = 'abcdef', + suffix = 'def'; + str.should.endWith(suffix); + }); + + it('should return false', function() { + var str = 'abcdef', + suffix = 'fed'; + str.should.not.endWith(suffix); + }); + + }); + + describe('tdd alias', function() { + + beforeEach(function() { + this.str = 'abcdef'; + this.str2 = 'a\nb\tc\r d ef'; + }); + + it('.startsWith', function() { + assert.startsWith(this.str, 'abc'); + }); + + it('.notStartsWith', function() { + assert.notStartsWith(this.str, 'cba'); + }); + + it('.endsWith', function() { + assert.endsWith(this.str, 'def'); + }); + + it('.notEndsWith', function() { + assert.notEndsWith(this.str, 'fed'); + }); + + it('.equalIgnoreCase', function() { + assert.equalIgnoreCase(this.str, 'AbCdEf'); + }); + + it('.notEqualIgnoreCase', function() { + assert.notEqualIgnoreCase(this.str, 'abDDD'); + }); + + it('.equalIgnoreSpaces', function() { + assert.equalIgnoreSpaces(this.str, this.str2); + }); + + it('.notEqualIgnoreSpaces', function() { + assert.notEqualIgnoreSpaces(this.str, this.str2 + 'g'); + }); + + it('.singleLine', function() { + assert.singleLine(this.str); + }); + + it('.notSingleLine', function() { + assert.notSingleLine("abc\ndef"); + }); + + it('.reverseOf', function() { + assert.reverseOf(this.str, 'fedcba'); + }); + + it('.notReverseOf', function() { + assert.notReverseOf(this.str, 'aaaaa'); + }); + + it('.palindrome', function() { + assert.palindrome('abcba'); + assert.palindrome('abccba'); + assert.palindrome(''); + }); + + it('.notPalindrome', function() { + assert.notPalindrome(this.str); + }); + + it('.entriesCount', function() { + assert.entriesCount('abcabd', 'ab', 2); + assert.entriesCount('ababd', 'ab', 2); + assert.entriesCount('abab', 'ab', 2); + assert.entriesCount('', 'ab', 0); + }); + + }); +}); diff --git a/chai-string/chai-string.d.ts b/chai-string/chai-string.d.ts new file mode 100644 index 0000000000..fd17665232 --- /dev/null +++ b/chai-string/chai-string.d.ts @@ -0,0 +1,45 @@ +// Type definitions for chai-string 1.1.4 +// Project: https://github.com/onechiporenko/chai-string +// Definitions by: Nick Malaguti +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Chai { + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + startsWith(expected: string, message?: string): Assertion; + startWith(expected: string, message?: string): Assertion; + endsWith(expected: string, message?: string): Assertion; + endWith(expected: string, message?: string): Assertion; + equalIgnoreCase(expected: string, message?: string): Assertion; + equalIgnoreSpaces(expected: string, message?: string): Assertion; + singleLine(message?: string): Assertion; + reverseOf(message?: string): Assertion; + palindrome(message?: string): Assertion; + entriesCount(substr: string, expected: number, message?: string): Assertion; + } + + export interface Assert { + startsWith(val: string, exp: string, msg?: string): void; + notStartsWith(val: string, exp: string, msg?: string): void; + endsWith(val: string, exp: string, msg?: string): void; + notEndsWith(val: string, exp: string, msg?: string): void; + equalIgnoreCase(val: string, exp: string, msg?: string): void; + notEqualIgnoreCase(val: string, exp: string, msg?: string): void; + equalIgnoreSpaces(val: string, exp: string, msg?: string): void; + notEqualIgnoreSpaces(val: string, exp: string, msg?: string): void; + singleLine(val: string, msg?: string): void; + notSingleLine(val: string, msg?: string): void; + reverseOf(val: string, exp: string, msg?: string): void; + notReverseOf(val: string, exp: string, msg?: string): void; + palindrome(val: string, msg?: string): void; + notPalindrome(val: string, msg?: string): void; + entriesCount(str: string, substr: string, count: number, msg?: string): void; + } +} + +declare module 'chai-string' { + function chaiString(chai: any, utils: any): void; + namespace chaiString {} + export = chaiString; +} diff --git a/chai-things/chai-things-tests.ts b/chai-things/chai-things-tests.ts new file mode 100644 index 0000000000..de6a4c3ffe --- /dev/null +++ b/chai-things/chai-things-tests.ts @@ -0,0 +1,59 @@ +/// + +import chai = require('chai'); +import chaiThings = require('chai-things'); + +chai.use(chaiThings); + +function test_somethingSyntax() { + [].should.not.include.something(); + [].should.not.include.something.that.equals(1); + + var array = [{ a: 1 }, { b: 2 }]; + array.should.include.something(); + array.should.include.something.that.deep.equals({ b: 2 }); + array.should.include.something.that.not.deep.equals({ b: 2 }); + array.should.not.include.something.that.deep.equals({ c: 3 }); + array.should.include.something.that.not.deep.equals({ c: 3 }); + array.should.include.something.with.property('b', 2); + array.should.not.include.something.with.property('b', 3); + + var array2 = [{ a: 'b' }, { a: 'b' }]; + array2.should.include.something.that.have.property("a"); + array2.should.include.something.that.have.property("a").not.equal("d"); +} + +function test_somethingVariantsSyntax() { + [].should.not.include.any(); + [].should.not.include.any.that.deep.equal({ b: 2 }); + + var array = [{ a: 1 }, { b: 2 }]; + array.should.include.a.thing(); + array.should.include.a.thing.that.deep.equals({ b: 2 }); + array.should.include.an.item(); + array.should.include.an.item.that.deep.equals({ b: 2 }); + array.should.include.one.that.deep.equals({ b: 2 }); + array.should.include.some(); + array.should.include.some.that.deep.equal({ b: 2 }); +} + +function test_allSyntax() { + [].should.all.equal(1); + [].should.all.not.equal(1); + + var array = [1, 1]; + array.should.all.equal(1); + array.should.all.not.equal(2); + array.should.not.all.equal(2); + array.should.not.all.not.equal(1); + + var array2 = [1, 2]; + array2.should.not.all.equal(1); + array2.should.not.all.equal(2); + array2.should.not.all.not.equal(1); + array2.should.not.all.not.equal(2); + + var array3 = [{ a: 'b' }, { a: 'c' }]; + array3.should.all.have.property("a"); + array3.should.all.have.property("a").not.equal("d"); +} \ No newline at end of file diff --git a/chai-things/chai-things.d.ts b/chai-things/chai-things.d.ts new file mode 100644 index 0000000000..bc2b89c46f --- /dev/null +++ b/chai-things/chai-things.d.ts @@ -0,0 +1,55 @@ +// Type definitions for chai-things +// Project: https://github.com/chaijs/chai-things +// Definitions by: David Broder-Rodgers +// Definitions: https://github.com/DavidBR-SW/DefinitelyTyped + +/// + +declare module Chai { + interface ArrayAssertion { + include: ArrayInclude; + contain: ArrayInclude; + not: ArrayAssertion; + all: Assertion; + } + + interface ArrayInclude { + (item: any): any; + a: Item; + an: Item; + one: Something; + some: Something; + something: Something; + any: Anything; + } + + interface Anything extends Assertion { + (): any; + that: Assertion + with: Assertion + } + + interface Something extends Assertion { + (): any; + that: Assertion + with: Assertion + } + + interface Item { + item: Something; + thing: Something; + } + + interface Deep { + equals: Equal; + } +} + +interface Array { + should: Chai.ArrayAssertion; +} + +declare module "chai-things" { + function chaiThings(chai: any, utils: any): void; + export = chaiThings; +} diff --git a/chai/chai-3.2.0-tests.ts b/chai/chai-3.2.0-tests.ts new file mode 100644 index 0000000000..9b646b1529 --- /dev/null +++ b/chai/chai-3.2.0-tests.ts @@ -0,0 +1,1948 @@ +/// +import chai = require('chai'); + +// ReSharper disable WrongExpressionStatement + +var expect = chai.expect; +var assert = chai.assert; +var should = chai.should(); +declare var err: Function; + +function chaiVersion() { + expect(chai).to.have.property('version'); + (<{}>chai).should.have.property('version'); +} + +function assertion() { + expect('test').to.be.a('string'); + 'test'.should.be.a('string'); + expect('foo').to.equal('foo'); + 'foo'.should.equal('foo'); + should.equal('foo', 'foo'); +} + +function fail() { + err(() => { + should.fail('foo', 'bar'); + }, 'expected fail to throw an AssertionError'); + err(() => { + should.fail('foo', 'bar', 'should fail'); + }, 'expected fail to throw an AssertionError'); + err(() => { + should.fail('foo', 'bar', 'should fail', 'equal'); + }, 'expected fail to throw an AssertionError'); + + err(() => { + expect.fail('foo', 'bar'); + }, 'expected fail to throw an AssertionError'); + err(() => { + expect.fail('foo', 'bar', 'should fail'); + }, 'expected fail to throw an AssertionError'); + err(() => { + expect.fail('foo', 'bar', 'should fail', 'equal'); + }, 'expected fail to throw an AssertionError'); +} + +// ReSharper disable once InconsistentNaming +function _true() { + expect(true).to.be.true; + true.should.be.true; + expect(false).to.not.be.true; + false.should.not.be.true; + expect(1).to.not.be.true; + (1).should.not.be.true; + + err(() => { + expect('test').to.be.true; + 'test'.should.be.true; + }, 'expected \'test\' to be true'); +} + +function ok() { + expect(true).to.be.ok; + true.should.be.ok; + expect(false).to.not.be.ok; + false.should.not.be.ok; + expect(1).to.be.ok; + (1).should.be.ok; + expect(0).to.not.be.ok; + (0).should.not.be.ok; + + err(() => { + expect('').to.be.ok; + ''.should.be.ok; + }, 'expected \'\' to be truthy'); + + err(() => { + expect('test').to.not.be.ok; + 'test'.should.not.be.ok; + }, 'expected \'test\' to be falsy'); +} + +function _false() { + expect(false).to.be.false; + false.should.be.false; + expect(true).to.not.be.false; + true.should.not.be.false; + expect(0).to.not.be.false; + (0).should.not.be.false; + + err(() => { + expect('').to.be.false; + ''.should.be.false; + }, 'expected \'\' to be false'); +} + +function _null() { + expect(null).to.be.null; + should.equal(null, null); + expect(false).to.not.be.null; + false.should.not.be.null; + + err(() => { + expect('').to.be.null; + ''.should.be.null; + }, 'expected \'\' to be null'); +} + +function _undefined() { + expect(undefined).to.be.undefined; + should.equal(undefined, undefined); + expect(null).to.not.be.undefined; + should.not.equal(null, undefined); + + err(() => { + expect('').to.be.undefined; + ''.should.be.undefined; + }, 'expected \'\' to be undefined'); +} + +function _NaN() { + expect(NaN).to.be.NaN; + expect(12).to.be.not.NaN; + expect("NaN").to.be.not.NaN; + (NaN).should.be.NaN; + (12).should.be.not.NaN; + ("NaN").should.be.not.NaN; +} + +function exist() { + var foo = 'bar'; + expect(foo).to.exist; + should.exist(foo); + expect(void (0)).to.not.exist; + should.not.exist(void (0)); +} + +function argumentsTest() { + var args = arguments; + expect(args).to.be.arguments; + args.should.be.arguments; + expect([]).to.not.be.arguments; + [].should.not.be.arguments; + expect(args).to.be.an('arguments').and.be.arguments; + args.should.be.an('arguments').and.be.arguments; + expect([]).to.be.an('array').and.not.be.Arguments; + [].should.be.an('array').and.not.be.Arguments; +} + +function equal() { + expect(undefined).to.equal(void (0)); + should.equal(undefined, void (0)); +} + +function _typeof() { + expect('test').to.be.a('string'); + 'test'.should.be.a('string'); + + err(() => { + expect('test').to.not.be.a('string'); + 'test'.should.not.be.a('string'); + }, 'expected \'test\' not to be a string'); + + expect(arguments).to.be.an('arguments'); + arguments.should.be.an('arguments'); + + expect(5).to.be.a('number'); + (5).should.be.a('number'); + + expect(new Number(1)).to.be.a('number'); + (new Number(1)).should.be.a('number'); + expect(Number(1)).to.be.a('number'); + Number(1).should.be.a('number'); + expect(true).to.be.a('boolean'); + true.should.be.a('boolean'); + expect(new Array()).to.be.a('array'); + (new Array()).should.be.a('array'); + expect(new Object()).to.be.a('object'); + (new Object()).should.be.a('object'); + expect({}).to.be.a('object'); + ({}).should.be.a('object'); + expect([]).to.be.a('array'); + [].should.be.a('array'); + expect(() => { }).to.be.a('function'); + (() => { }).should.be.a('function'); + expect(null).to.be.a('null'); + // N.B. previous line has no should equivalent + + err(() => { + expect(5).to.not.be.a('number', 'blah'); + (5).should.not.be.a('number', 'blah'); + }, 'blah: expected 5 not to be a number'); +} + +class Foo { } +function _instanceof() { + expect(new Foo()).to.be.an.instanceof(Foo); + (new Foo()).should.be.an.instanceof(Foo); + + err(() => { + expect(3).to.an.instanceof(Foo, 'blah'); + (3).should.an.instanceof(Foo, 'blah'); + }, 'blah: expected 3 to be an instance of Foo'); +} + +function within() { + expect(5).to.be.within(5, 10); + (5).should.be.within(5, 10); + expect(5).to.be.within(3, 6); + (5).should.be.within(3, 6); + expect(5).to.be.within(3, 5); + (5).should.be.within(3, 5); + expect(5).to.not.be.within(1, 3); + (5).should.not.be.within(1, 3); + expect('foo').to.have.length.within(2, 4); + 'foo'.should.have.length.within(2, 4); + expect([1, 2, 3]).to.have.length.within(2, 4); + [1, 2, 3].should.have.length.within(2, 4); + + err(() => { + expect(5).to.not.be.within(4, 6, 'blah'); + (5).should.not.be.within(4, 6, 'blah'); + }, 'blah: expected 5 to not be within 4..6', 'blah'); + + err(() => { + expect(10).to.be.within(50, 100, 'blah'); + (10).should.be.within(50, 100, 'blah'); + }, 'blah: expected 10 to be within 50..100'); + + err(() => { + expect('foo').to.have.length.within(5, 7, 'blah'); + 'foo'.should.have.length.within(5, 7, 'blah'); + }, 'blah: expected \'foo\' to have a length within 5..7'); + + err(() => { + expect([1, 2, 3]).to.have.length.within(5, 7, 'blah'); + [1, 2, 3].should.have.length.within(5, 7, 'blah'); + }, 'blah: expected [ 1, 2, 3 ] to have a length within 5..7'); +} + +function above() { + expect(5).to.be.above(2); + (5).should.be.above(2); + expect(5).to.be.greaterThan(2); + (5).should.be.greaterThan(2); + expect(5).to.not.be.above(5); + (5).should.not.be.above(5); + expect(5).to.not.be.above(6); + (5).should.not.be.above(6); + expect('foo').to.have.length.above(2); + 'foo'.should.have.length.above(2); + expect([1, 2, 3]).to.have.length.above(2); + [1, 2, 3].should.have.length.above(2); + + err(() => { + expect(5).to.be.above(6, 'blah'); + (5).should.be.above(6, 'blah'); + }, 'blah: expected 5 to be above 6', 'blah'); + + err(() => { + expect(10).to.not.be.above(6, 'blah'); + (10).should.not.be.above(6, 'blah'); + }, 'blah: expected 10 to be at most 6'); + + err(() => { + expect('foo').to.have.length.above(4, 'blah'); + 'foo'.should.have.length.above(4, 'blah'); + }, 'blah: expected \'foo\' to have a length above 4 but got 3'); + + err(() => { + expect([1, 2, 3]).to.have.length.above(4, 'blah'); + [1, 2, 3].should.have.length.above(4, 'blah'); + }, 'blah: expected [ 1, 2, 3 ] to have a length above 4 but got 3'); +} + +function least() { + expect(5).to.be.at.least(2); + (5).should.be.at.least(2); + expect(5).to.be.at.least(5); + (5).should.be.at.least(5); + expect(5).to.not.be.at.least(6); + (5).should.not.be.at.least(6); + expect('foo').to.have.length.of.at.least(2); + 'foo'.should.have.length.of.at.least(2); + expect([1, 2, 3]).to.have.length.of.at.least(2); + [1, 2, 3].should.have.length.of.at.least(2); + + err(() => { + expect(5).to.be.at.least(6, 'blah'); + (5).should.be.at.least(6, 'blah'); + }, 'blah: expected 5 to be at least 6', 'blah'); + + err(() => { + expect(10).to.not.be.at.least(6, 'blah'); + (10).should.not.be.at.least(6, 'blah'); + }, 'blah: expected 10 to be below 6'); + + err(() => { + expect('foo').to.have.length.of.at.least(4, 'blah'); + 'foo'.should.have.length.of.at.least(4, 'blah'); + }, 'blah: expected \'foo\' to have a length at least 4 but got 3'); + + err(() => { + expect([1, 2, 3]).to.have.length.of.at.least(4, 'blah'); + [1, 2, 3].should.have.length.of.at.least(4, 'blah'); + }, 'blah: expected [ 1, 2, 3 ] to have a length at least 4 but got 3'); + + err(() => { + expect([1, 2, 3, 4]).to.not.have.length.of.at.least(4, 'blah'); + [1, 2, 3, 4].should.not.have.length.of.at.least(4, 'blah'); + }, 'blah: expected [ 1, 2, 3, 4 ] to have a length below 4'); +} + +function below() { + expect(2).to.be.below(5); + (2).should.be.below(5); + expect(2).to.be.lessThan(5); + (2).should.be.lessThan(5); + expect(2).to.not.be.below(2); + (2).should.not.be.below(2); + expect(2).to.not.be.below(1); + (2).should.not.be.below(1); + expect('foo').to.have.length.below(4); + 'foo'.should.have.length.below(4); + expect([1, 2, 3]).to.have.length.below(4); + [1, 2, 3].should.have.length.below(4); + + err(() => { + expect(6).to.be.below(5, 'blah'); + (6).should.be.below(5, 'blah'); + }, 'blah: expected 6 to be below 5'); + + err(() => { + expect(6).to.not.be.below(10, 'blah'); + (6).should.not.be.below(10, 'blah'); + }, 'blah: expected 6 to be at least 10'); + + err(() => { + expect('foo').to.have.length.below(2, 'blah'); + 'foo'.should.have.length.below(2, 'blah'); + }, 'blah: expected \'foo\' to have a length below 2 but got 3'); + + err(() => { + expect([1, 2, 3]).to.have.length.below(2, 'blah'); + [1, 2, 3].should.have.length.below(2, 'blah'); + }, 'blah: expected [ 1, 2, 3 ] to have a length below 2 but got 3'); +} + +function most() { + expect(2).to.be.at.most(5); + (2).should.be.at.most(5); + expect(2).to.be.at.most(2); + (2).should.be.at.most(2); + expect(2).to.not.be.at.most(1); + (2).should.not.be.at.most(1); + expect(2).to.not.be.at.most(1); + (2).should.not.be.at.most(1); + expect('foo').to.have.length.of.at.most(4); + 'foo'.should.have.length.of.at.most(4); + expect([1, 2, 3]).to.have.length.of.at.most(4); + [1, 2, 3].should.have.length.of.at.most(4); + + err(() => { + expect(6).to.be.at.most(5, 'blah'); + (6).should.be.at.most(5, 'blah'); + }, 'blah: expected 6 to be at most 5'); + + err(() => { + expect(6).to.not.be.at.most(10, 'blah'); + (6).should.not.be.at.most(10, 'blah'); + }, 'blah: expected 6 to be above 10'); + + err(() => { + expect('foo').to.have.length.of.at.most(2, 'blah'); + 'foo'.should.have.length.of.at.most(2, 'blah'); + }, 'blah: expected \'foo\' to have a length at most 2 but got 3'); + + err(() => { + expect([1, 2, 3]).to.have.length.of.at.most(2, 'blah'); + [1, 2, 3].should.have.length.of.at.most(2, 'blah'); + }, 'blah: expected [ 1, 2, 3 ] to have a length at most 2 but got 3'); + + err(() => { + expect([1, 2]).to.not.have.length.of.at.most(2, 'blah'); + [1, 2].should.not.have.length.of.at.most(2, 'blah'); + }, 'blah: expected [ 1, 2 ] to have a length above 2'); +} + +function match() { + expect('foobar').to.match(/^foo/); + 'foobar'.should.match(/^foo/); + expect('foobar').to.not.match(/^bar/); + 'foobar'.should.not.match(/^bar/); + + expect('foobar').matches(/^foo/); + 'foobar'.should.not.matches(/^bar/); + + err(() => { + expect('foobar').to.match(/^bar/i, 'blah'); + 'foobar'.should.match(/^bar/i, 'blah'); + }, 'blah: expected \'foobar\' to match /^bar/i'); + + err(() => { + expect('foobar').to.not.match(/^foo/i, 'blah'); + 'foobar'.should.not.match(/^foo/i, 'blah'); + }, 'blah: expected \'foobar\' not to match /^foo/i'); +} + +function length2() { + expect('test').to.have.length(4); + 'test'.should.have.length(4); + expect('test').to.not.have.length(3); + 'test'.should.not.have.length(3); + expect([1, 2, 3]).to.have.length(3); + [1, 2, 3].should.have.length(3); + + err(() => { + expect(4).to.have.length(3, 'blah'); + (4).should.have.length(3, 'blah'); + }, 'blah: expected 4 to have a property \'length\''); + + err(() => { + expect('asd').to.not.have.length(3, 'blah'); + 'asd'.should.not.have.length(3, 'blah'); + }, 'blah: expected \'asd\' to not have a length of 3'); +} + +function eql() { + expect('test').to.eql('test'); + 'test'.should.eql('test'); + expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); + ({ foo: 'bar' }).should.eql({ foo: 'bar' }); + expect(1).to.eql(1); + (1).should.eql(1); + expect('4').to.not.eql(4); + '4'.should.not.eql(4); + + err(() => { + expect(4).to.eql(3, 'blah'); + (4).should.eql(3, 'blah'); + }, 'blah: expected 4 to deeply equal 3'); +} + +class Buffer { + constructor(arr: number[]) { + } +} +function buffer() { + expect(new Buffer([1])).to.eql(new Buffer([1])); + (new Buffer([1])).should.eql(new Buffer([1])); + + err(() => { + expect(new Buffer([0])).to.eql(new Buffer([1])); + (new Buffer([0])).should.eql(new Buffer([1])); + }, 'expected to deeply equal '); +} + +function equal2() { + expect('test').to.equal('test'); + 'test'.should.equal('test'); + should.equal('test', 'test'); + expect(1).to.equal(1); + (1).should.equal(1); + should.equal(1, 1); + + err(() => { + expect(4).to.equal(3, 'blah'); + (4).should.equal(3, 'blah'); + should.equal(4, 3, 'blah'); + }, 'blah: expected 4 to equal 3'); + + err(() => { + expect('4').to.equal(4, 'blah'); + '4'.should.equal(4, 'blah'); + should.equal(4, 4, 'blah'); + }, 'blah: expected \'4\' to equal 4'); +} + +function deepEqual() { + expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); + ({ foo: 'bar' }).should.deep.equal({ foo: 'bar' }); + expect({ foo: 'bar' }).not.to.deep.equal({ foo: 'baz' }); +} + +function deepEqual2() { + expect(/a/).to.deep.equal(/a/); + /a/.should.deep.equal(/a/); + expect(/a/).not.to.deep.equal(/b/); + expect(/a/).not.to.deep.equal({}); + expect(/a/g).to.deep.equal(/a/g); + /a/g.should.deep.equal(/a/g); + expect(/a/g).not.to.deep.equal(/b/g); + expect(/a/i).to.deep.equal(/a/i); + /a/i.should.deep.equal(/a/i); + expect(/a/i).not.to.deep.equal(/b/i); + expect(/a/m).to.deep.equal(/a/m); + /a/m.should.deep.equal(/a/m); + expect(/a/m).not.to.deep.equal(/b/m); +} + +// ReSharper disable once InconsistentNaming +function deepEqual3() { + var a = new Date(1, 2, 3); + var b = new Date(4, 5, 6); + expect(a).to.deep.equal(a); + a.should.deep.equal(a); + expect(a).not.to.deep.equal(b); + a.should.not.deep.equal(b); + expect(a).not.to.deep.equal({}); + a.should.not.deep.equal({}); +} + +function deepInclude() { + expect(['foo', 'bar']).to.deep.include(['bar', 'foo']); + ['foo', 'bar'].should.deep.include(['bar', 'foo']); + expect(['foo', 'bar']).not.to.deep.equal(['foo', 'baz']); + ['foo', 'bar'].should.not.deep.equal(['foo', 'baz']); +} + +class FakeArgs { + length: number; +} + +function empty() { + FakeArgs.prototype.length = 0; + + expect('').to.be.empty; + + ''.should.be.empty; + expect('foo').not.to.be.empty; + 'foo'.should.not.be.empty; + expect([]).to.be.empty; + [].should.be.empty; + expect(['foo']).not.to.be.empty; + ['foo'].should.not.be.empty; + expect(new FakeArgs).to.be.empty; + (new FakeArgs).should.be.empty; + expect({ arguments: 0 }).not.to.be.empty; + ({ arguments: 0 }).should.not.be.empty; + expect({}).to.be.empty; + ({}).should.be.empty; + expect({ foo: 'bar' }).not.to.be.empty; + ({ foo: 'bar' }).should.not.be.empty; + + err(() => { + expect('').not.to.be.empty; + ''.should.not.be.empty; + }, 'expected \'\' not to be empty'); + + err(() => { + expect('foo').to.be.empty; + 'foo'.should.be.empty; + 'foo'.should.be.empty; + }, 'expected \'foo\' to be empty'); + + err(() => { + expect([]).not.to.be.empty; + [].should.not.be.empty; + }, 'expected [] not to be empty'); + + err(() => { + expect(['foo']).to.be.empty; + ['foo'].should.be.empty; + }, 'expected [ \'foo\' ] to be empty'); + + err(() => { + expect(new FakeArgs).not.to.be.empty; + (new FakeArgs).should.not.be.empty; + }, 'expected { length: 0 } not to be empty'); + + err(() => { + expect({ arguments: 0 }).to.be.empty; + ({ arguments: 0 }).should.be.empty; + }, 'expected { arguments: 0 } to be empty'); + + err(() => { + expect({}).not.to.be.empty; + ({}).should.not.be.empty; + }, 'expected {} not to be empty'); + + err(() => { + expect({ foo: 'bar' }).to.be.empty; + ({ foo: 'bar' }).should.be.empty; + }, 'expected { foo: \'bar\' } to be empty'); +} + +function property() { + expect('test').to.have.property('length'); + 'test'.should.have.property('length'); + expect(4).to.not.have.property('length'); + (4).should.not.have.property('length'); + + expect({ 'foo.bar': 'baz' }) + .to.have.property('foo.bar'); + ({ 'foo.bar': 'baz' }).should.have.property('foo.bar'); + expect({ foo: { bar: 'baz' } }) + .to.not.have.property('foo.bar'); + ({ foo: { bar: 'baz' } }).should.not.have.property('foo.bar'); + + err(() => { + expect('asd').to.have.property('foo'); + 'asd'.should.have.property('foo'); + }, 'expected \'asd\' to have a property \'foo\''); + err(() => { + expect({ foo: { bar: 'baz' } }) + .to.have.property('foo.bar'); + ({ foo: { bar: 'baz' } }).should.have.property('foo.bar'); + }, 'expected { foo: { bar: \'baz\' } } to have a property \'foo.bar\''); +} + +function deepProperty() { + expect({ 'foo.bar': 'baz' }) + .to.not.have.deep.property('foo.bar'); + ({ 'foo.bar': 'baz' }).should + .not.have.deep.property('foo.bar'); + expect({ foo: { bar: 'baz' } }) + .to.have.deep.property('foo.bar'); + ({ foo: { bar: 'baz' } }).should + .have.deep.property('foo.bar'); + + err(() => { + expect({ 'foo.bar': 'baz' }) + .to.have.deep.property('foo.bar'); + ({ 'foo.bar': 'baz' }).should + .have.deep.property('foo.bar'); + }, 'expected { \'foo.bar\': \'baz\' } to have a deep property \'foo.bar\''); +} + +function property2() { + expect('test').to.have.property('length', 4); + 'test'.should.have.property('length', 4); + expect('asd').to.have.property('constructor', String); + 'asd'.should.have.property('constructor', String); + + err(() => { + expect('asd').to.have.property('length', 4, 'blah'); + 'asd'.should.have.property('length', 4, 'blah'); + }, 'blah: expected \'asd\' to have a property \'length\' of 4, but got 3'); + + err(() => { + expect('asd').to.not.have.property('length', 3, 'blah'); + 'asd'.should.not.have.property('length', 3, 'blah'); + }, 'blah: expected \'asd\' to not have a property \'length\' of 3'); + + err(() => { + expect('asd').to.not.have.property('foo', 3, 'blah'); + 'asd'.should.not.have.property('foo', 3, 'blah'); + }, 'blah: \'asd\' has no property \'foo\''); + + err(() => { + expect('asd').to.have.property('constructor', Number, 'blah'); + 'asd'.should.have.property('constructor', Number, 'blah'); + }, 'blah: expected \'asd\' to have a property \'constructor\' of [Function: Number], but got [Function: String]'); +} + +function deepProperty2() { + expect({ foo: { bar: 'baz' } }) + .to.have.deep.property('foo.bar', 'baz'); + ({ foo: { bar: 'baz' } }).should + .have.deep.property('foo.bar', 'baz'); + + err(() => { + expect({ foo: { bar: 'baz' } }) + .to.have.deep.property('foo.bar', 'quux', 'blah'); + ({ foo: { bar: 'baz' } }).should + .have.deep.property('foo.bar', 'quux', 'blah'); + }, 'blah: expected { foo: { bar: \'baz\' } } to have a deep property \'foo.bar\' of \'quux\', but got \'baz\''); + err(() => { + expect({ foo: { bar: 'baz' } }) + .to.not.have.deep.property('foo.bar', 'baz', 'blah'); + ({ foo: { bar: 'baz' } }).should + .not.have.deep.property('foo.bar', 'baz', 'blah'); + }, 'blah: expected { foo: { bar: \'baz\' } } to not have a deep property \'foo.bar\' of \'baz\''); + err(() => { + expect({ foo: 5 }) + .to.not.have.deep.property('foo.bar', 'baz', 'blah'); + ({ foo: 5 }).should + .not.have.deep.property('foo.bar', 'baz', 'blah'); + }, 'blah: { foo: 5 } has no deep property \'foo.bar\''); +} + +function ownProperty() { + expect('test').to.have.ownProperty('length'); + 'test'.should.have.ownProperty('length'); + expect('test').to.haveOwnProperty('length'); + 'test'.should.haveOwnProperty('length'); + expect({ length: 12 }).to.have.ownProperty('length'); + ({ length: 12 }).should.have.ownProperty('length'); + + err(() => { + expect({ length: 12 }).to.not.have.ownProperty('length', 'blah'); + ({ length: 12 }).should.not.have.ownProperty('length', 'blah'); + }, 'blah: expected { length: 12 } to not have own property \'length\''); +} + +function ownPropertyDescriptor() { + expect('test').to.have.ownPropertyDescriptor('length'); + expect('test').to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); + expect('test').not.to.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); + expect('test').to.haveOwnPropertyDescriptor('length').to.have.property('enumerable', false); + expect('test').to.haveOwnPropertyDescriptor('length').to.contain.keys('value'); + + 'test'.should.have.ownPropertyDescriptor('length'); + 'test'.should.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 4 }); + 'test'.should.not.have.ownPropertyDescriptor('length', { enumerable: false, configurable: false, writable: false, value: 3 }); + 'test'.should.haveOwnPropertyDescriptor('length').to.have.property('enumerable', false); + 'test'.should.haveOwnPropertyDescriptor('length').to.contain.keys('value'); +} + +function string() { + expect('foobar').to.have.string('bar'); + 'foobar'.should.have.string('bar'); + expect('foobar').to.have.string('foo'); + 'foobar'.should.have.string('foo'); + expect('foobar').to.not.have.string('baz'); + 'foobar'.should.not.have.string('baz'); + + err(() => { + expect(3).to.have.string('baz'); + (3).should.have.string('baz'); + }, 'expected 3 to be a string'); + + err(() => { + expect('foobar').to.have.string('baz', 'blah'); + 'foobar'.should.have.string('baz', 'blah'); + }, 'blah: expected \'foobar\' to contain \'baz\''); + + err(() => { + expect('foobar').to.not.have.string('bar', 'blah'); + 'foobar'.should.not.have.string('bar', 'blah'); + }, 'blah: expected \'foobar\' to not contain \'bar\''); +} + +function include() { + expect(['foo', 'bar']).to.include('foo'); + ['foo', 'bar'].should.include('foo'); + expect(['foo', 'bar']).to.include('foo'); + ['foo', 'bar'].should.include('foo'); + expect(['foo', 'bar']).to.include('bar'); + ['foo', 'bar'].should.include('bar'); + expect([1, 2]).to.include(1); + [1, 2].should.include(1); + expect(['foo', 'bar']).to.not.include('baz'); + ['foo', 'bar'].should.not.include('baz'); + expect(['foo', 'bar']).to.not.include(1); + ['foo', 'bar'].should.not.include(1); + // alias + + expect(['foo', 'bar']).includes('foo'); + ['foo', 'bar'].should.includes('foo'); + + err(() => { + expect(['foo']).to.include('bar', 'blah'); + ['foo'].should.include('bar', 'blah'); + }, 'blah: expected [ \'foo\' ] to include \'bar\''); + + err(() => { + expect(['bar', 'foo']).to.not.include('foo', 'blah'); + ['bar', 'foo'].should.not.include('foo', 'blah'); + }, 'blah: expected [ \'bar\', \'foo\' ] to not include \'foo\''); +} + +function keys() { + expect({ foo: 1 }).to.have.keys(['foo']); + ({ foo: 1 }).should.have.keys(['foo']); + expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); + ({ foo: 1, bar: 2 }).should.have.keys(['foo', 'bar']); + expect({ foo: 1, bar: 2 }).to.have.keys('foo', 'bar'); + ({ foo: 1, bar: 2 }).should.have.keys('foo', 'bar'); + expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar'); + ({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('foo', 'bar'); + expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('bar', 'foo'); + ({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('bar', 'foo'); + expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('baz'); + ({ foo: 1, bar: 2, baz: 3 }).should.contain.keys('baz'); + // alias + + expect({ foo: 1, bar: 2, baz: 3 }).contains.keys('baz'); + + expect({ foo: 1, bar: 2 }).to.have.all.keys(['foo', 'bar']); + expect({ foo: 1, bar: 2 }).to.have.any.keys(['foo', 'bar']); + ({ foo: 1, bar: 2, baz: 3 }).should.contain.all.keys('baz'); + ({ foo: 1, bar: 2, baz: 3 }).should.contain.any.keys('baz'); + + expect({ foo: 1, bar: 2 }).to.contain.keys('foo'); + ({ foo: 1, bar: 2 }).should.contain.keys('foo'); + expect({ foo: 1, bar: 2 }).to.contain.keys('bar', 'foo'); + ({ foo: 1, bar: 2 }).should.contain.keys('bar', 'foo'); + expect({ foo: 1, bar: 2 }).to.contain.keys(['foo']); + ({ foo: 1, bar: 2 }).should.contain.keys(['foo']); + expect({ foo: 1, bar: 2 }).to.contain.keys(['bar']); + ({ foo: 1, bar: 2 }).should.contain.keys(['bar']); + expect({ foo: 1, bar: 2 }).to.contain.keys(['bar', 'foo']); + ({ foo: 1, bar: 2 }).should.contain.keys(['bar', 'foo']); + + expect({ foo: 1, bar: 2 }).to.not.have.keys('baz'); + ({ foo: 1, bar: 2 }).should.not.have.keys('baz'); + expect({ foo: 1, bar: 2 }).to.not.have.keys('foo', 'baz'); + ({ foo: 1, bar: 2 }).should.not.have.keys('foo', 'baz'); + expect({ foo: 1, bar: 2 }).to.not.contain.keys('baz'); + ({ foo: 1, bar: 2 }).should.not.contain.keys('baz'); + expect({ foo: 1, bar: 2 }).to.not.contain.keys('foo', 'baz'); + ({ foo: 1, bar: 2 }).should.not.contain.keys('foo', 'baz'); + expect({ foo: 1, bar: 2 }).to.not.contain.keys('baz', 'foo'); + ({ foo: 1, bar: 2 }).should.not.contain.keys('baz', 'foo'); + + err(() => { + expect({ foo: 1 }).to.have.keys(); + ({ foo: 1 }).should.have.keys(); + }, 'keys required'); + + err(() => { + expect({ foo: 1 }).to.have.keys([]); + ({ foo: 1 }).should.have.keys([]); + }, 'keys required'); + + err(() => { + expect({ foo: 1 }).to.not.have.keys([]); + ({ foo: 1 }).should.not.have.keys([]); + }, 'keys required'); + + err(() => { + expect({ foo: 1 }).to.contain.keys([]); + ({ foo: 1 }).should.contain.keys([]); + }, 'keys required'); + + err(() => { + expect({ foo: 1 }).to.have.keys(['bar']); + ({ foo: 1 }).should.have.keys(['bar']); + }, 'expected { foo: 1 } to have key \'bar\''); + + err(() => { + expect({ foo: 1 }).to.have.keys(['bar', 'baz']); + ({ foo: 1 }).should.have.keys(['bar', 'baz']); + }, 'expected { foo: 1 } to have keys \'bar\', and \'baz\''); + + err(() => { + expect({ foo: 1 }).to.have.keys(['foo', 'bar', 'baz']); + ({ foo: 1 }).should.have.keys(['foo', 'bar', 'baz']); + }, 'expected { foo: 1 } to have keys \'foo\', \'bar\', and \'baz\''); + + err(() => { + expect({ foo: 1 }).to.not.have.keys(['foo']); + ({ foo: 1 }).should.not.have.keys(['foo']); + }, 'expected { foo: 1 } to not have key \'foo\''); + + err(() => { + expect({ foo: 1 }).to.not.have.keys(['foo']); + ({ foo: 1 }).should.not.have.keys(['foo']); + }, 'expected { foo: 1 } to not have key \'foo\''); + + err(() => { + expect({ foo: 1, bar: 2 }).to.not.have.keys(['foo', 'bar']); + ({ foo: 1, bar: 2 }).should.not.have.keys(['foo', 'bar']); + }, 'expected { foo: 1, bar: 2 } to not have keys \'foo\', and \'bar\''); + + err(() => { + expect({ foo: 1 }).to.not.contain.keys(['foo']); + ({ foo: 1 }).should.not.contain.keys(['foo']); + }, 'expected { foo: 1 } to not contain key \'foo\''); + + err(() => { + expect({ foo: 1 }).to.contain.keys('foo', 'bar'); + ({ foo: 1 }).should.contain.keys('foo', 'bar'); + }, 'expected { foo: 1 } to contain keys \'foo\', and \'bar\''); +} + +function chaining() { + var tea = { name: 'chai', extras: ['milk', 'sugar', 'smile'] }; + expect(tea).to.have.property('extras').with.lengthOf(3); + tea.should.have.property('extras').with.lengthOf(3); + + err(() => { + expect(tea).to.have.property('extras').with.lengthOf(4); + tea.should.have.property('extras').with.lengthOf(4); + }, 'expected [ \'milk\', \'sugar\', \'smile\' ] to have a length of 4 but got 3'); + + expect(tea).to.be.a('object').and.have.property('name', 'chai'); + tea.should.be.a('object').and.have.property('name', 'chai'); +} + +function exxtensible() { + expect({}).to.be.extensible; + expect(Object.preventExtensions({})).to.be.not.extensible; + ({}).should.be.extensible; + Object.preventExtensions({}).should.not.be.extensible; +} +function sealed() { + expect({}).to.be.not.sealed; + expect(Object.seal({})).to.be.sealed; + ({}).should.be.not.sealed; + Object.seal({}).should.be.sealed; +} + +function frozen() { + expect({}).to.be.not.frozen; + expect(Object.freeze({})).to.be.frozen; + ({}).should.be.not.frozen; + Object.freeze({}).should.be.frozen; +} + + +class PoorlyConstructedError { } +function _throw() { + // See GH-45: some poorly-constructed custom errors don't have useful names + // on either their constructor or their constructor prototype, but instead + // only set the name inside the constructor itself. + PoorlyConstructedError.prototype = Object.create(Error.prototype); + + var specificError = new RangeError('boo'); + + var goodFn = () => { } + , badFn = () => { throw new Error('testing'); } + , refErrFn = () => { throw new ReferenceError('hello'); } + , ickyErrFn = () => { throw new PoorlyConstructedError(); } + , specificErrFn = () => { throw specificError; }; + + expect(goodFn).to.not.throw(); + goodFn.should.not.throw(); + should.not.throw(goodFn); + expect(goodFn).to.not.throw(Error); + goodFn.should.not.throw(Error); + should.not.throw(goodFn, Error); + expect(goodFn).to.not.throw(specificError); + goodFn.should.not.throw(specificError); + should.not.throw(goodFn, specificError); + + expect(badFn).to.throw(); + badFn.should.throw(); + should.throw(badFn); + expect(badFn).to.throw(Error); + badFn.should.throw(Error); + should.throw(badFn, Error); + expect(badFn).to.not.throw(ReferenceError); + badFn.should.not.throw(ReferenceError); + should.not.throw(badFn, ReferenceError); + expect(badFn).to.not.throw(specificError); + badFn.should.not.throw(specificError); + should.not.throw(badFn, specificError); + + expect(refErrFn).to.throw(); + refErrFn.should.throw(); + should.throw(refErrFn); + expect(refErrFn).to.throw(ReferenceError); + refErrFn.should.throw(ReferenceError); + should.throw(refErrFn, ReferenceError); + expect(refErrFn).to.throw(Error); + refErrFn.should.throw(Error); + should.throw(refErrFn, Error); + expect(refErrFn).to.not.throw(TypeError); + refErrFn.should.not.throw(TypeError); + should.not.throw(refErrFn, TypeError); + expect(refErrFn).to.not.throw(specificError); + refErrFn.should.not.throw(specificError); + should.not.throw(refErrFn, specificError); + + expect(ickyErrFn).to.throw(); + ickyErrFn.should.throw(); + should.throw(ickyErrFn); + expect(ickyErrFn).to.throw(PoorlyConstructedError); + ickyErrFn.should.throw(PoorlyConstructedError); + should.throw(ickyErrFn, PoorlyConstructedError); + expect(ickyErrFn).to.throw(Error); + ickyErrFn.should.throw(Error); + should.throw(ickyErrFn, Error); + expect(ickyErrFn).to.not.throw(specificError); + ickyErrFn.should.not.throw(specificError); + should.not.throw(ickyErrFn, specificError); + expect(specificErrFn).to.throw(specificError); + specificErrFn.should.throw(specificError); + should.throw(ickyErrFn, specificError); + + expect(badFn).to.throw(/testing/); + badFn.should.throw(/testing/); + should.throw(badFn, /testing/); + expect(badFn).to.not.throw(/hello/); + badFn.should.not.throw(/hello/); + should.not.throw(badFn, /hello/); + expect(badFn).to.throw('testing'); + badFn.should.throw('testing'); + should.throw(badFn, 'testing'); + expect(badFn).to.not.throw('hello'); + badFn.should.not.throw('hello'); + should.not.throw(badFn, 'hello'); + + expect(badFn).to.throw(Error, /testing/); + badFn.should.throw(Error, /testing/); + should.throw(badFn, Error, /testing/); + expect(badFn).to.throw(Error, 'testing'); + badFn.should.throw(Error, 'testing'); + should.throw(badFn, Error, 'testing'); + + err(() => { + expect(goodFn).to.throw(); + goodFn.should.throw(); + should.throw(goodFn); + }, 'expected [Function] to throw an error'); + + err(() => { + expect(goodFn).to.throw(ReferenceError); + goodFn.should.throw(ReferenceError); + should.throw(goodFn, ReferenceError); + }, 'expected [Function] to throw ReferenceError'); + + err(() => { + expect(goodFn).to.throw(specificError); + goodFn.should.throw(specificError); + should.throw(goodFn, specificError); + }, 'expected [Function] to throw [RangeError: boo]'); + + err(() => { + expect(badFn).to.not.throw(); + badFn.should.not.throw(); + should.not.throw(badFn); + }, 'expected [Function] to not throw an error but [Error: testing] was thrown'); + + err(() => { + expect(badFn).to.throw(ReferenceError); + badFn.should.throw(ReferenceError); + should.throw(badFn, ReferenceError); + }, 'expected [Function] to throw \'ReferenceError\' but [Error: testing] was thrown'); + + err(() => { + expect(badFn).to.throw(specificError); + badFn.should.throw(specificError); + should.throw(badFn, specificError); + }, 'expected [Function] to throw [RangeError: boo] but [Error: testing] was thrown'); + + err(() => { + expect(badFn).to.not.throw(Error); + badFn.should.not.throw(Error); + should.not.throw(badFn, Error); + }, 'expected [Function] to not throw \'Error\' but [Error: testing] was thrown'); + + err(() => { + expect(refErrFn).to.not.throw(ReferenceError); + refErrFn.should.not.throw(ReferenceError); + should.not.throw(refErrFn, ReferenceError); + }, 'expected [Function] to not throw \'ReferenceError\' but [ReferenceError: hello] was thrown'); + + err(() => { + expect(badFn).to.throw(PoorlyConstructedError); + badFn.should.throw(PoorlyConstructedError); + should.throw(badFn, PoorlyConstructedError); + }, 'expected [Function] to throw \'PoorlyConstructedError\' but [Error: testing] was thrown'); + + err(() => { + expect(ickyErrFn).to.not.throw(PoorlyConstructedError); + ickyErrFn.should.not.throw(PoorlyConstructedError); + should.not.throw(ickyErrFn, PoorlyConstructedError); + }, /^(expected \[Function\] to not throw 'PoorlyConstructedError' but)(.*)(PoorlyConstructedError|\{ Object \()(.*)(was thrown)$/); + + err(() => { + expect(ickyErrFn).to.throw(ReferenceError); + ickyErrFn.should.throw(ReferenceError); + should.throw(ickyErrFn, ReferenceError); + }, /^(expected \[Function\] to throw 'ReferenceError' but)(.*)(PoorlyConstructedError|\{ Object \()(.*)(was thrown)$/); + + err(() => { + expect(specificErrFn).to.throw(new ReferenceError('eek')); + specificErrFn.should.throw(new ReferenceError('eek')); + should.throw(specificErrFn, new ReferenceError('eek')); + }, 'expected [Function] to throw [ReferenceError: eek] but [RangeError: boo] was thrown'); + + err(() => { + expect(specificErrFn).to.not.throw(specificError); + specificErrFn.should.not.throw(specificError); + should.not.throw(specificErrFn, specificError); + }, 'expected [Function] to not throw [RangeError: boo]'); + + err(() => { + expect(badFn).to.not.throw(/testing/); + badFn.should.not.throw(/testing/); + should.not.throw(badFn, /testing/); + }, 'expected [Function] to throw error not matching /testing/'); + + err(() => { + expect(badFn).to.throw(/hello/); + badFn.should.throw(/hello/); + should.throw(badFn, /hello/); + }, 'expected [Function] to throw error matching /hello/ but got \'testing\''); + + err(() => { + expect(badFn).to.throw(Error, /hello/, 'blah'); + badFn.should.throw(Error, /hello/, 'blah'); + should.throw(badFn, Error, /hello/, 'blah'); + }, 'blah: expected [Function] to throw error matching /hello/ but got \'testing\''); + + err(() => { + expect(badFn).to.throw(Error, 'hello', 'blah'); + badFn.should.throw(Error, 'hello', 'blah'); + should.throw(badFn, Error, 'hello', 'blah'); + }, 'blah: expected [Function] to throw error including \'hello\' but got \'testing\''); +} + +function use() { + // ReSharper disable once InconsistentNaming + chai.use((_chai) => { + _chai.can.use.any(); + }); +} + +class Klass { + val: number; + constructor() { this.val = 0; } + bar() { } + + static baz() { } +} + +function respondTo() { + var obj = new Klass(); + + expect(Klass).to.respondTo('bar'); + expect(obj).respondsTo('bar'); + Klass.should.respondTo('bar'); + Klass.should.respondsTo('bar'); + expect(Klass).to.not.respondTo('foo'); + Klass.should.not.respondTo('foo'); + expect(Klass).itself.to.respondTo('func'); + expect(Klass).itself.not.to.respondTo('bar'); + + expect(obj).not.to.respondTo('foo'); + obj.should.not.respondTo('foo'); + + err(() => { + expect(Klass).to.respondTo('baz', 'constructor'); + Klass.should.respondTo('baz', 'constructor'); + }, /^(constructor: expected)(.*)(\[Function: Klass\])(.*)(to respond to \'baz\')$/); + + err(() => { + expect(obj).to.respondTo('baz', 'object'); + obj.should.respondTo('baz', 'object'); + }, /^(object: expected)(.*)(\{ foo: \[Function\] \}|\{ Object \()(.*)(to respond to \'baz\')$/); +} + +function satisfy() { + function matcher(num: number) { + return num === 1; + } + + expect(1).to.satisfy(matcher); + (1).should.satisfy(matcher); + + err(() => { + expect(2).to.satisfy(matcher, 'blah'); + (2).should.satisfy(matcher, 'blah'); + }, 'blah: expected 2 to satisfy [Function: matcher]'); +} + +function closeTo() { + expect(1.5).to.be.closeTo(1.0, 0.5); + (1.5).should.be.closeTo(1.0, 0.5); + expect(10).to.be.closeTo(20, 20); + (10).should.be.closeTo(20, 20); + expect(-10).to.be.closeTo(20, 30); + (-10).should.be.closeTo(20, 30); + + err(() => { + expect(2).to.be.closeTo(1.0, 0.5, 'blah'); + (2).should.be.closeTo(1.0, 0.5, 'blah'); + }, 'blah: expected 2 to be close to 1 +/- 0.5'); + + err(() => { + expect(-10).to.be.closeTo(20, 29, 'blah'); + (-10).should.be.closeTo(20, 29, 'blah'); + }, 'blah: expected -10 to be close to 20 +/- 29'); +} + +function includeMembers() { + expect([1, 2, 3]).to.include.members([]); + [1, 2, 3].should.include.members([]); + + expect([1, 2, 3]).to.include.members([3, 2]); + + [1, 2, 3].should.include.members([3, 2]); + + expect([1, 2, 3]).to.not.include.members([8, 4]); + + [1, 2, 3].should.not.include.members([8, 4]); + + expect([1, 2, 3]).to.not.include.members([1, 2, 3, 4]); + + [1, 2, 3].should.not.include.members([1, 2, 3, 4]); +} + +function sameMembers() { + expect([5, 4]).to.have.same.members([4, 5]); + [5, 4].should.have.same.members([4, 5]); + expect([5, 4]).to.have.same.members([5, 4]); + [5, 4].should.have.same.members([5, 4]); + + expect([5, 4]).to.not.have.same.members([]); + [5, 4].should.not.have.same.members([]); + expect([5, 4]).to.not.have.same.members([6, 3]); + [5, 4].should.not.have.same.members([6, 3]); + expect([5, 4]).to.not.have.same.members([5, 4, 2]); + [5, 4].should.not.have.same.members([5, 4, 2]); + + assert.sameMembers([5, 4], [4, 5]); +} +function sameDeepMembers() { + expect([{ id: 5 }, { id: 4 }]).to.have.same.deep.members([{ id: 4 }, { id: 5 }]); + [{ id: 5 }, { id: 4 }].should.have.same.deep.members([{ id: 4 }, { id: 5 }]); + expect([{ id: 5 }, { id: 4 }]).to.have.same.members([{ id: 5 }, { id: 4 }]); + [{ id: 5 }, { id: 4 }].should.have.same.members([{ id: 5 }, { id: 4 }]); + + expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([]); + [{ id: 5 }, { id: 4 }].should.not.have.same.members([]); + expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([{ id: 6 }, { id: 3 }]); + [{ id: 5 }, { id: 4 }].should.not.have.same.members([{ id: 6 }, { id: 3 }]); + expect([{ id: 5 }, { id: 4 }]).to.not.have.same.members([{ id: 5 }, { id: 4 }, { id: 2 }]); + [{ id: 5 }, { id: 4 }].should.not.have.same.members([{ id: 5 }, { id: 4 }, { id: 2 }]); + + assert.sameDeepMembers([{ id: 5 }, { id: 4 }], [{ id: 4 }, { id: 5 }]); +} + +function members() { + expect([5, 4]).members([4, 5]); + expect([5, 4]).members([5, 4]); + + expect([5, 4]).not.members([]); + expect([5, 4]).not.members([6, 3]); + expect([5, 4]).not.members([5, 4, 2]); +} + +function increaseDecreaseChange() { + var obj = { val: 10 }; + var inc = () => { obj.val++; }; + var dec = () => { obj.val--; }; + var same = () => { }; + + expect(inc).to.increase(obj, "val"); + expect(inc).increases(obj, "val"); + expect(inc).to.change(obj, "val"); + + expect(dec).to.decrease(obj, "val"); + expect(dec).decreases(obj, "val"); + expect(dec).to.change(obj, "val"); + expect(dec).changes(obj, "val"); + + expect(inc).to.not.decrease(obj, "val"); + expect(dec).to.not.increase(obj, "val"); + expect(same).to.not.increase(obj, "val"); + expect(same).to.not.decrease(obj, "val"); + expect(same).to.not.change(obj, "val"); + + inc.should.increase(obj, "val"); + inc.should.change(obj, "val"); + + dec.should.decrease(obj, "val"); + dec.should.change(obj, "val"); + + inc.should.not.decrease(obj, "val"); + dec.should.not.increase(obj, "val"); + same.should.not.change(obj, "val"); +} + +//tdd +declare function suite(description: string, action: Function): void; +declare function test(description: string, action: Function): void; + +interface FieldObj { + field: any; +} + +class CrashyObject { + inspect(): void { + throw new Error('Arg\'s inspect() called even though the test passed'); + } +} + +suite('assert', () => { + + test('assert', () => { + var foo = 'bar'; + assert(foo === 'bar', 'expected foo to equal `bar`'); + + err(() => { + assert(foo === 'baz', 'expected foo to equal `bar`'); + }, 'expected foo to equal `bar`'); + }); + + test('isTrue', () => { + assert.isTrue(true); + + err(() => { + assert.isTrue(false); + }, 'expected false to be true'); + + err(() => { + assert.isTrue(1); + }, 'expected 1 to be true'); + + err(() => { + assert.isTrue('test'); + }, 'expected \'test\' to be true'); + }); + + test('ok', () => { + assert.ok(true); + assert.ok(1); + assert.ok('test'); + assert.isOk(true); + assert.isOk(1); + assert.isOk('test'); + + err(() => { + assert.ok(false); + }, 'expected false to be truthy'); + + err(() => { + assert.ok(0); + }, 'expected 0 to be truthy'); + + err(() => { + assert.ok(''); + }, 'expected \'\' to be truthy'); + }); + + test('notOk', () => { + assert.notOk(false); + assert.notOk(0); + assert.notOk(''); + assert.isNotOk(false); + assert.isNotOk(0); + assert.isNotOk(''); + + err(() => { + assert.notOk(true); + }, 'expected true to be falsy'); + + err(() => { + assert.notOk(1); + }, 'expected 1 to be falsy'); + + err(() => { + assert.notOk('test'); + }, 'expected \'test\' to be falsy'); + }); + + test('isFalse', () => { + assert.isFalse(false); + + err(() => { + assert.isFalse(true); + }, 'expected true to be false'); + + err(() => { + assert.isFalse(0); + }, 'expected 0 to be false'); + }); + + test('equal', () => { + assert.equal(void (0), undefined); + }); + + test('typeof / notTypeOf', () => { + assert.typeOf('test', 'string'); + assert.typeOf(true, 'boolean'); + assert.typeOf(5, 'number'); + + err(() => { + assert.typeOf(5, 'string'); + }, 'expected 5 to be a string'); + + }); + + test('notTypeOf', () => { + assert.notTypeOf('test', 'number'); + + err(() => { + assert.notTypeOf(5, 'number'); + }, 'expected 5 not to be a number'); + }); + + test('instanceOf', () => { + assert.instanceOf(new Foo(), Foo); + + err(() => { + assert.instanceOf(5, Foo); + }, 'expected 5 to be an instance of Foo'); + assert.instanceOf(new CrashyObject(), CrashyObject); + }); + + test('notInstanceOf', () => { + assert.notInstanceOf(new Foo(), String); + + err(() => { + assert.notInstanceOf(new Foo(), Foo); + }, 'expected {} to not be an instance of Foo'); + }); + + test('isObject', () => { + assert.isObject({}); + assert.isObject(new Foo()); + + err(() => { + assert.isObject(true); + }, 'expected true to be an object'); + + err(() => { + assert.isObject(Foo); + }, 'expected [Function: Foo] to be an object'); + + err(() => { + assert.isObject('foo'); + }, 'expected \'foo\' to be an object'); + }); + + test('isNotObject', () => { + assert.isNotObject(5); + + err(() => { + assert.isNotObject({}); + }, 'expected {} not to be an object'); + }); + + test('notEqual', () => { + assert.notEqual(3, 4); + + err(() => { + assert.notEqual(5, 5); + }, 'expected 5 to not equal 5'); + }); + + test('strictEqual', () => { + assert.strictEqual('foo', 'foo'); + + err(() => { + assert.strictEqual('5', 5); + }, 'expected \'5\' to equal 5'); + }); + + test('notStrictEqual', () => { + assert.notStrictEqual(5, '5'); + + err(() => { + assert.notStrictEqual(5, 5); + }, 'expected 5 to not equal 5'); + }); + + test('deepEqual', () => { + assert.deepEqual({ tea: 'chai' }, { tea: 'chai' }); + + err(() => { + assert.deepEqual({ tea: 'chai' }, { tea: 'black' }); + }, 'expected { tea: \'chai\' } to deeply equal { tea: \'black\' }'); + + var obja = Object.create({ tea: 'chai' }) + , objb = Object.create({ tea: 'chai' }); + + assert.deepEqual(obja, objb); + + var obj1 = Object.create({ tea: 'chai' }) + , obj2 = Object.create({ tea: 'black' }); + + err(() => { + assert.deepEqual(obj1, obj2); + }, 'expected { tea: \'chai\' } to deeply equal { tea: \'black\' }'); + }); + + test('deepEqual (ordering)', () => { + var a = { a: 'b', c: 'd' } + , b = { c: 'd', a: 'b' }; + assert.deepEqual(a, b); + }); + + test('deepEqual (circular)', () => { + var circularObject: any = {} + , secondCircularObject: any = {}; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.deepEqual(circularObject, secondCircularObject); + + err(() => { + secondCircularObject.field2 = secondCircularObject; + assert.deepEqual(circularObject, secondCircularObject); + }, 'expected { field: [Circular] } to deeply equal { Object (field, field2) }'); + }); + + test('notDeepEqual', () => { + assert.notDeepEqual({ tea: 'jasmine' }, { tea: 'chai' }); + err(() => { + assert.notDeepEqual({ tea: 'chai' }, { tea: 'chai' }); + }, 'expected { tea: \'chai\' } to not deeply equal { tea: \'chai\' }'); + }); + + test('notDeepEqual (circular)', () => { + var circularObject: any = {} + , secondCircularObject: any = { tea: 'jasmine' }; + circularObject.field = circularObject; + secondCircularObject.field = secondCircularObject; + + assert.notDeepEqual(circularObject, secondCircularObject); + + err(() => { + delete secondCircularObject.tea; + assert.notDeepEqual(circularObject, secondCircularObject); + }, 'expected { field: [Circular] } to not deeply equal { field: [Circular] }'); + }); + + test('isNull', () => { + assert.isNull(null); + + err(() => { + assert.isNull(undefined); + }, 'expected undefined to equal null'); + }); + + test('isNotNull', () => { + assert.isNotNull(undefined); + + err(() => { + assert.isNotNull(null); + }, 'expected null to not equal null'); + }); + + test('isUndefined', () => { + assert.isUndefined(undefined); + + err(() => { + assert.isUndefined(null); + }, 'expected null to equal undefined'); + }); + + test('isDefined', () => { + assert.isDefined(null); + + err(() => { + assert.isDefined(undefined); + }, 'expected undefined to not equal undefined'); + }); + + test('isNaN', () => { + assert.isNaN(NaN); + + err(() => { + assert.isNaN(12); + }, 'expected 12 to be NaN'); + }); + + test('isNotNaN', () => { + assert.isNotNaN(12); + + err(() => { + assert.isNotNaN(NaN); + }, 'expected NaN to not NaN'); + }); + + test('isFunction', () => { + var func = () => { + }; + assert.isFunction(func); + + err(() => { + assert.isFunction({}); + }, 'expected {} to be a function'); + }); + + test('isNotFunction', () => { + assert.isNotFunction(5); + + err(() => { + assert.isNotFunction(() => { + }); + }, 'expected [Function] not to be a function'); + }); + + test('isArray', () => { + assert.isArray([]); + assert.isArray(new Array()); + + err(() => { + assert.isArray({}); + }, 'expected {} to be an array'); + }); + + test('isNotArray', () => { + assert.isNotArray(3); + + err(() => { + assert.isNotArray([]); + }, 'expected [] not to be an array'); + + err(() => { + assert.isNotArray(new Array()); + }, 'expected [] not to be an array'); + }); + + test('isString', () => { + assert.isString('Foo'); + assert.isString(new String('foo')); + + err(() => { + assert.isString(1); + }, 'expected 1 to be a string'); + }); + + test('isNotString', () => { + assert.isNotString(3); + assert.isNotString(['hello']); + + err(() => { + assert.isNotString('hello'); + }, 'expected \'hello\' not to be a string'); + }); + + test('isNumber', () => { + assert.isNumber(1); + assert.isNumber(Number('3')); + + err(() => { + assert.isNumber('1'); + }, 'expected \'1\' to be a number'); + }); + + test('isNotNumber', () => { + assert.isNotNumber('hello'); + assert.isNotNumber([5]); + + err(() => { + assert.isNotNumber(4); + }, 'expected 4 not to be a number'); + }); + + test('isBoolean', () => { + assert.isBoolean(true); + assert.isBoolean(false); + + err(() => { + assert.isBoolean('1'); + }, 'expected \'1\' to be a boolean'); + }); + + test('isNotBoolean', () => { + assert.isNotBoolean('true'); + + err(() => { + assert.isNotBoolean(true); + }, 'expected true not to be a boolean'); + + err(() => { + assert.isNotBoolean(false); + }, 'expected false not to be a boolean'); + }); + + test('include', () => { + assert.include('foobar', 'bar'); + assert.include([1, 2, 3], 3); + + err(() => { + assert.include('foobar', 'baz'); + }, 'expected \'foobar\' to contain \'baz\''); + + err(() => { + assert.include(undefined, 'bar'); + }, 'expected an array or string'); + }); + + test('notInclude', () => { + assert.notInclude('foobar', 'baz'); + assert.notInclude([1, 2, 3], 4); + + err(() => { + assert.notInclude('foobar', 'bar'); + }, 'expected \'foobar\' to not contain \'bar\''); + + err(() => { + assert.notInclude(undefined, 'bar'); + }, 'expected an array or string'); + }); + + test('lengthOf', () => { + assert.lengthOf([1, 2, 3], 3); + assert.lengthOf('foobar', 6); + + err(() => { + assert.lengthOf('foobar', 5); + }, 'expected \'foobar\' to have a length of 5 but got 6'); + + err(() => { + assert.lengthOf(1, 5); + }, 'expected 1 to have a property \'length\''); + }); + + test('match', () => { + assert.match('foobar', /^foo/); + assert.notMatch('foobar', /^bar/); + + err(() => { + assert.match('foobar', /^bar/i); + }, 'expected \'foobar\' to match /^bar/i'); + + err(() => { + assert.notMatch('foobar', /^foo/i); + }, 'expected \'foobar\' not to match /^foo/i'); + }); + + test('property', () => { + var obj = { foo: { bar: 'baz' } }; + var simpleObj = { foo: 'bar' }; + assert.property(obj, 'foo'); + assert.deepProperty(obj, 'foo.bar'); + assert.notProperty(obj, 'baz'); + assert.notProperty(obj, 'foo.bar'); + assert.notDeepProperty(obj, 'foo.baz'); + assert.deepPropertyVal(obj, 'foo.bar', 'baz'); + assert.deepPropertyNotVal(obj, 'foo.bar', 'flow'); + + err(() => { + assert.property(obj, 'baz'); + }, 'expected { foo: { bar: \'baz\' } } to have a property \'baz\''); + + err(() => { + assert.deepProperty(obj, 'foo.baz'); + }, 'expected { foo: { bar: \'baz\' } } to have a deep property \'foo.baz\''); + + err(() => { + assert.notProperty(obj, 'foo'); + }, 'expected { foo: { bar: \'baz\' } } to not have property \'foo\''); + + err(() => { + assert.notDeepProperty(obj, 'foo.bar'); + }, 'expected { foo: { bar: \'baz\' } } to not have deep property \'foo.bar\''); + + err(() => { + assert.propertyVal(simpleObj, 'foo', 'ball'); + }, 'expected { foo: \'bar\' } to have a property \'foo\' of \'ball\', but got \'bar\''); + + err(() => { + assert.deepPropertyVal(obj, 'foo.bar', 'ball'); + }, 'expected { foo: { bar: \'baz\' } } to have a deep property \'foo.bar\' of \'ball\', but got \'baz\''); + + err(() => { + assert.propertyNotVal(simpleObj, 'foo', 'bar'); + }, 'expected { foo: \'bar\' } to not have a property \'foo\' of \'bar\''); + + err(() => { + assert.deepPropertyNotVal(obj, 'foo.bar', 'baz'); + }, 'expected { foo: { bar: \'baz\' } } to not have a deep property \'foo.bar\' of \'baz\''); + }); + + test('throws', () => { + assert.throws(() => { + throw new Error('foo'); + }); + assert.throws(() => { + throw new Error('bar'); + }, 'bar'); + assert.throws(() => { + throw new Error('bar'); + }, /bar/); + assert.throws(() => { + throw new Error('bar'); + }, Error); + assert.throws(() => { + throw new Error('bar'); + }, Error, 'bar'); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, TypeError); + }, 'expected [Function] to throw \'TypeError\' but [Error: foo] was thrown'); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'foo\''); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, Error, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'foo\''); + + err(() => { + assert.throws(() => { + throw new Error('foo'); + }, TypeError, 'bar'); + }, 'expected [Function] to throw \'TypeError\' but [Error: foo] was thrown'); + + err(() => { + assert.throws(() => { + }); + }, 'expected [Function] to throw an error'); + + err(() => { + assert.throws(() => { + throw new Error(''); + }, 'bar'); + }, 'expected [Function] to throw error including \'bar\' but got \'\''); + + err(() => { + assert.throws(() => { + throw new Error(''); + }, /bar/); + }, 'expected [Function] to throw error matching /bar/ but got \'\''); + }); + + test('doesNotThrow', () => { + assert.doesNotThrow(() => { + }); + assert.doesNotThrow(() => { + }, 'foo'); + + err(() => { + assert.doesNotThrow(() => { + throw new Error('foo'); + }); + }, 'expected [Function] to not throw an error but [Error: foo] was thrown'); + }); + + test('ifError', () => { + assert.ifError(false); + assert.ifError(null); + assert.ifError(undefined); + + err(() => { + assert.ifError('foo'); + }, 'expected \'foo\' to be falsy'); + }); + + test('operator', () => { + assert.operator(1, '<', 2); + assert.operator(2, '>', 1); + assert.operator(1, '==', 1); + assert.operator(1, '<=', 1); + assert.operator(1, '>=', 1); + assert.operator(1, '!=', 2); + assert.operator(1, '!==', 2); + + err(() => { + assert.operator(1, '=', 2); + }, 'Invalid operator "="'); + + err(() => { + assert.operator(2, '<', 1); + }, 'expected 2 to be < 1'); + + err(() => { + assert.operator(1, '>', 2); + }, 'expected 1 to be > 2'); + + err(() => { + assert.operator(1, '==', 2); + }, 'expected 1 to be == 2'); + + err(() => { + assert.operator(2, '<=', 1); + }, 'expected 2 to be <= 1'); + + err(() => { + assert.operator(1, '>=', 2); + }, 'expected 1 to be >= 2'); + + err(() => { + assert.operator(1, '!=', 1); + }, 'expected 1 to be != 1'); + + err(() => { + assert.operator(1, '!==', '1'); + }, 'expected 1 to be !== \'1\''); + }); + + test('closeTo', () => { + assert.closeTo(1.5, 1.0, 0.5); + assert.closeTo(10, 20, 20); + assert.closeTo(-10, 20, 30); + + err(() => { + assert.closeTo(2, 1.0, 0.5); + }, 'expected 2 to be close to 1 +/- 0.5'); + + err(() => { + assert.closeTo(-10, 20, 29); + }, 'expected -10 to be close to 20 +/- 29'); + }); + + test('members', () => { + assert.includeMembers([1, 2, 3], [2, 3]); + assert.includeMembers([1, 2, 3], []); + assert.includeMembers([1, 2, 3], [3]); + + err(() => { + assert.includeMembers([5, 6], [7, 8]); + }, 'expected [ 5, 6 ] to be a superset of [ 7, 8 ]'); + + err(() => { + assert.includeMembers([5, 6], [5, 6, 0]); + }, 'expected [ 5, 6 ] to be a superset of [ 5, 6, 0 ]'); + }); + + test('memberEquals', () => { + assert.sameMembers([], []); + assert.sameMembers([1, 2, 3], [3, 2, 1]); + assert.sameMembers([4, 2], [4, 2]); + + err(() => { + assert.sameMembers([], [1, 2]); + }, 'expected [] to have the same members as [ 1, 2 ]'); + + err(() => { + assert.sameMembers([1, 54], [6, 1, 54]); + }, 'expected [ 1, 54 ] to have the same members as [ 6, 1, 54 ]'); + }); + + + test('isAbove', () => { + assert.isAbove(10, 5); + + err(() => { + assert.isAbove(1, 5); + }, 'expected 1 to be above 5'); + err(() => { + assert.isAbove(5, 5); + }, 'expected 5 to be above 5'); + }); + + test('isBelow', () => { + assert.isBelow(5, 10); + + err(() => { + assert.isBelow(5, 1); + }, 'expected 5 to be above 1'); + err(() => { + assert.isBelow(5, 5); + }, 'expected 5 to be below 5'); + }); + + test('extensible', () => { assert.extensible({}); }); + test('isExtensible', () => { assert.isExtensible({}); }); + test('notExtensible', () => { assert.notExtensible(Object.preventExtensions({})); }); + test('isNotExtensible', () => { assert.isNotExtensible(Object.preventExtensions({})); }); + + test('sealed', () => { assert.sealed(Object.seal({})); }); + test('isSealed', () => { assert.isSealed(Object.seal({})); }); + test('notSealed', () => { assert.notSealed({}); }); + test('isNotSealed', () => { assert.isNotSealed({}); }); + + test('frozen', () => { assert.frozen(Object.freeze({})); }); + test('isFrozen', () => { assert.isFrozen(Object.freeze({})); }); + test('notFrozen', () => { assert.notFrozen({}); }); + test('isNotFrozen', () => { assert.isNotFrozen({}); }); + +}); diff --git a/chai/chai-3.2.0.d.ts b/chai/chai-3.2.0.d.ts new file mode 100644 index 0000000000..e68e6fa3b4 --- /dev/null +++ b/chai/chai-3.2.0.d.ts @@ -0,0 +1,388 @@ +// Type definitions for chai 3.2.0 +// Project: http://chaijs.com/ +// Definitions by: Jed Mao , +// Bart van der Schoor , +// Andrew Brown , +// Olivier Chevet +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// + +declare module Chai { + + interface ChaiStatic { + expect: ExpectStatic; + should(): Should; + /** + * Provides a way to extend the internals of Chai + */ + use(fn: (chai: any, utils: any) => void): any; + assert: AssertStatic; + config: Config; + AssertionError: typeof AssertionError; + } + + export interface ExpectStatic extends AssertionStatic { + fail(actual?: any, expected?: any, message?: string, operator?: string): void; + } + + export interface AssertStatic extends Assert { + } + + export interface AssertionStatic { + (target: any, message?: string): Assertion; + } + + interface ShouldAssertion { + equal(value1: any, value2: any, message?: string): void; + Throw: ShouldThrow; + throw: ShouldThrow; + exist(value: any, message?: string): void; + } + + interface Should extends ShouldAssertion { + not: ShouldAssertion; + fail(actual: any, expected: any, message?: string, operator?: string): void; + } + + interface ShouldThrow { + (actual: Function): void; + (actual: Function, expected: string|RegExp, message?: string): void; + (actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + not: Assertion; + deep: Deep; + any: KeyFilter; + all: KeyFilter; + a: TypeComparison; + an: TypeComparison; + include: Include; + includes: Include; + contain: Include; + contains: Include; + ok: Assertion; + true: Assertion; + false: Assertion; + null: Assertion; + undefined: Assertion; + NaN: Assertion; + exist: Assertion; + empty: Assertion; + arguments: Assertion; + Arguments: Assertion; + equal: Equal; + equals: Equal; + eq: Equal; + eql: Equal; + eqls: Equal; + property: Property; + ownProperty: OwnProperty; + haveOwnProperty: OwnProperty; + ownPropertyDescriptor: OwnPropertyDescriptor; + haveOwnPropertyDescriptor: OwnPropertyDescriptor; + length: Length; + lengthOf: Length; + match: Match; + matches: Match; + string(string: string, message?: string): Assertion; + keys: Keys; + key(string: string): Assertion; + throw: Throw; + throws: Throw; + Throw: Throw; + respondTo: RespondTo; + respondsTo: RespondTo; + itself: Assertion; + satisfy: Satisfy; + satisfies: Satisfy; + closeTo(expected: number, delta: number, message?: string): Assertion; + members: Members; + increase: PropertyChange; + increases: PropertyChange; + decrease: PropertyChange; + decreases: PropertyChange; + change: PropertyChange; + changes: PropertyChange; + extensible: Assertion; + sealed: Assertion; + frozen: Assertion; + + } + + interface LanguageChains { + to: Assertion; + be: Assertion; + been: Assertion; + is: Assertion; + that: Assertion; + which: Assertion; + and: Assertion; + has: Assertion; + have: Assertion; + with: Assertion; + at: Assertion; + of: Assertion; + same: Assertion; + } + + interface NumericComparison { + above: NumberComparer; + gt: NumberComparer; + greaterThan: NumberComparer; + least: NumberComparer; + gte: NumberComparer; + below: NumberComparer; + lt: NumberComparer; + lessThan: NumberComparer; + most: NumberComparer; + lte: NumberComparer; + within(start: number, finish: number, message?: string): Assertion; + } + + interface NumberComparer { + (value: number, message?: string): Assertion; + } + + interface TypeComparison { + (type: string, message?: string): Assertion; + instanceof: InstanceOf; + instanceOf: InstanceOf; + } + + interface InstanceOf { + (constructor: Object, message?: string): Assertion; + } + + interface Deep { + equal: Equal; + include: Include; + property: Property; + members: Members; + } + + interface KeyFilter { + keys: Keys; + } + + interface Equal { + (value: any, message?: string): Assertion; + } + + interface Property { + (name: string, value?: any, message?: string): Assertion; + } + + interface OwnProperty { + (name: string, message?: string): Assertion; + } + + interface OwnPropertyDescriptor { + (name: string, descriptor: PropertyDescriptor, message?: string): Assertion; + (name: string, message?: string): Assertion; + } + + interface Length extends LanguageChains, NumericComparison { + (length: number, message?: string): Assertion; + } + + interface Include { + (value: Object, message?: string): Assertion; + (value: string, message?: string): Assertion; + (value: number, message?: string): Assertion; + keys: Keys; + members: Members; + any: KeyFilter; + all: KeyFilter; + } + + interface Match { + (regexp: RegExp|string, message?: string): Assertion; + } + + interface Keys { + (...keys: string[]): Assertion; + (keys: any[]): Assertion; + (keys: Object): Assertion; + } + + interface Throw { + (): Assertion; + (expected: string, message?: string): Assertion; + (expected: RegExp, message?: string): Assertion; + (constructor: Error, expected?: string, message?: string): Assertion; + (constructor: Error, expected?: RegExp, message?: string): Assertion; + (constructor: Function, expected?: string, message?: string): Assertion; + (constructor: Function, expected?: RegExp, message?: string): Assertion; + } + + interface RespondTo { + (method: string, message?: string): Assertion; + } + + interface Satisfy { + (matcher: Function, message?: string): Assertion; + } + + interface Members { + (set: any[], message?: string): Assertion; + } + + interface PropertyChange { + (object: Object, prop: string, msg?: string): Assertion; + } + + export interface Assert { + /** + * @param expression Expression to test for truthiness. + * @param message Message to display on error. + */ + (expression: any, message?: string): void; + + fail(actual?: any, expected?: any, msg?: string, operator?: string): void; + + ok(val: any, msg?: string): void; + isOk(val: any, msg?: string): void; + notOk(val: any, msg?: string): void; + isNotOk(val: any, msg?: string): void; + + equal(act: any, exp: any, msg?: string): void; + notEqual(act: any, exp: any, msg?: string): void; + + strictEqual(act: any, exp: any, msg?: string): void; + notStrictEqual(act: any, exp: any, msg?: string): void; + + deepEqual(act: any, exp: any, msg?: string): void; + notDeepEqual(act: any, exp: any, msg?: string): void; + + isTrue(val: any, msg?: string): void; + isFalse(val: any, msg?: string): void; + + isNull(val: any, msg?: string): void; + isNotNull(val: any, msg?: string): void; + + isUndefined(val: any, msg?: string): void; + isDefined(val: any, msg?: string): void; + + isNaN(val: any, msg?: string): void; + isNotNaN(val: any, msg?: string): void; + + isAbove(val: number, abv: number, msg?: string): void; + isBelow(val: number, blw: number, msg?: string): void; + + isFunction(val: any, msg?: string): void; + isNotFunction(val: any, msg?: string): void; + + isObject(val: any, msg?: string): void; + isNotObject(val: any, msg?: string): void; + + isArray(val: any, msg?: string): void; + isNotArray(val: any, msg?: string): void; + + isString(val: any, msg?: string): void; + isNotString(val: any, msg?: string): void; + + isNumber(val: any, msg?: string): void; + isNotNumber(val: any, msg?: string): void; + + isBoolean(val: any, msg?: string): void; + isNotBoolean(val: any, msg?: string): void; + + typeOf(val: any, type: string, msg?: string): void; + notTypeOf(val: any, type: string, msg?: string): void; + + instanceOf(val: any, type: Function, msg?: string): void; + notInstanceOf(val: any, type: Function, msg?: string): void; + + include(exp: string, inc: any, msg?: string): void; + include(exp: any[], inc: any, msg?: string): void; + + notInclude(exp: string, inc: any, msg?: string): void; + notInclude(exp: any[], inc: any, msg?: string): void; + + match(exp: any, re: RegExp, msg?: string): void; + notMatch(exp: any, re: RegExp, msg?: string): void; + + property(obj: Object, prop: string, msg?: string): void; + notProperty(obj: Object, prop: string, msg?: string): void; + deepProperty(obj: Object, prop: string, msg?: string): void; + notDeepProperty(obj: Object, prop: string, msg?: string): void; + + propertyVal(obj: Object, prop: string, val: any, msg?: string): void; + propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void; + deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void; + + lengthOf(exp: any, len: number, msg?: string): void; + //alias frenzy + throw(fn: Function, msg?: string): void; + throw(fn: Function, regExp: RegExp): void; + throw(fn: Function, errType: Function, msg?: string): void; + throw(fn: Function, errType: Function, regExp: RegExp): void; + + throws(fn: Function, msg?: string): void; + throws(fn: Function, regExp: RegExp): void; + throws(fn: Function, errType: Function, msg?: string): void; + throws(fn: Function, errType: Function, regExp: RegExp): void; + + Throw(fn: Function, msg?: string): void; + Throw(fn: Function, regExp: RegExp): void; + Throw(fn: Function, errType: Function, msg?: string): void; + Throw(fn: Function, errType: Function, regExp: RegExp): void; + + doesNotThrow(fn: Function, msg?: string): void; + doesNotThrow(fn: Function, regExp: RegExp): void; + doesNotThrow(fn: Function, errType: Function, msg?: string): void; + doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void; + + operator(val: any, operator: string, val2: any, msg?: string): void; + closeTo(act: number, exp: number, delta: number, msg?: string): void; + + sameMembers(set1: any[], set2: any[], msg?: string): void; + sameDeepMembers(set1: any[], set2: any[], msg?: string): void; + includeMembers(superset: any[], subset: any[], msg?: string): void; + + ifError(val: any, msg?: string): void; + + isExtensible(obj: {}, msg?: string): void; + extensible(obj: {}, msg?: string): void; + isNotExtensible(obj: {}, msg?: string): void; + notExtensible(obj: {}, msg?: string): void; + + isSealed(obj: {}, msg?: string): void; + sealed(obj: {}, msg?: string): void; + isNotSealed(obj: {}, msg?: string): void; + notSealed(obj: {}, msg?: string): void; + + isFrozen(obj: Object, msg?: string): void; + frozen(obj: Object, msg?: string): void; + isNotFrozen(obj: Object, msg?: string): void; + notFrozen(obj: Object, msg?: string): void; + + + } + + export interface Config { + includeStack: boolean; + } + + export class AssertionError { + constructor(message: string, _props?: any, ssf?: Function); + name: string; + message: string; + showDiff: boolean; + stack: string; + } +} + +declare var chai: Chai.ChaiStatic; + +declare module "chai" { + export = chai; +} + +interface Object { + should: Chai.Assertion; +} diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index 9b646b1529..df09aea3e7 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -1166,6 +1166,25 @@ function closeTo() { }, 'blah: expected -10 to be close to 20 +/- 29'); } +function approximately() { + expect(1.5).to.be.approximately(1.0, 0.5); + (1.5).should.be.approximately(1.0, 0.5); + expect(10).to.be.approximately(20, 20); + (10).should.be.approximately(20, 20); + expect(-10).to.be.approximately(20, 30); + (-10).should.be.approximately(20, 30); + + err(() => { + expect(2).to.be.approximately(1.0, 0.5, 'blah'); + (2).should.be.approximately(1.0, 0.5, 'blah'); + }, 'blah: expected 2 to be close to 1 +/- 0.5'); + + err(() => { + expect(-10).to.be.approximately(20, 29, 'blah'); + (-10).should.be.approximately(20, 29, 'blah'); + }, 'blah: expected -10 to be close to 20 +/- 29'); +} + function includeMembers() { expect([1, 2, 3]).to.include.members([]); [1, 2, 3].should.include.members([]); @@ -1255,6 +1274,20 @@ function increaseDecreaseChange() { same.should.not.change(obj, "val"); } +function oneOf() { + var obj = { z: 3 }; + + expect(5).to.be.oneOf([1, 5, 4]); + expect('z').to.be.oneOf(['x', 'y', 'z']); + expect(obj).to.be.oneOf([obj]); + + expect(5).to.not.be.oneOf([1, -12, 4]); + expect(5).to.not.be.oneOf([1, [5], 4]); + expect('z').to.not.be.oneOf(['w', 'x', 'y']); + expect('z').to.not.be.oneOf(['x', 'y', ['z']]); + expect(obj).to.not.be.oneOf([{ z: 3 }]); +} + //tdd declare function suite(description: string, action: Function): void; declare function test(description: string, action: Function): void; @@ -1879,6 +1912,20 @@ suite('assert', () => { }, 'expected -10 to be close to 20 +/- 29'); }); + test('approximately', () => { + assert.approximately(1.5, 1.0, 0.5); + assert.approximately(10, 20, 20); + assert.approximately(-10, 20, 30); + + err(() => { + assert.approximately(2, 1.0, 0.5); + }, 'expected 2 to be close to 1 +/- 0.5'); + + err(() => { + assert.approximately(-10, 20, 29); + }, 'expected -10 to be close to 20 +/- 29'); + }); + test('members', () => { assert.includeMembers([1, 2, 3], [2, 3]); assert.includeMembers([1, 2, 3], []); @@ -1945,4 +1992,55 @@ suite('assert', () => { test('notFrozen', () => { assert.notFrozen({}); }); test('isNotFrozen', () => { assert.isNotFrozen({}); }); + test('isNotTrue', () => { + assert.isNotTrue(false); + + err(() => { + assert.isNotTrue(true); + }, 'expected true to not be true'); + }); + + test('isNotFalse', () => { + assert.isNotFalse(true); + + err(() => { + assert.isNotFalse(false); + }, 'expected false to not be false'); + }); + + test('isAtLeast', () => { + assert.isAtLeast(5, 3); + assert.isAtLeast(5, 5); + + err(() => { + assert.isAtLeast(3, 5); + }, 'expected 3 to be greater than or equal to 5'); + }); + + test('isAtMost', () => { + assert.isAtMost(3, 5); + assert.isAtMost(5, 5); + + err(() => { + assert.isAtMost(5, 3); + }, 'expected 5 to be less than or equal to 3'); + }); + + test('oneOf', () => { + var obj = { z: 3 }; + + assert.oneOf(5, [1, 5, 4]); + assert.oneOf('z', ['x', 'y', 'z']); + assert.oneOf(obj, [obj]); + + err(() => { + assert.oneOf(5, [1, [5], 4]); + }, 'expected 5 to be one of [1, [5], 4]'); + err(() => { + assert.oneOf('z', ['w', 'x', 'y']); + }, 'expected "z" to be one of [w, x, y]'); + err(() => { + assert.oneOf(obj, [{ z: 3 }]); + }, 'expected { z: 3 } to be one of [{ z: 3 }]'); + }); }); diff --git a/chai/chai.d.ts b/chai/chai.d.ts index 28aaf48c25..074827b65e 100644 --- a/chai/chai.d.ts +++ b/chai/chai.d.ts @@ -1,9 +1,10 @@ -// Type definitions for chai 3.2.0 +// Type definitions for chai 3.4.0 // Project: http://chaijs.com/ // Definitions by: Jed Mao , // Bart van der Schoor , // Andrew Brown , -// Olivier Chevet +// Olivier Chevet , +// Matt Wistrand // Definitions: https://github.com/borisyankov/DefinitelyTyped // @@ -19,7 +20,7 @@ declare module Chai { use(fn: (chai: any, utils: any) => void): any; assert: AssertStatic; config: Config; - AssertionError: AssertionError; + AssertionError: typeof AssertionError; } export interface ExpectStatic extends AssertionStatic { @@ -97,7 +98,8 @@ declare module Chai { itself: Assertion; satisfy: Satisfy; satisfies: Satisfy; - closeTo(expected: number, delta: number, message?: string): Assertion; + closeTo: CloseTo; + approximately: CloseTo; members: Members; increase: PropertyChange; increases: PropertyChange; @@ -108,7 +110,7 @@ declare module Chai { extensible: Assertion; sealed: Assertion; frozen: Assertion; - + oneOf(list: any[], message?: string): Assertion; } interface LanguageChains { @@ -155,6 +157,10 @@ declare module Chai { (constructor: Object, message?: string): Assertion; } + interface CloseTo { + (expected: number, delta: number, message?: string): Assertion; + } + interface Deep { equal: Equal; include: Include; @@ -259,6 +265,9 @@ declare module Chai { isTrue(val: any, msg?: string): void; isFalse(val: any, msg?: string): void; + isNotTrue(val: any, msg?: string): void; + isNotFalse(val: any, msg?: string): void; + isNull(val: any, msg?: string): void; isNotNull(val: any, msg?: string): void; @@ -271,6 +280,9 @@ declare module Chai { isAbove(val: number, abv: number, msg?: string): void; isBelow(val: number, blw: number, msg?: string): void; + isAtLeast(val: number, atlst: number, msg?: string): void; + isAtMost(val: number, atmst: number, msg?: string): void; + isFunction(val: any, msg?: string): void; isNotFunction(val: any, msg?: string): void; @@ -339,6 +351,7 @@ declare module Chai { operator(val: any, operator: string, val2: any, msg?: string): void; closeTo(act: number, exp: number, delta: number, msg?: string): void; + approximately(act: number, exp: number, delta: number, msg?: string): void; sameMembers(set1: any[], set2: any[], msg?: string): void; sameDeepMembers(set1: any[], set2: any[], msg?: string): void; @@ -361,7 +374,7 @@ declare module Chai { isNotFrozen(obj: Object, msg?: string): void; notFrozen(obj: Object, msg?: string): void; - + oneOf(inList: any, list: any[], msg?: string): void; } export interface Config { diff --git a/chartjs/chart.d.ts b/chartjs/chart.d.ts index 62f393b8a1..464655f78c 100644 --- a/chartjs/chart.d.ts +++ b/chartjs/chart.d.ts @@ -136,6 +136,8 @@ interface BarChartOptions extends ChartOptions { barStrokeWidth?: number; barValueSpacing?: number; barDatasetSpacing?: number; + scaleShowHorizontalLines?: boolean; + scaleShowVerticalLines?: boolean; } interface RadarChartOptions extends ChartSettings { diff --git a/chrome/chrome-tests.ts b/chrome/chrome-tests.ts index 3417384358..e184a82167 100644 --- a/chrome/chrome-tests.ts +++ b/chrome/chrome-tests.ts @@ -254,3 +254,11 @@ function testOptionsPage() { }); } +chrome.storage.sync.get("myKey", function (loadedData) { + var myValue: { x: number } = loadedData["myKey"]; +}); + +chrome.storage.onChanged.addListener(function (changes) { + var myNewValue: { x: number } = changes["myKey"].newValue; + var myOldValue: { x: number } = changes["myKey"].oldValue; +}); diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index b278917047..17613b88c2 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -1,6 +1,6 @@ // Type definitions for Chrome extension development // Project: http://developer.chrome.com/extensions/ -// Definitions by: Matthew Kimber , otiai10 , couven92 +// Definitions by: Matthew Kimber , otiai10 , couven92 // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -2646,13 +2646,13 @@ declare module chrome.extension { * Parameter request: The request sent by the calling script. * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. */ - addListener(callback: (request: any, sender: runtime.MessageSender, sendResponse: () => void) => void): void; + addListener(callback: (request: any, sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; /** * @param callback The callback parameter should be a function that looks like this: * function(runtime.MessageSender sender, function sendResponse) {...}; * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object, or undefined if there is no response. If you have more than one onRequest listener in the same document, then only one may send a response. */ - addListener(callback: (sender: runtime.MessageSender, sendResponse: () => void) => void): void; + addListener(callback: (sender: runtime.MessageSender, sendResponse: (response: any) => void) => void): void; } /** @@ -5553,7 +5553,7 @@ declare module chrome.runtime { * Optional parameter message: The message sent by the calling script. * Parameter sendResponse: Function to call (at most once) when you have a response. The argument should be any JSON-ifiable object. If you have more than one onMessage listener in the same document, then only one may send a response. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called). */ - addListener(callback: (message: any, sender: MessageSender, sendResponse: Function) => void): void; + addListener(callback: (message: any, sender: MessageSender, sendResponse: (response: any) => void) => void): void; } interface ExtensionConnectEvent extends chrome.events.Event { @@ -5866,13 +5866,13 @@ declare module chrome.sessions { * @since Chrome 20. */ declare module chrome.storage { - interface StorageArea { + interface StorageArea { /** * Gets the amount of space (in bytes) being used by one or more items. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ - getBytesInUse(callback: (bytesInUse: number) => void): void; + getBytesInUse(callback: (bytesInUse: number) => void): void; /** * Gets the amount of space (in bytes) being used by one or more items. * @param key A single key to get the total usage for. Pass in null to get the total usage of all of storage. @@ -5886,11 +5886,11 @@ declare module chrome.storage { * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ - getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void; + getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void; /** * Removes all items from storage. * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). + * Callback on success, or on failure (in which case runtime.lastError will be set). */ clear(callback?: () => void): void; /** @@ -5905,14 +5905,14 @@ declare module chrome.storage { * Removes one item from storage. * @param key A single key for items to remove. * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). + * Callback on success, or on failure (in which case runtime.lastError will be set). */ remove(key: string, callback?: () => void): void; /** * Removes items from storage. * @param keys A list of keys for items to remove. * @param callback Optional. - * Callback on success, or on failure (in which case runtime.lastError will be set). + * Callback on success, or on failure (in which case runtime.lastError will be set). */ remove(keys: string[], callback?: () => void): void; /** @@ -5920,77 +5920,78 @@ declare module chrome.storage { * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ - get(callback: (items: Object) => void): void; + get(callback: (items: { [key: string]: any }) => void): void; /** * Gets one or more items from storage. * @param key A single key to get. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ - get(key: string, callback: (items: Object) => void): void; + get(key: string, callback: (items: { [key: string]: any }) => void): void; /** * Gets one or more items from storage. * @param keys A list of keys to get. An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ - get(keys: string[], callback: (items: Object) => void): void; + get(keys: string[], callback: (items: { [key: string]: any }) => void): void; /** * Gets one or more items from storage. * @param keys A dictionary specifying default values. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ - get(keys: Object, callback: (items: Object) => void): void; - } + get(keys: Object, callback: (items: { [key: string]: any }) => void): void; + } - interface StorageChange { + interface StorageChange { /** Optional. The new value of the item, if there is a new value. */ - newValue?: any; + newValue?: any; /** Optional. The old value of the item, if there was an old value. */ - oldValue?: any; - } + oldValue?: any; + } interface LocalStorageArea extends StorageArea { /** The maximum amount (in bytes) of data that can be stored in local storage, as measured by the JSON stringification of every value plus every key's length. This value will be ignored if the extension has the unlimitedStorage permission. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; - } + QUOTA_BYTES: number; + } interface SyncStorageArea extends StorageArea { /** @deprecated since Chrome 40. The storage.sync API no longer has a sustained write operation quota. */ - MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; + MAX_SUSTAINED_WRITE_OPERATIONS_PER_MINUTE: number; /** The maximum total amount (in bytes) of data that can be stored in sync storage, as measured by the JSON stringification of every value plus every key's length. Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - QUOTA_BYTES: number; + QUOTA_BYTES: number; /** The maximum size (in bytes) of each individual item in sync storage, as measured by the JSON stringification of its value plus its key length. Updates containing items larger than this limit will fail immediately and set runtime.lastError. */ - QUOTA_BYTES_PER_ITEM: number; + QUOTA_BYTES_PER_ITEM: number; /** The maximum number of items that can be stored in sync storage. Updates that would cause this limit to be exceeded will fail immediately and set runtime.lastError. */ - MAX_ITEMS: number; + MAX_ITEMS: number; /** * The maximum number of set, remove, or clear operations that can be performed each hour. This is 1 every 2 seconds, a lower ceiling than the short term higher writes-per-minute limit. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. */ - MAX_WRITE_OPERATIONS_PER_HOUR: number; + MAX_WRITE_OPERATIONS_PER_HOUR: number; /** * The maximum number of set, remove, or clear operations that can be performed each minute. This is 2 per second, providing higher throughput than writes-per-hour over a shorter period of time. * Updates that would cause this limit to be exceeded fail immediately and set runtime.lastError. * @since Chrome 40. */ MAX_WRITE_OPERATIONS_PER_MINUTE: number; - } + } - interface StorageChangedEvent extends chrome.events.Event { + interface StorageChangedEvent extends chrome.events.Event { /** * @param callback * Parameter changes: Object mapping each key that changed to its corresponding storage.StorageChange for that item. * Parameter areaName: Since Chrome 22. The name of the storage area ("sync", "local" or "managed") the changes are for. */ - addListener(callback: (changes: Object, areaName: string) => void): void; - } + addListener(callback: (changes: { [key: string]: StorageChange }, areaName: string) => void): void; + } /** Items in the local storage area are local to each machine. */ var local: LocalStorageArea; /** Items in the sync storage area are synced using Chrome Sync. */ var sync: SyncStorageArea; + /** * Items in the managed storage area are set by the domain administrator, and are read-only for the extension; trying to modify this namespace results in an error. * @since Chrome 33. @@ -5998,7 +5999,7 @@ declare module chrome.storage { var managed: StorageArea; /** Fired when one or more items change. */ - var onChanged: StorageChangedEvent; + var onChanged: StorageChangedEvent; } //////////////////// @@ -7577,31 +7578,31 @@ declare module chrome.webNavigation { } interface WebNavigationEvent extends chrome.events.Event { - addListener(callback: (details: WebNavigationCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationFramedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationFramedCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationFramedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationFramedErrorEvent extends WebNavigationFramedEvent { - addListener(callback: (details: WebNavigationFramedErrorCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationFramedErrorCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationSourceEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationSourceCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationSourceCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationParentedEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationParentedCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationParentedCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationTransitionalEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationTransitionCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationTransitionCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } interface WebNavigationReplacementEvent extends WebNavigationEvent { - addListener(callback: (details: WebNavigationReplacementCallbackDetails, filters?: WebNavigationEventFilter) => void): void; + addListener(callback: (details: WebNavigationReplacementCallbackDetails) => void, filters?: WebNavigationEventFilter): void; } /** diff --git a/codemirror/codemirror-showhint.d.ts b/codemirror/codemirror-showhint.d.ts index 48a904a3bb..8b620a414f 100644 --- a/codemirror/codemirror-showhint.d.ts +++ b/codemirror/codemirror-showhint.d.ts @@ -41,9 +41,7 @@ declare module CodeMirror { off(eventName: string, handler: (doc: CodeMirror.Doc, event: any) => void): void; } - /** Extend CodeMirror.Doc with a state object, so that the Doc.state.completionActive property is reachable*/ interface Doc { - state: any; showHint: (options: ShowHintOptions) => void; } diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 2ca58c7024..3fb29e4259 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -390,6 +390,9 @@ declare module CodeMirror { The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. */ on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; + + /** Expose the state object, so that the Editor.state.completionActive property is reachable*/ + state: any; } interface EditorFromTextArea extends Editor { @@ -589,6 +592,8 @@ declare module CodeMirror { /** The reverse of posFromIndex. */ indexFromPos(object: CodeMirror.Position): number; + /** Expose the state object, so that the Doc.state.completionActive property is reachable*/ + state: any; } interface LineHandle { diff --git a/commander/commander.d.ts b/commander/commander.d.ts index cf04591bb0..d0efa63051 100644 --- a/commander/commander.d.ts +++ b/commander/commander.d.ts @@ -65,10 +65,11 @@ declare module commander { * * @param {String} name * @param {String} [desc] + * @param {Mixed} [opts] * @return {Command} the new command * @api public */ - command(name:string, desc?:string):ICommand; + command(name:string, desc?:string, opts?: any):ICommand; /** * Add an implicit `help [cmd]` subcommand diff --git a/commonmark/commonmark-tests.ts b/commonmark/commonmark-tests.ts new file mode 100644 index 0000000000..4896c04646 --- /dev/null +++ b/commonmark/commonmark-tests.ts @@ -0,0 +1,47 @@ +/// + +import commonmark = require('commonmark'); + +function logNode(node: commonmark.Node) { + + console.log( + node.destination, + node.firstChild, + node.info, + node.isContainer, + node.lastChild, + node.level, + node.listDelimiter, + node.listStart, + node.listTight, + node.listType, + node.literal, + node.next, + node.onEnter, + node.onExit, + node.parent, + node.prev, + node.sourcepos, + node.title, + node.type); + +} + +var parser = new commonmark.Parser({ smart: true, time: true }); +var node = parser.parse('# a piece of _markdown_'); + + +let w = node.walker(); +let step = w.next(); +if (step.entering) { + logNode(step.node); +} + + +let xmlRenderer = new commonmark.XmlRenderer({ sourcepos: true, time: true }); +let xml = xmlRenderer.render(node); +console.log(xml); + +let htmlRenderer = new commonmark.HtmlRenderer({ safe: true, smart: true, sourcepos: true, time: true}); +let html = htmlRenderer.render(node); +console.log(html); \ No newline at end of file diff --git a/commonmark/commonmark.d.ts b/commonmark/commonmark.d.ts new file mode 100644 index 0000000000..8f12714515 --- /dev/null +++ b/commonmark/commonmark.d.ts @@ -0,0 +1,214 @@ +// Type definitions for commonmark.js 0.22.1 +// Project: https://github.com/jgm/commonmark.js +// Definitions by: Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module commonmark { + + export interface NodeWalkingStep { + /** + * a boolean, which is true when we enter a Node from a parent or sibling, and false when we reenter it from a child + */ + entering: boolean; + /** + * The node belonging to this step + */ + node: Node; + } + + export interface NodeWalker { + /** + * Returns an object with properties entering and node. Returns null when we have finished walking the tree. + */ + next(): NodeWalkingStep; + /** + * Resets the iterator to resume at the specified node and setting for entering. (Normally this isn't needed unless you do destructive updates to the Node tree.) + */ + resumeAt(node: Node, entering?: boolean): void; + } + + export interface Position extends Array> { + } + + export interface ListData { + type?: string, + tight?: boolean, + delimiter?: string, + bulletChar?: string + } + + export class Node { + constructor(nodeType: string, sourcepos?: Position); + isContainer: boolean; + + /** + * (read-only): one of Text, Softbreak, Hardbreak, Emph, Strong, Html, Link, Image, Code, Document, Paragraph, BlockQuote, Item, List, Heading, CodeBlock, HtmlBlock ThematicBreak. + */ + type: string; + /** + * (read-only): a Node or null. + */ + firstChild: Node; + /** + * (read-only): a Node or null. + */ + lastChild: Node; + /** + * (read-only): a Node or null. + */ + next: Node; + /** + * (read-only): a Node or null. + */ + prev: Node; + /** + * (read-only): a Node or null. + */ + parent: Node; + /** + * (read-only): an Array with the following form: [[startline, startcolumn], [endline, endcolumn]] + */ + sourcepos: Position; + /** + * the literal String content of the node or null. + */ + literal: string; + /** + * link or image destination (String) or null. + */ + destination: string; + /** + * link or image title (String) or null. + */ + title: string; + /** + * fenced code block info string (String) or null. + */ + info: string; + /** + * heading level (Number). + */ + level: number; + /** + * either Bullet or Ordered (or undefined). + */ + listType: string; + /** + * true if list is tight + */ + listTight: boolean; + /** + * a Number, the starting number of an ordered list. + */ + listStart: number; + /** + * a String, either ) or . for an ordered list. + */ + listDelimiter: string; + /** + * used only for CustomBlock or CustomInline. + */ + onEnter: string; + /** + * used only for CustomBlock or CustomInline. + */ + onExit: string; + /** + * Append a Node child to the end of the Node's children. + */ + appendChild(child: Node): void; + /** + * Prepend a Node child to the beginning of the Node's children. + */ + prependChild(child: Node): void; + /** + * Remove the Node from the tree, severing its links with siblings and parents, and closing up gaps as needed. + */ + unlink(): void; + /** + * Insert a Node sibling after the Node. + */ + insertAfter(sibling: Node): void; + /** + * Insert a Node sibling before the Node. + */ + insertBefore(sibling: Node): void; + /** + * Returns a NodeWalker that can be used to iterate through the Node tree rooted in the Node + */ + walker(): NodeWalker; + /** + * Setting the backing object of listType, listTight, listStat and listDelimiter directly. + * Not needed unless creating list nodes directly. Should be fixed from v>0.22.1 + * https://github.com/jgm/commonmark.js/issues/74 + */ + _listData: ListData; + } + + /** + * Instead of converting Markdown directly to HTML, as most converters do, commonmark.js parses Markdown to an AST (abstract syntax tree), and then renders this AST as HTML. + * This opens up the possibility of manipulating the AST between parsing and rendering. For example, one could transform emphasis into ALL CAPS. + */ + export class Parser { + /** + * Constructs a new Parser + */ + constructor(options?: ParserOptions); + parse(input: string): Node; + } + + export interface ParserOptions { + /** + * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. + */ + smart?: boolean; + time?: boolean; + } + + export interface HtmlRenderingOptions extends XmlRenderingOptions { + /** + * if true, raw HTML will not be passed through to HTML output (it will be replaced by comments), and potentially unsafe URLs in links and images (those beginning with javascript:, vbscript:, file:, and with a few exceptions data:) will be replaced with empty strings. + */ + safe?: boolean; + /** + * if true, straight quotes will be made curly, -- will be changed to an en dash, --- will be changed to an em dash, and ... will be changed to ellipses. + */ + smart?: boolean; + /** + * if true, source position information for block-level elements will be rendered in the data-sourcepos attribute (for HTML) or the sourcepos attribute (for XML). + */ + sourcepos?: boolean; + } + + export class HtmlRenderer { + constructor(options?: HtmlRenderingOptions) + render(root: Node): string; + /** + * Let's you override the softbreak properties of a renderer. So, to make soft breaks render as hard breaks in HTML: + * writer.softbreak = "
"; + */ + softbreak: string; + /** + * Override the function that will be used to escape (sanitize) the html output. Return value is used to add to the html output + * @param input the input to escape + * @param isAttributeValue indicates wheter or not the input value will be used as value of an html attribute. + */ + escape: (input: string, isAttributeValue: boolean) => string; + } + + export interface XmlRenderingOptions { + time?: boolean; + sourcepos?: boolean; + } + + export class XmlRenderer { + constructor(options?: XmlRenderingOptions) + render(root: Node): string; + } + +} + +declare module 'commonmark' { + export = commonmark; +} \ No newline at end of file diff --git a/connect-timeout/connect-timeout-tests.ts b/connect-timeout/connect-timeout-tests.ts new file mode 100644 index 0000000000..920c7fdc67 --- /dev/null +++ b/connect-timeout/connect-timeout-tests.ts @@ -0,0 +1,28 @@ +/// +/// +/// +/// + +import express = require("express"); +import timeout = require("connect-timeout"); +import bodyParser = require("body-parser"); +import cookieParser = require("cookie-parser"); + +// example of using this top-level; note the use of haltOnTimedout +// after every middleware; it will stop the request flow on a timeout +var app = express(); +app.use(timeout("5s", { respond: false })); +app.use(bodyParser()); +app.use(haltOnTimedout); +app.use(cookieParser()); +app.use(haltOnTimedout); + +// Add your routes here, etc. + +function haltOnTimedout(req: express.Request, res: express.Response, next: Function) { + if (!req.timedout) { + next(); + } +} + +app.listen(3000); diff --git a/connect-timeout/connect-timeout.d.ts b/connect-timeout/connect-timeout.d.ts new file mode 100644 index 0000000000..8494a3afbf --- /dev/null +++ b/connect-timeout/connect-timeout.d.ts @@ -0,0 +1,36 @@ +// Type definitions for connect-timeout +// Project: https://github.com/expressjs/timeout +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module Express { + export interface Request { + /** + * @summary Clears the timeout on the request. + */ + clearTimeout(): void; + + /** + * + * @return {boolean} true if timeout fired; false otherwise. + */ + timedout(event: string, message: string): boolean; + } +} + +declare module "connect-timeout" { + import express = require("express"); + + interface TimeoutOptions extends Object { + /** + * @summary Controls if this module will "respond" in the form of forwarding an error. + * @type {boolean} + */ + respond: boolean; + } + + function timeout(timeout: string, options?: TimeoutOptions): express.RequestHandler; + export = timeout; +} diff --git a/console-stamp/console-stamp-tests.ts b/console-stamp/console-stamp-tests.ts new file mode 100644 index 0000000000..e6ae6895b0 --- /dev/null +++ b/console-stamp/console-stamp-tests.ts @@ -0,0 +1,21 @@ +/// + +import consoleStamp = require("console-stamp"); + +consoleStamp(console); + +var options = {}; +consoleStamp(console, options); + +var options2 = { + metadata: function ():string { + return 'string'; + }, + colors: { + stamp: "yellow", + label: "white", + metadata: "green" + }, + label: true +}; +consoleStamp(console, options2); diff --git a/console-stamp/console-stamp.d.ts b/console-stamp/console-stamp.d.ts new file mode 100644 index 0000000000..a798dc66cc --- /dev/null +++ b/console-stamp/console-stamp.d.ts @@ -0,0 +1,46 @@ +// Type definitions for console-stamp 0.2.0 +// Project: https://github.com/starak/node-console-stamp +// Definitions by: Eric Byers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'console-stamp' { + + function consoleStamp(console:{}, options?: { + /** + * A string with date format based on Javascript Date Format + */ + pattern?: string + + /** + * If true it will show the label (LOG | INFO | WARN | ERROR) + */ + label?: boolean; + + /** + * An array containing the methods to include in the patch + */ + include?: any; + + /** + * An array containing the methods to exclude in the patch) + */ + exclude?: any; + + /** + * Types can be String, Object (interpreted with util.inspect), or Function. See the test-metadata.js for examples. + * Note that metadata can still be sent as the third parameter (as in vesion 1.6) as a backward compatibillity feature, but this is deprecated. + */ + metadata?: any; + + /** + * An object representing a color theme. More info https://www.npmjs.com/package/colors + */ + colors?: { + stamp?: any; + label?: any; + metadata?: any; + }; + }): void; + + export = consoleStamp; +} diff --git a/contentful-resolve-response/contentful-resolve-response-tests.ts b/contentful-resolve-response/contentful-resolve-response-tests.ts new file mode 100644 index 0000000000..098641e7bb --- /dev/null +++ b/contentful-resolve-response/contentful-resolve-response-tests.ts @@ -0,0 +1,20 @@ +/// +import resolveResponse = require('contentful-resolve-response'); + +var response = { + items: [ + { + someValue: 'wow', + someLink: {sys: {type: 'Link', linkType: 'Entry', id: 'suchId'}} + } + ], + includes: { + Entry: [ + {sys: {type: 'Entry', id: 'suchId'}, very: 'doge'} + ] + } +}; + +var items = resolveResponse(response) + +console.log(items); diff --git a/contentful-resolve-response/contentful-resolve-response.d.ts b/contentful-resolve-response/contentful-resolve-response.d.ts new file mode 100644 index 0000000000..bd2daef9e6 --- /dev/null +++ b/contentful-resolve-response/contentful-resolve-response.d.ts @@ -0,0 +1,9 @@ +// Type definitions for contentful-resolve-response v0.1.2 +// Project: https://github.com/contentful/contentful-resolve-response +// Definitions by: Anton Karsten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'contentful-resolve-response' { + function resolveResponse(response: any): any; + export = resolveResponse; +} diff --git a/cookies/cookies-tests.ts b/cookies/cookies-tests.ts new file mode 100644 index 0000000000..3e3274a4d4 --- /dev/null +++ b/cookies/cookies-tests.ts @@ -0,0 +1,42 @@ +/// +/// + +import * as Cookies from 'cookies'; +import * as http from 'http'; + +const server = http.createServer((req, res) => { + const cookies = new Cookies(req, res); + let unsigned: string, + signed: string, + tampered: string + + if (req.url == "/set") { + cookies + // set a regular cookie + .set("unsigned", "foo", { httpOnly: false }) + + // set a signed cookie + .set("signed", "bar", { signed: true }) + + // mimic a signed cookie, but with a bogus signature + .set("tampered", "baz") + .set("tampered.sig", "bogus") + + res.writeHead(302, { "Location": "/" }) + return res.end("Now let's check.") + } + + unsigned = cookies.get("unsigned") + signed = cookies.get("signed", { signed: true }) + tampered = cookies.get("tampered", { signed: true }) + + res.writeHead(200, { "Content-Type": "text/plain" }) + res.end( + "unsigned expected: foo\n\n" + + "unsigned actual: " + unsigned + "\n\n" + + "signed expected: bar\n\n" + + "signed actual: " + signed + "\n\n" + + "tampered expected: undefined\n\n" + + "tampered: " + tampered + "\n\n" + ) +}) \ No newline at end of file diff --git a/cookies/cookies.d.ts b/cookies/cookies.d.ts new file mode 100644 index 0000000000..5cc5f698a3 --- /dev/null +++ b/cookies/cookies.d.ts @@ -0,0 +1,100 @@ +// Type definitions for cookie-parser v0.5.1 +// Project: https://github.com/pillarjs/cookies +// Definitions by: Wang Zishi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "cookies" { + import * as http from "http" + + module cookies { + interface ICookies { + /** + * This extracts the cookie with the given name from the + * Cookie header in the request. If such a cookie exists, + * its value is returned. Otherwise, nothing is returned. + */ + get(name: string): string; + /** + * This extracts the cookie with the given name from the + * Cookie header in the request. If such a cookie exists, + * its value is returned. Otherwise, nothing is returned. + */ + get(name: string, opts: IOptions): string; + + /** + * This sets the given cookie in the response and returns + * the current context to allow chaining.If the value is omitted, + * an outbound header with an expired date is used to delete the cookie. + */ + set(name: string, value: string): ICookies; + /** + * This sets the given cookie in the response and returns + * the current context to allow chaining.If the value is omitted, + * an outbound header with an expired date is used to delete the cookie. + */ + set(name: string, value: string, opts: IOptions): ICookies; + } + + interface IOptions { + /** + * a number representing the milliseconds from Date.now() for expiry + */ + maxAge?: number; + /** + * a Date object indicating the cookie's expiration + * date (expires at the end of session by default). + */ + expires?: Date; + /** + * a string indicating the path of the cookie (/ by default). + */ + path?: string; + /** + * a string indicating the domain of the cookie (no default). + */ + domain?: string; + /** + * a boolean indicating whether the cookie is only to be sent + * over HTTPS (false by default for HTTP, true by default for HTTPS). + */ + secure?: boolean; + /** + * a boolean indicating whether the cookie is only to be sent + * over HTTPS (use this if you handle SSL not in your node process). + */ + secureProxy?: boolean; + /** + * a boolean indicating whether the cookie is only to be sent over HTTP(S), + * and not made available to client JavaScript (true by default). + */ + httpOnly?: boolean; + /** + * a boolean indicating whether the cookie is to be signed (false by default). + * If this is true, another cookie of the same name with the .sig suffix + * appended will also be sent, with a 27-byte url-safe base64 SHA1 value + * representing the hash of cookie-name=cookie-value against the first Keygrip key. + * This signature key is used to detect tampering the next time a cookie is received. + */ + signed?: boolean; + /** + * a boolean indicating whether to overwrite previously set + * cookies of the same name (false by default). If this is true, + * all cookies set during the same request with the same + * name (regardless of path or domain) are filtered out of + * the Set-Cookie header when setting this cookie. + */ + overwrite?: boolean; + } + } + + interface CookiesStatic { + new (request: http.IncomingMessage, response: http.ServerResponse): cookies.ICookies; + new (request: http.IncomingMessage, response: http.ServerResponse, keys?: Array): cookies.ICookies; + } + + const cookies: CookiesStatic; + + export = cookies +} \ No newline at end of file diff --git a/cordova-plugin-mapsforge/cordova-plugin-mapsforge-tests.ts b/cordova-plugin-mapsforge/cordova-plugin-mapsforge-tests.ts new file mode 100644 index 0000000000..52ef78700b --- /dev/null +++ b/cordova-plugin-mapsforge/cordova-plugin-mapsforge-tests.ts @@ -0,0 +1,73 @@ +/// + + +mapsforge.embedded.initialize(["/mnt/sdcard/spain.map",0,0]); //Creates the view +mapsforge.embedded.setCenter(43.360056,-5.845757); //Sets the center of the view +mapsforge.embedded.setMaxZoom(18); +mapsforge.embedded.setZoom(15); + +//Adding a marker +var markerKey: number; +mapsforge.embedded.addMarker([mapsforge.embedded.MARKER_YELLOW,43.360056,-5.845757],function(key){markerKey = key;}); + +//Adding a polyline +var points = [43.360056,-5.845757, 43.160056,-5.645757,43.560056,-5.895757]; +var polylineKey: number; +mapsforge.embedded.addPolyline([mapsforge.embedded.COLOR_GREEN,10,points], function(key){polylineKey = key;}, function(error){alert(error);}); + + + +mapsforge.cache.initialize("/mnt/sdcard/spain.map"); //Initializes the renderer with the offline map + +/*Now you can use the Leaflet code seen before*/ + +mapsforge.cache.setExternalCache(false); //Sets the cache to internal for faster performance + +//Now we set the cache size to 50 MB. This will increase the time between cleanings, but +//it will also make those cleanings slower, since there are a lot more of images to +//delete...so be careful when you choose the cache size +mapsforge.cache.setMaxCacheSize(50); + + + +var L: any; + +interface TilePoint { + x: number; + y: number; + z: number; +} + +interface Tile { + src: string; + _layer: any; + onload: any; + onerror: any; +} + +L.OfflineTileLayer = L.TileLayer.extend({ + getTileUrl : function(tilePoint: TilePoint, tile: Tile) { + var zoom = tilePoint.z, x = tilePoint.x, y = tilePoint.y; + + if (mapsforge.cache) { + mapsforge.cache.getTile([x,y,zoom], function(result) {tile.src=result;}, + function() {tile.src = "path to an error image";}); + }else{ + tile.src = "path to an error image"; + } + }, + + _loadTile: function (tile: Tile, tilePoint: TilePoint) { + tile._layer = this; + tile.onload = this._tileOnLoad; + tile.onerror = this._tileOnError; + + this._adjustTilePoint(tilePoint); + this.getTileUrl(tilePoint, tile); + + this.fire('tileloadstart', { + tile: tile, + url: tile.src + }); + } +}); diff --git a/cordova-plugin-mapsforge/cordova-plugin-mapsforge.d.ts b/cordova-plugin-mapsforge/cordova-plugin-mapsforge.d.ts new file mode 100644 index 0000000000..6314a09fb8 --- /dev/null +++ b/cordova-plugin-mapsforge/cordova-plugin-mapsforge.d.ts @@ -0,0 +1,249 @@ +// Type definitions for cordova-plugin-mapsforge +// Project: https://github.com/afsuarez/mapsforge-cordova-plugin +// Definitions by: rafw87 +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface Window { + mapsforge: MapsforgePlugin; +} + +declare var mapsforge: MapsforgePlugin; + +interface MapsforgePlugin { + embedded: MapsforgeEmbeddedPlugin; + cache: MapsforgeCachePlugin; +} + +interface MapsforgeEmbeddedPlugin { + + COLOR_DKGRAY: number|string; + COLOR_CYAN: number|string; + COLOR_BLACK: number|string; + COLOR_BLUE: number|string; + COLOR_GREEN: number|string; + COLOR_RED: number|string; + COLOR_WHITE: number|string; + COLOR_TRANSPARENT: number|string; + COLOR_YELLOW: number|string; + + MARKER_RED: number|string; + MARKER_GREEN: number|string; + MARKER_BLUE: number|string; + MARKER_YELLOW: number|string; + MARKER_BLACK: number|string; + MARKER_WHITE: number|string; + + /** + * The map file path provided must be the absolute file path. You can specify the width and height values for the view that will be added, + * or you can set them to 0 for set the value to MATCH_PARENT. You must call this method before any other method. + * @param args Array in the following form: [String mapFilePath, int viewWidth, int viewHeight]. + * @param success Success callback. + * @param error Error callback + */ + initialize(args: any[], success?: () => void, error?: (message: string) => void): void; + + /** + * To show the map view. + * @param success Success callback. + * @param error Error callback + */ + show(success?: () => void, error?: (message: string) => void): void; + + /** + * To hide the map view. + * @param success Success callback. + * @param error Error callback + */ + hide(success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the center of the map to the given coordinates. + * @param lat Latitude of the new center. + * @param lng Longitude of the new center. + * @param success Success callback. + * @param error Error callback + */ + setCenter(lat: number, lng: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the zoom to the specified value (if it is between the zoom limits). + * @param zoomLevel New zoom level. + * @param success Success callback. + * @param error Error callback + */ + setZoom(zoomLevel: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the maximum zoom level. + * @param maxZoom New maximum zoom level. + * @param success Success callback. + * @param error Error callback + */ + setMaxZoom(maxZoom: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the minimum zoom level. + * @param minZoom New minimum zoom level. + * @param success Success callback. + * @param error Error callback + */ + setMinZoom(minZoom: number, success?: () => void, error?: (message: string) => void): void; + + /** + * The path to the map ile is required, and the path to the render theme may be null in order to apply the default render theme. + * @param args Array in the following form: [String mapFilePath, String renderThemePath] + * @param success Success callback. + * @param error Error callback + */ + setOfflineTileLayer(args: any[], success?: () => void, error?: (message: string) => void): void; + + /** + * + * @param args Array in the following form: [String providerName, String host, String baseUrl, String extension, int port] + * @param success Success callback. + * @param error Error callback + */ + setOnlineTileLayer(args: any[], success?: () => void, error?: (message: string) => void): void; + + /** + * Adds a marker to the map in the specified coordinates and returns the key for that marker to the success function. + * @param arg Array in the following form: [String marker_color, double lat, double lng]. + * The color of the marker should be one of the constants from mapsforge.embedded object; if the marker doesn't exist a green marker will be used instead. + * @param success Success callback. Gets the key of created marker. That key is the one you have to use if you want to delete it. + * @param error Error callback + */ + addMarker(arg: any[], success?: (key: number) => void, error?: (message: string) => void): void; + + /** + * + * @param arg Array in the following form: [int color, int strokeWidth,[double points]]. + * The color can be one of the constants specified before, or the new color you want. + * This function will use the odd positions of the array of points for the latitudes and the even positions for the longitudes. + * Example: [lat1, lng1, lat2, lng2, lat3, lng3]. + * If the length of the array is not even, the function will throw an exception and return the error message to the error function. + * @param success Success callback. Gets the key of created polyline. + * @param error Error callback + */ + addPolyline(arg: any[], success?: (key: number) => void, error?: (message: string) => void): void; + + /** + * Deletes the layer(markers or polylines) with the specified key from the map. + * @param key Key of marker or polyline. + * @param success Success callback. + * @param error Error callback + */ + deleteLayer(key: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Initializes again the map if the onStop method was called. + * @param success Success callback. + * @param error Error callback + */ + onStart(success?: () => void, error?: (message: string) => void): void; + + + /** + * Stops the rendering. Useful for when the app goes to the background. You have to call the onStart method to restart it. + * @param success Success callback. + * @param error Error callback + */ + onStop(success?: () => void, error?: (message: string) => void): void; + + /** + * Stops and cleans the resources that have been used. + * @param success Success callback. + * @param error Error callback + */ + onDestroy(success?: () => void, error?: (message: string) => void): void; +} + +interface MapsforgeCachePlugin { + + /** + * You should call this method before any other one, and provide it with the absolute map file path. + * @param mapFilePath Absolute map file path. + * @param success Success callback. + * @param error Error callback + */ + initialize(mapFilePath: string, success?: () => void, error?: (message: string) => void): void; + + /** + * This method is the one that provides the tiles, generating them if their are not in the cache. + * @param args Array in the following form: [double lat, double lng, byte zoom] + * @param success Success callback. Gets the tile path. + * @param error Error callback + */ + getTile(args: any[], success?: (tilePath: string) => void, error?: (message: string) => void): void; + + /** + * Enables or disables the cache. If disabled, the plugin will generate the tiles always from scratch. Cache is enabled by default. + * @param enabled Cache enabled or disabled. + * @param success Success callback. + * @param error Error callback + */ + setCacheEnabled(enabled: boolean, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets whether or not the cache should be placed in the internal memory or in the SD card. + * By default it is placed in SD card, so devices with not too much memory have a better performance. + * @param external Cache external or internal. + * @param success Success callback. + * @param error Error callback + */ + setExternalCache(external: boolean, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the map file to be used for rendering to the map specified by its absolute path. + * @param absolutePath Absolute map file path. + * @param success Success callback. + * @param error Error callback + */ + setMapFile(absolutePath: string, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the age for the generated images. This means that when the cache is being cleaned, all images younger than the specified value will be kept in the cache in order to avoid deleting images that are being used at the moment. + * @param milliseconds Max cache age in milliseconds. + * @param success Success callback. + * @param error Error callback + */ + setMaxCacheAge(milliseconds: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the maximum size for the cache. This size must be specified in megabytes. If there is not that space available, the cache will fit the maximum size. + * @param sizeInMB Max cache size in megabytes. + * @param success Success callback. + * @param error Error callback + */ + setMaxCacheSize(sizeInMB: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets the tile size. By default the tile size is set to 256. + * @param size Tile size. + * @param success Success callback. + * @param error Error callback + */ + setMaxCacheSize(size: number, success?: () => void, error?: (message: string) => void): void; + + /** + * This method sets the size in megabytes that will remain always available in memory in order to avoid that the application uses all space available. + * @param sizeInMB Size in megabytes that will remain always available in memory. + * @param success Success callback. + * @param error Error callback + */ + setCacheCleaningTrigger(sizeInMB: number, success?: () => void, error?: (message: string) => void): void; + + /** + * Sets a flag to destroy the cache when the onDestroy method is called. + * @param destroy If true, cache will be destroyed when the onDestroy method will be called. + * @param success Success callback. + * @param error Error callback + */ + destroyCacheOnExit(destroy: boolean, success?: () => void, error?: (message: string) => void): void; + + /** + * Deletes the cache depending on the flag state. + * @param success Success callback. + * @param error Error callback + */ + onDestroy(success?: () => void, error?: (message: string) => void): void; +} diff --git a/cordova/plugins/NetworkInformation.d.ts b/cordova/plugins/NetworkInformation.d.ts index 53093284f1..1ba2ae9e03 100644 --- a/cordova/plugins/NetworkInformation.d.ts +++ b/cordova/plugins/NetworkInformation.d.ts @@ -45,16 +45,16 @@ interface Connection { * Connection.CELL * Connection.NONE */ - type: number + type: string } declare var Connection: { - UNKNOWN: number; - ETHERNET: number; - WIFI: number; - CELL_2G: number; - CELL_3G: number; - CELL_4G: number; - CELL: number; - NONE: number; -} \ No newline at end of file + UNKNOWN: string; + ETHERNET: string; + WIFI: string; + CELL_2G: string; + CELL_3G: string; + CELL_4G: string; + CELL: string; + NONE: string; +} diff --git a/couchbase/couchbase-tests.ts b/couchbase/couchbase-tests.ts index 4305300eea..a1a3ee6bba 100644 --- a/couchbase/couchbase-tests.ts +++ b/couchbase/couchbase-tests.ts @@ -1,21 +1,16 @@ /// import couchbase = require('couchbase'); -var db = new couchbase.Connection({ bucket: "default" }, function (err) { - if (err) throw err; +var cluster = new couchbase.Cluster('couchbase://127.0.0.1'); +var bucket = cluster.openBucket('default'); - // TS 0.9.5 bug https://typescript.codeplex.com/workitem/2035, todo: remove cast after fix - (db).set('testdoc', { name: 'Frank' }, function (err, result) { - if (err) throw err; +bucket.upsert('testdoc', { name: 'Frank' }, (error) => { + if (error) throw error; - var s: string = err.message; + bucket.get('testdoc', (err, result) => { + if (err) throw err; - // TS 0.9.5 bug https://typescript.codeplex.com/workitem/2035, todo: remove cast after fix - (db).get('testdoc', function (err, result) { - if (err) throw err; - - console.log(result.value); - // {name: Frank} - }); + console.log(result.value); + // {name: Frank} }); }); \ No newline at end of file diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 3a8605b731..6afd3a7819 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -1,729 +1,1129 @@ -// Type definitions for Couchbase Couchnode +// Type definitions for Couchbase Node.js SDK 2.1.2 // Project: https://github.com/couchbase/couchnode -// Definitions by: Basarat Ali Syed +// Definitions by: Marwan Aouida // Definitions: https://github.com/borisyankov/DefinitelyTyped /// + declare module 'couchbase' { - /** - * Enumeration of all error codes. See libcouchbase documentation - * for more details on what these errors represent. - * - * @global - * @readonly - * @enum {number} - */ - export var errors: { - /** Operation was successful **/ - success: number; + import events = require('events'); + /** + * Enumeration of all error codes. See libcouchbase documentation for more details on what these errors represent. + */ + enum errors { + /** Operation was successful. **/ + success, + /** Authentication should continue. **/ - authContinue: number; - + authContinue, + /** Error authenticating. **/ - authError: number; - + authError, + /** The passed incr/decr delta was invalid. **/ - deltaBadVal: number; - + deltaBadVal, + /** Object is too large to be stored on the cluster. **/ - objectTooBig: number; - + objectTooBig, + + /** Operation was successful. **/ + serverBusy, + /** Server is too busy to handle your request right now. **/ - serverBusy: number; - - /** Internal libcouchbase error. **/ - cLibInternal: number; - + cLibInternal, + /** An invalid arguement was passed. **/ - cLibInvalidArgument: number; - + cLinInvalidArgument, + /** The server is out of memory. **/ - cLibOutOfMemory: number; - + cLibOutOfMemory, + /** An invalid range was specified. **/ - invalidRange: number; - + invalidRange, + /** An unknown error occured within libcouchbase. **/ - cLibGenericError: number; - + cLibGenericError, + /** A temporary error occured. Try again. **/ - temporaryError: number; - + temporaryError, + /** The key already exists on the server. **/ - keyAlreadyExists: number; - + keyAlreadyExists, + /** The key does not exist on the server. **/ - keyNotFound: number; - + keyNotFound, + /** Failed to open library. **/ - failedToOpenLibrary: number; - + failedToOpenLibrary, + /** Failed to find expected symbol in library. **/ - failedToFindSymbol: number; - + failedToFindSymbol, + /** A network error occured. **/ - networkError: number; - + networkError, + /** Operations were performed on the incorrect server. **/ - wrongServer: number; - + wrongServer, + /** Operations were performed on the incorrect server. **/ - notMyVBucket: number; - - /** The document was not stored. */ - notStored: number; - + notMyVBucket, + + /** The document was not stored. **/ + notSorted, + /** An unsupported operation was sent to the server. **/ - notSupported: number; - + notSupported, + /** An unknown command was sent to the server. **/ - unknownCommand: number; - + unknownCommand, + /** An unknown host was specified. **/ - unknownHost: number; - + unknownHost, + /** A protocol error occured. **/ - protocolError: number; - + protocolError, + /** The operation timed out. **/ - timedOut: number; - + timedOut, + /** Error connecting to the server. **/ - connectError: number; - + connectError, + /** The bucket you request was not found. **/ - bucketNotFound: number; - + bukcketNotFound, + /** libcouchbase is out of memory. **/ - clientOutOfMemory: number; - + clientOutOfMemory, + /** A temporary error occured in libcouchbase. Try again. **/ - clientTemporaryError: number; - - /** A bad handle was passed. */ - badHandle: number; - + clientTemporaryError, + + /** A bad handle was passed. **/ + badHandle, + /** A server bug caused the operation to fail. **/ - serverBug: number; - + serverBug, + /** The host format specified is invalid. **/ - invalidHostFormat: number; - - /** Not enough nodes to meet the operations durability requirements. **/ - notEnoughNodes: number; - + invalidHostFormat, + + /** Not enough nodes to meet the operations durability requirements. **/ + notEnoughNodes, + /** Duplicate items. **/ - duplicateItems: number; - + duplicateItems, + /** Key mapping failed and could not match a server. **/ - noMatchingServerForKey: number; - + noMatchingServerForKey, + /** A bad environment variable was specified. **/ - badEnvironmentVariable: number; + badEnvironmentVariable, + /** Couchnode is out of memory. **/ - outOfMemory: number; - + outOfMemory, + /** Invalid arguements were passed. **/ - invalidArguments: number; - + invalidArguments, + /** An error occured while trying to schedule the operation. **/ - schedulingError: number; - + schedulingError, + /** Not all operations completed successfully. **/ - checkResults: number; - + checkResults, + /** A generic error occured in Couchnode. **/ - genericError: number; - + genericError, + /** The specified durability requirements could not be satisfied. **/ - durabilityFailed: number; - + durabilityFailed, + /** An error occured during a RESTful operation. **/ - restError: number; + restError } /** - * Enumeration of all value encoding formats. - * - * @global - * @readonly - * @enum {number} + * Represents a singular cluster containing your buckets. */ - export var format: { - /** Store as raw bytes. **/ - raw: number; + class Cluster { + /** + * Create a new instance of the Cluster class. + * @param cnstr The connection string for your cluster. + * @param options The options object. + */ + constructor(cnstr?: string, options?: ClusterConstructorOptions); - /** Store as JSON encoded string. **/ - json: number; + /** + * Creates a manager allowing the management of a Couchbase cluster. + */ + manager(): ClusterManager; - /** Store as UTF-8 encoded string. **/ - utf8: number; + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + */ + openBucket(name?: string): Bucket; - /** Automatically determine best storage format. **/ - auto: number; - }; - /** - * The *CAS* value is a special object which indicates the current state - * of the item on the server. Each time an object is mutated on the server, the - * value is changed. CAS objects can be used in conjunction with - * mutation operations to ensure that the value on the server matches the local - * value retrieved by the client. This is useful when doing document updates - * on the server as you can ensure no changes were applied by other clients - * while you were in the process of mutating the document locally. - * - * In Couchnode, this is an opaque value. As such, you cannot generate - * CAS objects, but should rather use the values returned from a - * {@link KeyCallback}. - * - * @typedef {object} CAS - */ - export interface CAS extends Object { + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param password Password for the bucket. + */ + openBucket(name?: string, password?: string): Bucket; + + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param callback Callback to invoke on connection success or failure. + */ + openBucket(name?: string, callback?: Function): Bucket; + + /** + * Open a bucket to perform operations. This will begin the handshake process immediately and operations will complete later. Subscribe to the connect event to be alerted when the connection is ready, though be aware operations can be successfully queued before this. + * @param name The name of the bucket to open. + * @param password Password for the bucket. + * @param callback Callback to invoke on connection success or failure. + */ + openBucket(name?: string, password?: string, callback?: Function): Bucket; + } + + interface ClusterConstructorOptions { + /** + * The path to the certificate to use for SSL connections + */ + certpath: string; + } + + interface CreateBucketOptions { + /** + * The bucket name + */ + name?: string; + authType?: string, + bucketType?: string; + ramQuotaMB?: number; + replicaNumber?: number; } /** - * @class Result - * @classdesc - * The virtual class used for results of various operations. - * @private + * Class for performing management operations against a cluster. */ - export class Result { + interface ClusterManager { /** - * The CAS value for the document that was affected by the operation. - * @var {CAS} Result#cas + * + * @param name + * @param callback */ - cas: CAS; + createBucket(name: string, callback: Function): void; + /** - * The flags associate with the document. - * @var {integer} Result#flags + * + * @param name + * @param opts + * @param callback */ - flags: number; + createBucket(name: string, opts: any, callback: Function): void; + /** - * The resulting document from the retrieval operation that was executed. - * @var {Mixed} Result#value + * + * @param callback */ - value: any; + listBuckets(callback: Function): void; + + /** + * + * @param name + * @param callback + */ + removeBucket(name: string, callback: Function): void; } /** - * @class CouchbaseError - * @classdesc * The virtual class thrown for all Couchnode errors. - * @private - * @extends node#Error */ - export interface CouchbaseError extends Error { + interface CouchbaseError extends Error { /** * The error code for this error. - * @var {errors} Error#code */ - code: number; + code: errors; + } + + interface AppendOptions { + /** + * The CAS value to check. If the item on the server contains a different CAS value, the operation will fail. Note that if this option is undefined, no comparison will be performed. + */ + cas?: Bucket.CAS; /** - * The internal error that occured to cause this one. This is used to wrap - * low-level errors before throwing them from couchnode to simplify error - * handling. - * @var {(node#Error)} Error#innerError + * Ensures this operation is persisted to this many nodes. */ - innerError: Error; + persist_to?: number; /** - * A reason string describing the reason this error occured. This value is - * almost exclusively used for REST request errors. - * @var {string} Error#reason + * Ensures this operation is replicated to this many nodes. */ - reason: string; - } - - /** - * Connect callback - * This callback is invoked when a connection is successfully established. - * - * @typedef {function} ConnectCallback - * - * @param {undefined|Error} error - * The error that occurred while trying to connect to the cluster. - */ - export interface ConnectCallback { - (error: CouchbaseError): any; - } - - /** - * Design Document Management callbacks - * This callback is invoked by the *DesignDoc operations. - * - * @typedef {function} DDocCallback - * - * @param {undefined|Error} error - * An error indicator. Note that this error value may be ignored, but its - * absence is indicative that the response in the *result* parameter is ok. - * If it is set, then the request likely failed. - * @param {object} result - * The result returned from the server - */ - export interface DDocCallback { - (error: CouchbaseError, result: any): any; - } - - /** - * Single-Key callbacks. - * This callback is passed to all of the single key functions. - * - * A typical use pattern is to pass the result> parameter from the - * callback as the options parameter to one of the next operations. - * - * @typedef {function} KeyCallback - * - * @param {undefined|Error} error - * The error for the operation. This can either be an Error object - * or a false value. The error contains the following fields: - * @param {Result} result - * The result of the operation that was executed. - */ - export interface KeyCallback { - (error: CouchbaseError, result: Result): any; - } - - /** - * Multi-Key callbacks - * This callback is invoked by the *Multi operations. - * It differs from the in {@linkcode KeyCallback} that the - * response object is an object of {key: response} - * where each response object contains the response for that particular - * key. - * - * @typedef {function} MultiCallback - * - * @param {undefined|Error} error - * An error indicator. Note that this error - * value may be ignored, but its absence is indicative that each - * response in the results parameter is ok. If it - * is set, then at least one of the result objects failed - * @param {Object.} results - * The results of the operation as a dictionary of keys mapped to Result - * objects. - */ - export interface MultiCallback { - (error: CouchbaseError, result: { [key: string]: Result }): any; - } - - /** - * Query callback. - * This callback is invoked by the query operations. - * - * @typedef {function} QueryCallback - * - * @param {undefined|Error} error - * An error indicator. Note that this error - * value may be ignored, but its absence is indicative that the - * response in the results parameter is ok. If it - * is set, then the request failed. - * @param {object} results - * The results returned from the server - */ - export interface QueryCallback { - (error: CouchbaseError, result: any): any; - } - - /** - * @typedef {function} StatsCallback - * - * @param {Error} error - * @param {Object.} results - * An object containing per-server, per key entries - * - * @see Connection#stats - */ - export interface StatsCallback { - (error: CouchbaseError, result: any): any; - } - - - ///////////////////////// - // Various options structures - ///////////////////////// - - export interface ConnectionOptions { - host?: any; // string | string[] - bucket?: string; - password?: string; - } - - // Not comming up with a base interface system as that is not how the original code is written. - // Use a custom base interface system has the potential to become difficult to keep up to date. - - export interface AddOptions { - expiry?: number; - flags?: number; - format?: number - persist_to?: number; replicate_to?: number; } - export interface AddMultiOptionsForValue { - value: any; + interface PrependOptions extends AppendOptions { } + + interface RemoveOptions extends AppendOptions { } + + interface ReplaceOptions extends AppendOptions { + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ expiry?: number; - flags?: number; - format?: number; } - export interface AddMultiOptions { - expiry?: number; - flags?: number; - format?: number + interface UpsertOptions extends ReplaceOptions { } + + interface TouchOptions { + /** + * Ensures this operation is persisted to this many nodes. + */ persist_to?: number; + + /** + * Ensures this operation is replicated to this many nodes. + */ replicate_to?: number; - - spooled?: boolean; } - export interface AppendOptions { - expiry?: number; - flags?: number; - format?: number; - persist_to?: number; - replicate_to?: number; - - cas: CAS; - } - - export interface AppendMultiOptionsForValue { - value: any; - cas?: CAS; - expiry?: number; - } - - export interface AppendMultiOptions { - expiry?: number; - persist_to?: number; - replicate_to?: number; - - spooled?: boolean; - } - - export interface DecrOptions { - offset?: number; + interface CounterOptions { + /** + * Sets the initial value for the document if it does not exist. Specifying a value of undefined will cause the operation to fail if the document does not exist, otherwise this value must be equal to or greater than 0. + */ initial?: number; + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ expiry?: number; + + /** + * Ensures this operation is persisted to this many nodes + */ persist_to?: number; + + /** + * Ensures this operation is replicated to this many nodes + */ replicate_to?: number; } - export interface DecrMultiOptionsForValue { - offset?: number; - initial?: number; - - expiry?: number; + interface GetAndLockOptions { + lockTime?: number; } - export interface DecrMultiOptions { - spooled?: boolean; - } + interface GetReplicaOptions { - export interface GetOptions { - expiry?: number; - format?: number; - } - - export interface GetMultiOptions { - spooled?: boolean; - format?: number; - } - - export interface GetReplicaOptions { + /** + * The index for which replica you wish to retrieve this value from, or if undefined, use the value from the first server that replies. + */ index?: number; - format?: number; } - export interface GetReplicaMultiOptions { - spooled?: boolean; - format?: number; - } + interface InsertOptions { - export interface IncrOptions extends DecrOptions { } - - export interface IncrMultiOptionsForValue extends DecrMultiOptionsForValue { } - - export interface IncrMultiOptions extends DecrMultiOptions { } - - export interface LockOptions { - lockTime?: number - } - - export interface LockMultiOptions { - spooled?: boolean; - format?: number; - } - - export interface ObserveOptions { - cas: CAS; // verified not optional - } - - export interface ObserveMultiOptionsForValue { - cas: CAS; // verified not optional - } - - export interface ObserveMultiOptions { - spooled?: boolean; - } - - export interface PrependOptions { + /** + * Set the initial expiration time for the document. A value of 0 represents never expiring. + */ expiry?: number; - flags?: number; - format?: number; + + /** + * Ensures this operation is persisted to this many nodes. + */ persist_to?: number; + + /** + * Ensures this operation is replicated to this many nodes. + */ replicate_to?: number; - - cas?: CAS; - } - - export interface PrependMultiOptionsFoValue { - value: any; - cas: CAS; - expiry?: number; - } - - export interface PrependMultiOptions { - spooled?: boolean; - - expiry?: number; - persist_to?: number; - replicate_to?: number; - } - - export interface RemoveOptions { - cas?: CAS; - persist_to?: number; - replicate_to?: number; - } - - export interface RemoveMultiOptionsForValue { - cas?: CAS; - } - - export interface RemoveMultiOptions { - spooled?: boolean; - - persist_to?: number; - replicate_to?: number; - } - - // Options for Replace functions follow Set Options and this is mentioned explicitly in the documentation - - export interface ReplaceOptions extends SetOptions { } - - export interface ReplaceMultiOptionsForValue extends SetMultiOptionsForValue { } - - export interface ReplaceMultiOptions extends SetMultiOptions { } - - export interface SetOptions { - expiry?: number; - flags?: number; - format?: number; - persist_to?: number; - replicate_to?: number; - - cas?: CAS; - } - - export interface SetMultiOptionsForValue { - value: any; - cas?: CAS; - expiry?: number; - flags?: number; - format?: number; - } - - export interface SetMultiOptions { - expiry?: number; - flags?: number; - format?: number - persist_to?: number; - replicate_to?: number; - - spooled?: boolean; - } - - export interface TouchOptions { - expiry?: number; - persist_to?: number; - replicate_to?: number; - - cas?: CAS; - } - - export interface UnlockOptions { - cas: CAS; // verified not optional - } - - export interface UnlockMultiOptionsForValue { - cas: CAS; // verified not optional - } - - export interface UnlockMultiOptions { - spooled?: boolean; } /** - * @class - * A class representing a connection to a Couchbase cluster. - * Normally, your application should only need to create one of these per - * bucket and use it continuously. Operations are executed asynchronously - * and pipelined when possible. - * - * @desc - * Instantiate a new Connection object. Note that it is safe to perform - * operations before the connect callback is invoked. In this case, the - * operations are queued until the connection is ready (or an unrecoverable - * error has taken place). - * - * @param {Object} [options] - * A dictionary of options to use. You may pass - * other options than those defined below which correspond to the various - * options available on the Connection object (see their documentation). - * For example, it may be helpful to set timeout properties before connecting. - * @param {string|string[]} [options.host="localhost:8091"] - * A string or array of strings indicating the hosts to connect to. If the - * value is an array, all the hosts in the array will be tried until one of - * them succeeds. - * @param {string} [options.bucket="default"] - * The bucket to connect to. If not specified, the default is - * 'default'. - * @param {string} [options.password=""] - * The password for a password protected bucket. - * @param {ConnectCallback} callback - * A callback that will be invoked when the instance has completed connecting - * to the server. Note that this isn't required - however if the connection - * fails, an exception will be thrown if the callback is not provided. - * - * @example - * var couchbase = require('couchbase'); - * var db = new couchbase.Connection({}, function(err) { - * if (err) { - * console.log('Connection Error', err); - * } else { - * console.log('Connected!'); - * } - * }); + * A class for performing management operations against a bucket. This class should not be instantiated directly, but instead through the use of the Bucket#manager method instead. */ - export class Connection { - constructor(callback: ConnectCallback); - constructor(options: ConnectionOptions, callback: ConnectCallback); - - ///////////////////////// - // Members - ///////////////////////// + interface BucketManager { + + /** + * Flushes the cluster, deleting all data stored within this bucket. Note that this method requires the Flush permission to be enabled on the bucket from the management console before it will work. + * @param callback The callback function. + */ + flush(callback: Function): void; /** - * Get information about the Couchnode version (i.e. this library) as an array - * of [versionNumber, versionString]. - * - * @member {Mixed[]} Connection#clientVersion + * Retrieves a specific design document from this bucket. + * @param name + * @param callback The callback function. */ - clientVersion: any[]; + getDesignDocument(name: string, callback: Function): void; + /** + * Retrieves a list of all design documents registered to a bucket. + * @param callback The callback function. + */ + getDesignDocuments(callback: Function): void; + + /** + * Registers a design document to this bucket, failing if it already exists. + * @param name + * @param data + * @param callback The callback function. + * @returns {} + */ + insertDesignDocument(name: string, data: any, callback: Function): void; + + /** + * Unregisters a design document from this bucket. + * @param name + * @param callback The callback function. + * @returns {} + */ + removeDesignDocument(name: string, callback: Function): void; + + /** + * Registers a design document to this bucket, overwriting any existing design document that was previously registered. + * @param name + * @param data + * @param callback The callback function. + * @returns {} + */ + upsertDesignDocument(name: string, data: any, callback: Function): void; + } + + /** + * Class for dynamically construction of view queries. This class should never be constructed directly, instead you should use ViewQuery.from to construct this object. + */ + class ViewQuery { + /** + * Instantiates a ViewQuery object for the specified design document and view name. + * @param ddoc The design document to use. + * @param name The view to use. + */ + static from(ddoc: string, name: string): ViewQuery; + + /** + * Specifies the design document and view name to use for this query. + * @param ddoc The design document to use. + * @param name The view to use. + */ + from(ddoc: string, name: string): ViewQuery; + + /** + * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. + * @param opts + */ + custom(opts: any): ViewQuery; + + /** + * Flag to request a view request accross all nodes in the case of a development view. + * @param full_set + */ + full_set(full_set: boolean): ViewQuery; + + /** + * Specifies whether to preform grouping during view execution. + * @param group + */ + group(group: boolean): ViewQuery; + + /** + * Specifies the level at which to perform view grouping. + * @param group_level + */ + group_level(group_level: number): ViewQuery; + + /** + * Specifies a range of document id's to retrieve from the index. + * @param start + * @param end + */ + id_range(start: any, end: any): ViewQuery; + + /** + * Flag to request a view request include the full document value. + * @param include_docs + */ + include_docs(include_docs: boolean): ViewQuery; + + /** + * Specifies a specified key to retrieve from the index. + * @param key + */ + key(key: any): ViewQuery; + + /** + * Specifies a list of keys you wish to retrieve from the index. + * @param keys + */ + keys(key: any[]): ViewQuery; + + /** + * Specifies the maximum number of results to return. + * @param limit + */ + limit(limit: number): ViewQuery; + + /** + * Sets the error handling mode for this query. + * @param mode + */ + on_error(mode: ViewQuery.ErrorMode): ViewQuery; + + /** + * Specifies the desired ordering for the results. + * @param order + */ + order(order: ViewQuery.Order): ViewQuery; + + /** + * Specifies a range of keys to retrieve from the index. You may specify both a start and an end point and additionally specify whether or not the end value is inclusive or exclusive. + * @param start + * @param end + * @param inclusive_end + */ + range(start: any | any[], end: any | any[], inclusive_end?: boolean): ViewQuery; + + /** + * Specifies whether to execute the map-reduce reduce step. + * @param reduce + */ + reduce(reduce: boolean): ViewQuery; + + /** + * Specifies how many results to skip from the beginning of the result set. + * @param skip + */ + skip(skip: number): ViewQuery; + + /** + * Specifies how this query will affect view indexing, both before and after the query is executed. + * @param stale + */ + stale(stale: ViewQuery.Update): ViewQuery; + } + + module ViewQuery { + /** + * Enumeration for specifying on_error behaviour. + */ + enum ErrorMode { + /** + * Continues querying when an error occurs. + */ + CONTINUE, + + /** + * Stops and errors query when an error occurs. + */ + STOP + } + + /** + * Enumeration for specifying view result ordering. + */ + enum Order { + /** + * Orders with lower values first and higher values last. + */ + ASCENDING, + + /** + * Orders with higher values first and lower values last. + */ + DESCENDING + } + + /** + * Enumeration for specifying view update semantics. + */ + enum Update { + /** + * Causes the view to be fully indexed before results are retrieved. + */ + BEFORE, + + /** + * Allows the index to stay in whatever state it is already in prior retrieval of the query results. + */ + NONE, + + /** + * Forces the view to be indexed after the results of this query has been fetched. + */ + AFTER + } + } + + /** + * Class for dynamically construction of N1QL queries. This class should never be constructed directly, instead you should use the N1qlQuery.fromString static method to instantiate a N1qlStringQuery. + */ + class N1qlQuery { + /** + * Creates a query object directly from the passed query string. + * @param str + */ + static fromString(str: string): N1qlStringQuery; + + /** + * Returns the fully prepared string representation of this query. + */ + toString(): string; + } + + module N1qlQuery { + /** + * Enumeration for specifying N1QL consistency semantics. + */ + enum Consistency { + /** + * This is the default (for single-statement requests). + */ + NOT_BOUND, + + /** + * This implements strong consistency per request. + */ + REQUEST_PLUS, + + /** + * This implements strong consistency per statement. + */ + STATEMENT_PLUS + } + } + + /** + * Class for holding a explicitly defined N1QL query string. + */ + class N1qlStringQuery extends N1qlQuery { + /** + * Specifies whether this query is adhoc or should be prepared. + * @param adhoc + */ + adhoc(adhoc: boolean): N1qlStringQuery; + + /** + * Specify the consistency level for this query. + * @param val + */ + consistency(val: N1qlQuery.Consistency): N1qlStringQuery; + + /** + * Returns the fully prepared object representation of this query. + */ + toObject(): any; + + /** + * Returns the fully prepared string representation of this query. + */ + toString(): string; + } + + /** + * Class for dynamically construction of spatial queries. This class should never be constructed directly, instead you should use SpatialQuery.from to construct this object. + */ + class SpatialQuery { + /** + * Instantiates a SpatialQuery object for the specified design document and view name. + * @param ddoc The design document to use. + * @param name The view to use. + */ + static from(ddoc: string, name: string): SpatialQuery; + + /** + * Specifies the design document and view name to use for this query. + * @param ddoc + * @param name + */ + from(ddoc: string, name: string): SpatialQuery; + + /** + * Specifies a bounding box to query the index for. This value must be an array of exactly 4 numbers which represents the left, top, right and bottom edges of the bounding box (in that order). + * @param bbox + */ + bbox(bbox: number[]): SpatialQuery; + + /** + * Allows you to specify custom view options that may not be available though the fluent interface defined by this class. + * @param opts + */ + custom(opts: any): SpatialQuery; + + /** + * Specifies the maximum number of results to return. + * @param limit + */ + limit(limit: number): SpatialQuery; + + /** + * Specifies how many results to skip from the beginning of the result set. + * @param skip + */ + skip(skip: number): SpatialQuery; + + /** + * Specifies how this query will affect view indexing, both before and after the query is executed. + * @param stale + */ + stale(stale: SpatialQuery.Update): SpatialQuery; + } + + module SpatialQuery { + /** + * Enumeration for specifying view update semantics. + */ + enum Update { + /** + * Causes the view to be fully indexed before results are retrieved. + */ + BEFORE, + + /** + * Allows the index to stay in whatever state it is already in prior retrieval of the query results. + */ + NONE, + + /** + * Forces the view to be indexed after the results of this query has been fetched. + */ + AFTER + } + } + + /** + * The Bucket class represents a connection to a Couchbase bucket. Never instantiate this class directly. Instead use the Cluster#openBucket method instead. + */ + interface Bucket { + /** + * Returns the version of the Node.js library as a string. + */ + clientVersion: string; + + /** + * Gets or sets the config throttling in milliseconds. The config throttling is the time that Bucket will wait before forcing a configuration refresh. If no refresh occurs before this period while a configuration is marked invalid, an update will be triggered. + */ + configThrottle: number; + + /** + * Sets or gets the connection timeout in milliseconds. This is the timeout value used when connecting to the configuration port during the initial connection (in this case, use this as a key in the 'options' parameter in the constructor) and/or when Bucket attempts to reconnect in-situ (if the current connection has failed). + */ connectionTimeout: number; - lcbVersion: any[]; + /** + * Gets or sets the durability interval in milliseconds. The durability interval is the time that Bucket will wait between requesting new durability information during a durability poll. + */ + durabilityInterval: number; + /** + * Gets or sets the durability timeout in milliseconds. The durability timeout is the time that Bucket will wait for a response from the server in regards to a durability request. If there are no responses received within this time frame, the request fails with an error. + */ + durabilityTimeout: number; + + /** + * Returns the libcouchbase version as a string. This information will usually be in the format of 2.4.0-fffffff representing the major, minor, patch and git-commit that the built libcouchbase is based upon. + */ + lcbVersion: string; + + /** + * Gets or sets the management timeout in milliseconds. The management timeout is the time that Bucket will wait for a response from the server for a management request. If the response is not received within this time frame, the request is failed out with an error. + */ + managementTimeout: number; + + /** + * Sets or gets the node connection timeout in msecs. This value is similar to Bucket#connectionTimeout, but defines the time to wait for a particular node to respond before trying the next one. + */ + nodeConnectionTimeout: number; + + /** + * Gets or sets the operation timeout in milliseconds. The operation timeout is the time that Bucket will wait for a response from the server for a CRUD operation. If the response is not received within this time frame, the operation is failed with an error. + */ operationTimeout: number; - serverNodes: string[]; + /** + * Gets or sets the view timeout in milliseconds. The view timeout is the time that Bucket will wait for a response from the server for a view request. If the response is not received within this time frame, the request fails with an error. + */ + viewTimeout: number; - ///////////////////////// - // Methods - ///////////////////////// + /** + * Similar to Bucket#upsert, but instead of setting a new key, it appends data to the existing key. Note that this function only makes sense when the stored data is a string; 'appending' to a JSON document may result in parse errors when the document is later retrieved. + * @param key The target document key. + * @param fragment The document's contents to append. + * @param callback The callback function. + */ + append(key: any | Buffer, fragment: any, callback: Bucket.OpCallback): void; - // TODO: not sure if these methods return void. Docmentation mentions nothing. - // TODO: For "multi" key methods the documentation says callback can be either KeyCallback | MultiCallback. Sticking with MultiCallback. - // TODO: Verify that kv is not a key value and indeed is string[] e.g. getMulti , getReplicaMulti, lockMulti + /** + * + * @param key The target document key. + * @param fragment The document's contents to append. + * @param options The options object. + * @param callback The callback function. + */ + append(key: any | Buffer, fragment: any, options: AppendOptions, callback: Bucket.OpCallback): void; - add(key: string, value: any, callback: KeyCallback): void; - add(key: string, value: any, options: AddOptions, callback: KeyCallback): void; - addMulti(kv: { [key: string]: AddMultiOptionsForValue }, options: AddMultiOptions, callback: MultiCallback): void; + /** + * Increments or decrements a key's numeric value. + * Note that JavaScript does not support 64-bit integers (while libcouchbase and the server do). You might receive an inaccurate value if the number is greater than 53-bits (JavaScript's maximum integer precision). + * @param key The target document key. + * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. + * @param callback The callback function. + */ + counter(key: any | Buffer, delta: number, callback: Bucket.OpCallback): void; + + /** + * + * @param key The target document key. + * @param delta The amount to add or subtract from the counter value. This value may be any non-zero integer. + * @param options The options object. + * @param callback The callback function. + */ + counter(key: any | Buffer, delta: number, options: CounterOptions, callback: Bucket.OpCallback): void; - append(key: string, fragment: string, callback: KeyCallback): void; - append(key: string, fragment: string, options: AppendOptions, callback: KeyCallback): void; - append(key: string, fragment: Buffer, callback: KeyCallback): void; - append(key: string, fragment: Buffer, options: AppendOptions, callback: KeyCallback): void; - appendMulti(kv: { [key: string]: AppendMultiOptionsForValue }, options: AppendMultiOptions, callback: MultiCallback): void; + /** + * Shuts down this connection. + */ + disconnect(): void; - decr(key: string, callback: KeyCallback): void; - decr(key: string, options: DecrOptions, callback: KeyCallback): void; - decrMulti(kv: { [key: string]: DecrMultiOptionsForValue }, options: DecrMultiOptions, callback: MultiCallback): void; + /** + * Enables N1QL support on the client. A cbq-server URI must be passed. This method will be deprecated in the future in favor of automatic configuration through the connected cluster. + * @param hosts An array of host/port combinations which are N1QL servers attached to this cluster. + */ + enableN1ql(hosts: string | string[]): void; - get(key: string, callback: KeyCallback): void; - get(key: string, options: GetOptions, callback: KeyCallback): void; - getMulti(kv: string[], options: { [key: string]: GetMultiOptions }, callback:MultiCallback): void; + /** + * Retrieves a document. + * @param key The target document key. + * @param callback The callback function. + */ + get(key: any | Buffer, callback: Bucket.OpCallback): void; - getDesignDoc(name: string, callback: DDocCallback): void; + /** + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + get(key: any | Buffer, options: any, callback: Bucket.OpCallback): void; - getReplica(key: string, callback: KeyCallback): void; - getReplica(key: string, options: GetReplicaOptions, callback: KeyCallback): void; - getReplicaMulti(kv: string[], options: GetReplicaMultiOptions, callback: MultiCallback): void; + /** + * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. + * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. + * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. + * @param key The target document key. + * @param callback The callback function. + */ + getAndLock(key: any, callback: Bucket.OpCallback): void; - incr(key: string, callback: KeyCallback): void; - incr(key: string, options: IncrOptions, callback: KeyCallback): void; - incrMulti(kv: { [key: string]: IncrMultiOptionsForValue }, options: IncrMultiOptions, callback: MultiCallback): void; + /** + * Lock the document on the server and retrieve it. When an document is locked, its CAS changes and subsequent operations on the document (without providing the current CAS) will fail until the lock is no longer held. + * This function behaves identically to Bucket#get in that it will return the value. It differs in that the document is also locked. This ensures that attempts by other client instances to access this document while the lock is held will fail. + * Once locked, a document can be unlocked either by explicitly calling Bucket#unlock or by performing a storage operation (e.g. Bucket#upsert, Bucket#replace, Bucket::append) with the current CAS value. Note that any other lock operations on this key will fail while a document is locked. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + * @returns {} + */ + getAndLock(key: any, options: GetAndLockOptions, callback: Bucket.OpCallback): void; - lock(key: string, callback: KeyCallback): void; - lock(key: string, options: LockOptions, callback: KeyCallback): void; - lockMulti(kv: string[], options: { [key: string]: LockMultiOptions }, callback: MultiCallback): void; + /** + * Retrieves a document and updates the expiry of the item at the same time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). + * @param options The options object. + * @param callback The callback function. + */ + getAndTouch(key: any | Buffer, expiry: number, options: any, callback: Bucket.OpCallback): void; + + /** + * Retrieves a document and updates the expiry of the item at the same time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). + * @param callback The callback function. + */ + getAndTouch(key: any | Buffer, expiry: number, callback: Bucket.OpCallback): void; - observe(key: string, options: ObserveOptions, callback: KeyCallback): void; - observeMulti(kv: { [key: string]: ObserveMultiOptionsForValue }, options: { [key: string]: ObserveMultiOptions }, callback: MultiCallback): void; + /** + * Retrieves a list of keys + * @param keys The target document keys. + * @param callback The callback function. + */ + getMulti(key: any[] | Buffer[], callback: Bucket.MultiGetCallback): void; - on(event: string, listener: Function): void; - on(event: 'connect', listener: (err: Error) => any): void; - on(event: 'error', listener: (err: Error) => any): void; + /** + * Get a document from a replica server in your cluster. + * @param key The target document key. + * @param callback The callback function. + */ + getReplica(key: any | Buffer, callback: Bucket.OpCallback): void; - prepend(key: string, fragment: string, callback: KeyCallback): void; - prepend(key: string, fragment: string, options: PrependOptions, callback: KeyCallback): void; - prepend(key: string, fragment: Buffer, callback: KeyCallback): void; - prepend(key: string, fragment: Buffer, options: PrependOptions, callback: KeyCallback): void; - prependMulti(kv: { [key: string]: PrependMultiOptionsFoValue }, options: { [key: string]: PrependMultiOptions }, callback: MultiCallback): void; + /** + * Get a document from a replica server in your cluster. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + getReplica(key: any | Buffer, options: GetReplicaOptions, callback: Bucket.OpCallback): void; - remove(key: string, callback: KeyCallback): void; - remove(key: string, options: RemoveOptions, callback: KeyCallback): void; - removeMulti(kv: { [key: string]: RemoveMultiOptionsForValue }, options: RemoveMultiOptions, callback: MultiCallback): void; - removeMulti(kv: string[], options: RemoveMultiOptions, callback: MultiCallback): void; + /** + * Identical to Bucket#upsert but will fail if the document already exists. + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + insert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; + + /** + * Identical to Bucket#upsert but will fail if the document already exists. + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + insert(key: any | Buffer, value: any, options: InsertOptions, callback: Bucket.OpCallback): void; - removeDesignDoc(name: string, callback: DDocCallback): void; + /** + * Returns an instance of a BuckerManager for performing management operations against a bucket. + */ + manager(): BucketManager; - replace(key: string, value: any, callback: KeyCallback): void; - replace(key: string, value: any, options: ReplaceOptions, callback: KeyCallback): void; - replaceMulti(kv: { [key: string]: ReplaceMultiOptionsForValue }, options: ReplaceMultiOptions, callback: MultiCallback): void; + /** + * Like Bucket#append, but prepends data to the existing value. + * @param key The target document key. + * @param fragment The document's contents to prepend. + * @param callback The callback function. + */ + prepend(key: any, fragment: any, callback: Bucket.OpCallback): void; - set(key: string, value: any, callback: KeyCallback): void; - set(key: string, value: any, options: SetOptions, callback: KeyCallback): void; - setMulti(kv: { [key: string]: SetMultiOptionsForValue }, options: SetMultiOptions, callback: MultiCallback): void; + /** + * Like Bucket#append, but prepends data to the existing value. + * @param key The target document key. + * @param fragment The document's contents to prepend. + * @param options The options object. + * @param callback The callback function. + */ + prepend(key: any, fragment: any, options: PrependOptions, callback: Bucket.OpCallback): void; - setDesignDoc(name: string, data: any, callback: DDocCallback): void; + /** + * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. + * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. + * @param query The query to execute. + * @param callback The callback function. + */ + query(query: ViewQuery | N1qlQuery, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; - shutdown(): void; + /** + * Executes a previously prepared query object. This could be a ViewQuery or a N1qlQuery. + * Note: N1qlQuery queries are currently an uncommitted interface and may be subject to change in 2.0.0's final release. + * @param query The query to execute. + * @param params A list or map to do replacements on a N1QL query. + * @param callback The callback function. + */ + query(query: ViewQuery | N1qlQuery, params: Object | Array, callback: Bucket.QueryCallback): Bucket.ViewQueryResponse | Bucket.N1qlQueryResponse; - stats(callback: StatsCallback): void; - stats(key: string, callback: StatsCallback): void; + /** + * Deletes a document on the server. + * @param key The target document key. + * @param callback The callback function. + */ + remove(key: any | Buffer, callback: Bucket.OpCallback): void; - strError(code: number): string; + /** + * Deletes a document on the server. + * @param key The target document key. + * @param options The options object. + * @param callback The callback function. + */ + remove(key: any | Buffer, options: RemoveOptions, callback: Bucket.OpCallback): void; - touch(key: string, callback: KeyCallback): void; - touch(key: string, options: TouchOptions, callback: KeyCallback): void; + /** + * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + replace(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; - unlock(key: string, options: UnlockOptions, callback: KeyCallback): void; - unlockMulti(kv: { [key: string]: UnlockMultiOptionsForValue }, options: { [key: string]: UnlockMultiOptions }, callback: UnlockMultiOptions): void; + /** + * Identical to Bucket#upsert, but will only succeed if the document exists already (i.e. the inverse of Bucket#insert). + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + replace(key: any | Buffer, value: any, options: ReplaceOptions, callback: Bucket.OpCallback): void; - view(ddoc: string, name: string): ViewQuery; - view(ddoc: string, name: string, query: any): ViewQuery; + /** + * Configures a custom set of transcoder functions for encoding and decoding values that are being stored or retreived from the server. + * @param encoder The function for encoding. + * @param decoder The function for decoding. + */ + setTranscoder(encoder: Bucket.EncoderFunction, decoder: Bucket.DecoderFunction): void; + + /** + * Update the document expiration time. + * @param key The target document key. + * @param expiry The expiration time to use. If a value of 0 is provided, then the current expiration time is cleared and the key is set to never expire. Otherwise, the key is updated to expire in the time provided (in seconds). Values larger than 302460*60 seconds (30 days) are interpreted as absolute times (from the epoch). + * @param options The options object. + * @param callback The callback function. + */ + touch(key: any | Buffer, expiry: number, options: TouchOptions, callback: Bucket.OpCallback): void; + + /** + * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. + * @param key The target document key. + * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. + * @param callback The callback function. + */ + unlock(key: any | Buffer, cas: Bucket.CAS, callback: Bucket.OpCallback): void; + + /** + * Unlock a previously locked document on the server. See the Bucket#lock method for more details on locking. + * @param key The target document key. + * @param cas The CAS value returned when the key was locked. This operation will fail if the CAS value provided does not match that which was the result of the original lock operation. + * @param options The options object. + * @param callback The callback function. + */ + unlock(key: any | Buffer, cas: Bucket.CAS, options: any, callback: Bucket.OpCallback): void; + + /** + * Stores a document to the bucket. + * @param key The target document key. + * @param value The document's contents. + * @param callback The callback function. + */ + upsert(key: any | Buffer, value: any, callback: Bucket.OpCallback): void; + + /** + * Stores a document to the bucket. + * @param key The target document key. + * @param value The document's contents. + * @param options The options object. + * @param callback The callback function. + */ + upsert(key: any | Buffer, value: any, options: UpsertOptions, callback: Bucket.OpCallback): void; } - export class ViewQuery { - firstPage(q: any, callback: Function): void; - query(q: any, callback: Function): void; - } + module Bucket { + + /** + * his is used as a callback from executed queries. It is a shortcut method that automatically subscribes to the rows and error events of the Bucket.ViewQueryResponse. + */ + interface QueryCallback { + /** + * @param error The error for the operation. This can either be an Error object or a falsy value. + * @param rows The rows returned from the query. + * @param meta The metadata returned by the query. + */ + (error: CouchbaseError, rows: any[], meta: Bucket.ViewQueryResponse.Meta): void; + } -} + /** + * Single-Key callbacks. + * This callback is passed to all of the single key functions. + * It returns a result objcet containing a combination of a CAS and a value, depending on which operation was invoked. + */ + interface OpCallback { + /** + * @param error The error for the operation. This can either be an Error object or a value which evaluates to false (null, undefined, 0 or false). + * @param result The result of the operation that was executed. This usually contains at least a cas property, and on some operations will contain a value property as well. + */ + (error: CouchbaseError | number, result: any): void; + } + + /** + * Multi-Get Callback. + * This callback is used to return results from a getMulti operation. + */ + interface MultiGetCallback { + /** + * @param error The number of keys that failed to be retrieved. The precise errors are available by checking the error property of the individual documents. + * @param results This is a map of keys to results. The result for each key will optionally contain an error if one occured, or if no error occured will contain the CAS and value of the document. + */ + (error: number, results: any[]): void; + } + + /** + * Transcoder Encoding Function. + * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction. + */ + interface EncoderFunction { + /** + * Transcoder Encoding Function. + * This function will receive a value when a storage operation is invoked that needs to encode user-provided data for storage into Couchbase. It expects to be returned a Buffer object to store along with an integer representing any flag metadata relating to how to decode the key later using the matching DecoderFunction. + * @param value The value needing encoding. + */ + (value: any): Bucket.TranscoderDoc; + } + + /** + * Transcoder Decoding Function. + * This function will receive an object containing a Buffer value and an integer value representing any flags metadata whenever a retrieval operation is executed. It is expected that this function will return a value representing the original value stored and encoded with its matching EncoderFunction. + */ + interface DecoderFunction { + /** + * + * @param doc The data from Couchbase to decode. + */ + (doc: Bucket.TranscoderDoc): any + } + + /** + * The CAS value is a special object that indicates the current state of the item on the server. Each time an object is mutated on the server, the value is changed. CAS objects can be used in conjunction with mutation operations to ensure that the value on the server matches the local value retrieved by the client. This is useful when doing document updates on the server as you can ensure no changes were applied by other clients while you were in the process of mutating the document locally. + * In the Node.js SDK, the CAS is represented as an opaque value. As such,y ou cannot generate CAS objects, but should rather use the values returned from a Bucket.OpCallback. + */ + interface CAS { + + } + + /** + * An event emitter allowing you to bind to various query result set events. + */ + interface N1qlQueryResponse extends events.EventEmitter { + + } + + module N1qlQueryResponse { + /** + * The meta-information available from a view query response. + */ + interface Meta { + /** + * The identifier for this query request. + */ + requestID: number; + } + } + + /** + * A class used in relation to transcoders. + */ + class TranscoderDoc { + value: Buffer; + flags: number; + } + + /** + * An event emitter allowing you to bind to various query result set events. + */ + interface ViewQueryResponse extends events.EventEmitter { + + } + + module ViewQueryResponse { + /** + * The meta-information available from a view query response. + */ + interface Meta { + /** + * The total number of rows available in the index of the view that was queried. + */ + total_rows: number; + } + } + } +} \ No newline at end of file diff --git a/cradle/cradle-tests.ts b/cradle/cradle-tests.ts new file mode 100644 index 0000000000..655e92a87b --- /dev/null +++ b/cradle/cradle-tests.ts @@ -0,0 +1,185 @@ +/// + +import cradle = require("cradle"); + +cradle.setup({ + host: 'living-room.couch', + cache: true, + raw: false, + forceSave: true +}); + +const connection = new cradle.Connection(); +const connection2 = new(cradle.Connection); +const connection3 = new(cradle.Connection)('173.45.66.92'); + +connection.databases(function(error, response) {}); +connection.config(function(error, response) {}); +connection.databases(function(error, response) {}); +connection.info(function(error, response) {}); +connection.stats(function(error, response) {}); +connection.activeTasks(function(error, response) {}); +connection.uuids(function(error, response) {}); +connection.uuids(10, function(error, response) {}); +connection.replicate({ + source: "database", + target: "targetDatabase" +}, function(error, response) {}); + +const db = connection.database('starwars'); + +db.exists(function (error, exists) { + if (error) { + console.log('error', error); + } else if (exists) { + console.log('the force is with you.'); + } else { + console.log('database does not exists.'); + db.create(function(error){ + /* do something if there's an erroror */ + /* populate design documents */ + }); + } +}); + +db.get<{ + name: string; +}>('vader', function (error, doc) { + doc.name; // 'Darth Vader' +}); + +db.get('luke', function (error, doc) { + doc.prop; +}); + + db.get(['luke', 'vader'], function (error, doc) { + // + }); + +db.save('skywalker', { + force: 'light', + name: 'Luke Skywalker' +}, function (error, res) { + if (error) { + // Handle erroror + } else { + // Handle success + } +}); + +db.save({ + force: 'dark', name: 'Darth' + }, function (err, res) { + // Handle response + }); + +db.save('luke', '1-94B6F82', { + force: 'dark', name: 'Luke' +}, function (err, res) { + // Handle response +}); + +db.save([ + { name: 'Yoda' }, + { name: 'Han Solo' }, + { name: 'Leia' } +], function (err, res) { + // Handle response +}); + +db.merge('luke', {jedi: true}, function (err, res) { + // Luke is now a jedi, + // but remains on the dark side of the force. +}); + +db.view('characters/all', function (err, res) { + res.forEach(function (row: any) { + console.log("%s is on the %s side of the force.", row.name, row.force); + }); +}); + +db.view('characters/all', {group: true, reduce: true} , function (err, res) { + res.forEach(function (row: any) { + console.log("%s is on the %s side of the force.", row.name, row.force); + }); + }); + + db.temporaryView({ + map: function (doc: any) { + // + } + }, function (err, res) { + if (err) console.log(err); + console.log(res); + }); + +db.remove('luke', '1-94B6F82', function (err, res) { + // Handle response +}); + +db.update('my_designdoc/update_handler_name', 'luke', undefined, { my_param: false }, function (err, res) { + // Handle the response, specified by the update handler +}); + +db.changes(function (err, list) { + list.forEach(function (change) { console.log(change) }); +}); + +db.changes({ since: 42 }, function (err, list) { + // +}); + +const feed = db.changes({ since: 42 }); + +feed.on('change', function (change: any) { + console.log(change); +}); + +const idAndRevData = { + id: 'luke', + rev: 'my-rev' +}; + +const attachmentData = { + name: 'fooAttachment.txt', + 'Content-Type': 'text/plain', + body: 'Foo document text' +}; + +db.saveAttachment(idAndRevData, attachmentData, function (err, reply) { + if (err) { + console.dir(err) + return + } + console.dir(reply) +}); + + +db.getAttachment('luke', 'foo.txt', function (err, reply) { + if (err) { + console.dir(err); + return; + } + console.dir(reply); +}); + +db.removeAttachment('luke', 'foo.txt', function (err, reply) { + if (err) { + console.dir(err); + return; + } + console.dir(reply); +}); + +db.info(function(error, response) {}); +db.all(function(error, response) {}); +db.all({ + body: { + keys: ['key1', 'key2'] + } +}, function(error, response) {}); +db.compact(function(error, response) {}); +db.compact('design', function(error, response) {}); +db.viewCleanup(function(error, response) {}); +db.replicate('database', function(error, response) {}); +db.replicate('database', {}, function(error, response) {}); diff --git a/cradle/cradle.d.ts b/cradle/cradle.d.ts new file mode 100644 index 0000000000..6434af26c5 --- /dev/null +++ b/cradle/cradle.d.ts @@ -0,0 +1,122 @@ +// Type definitions for cradle +// Project: https://github.com/flatiron/cradle +// Definitions by: Panu Horsmalahti +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "cradle" { + interface Options { + host?: string; + hostname?: string; + cache?: boolean; + raw?: boolean; + forceSave?: boolean; + auth?: string | { + username: string; + password: string; + } + ca?: string; + secure?: boolean; + retries?: number; + retryTimeout?: number; + maxSockets?: number; + } + + interface Callback { + (error: any, response: any): void; + } + + interface ErrorCallback { + (error: any): void; + } + + export class Connection { + constructor(uri?: string, port?: number, options?: Options); + database(name: string): Database; + databases(Callback: Callback): void; + config(callback: Callback): void; + info(callback: Callback): void; + stats(callback: Callback): void; + activeTasks(callback: Callback): void; + uuids(callback: Callback): void; + uuids(count: number, callback: Callback): void; + replicate(options: { + source: string | { + url: string; + }; + target: string | { + url: string; + }; + cancel?: boolean; + continuous?: boolean; + create_target?: boolean; + doc_ids?: string[]; + filter?: string; + proxy?: string; + query_params?: any; + }, callback: Callback): void; + } + + export interface ChangesOptions { + since: number; + } + + export class Database { + name: string; + get(id: string, callback: (error: any, document: any) => void): void; + get(id: string, callback: (error: any, document: T) => void): void; + get(id: string, rev: string, callback: (error: any, document: any) => void): void; + get(id: string, rev: string, callback: (error: any, document: T) => void): void; + get(ids: string[], callback: Callback): void; + save(document: any, callback: Callback): void; + save(id: string, document: any, callback: Callback): void; + save(id: string, revision: string, document: any, + callback: Callback): void; + save(document: T, callback: Callback): void; + save(id: string, document: T, callback: Callback): void; + save(id: string, revision: string, document: T, + callback: Callback): void; + save(documents: any[], callback: Callback): void; + merge(id: string, document: any, callback: Callback): void; + merge(id: string, document: T, callback: Callback): void; + remove(id: string, revision: string, callback: Callback): void; + update(name: string, id: string, queryObject: any, documentBody: any, + callback: Callback): void; + view(name: string, callback: Callback): void; + view(name: string, options: { + group?: boolean; + reduce?: boolean; + key?: string; + startkey?: any; + endkey?: any; + include_docs?: boolean; + limit?: number; + descending?: boolean; + }, callback: Callback): void; + temporaryView(view: any, callback: Callback): void; + create(callback: ErrorCallback): void; + exists(callback: (error: any, exists: boolean) => void): void; + destroy(callback: ErrorCallback): void; + changes(options: ChangesOptions): any; + changes(callback: (error: any, list: any[]) => void): void; + changes(options: ChangesOptions, callback: (error: any, + list: any[]) => void): void; + saveAttachment(idAndRevData: { + id: string; + rev: string; + }, attachmentData: any, callback: Callback): void; + getAttachment(id: string, attachmentName: string, + callback: Callback): void; + removeAttachment(id: string, attachmentName: string, + callback: Callback): void; + info(callback: Callback): void; + all(callback: Callback): void; + all(options: any, callback: Callback): void; + compact(callback: Callback): void; + compact(design: string, callback: Callback): void; + viewCleanup(callback: Callback): void; + replicate(target: string, callback: Callback): void; + replicate(target: string, options: any, callback: Callback): void; + } + + export function setup(options: Options): void; +} diff --git a/create-error/create-error-tests.ts b/create-error/create-error-tests.ts new file mode 100644 index 0000000000..76b66adf27 --- /dev/null +++ b/create-error/create-error-tests.ts @@ -0,0 +1,149 @@ +/// +/// +/// + +import * as createError from 'create-error'; +import * as assert from 'assert'; + +// Example taken from https://github.com/tgriesser/create-error/blob/0.3.1/README.md#use + +interface MyCustomError extends createError.Error { + messages: string[]; + someVal: string; +} +var MyCustomError = createError('MyCustomError'); + +interface SubCustomError extends MyCustomError { +} +var SubCustomError = createError(MyCustomError, 'CoolSubError', {messages: []}); + +var sub = new SubCustomError('My Message', {someVal: 'value'}); + +sub instanceof SubCustomError // true +sub instanceof MyCustomError // true +sub instanceof Error // true + +assert.deepEqual(sub.messages, []) // true +assert.equal(sub.someVal, 'value') // true + + +// Taken and adapted from https://github.com/tgriesser/create-error/blob/0.3.1/test/index.js + +var equal = assert.equal; +var deepEqual = assert.deepEqual; + +describe('create-error', function() { + + describe('error creation', function() { + + it('should create a new error', function() { + var TestingError = createError('TestingError'); + var a = new TestingError('msgA'); + var b = new TestingError('msgB'); + equal((a instanceof TestingError), true); + equal((a instanceof Error), true); + equal(a.message, 'msgA'); + equal(b.message, 'msgB'); + equal((a.stack.length > 0), true); + }); + + it('should attach properties in the second argument', function() { + interface TestingError extends createError.Error { + anArray: string[]; + } + var TestingError = createError('TestingError', {anArray: []}); + var a = new TestingError('Test the array'); + deepEqual(a.anArray, []); + }); + + it('should give the name "CustomError" if the name is omitted', function() { + var TestingError = createError(); + var a = new TestingError("msg"); + equal(a.name, 'CustomError'); + }); + + it('should not reference the same property in subsequent errors', function() { + interface TestingError extends createError.Error { + anArray: string[]; + } + var TestingError = createError('TestingError', {anArray: []}); + var a = new TestingError('Test the array'); + a.anArray.push('a'); + var b = new TestingError(''); + deepEqual(b.anArray, []); + }); + + it('should allow for empty objects on the cloned hash', function() { + interface TestingError extends createError.Error { + anEmptyObj: Object; + } + var TestingError = createError('TestingError', {anEmptyObj: Object.create(null)}); + var a = new TestingError('Test the array'); + deepEqual(a.anEmptyObj, Object.create(null)); + }); + + it('attaches attrs in the second arg of the error ctor, #3', function() { + interface RequestError extends createError.Error { + status: number; + } + var RequestError = createError('RequestError', {status: 400}); + var reqErr = new RequestError('404 Error', {status: 404}); + equal(reqErr.status, 404); + equal(reqErr.message, '404 Error'); + equal(reqErr.name, 'RequestError'); + }); + + }); + + describe('subclassing errors', function() { + + it('takes an object in the first argument', function() { + var TestingError = createError('TestingError'); + var SubTestingError = createError(TestingError, 'SubTestingError'); + var x = new SubTestingError(); + equal((x instanceof SubTestingError), true); + equal((x instanceof TestingError), true); + equal((x instanceof Error), true); + }); + + it('attaches the properties appropriately.', function() { + interface SubTestingError extends createError.Error { + key: string[]; + } + var TestingError = createError('TestingError'); + var SubTestingError = createError(TestingError, 'SubTestingError', {key: []}); + var x = new SubTestingError(); + deepEqual(x.key, []); + }); + + it('allows for a default message, #4', function() { + var TestingError = createError('TestingError', {message: 'Error with testing'}); + var x = new TestingError(); + equal(x.message, 'Error with testing'); + }); + + }); + + describe('invalid values sent to the second argument', function() { + + it('should ignore falsy values', function() { + var TestingError = createError('TestingError', ''); + var TestingError2 = createError('TestingError', null); + var TestingError3 = createError('TestingError', void 0); + var a = new TestingError('Test the array'); + var b = new TestingError2('Test the array'); + var c = new TestingError3('Test the array'); + }); + + it('should ignore arrays', function() { + interface TestingError extends createError.Error { + anArray: string[]; + } + var TestingError = createError('TestingError', [{anArray: []}]); + var a = new TestingError('Test the array'); + equal(a.anArray, void 0); + }); + + }); + +}); diff --git a/create-error/create-error.d.ts b/create-error/create-error.d.ts new file mode 100644 index 0000000000..5db02e474a --- /dev/null +++ b/create-error/create-error.d.ts @@ -0,0 +1,21 @@ +// Type definitions for create-error.js 0.3.1 +// Project: https://github.com/tgriesser/create-error +// Definitions by: Tanguy Krotoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'create-error' { + // FIXME See Global type references https://github.com/Microsoft/TypeScript/issues/983 + type Err = Error; + + namespace createError { + interface Error extends Err { + new (message?: string, obj?: any): T; + } + } + + function createError(): createError.Error; + function createError>(name: string, properties?: any): T; + function createError>(Target: createError.Error, name?: string, properties?: any): T; + + export = createError; +} diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts new file mode 100644 index 0000000000..f8b5606070 --- /dev/null +++ b/cucumber/cucumber-tests.ts @@ -0,0 +1,40 @@ +/// + +function StepSample() { + type Callback = cucumber.CallbackStepDefinition; + var step = this; + var hook = this; + + hook.Before(function(scenario, callback){ + scenario.isFailed() && callback.pending(); + }) + + hook.Around(function(scenario, runScenario) { + scenario.isFailed() && runScenario(null, function(){ + console.log('finish tasks'); + }); + }); + + hook.registerHandler('AfterFeatures', function (event, callback) { + callback(); + }); + + step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) { + this.visit('https://github.com/cucumber/cucumber-js', callback); + }); + + step.When(/^I go to the README file$/, function(title:string, callback:Callback) { + callback.pending(); + }); + + step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) { + var pageTitle = this.browser.text('title'); + + if (title === pageTitle) { + callback(); + } else { + callback(new Error("Expected to be on page with title " + title)); + } + }); +} + diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts new file mode 100644 index 0000000000..75faeff7a5 --- /dev/null +++ b/cucumber/cucumber.d.ts @@ -0,0 +1,57 @@ +// Type definitions for cucumber-js +// Project: https://github.com/cucumber/cucumber-js +// Definitions by: Abraão Alves +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module cucumber { + + export interface CallbackStepDefinition{ + pending : () => Thenable; + (errror?:any):void; + } + + interface StepDefinitionCode { + (...stepArgs: Array): Thenable | any | void; + } + + interface StepDefinitionOptions{ + timeout?: number; + } + + export interface StepDefinitions { + Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Given(pattern: RegExp | string, code: StepDefinitionCode): void; + When(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + When(pattern: RegExp | string, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void; + Then(pattern: RegExp | string, code: StepDefinitionCode): void; + setDefaultTimeout(time:number): void; + } + + interface HookScenario{ + attach(text: string, mimeType?: string, callback?: (err?:any) => void): void; + isFailed() : boolean; + } + + interface HookCode { + (scenario: HookScenario, callback?: CallbackStepDefinition): void; + } + + interface AroundCode{ + (scenario: HookScenario, runScenario?: (error:string, callback?:Function)=>void): void; + } + + export interface Hooks { + Before(code: HookCode): void; + After(code: HookCode): void; + Around(code: AroundCode):void; + setDefaultTimeout(time:number): void; + registerHandler(handlerOption:string, code:(event:any, callback:CallbackStepDefinition) =>void): void; + } +} + +declare module 'cucumber'{ + export = cucumber; +} \ No newline at end of file diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 396d0307e6..1f5ebe7a1e 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -791,7 +791,7 @@ declare module d3 { /** * Returns the first non-null element in the selection, or null otherwise. */ - node(): EventTarget; + node(): Node; /** * Returns the total number of elements in the selection. @@ -854,7 +854,7 @@ declare module d3 { call(func: (transition: Transition, ...args: any[]) => any, ...args: any[]): Transition; empty(): boolean; - node(): EventTarget; + node(): Node; size(): number; } @@ -3032,6 +3032,46 @@ declare module d3 { padding(padding: number): Pack; } + export function partition(): Partition; + export function partition(): Partition; + + module partition { + interface Link { + source: T; + target: T; + } + + interface Node { + parent?: Node; + children?: number; + value?: number; + depth?: number; + x?: number; + y?: number; + dx?: number; + dy?: number; + } + + } + + export interface Partition { + nodes(root: T): T[]; + + links(nodes: T[]): partition.Link[]; + + children(): (node: T, depth: number) => T[]; + children(children: (node: T, depth: number) => T[]): Partition; + + sort(): (a: T, b: T) => number; + sort(comparator: (a: T, b: T) => number): Partition; + + value(): (node: T) => number; + value(value: (node: T) => number): Partition; + + size(): [number, number]; + size(size: [number, number]): Partition; + } + export function pie(): Pie; export function pie(): Pie; diff --git a/dagre/dagre.d.ts b/dagre/dagre.d.ts index fb5bd95d97..d16df52163 100644 --- a/dagre/dagre.d.ts +++ b/dagre/dagre.d.ts @@ -31,3 +31,7 @@ declare module Dagre{ } declare var dagre: Dagre.DagreFactory; + +declare module "dagre" { + export = dagre; +} diff --git a/debounce/debounce-tests.ts b/debounce/debounce-tests.ts new file mode 100644 index 0000000000..947fbcdae5 --- /dev/null +++ b/debounce/debounce-tests.ts @@ -0,0 +1,14 @@ +/// + +import debounce from "debounce"; + +const doThings = () => 1; + +debounce(function(){ doThings(); })(); + +debounce(function(){ doThings(); }, 1000)(); + +debounce(function(a: string){ doThings(); }, 1000)("foo"); + +// Immediate true should return the value +const imm1: number = (debounce((x: number) => x * 2, 100, true))(2); diff --git a/debounce/debounce.d.ts b/debounce/debounce.d.ts new file mode 100644 index 0000000000..7aa24601a7 --- /dev/null +++ b/debounce/debounce.d.ts @@ -0,0 +1,11 @@ +// Type definitions for compose-function +// Project: https://github.com/component/debounce +// Definitions by: Denis Sokolov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "debounce" { + // Overload on boolean constants would allow us to narrow further, + // but it is not implemented for TypeScript yet + function f(f: A, interval?: number, immediate?: boolean): A + export default f; +} diff --git a/debug/debug-tests.ts b/debug/debug-tests.ts index 63a0a3ac4e..a264003409 100644 --- a/debug/debug-tests.ts +++ b/debug/debug-tests.ts @@ -1,4 +1,3 @@ -/// /// import debug = require("debug"); @@ -6,7 +5,7 @@ import debug = require("debug"); debug.disable(); debug.enable("DefinitelyTyped:*"); -var log: debug.Debugger = debug("DefinitelyTyped:log"); +var log:debug.IDebugger = debug("DefinitelyTyped:log"); log("Just text"); log("Formatted test (%d arg)", 1); @@ -15,6 +14,6 @@ log("Formatted %s (%d args)", "test", 2); log("Enabled?: %s", debug.enabled("DefinitelyTyped:log")); log("Namespace: %s", log.namespace); -var error: debug.Debugger = debug("DefinitelyTyped:error"); +var error:debug.IDebugger = debug("DefinitelyTyped:error"); error.log = console.error.bind(console); error("This should be printed to stderr"); diff --git a/debug/debug.d.ts b/debug/debug.d.ts index 1a71725a86..b43cd238c3 100644 --- a/debug/debug.d.ts +++ b/debug/debug.d.ts @@ -1,30 +1,38 @@ // Type definitions for debug // Project: https://github.com/visionmedia/debug -// Definitions by: Seon-Wook Park +// Definitions by: Seon-Wook Park , Gal Talmor // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module "debug" { - - function d(namespace: string): d.Debugger; - - module d { - export var log: Function; - - function enable(namespaces: string): void; - function disable(): void; - - function enabled(namespace: string): boolean; - - export interface Debugger { - (formatter: any, ...args: any[]): void; - - enabled: boolean; - log: Function; - namespace: string; - } - } - - export = d; +declare var debug: debug.IDebug; +// Support AMD require +declare module 'debug' { + export = debug; } +declare module debug { + export interface IDebug { + (namespace: string): debug.IDebugger, + coerce: (val: any) => any, + disable: () => void, + enable: (namespaces: string) => void, + enabled: (namespaces: string) => boolean, + + names: string[], + skips: string[], + + formatters: IFormatters + } + + export interface IFormatters { + [formatter: string]: Function + } + + export interface IDebugger { + (formatter: any, ...args: any[]): void; + + enabled: boolean; + log: Function; + namespace: string; + } +} diff --git a/devextreme/devextreme-15.1.8.d.ts b/devextreme/devextreme-15.1.8.d.ts new file mode 100644 index 0000000000..83e69504be --- /dev/null +++ b/devextreme/devextreme-15.1.8.d.ts @@ -0,0 +1,6580 @@ +// Type definitions for DevExtreme 15.1.8 +// Project: http://js.devexpress.com/ +// Definitions by: DevExpress Inc. +// Definitions: https://github.com/borisyankov/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; + /** Requests that the browser call a specified function to update animation before the next repaint. */ + export function requestAnimationFrame(callback: Function): number; + /** Cancels an animation frame request scheduled with the requestAnimationFrame method. */ + 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; + } + 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 Windows8. */ + win8?: 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 { + inserted?: (values: Object, key: any) => void; + inserting?: (values: Object) => void; + loaded?: (result: Array) => void; + loading?: (loadOptions: LoadOptions) => void; + modified?: () => void; + modifying?: () => void; + removed?: (key: any) => void; + removing?: (key: any) => void; + updated?: (key: any, values: Object) => void; + updating?: (key: any, values: Object) => void; + /** 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 { + inserted: JQueryCallback; + inserting: JQueryCallback; + loaded: JQueryCallback; + loading: JQueryCallback; + modified: JQueryCallback; + modifying: JQueryCallback; + removed: JQueryCallback; + removing: JQueryCallback; + updated: JQueryCallback; + updating: JQueryCallback; + 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; + } + /** An object that provides access to a data web service or local data storage for collection container widgets. */ + export class DataSource implements EventsMixin { + constructor(options?: DataSourceOptions); + changed: JQueryCallback; + loadError: JQueryCallback; + loadingChanged: JQueryCallback; + /** 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(): JQueryPromise>; + /** 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; + 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; + 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 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; + /** 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; + itemClickAction?: any; + itemHoldAction?: Function; + /** The time period in milliseconds before the onItemHold event is raised. */ + itemHoldTimeout?: number; + itemRender?: any; + itemRenderedAction?: Function; + /** An array of items displayed by the widget. */ + items?: Array; + /** + * A function performed when a widget item is selected. + * @deprecated onSelectionChanged.md + */ + itemSelectAction?: Function; + /** 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; + contentReadyAction?: 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; + itemRender?: 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; + valueChangeAction?: 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; + }; + /** 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 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 { + menuItemRender?: any; + /** 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; + } + /** 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; + changeAction?: Function; + /** A handler for the copy event. */ + onCopy?: Function; + copyAction?: Function; + /** A handler for the cut event. */ + onCut?: Function; + cutAction?: Function; + /** A handler for the enterKey event. */ + onEnterKey?: Function; + enterKeyAction?: Function; + /** A handler for the focusIn event. */ + onFocusIn?: Function; + focusInAction?: Function; + /** A handler for the focusOut event. */ + onFocusOut?: Function; + focusOutAction?: Function; + /** A handler for the input event. */ + onInput?: Function; + inputAction?: Function; + /** A handler for the keyDown event. */ + onKeyDown?: Function; + keyDownAction?: Function; + /** A handler for the keyPress event. */ + onKeyPress?: Function; + keyPressAction?: Function; + /** A handler for the keyUp event. */ + onKeyUp?: Function; + keyUpAction?: Function; + /** A handler for the paste event. */ + onPaste?: Function; + pasteAction?: 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; + /** Specifies whether or not the widget supports the focused state and keyboard navigation. */ + focusStateEnabled?: boolean; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + 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; + } + /** 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; + titleTemplate?: any; + /** The template to be used for rendering an item title. */ + itemTitleTemplate?: any; + } + /** 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 { + /** 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 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; + pullDownAction?: 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; + reachBottomAction?: 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; + scrollAction?: Function; + /** Specifies when the widget shows the scrollbar. */ + showScrollbar?: string; + /** A handler for the update event. */ + onUpdated?: Function; + updateAction?: 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 CollectionWidgetOptions, DataExpressionMixinOptions { + /** 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; + /** A handler for the hidden event. */ + onHidden?: Function; + hiddenAction?: Function; + /** A handler for the hiding event. */ + onHiding?: Function; + hidingAction?: 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; + showingAction?: Function; + /** A handler for the shown event. */ + onShown?: Function; + shownAction?: 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; + } + /** 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. */ + autoAdjust?: boolean; + /** An object, a string, or an array specifying the location displayed at the center of the widget. */ + 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; + clickAction?: 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; + markerAddedAction?: Function; + /** A URL pointing to the custom icon to be used for map markers. */ + markerIconSrc?: string; + /** A handler for the markerRemoved event. */ + onMarkerRemoved?: Function; + markerRemovedAction?: 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; + readyAction?: Function; + /** A handler for the routeAdded event. */ + onRouteAdded?: Function; + routeAddedAction?: Function; + /** A handler for the routeRemoved event. */ + onRouteRemoved?: Function; + routeRemovedAction?: 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 the 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; + groupRender?: any; + /** 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; + pageLoadingAction?: Function; + /** 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; + pullRefreshAction?: 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; + scrollAction?: 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; + contentReadyAction?: Function; + titleRender?: any; + /** 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; + } + /** 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; + groupRender?: any; + /** 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; + itemDeleteAction?: Function; + /** A handler for the itemReordered event. */ + onItemReordered?: Function; + itemReorderAction?: Function; + /** A handler for the itemClick event. */ + onItemClick?: any; + /** A handler for the itemSwipe event. */ + onItemSwipe?: Function; + itemSwipeAction?: 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; + pageLoadingAction?: 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; + pullRefreshAction?: 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; + scrollAction?: 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; + itemUnselectAction?: Function; + 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; + /** 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; + closeAction?: Function; + openAction?: Function; + shownAction?: Function; + hiddenAction?: Function; + /** Specifies whether or not the widget allows an end-user to enter a custom value. */ + fieldEditEnabled?: boolean; + editEnabled?: 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; + } + /** 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; + } + /** A date box widget. */ + export class dxDateBox extends dxDropDownEditor { + constructor(element: JQuery, options?: dxDateBoxOptions); + constructor(element: Element, options?: dxDateBoxOptions); + } + export interface dxCheckBoxOptions extends EditorOptions { + /** 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 { + /** 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; + clickAction?: 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 { + /** 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); + } +} +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; +} + +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 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 { + /** 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 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; + menuGroupRender?: any; + /** The name of the template used to display a group header. */ + menuGroupTemplate?: any; + menuItemRender?: 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; + buttonClickAction?: any; + /** The name of the icon to be displayed by the DropDownMenu button. */ + buttonIcon?: string; + buttonIconSrc?: string; + /** The text displayed in the DropDownMenu button. */ + buttonText?: string; + /** A data source used to fetch data to be displayed by the widget. */ + dataSource?: any; + /** A handler for the itemClick event. */ + onItemClick?: any; + itemClickAction?: any; + itemRender?: 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; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: 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 { + cancelClickAction?: any; + /** 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; + 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 th 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 initial 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; + /** Specifies the data field against which the header items of this field should be sorted. */ + 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; + } + 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. */ + filter?: Object; + /** An array of pivot grid fields. */ + fields?: Array; + /** Indicates whether or not the local sorting of the XMLA data should be performed. */ + localSorting?: boolean; + /** 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 loading data. */ + 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; + 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; + /** 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 the scheduler data can be edited at runtime. */ + editing?: 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. */ + mainColor?: 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 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. */ + scrollToTime(hours: number, minutes: number): 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 dxColorPickerOptions extends dxColorBoxOptions { } + /** + * A widget used to specify a color value. + * @deprecated Use the dxColorBox widget instead + */ + export class dxColorPicker extends dxColorBox { + constructor(element: JQuery, options?: dxColorPickerOptions); + constructor(element: Element, options?: dxColorPickerOptions); + } + export interface dxTreeViewOptions extends CollectionWidgetOptions { + /** 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; + /** + * An array of currently expanded item objects. + * @deprecated Use item.expanded field instead + */ + expandedItems?: Array; + /** Specifies whether or not a check box is displayed at each tree view item. */ + showCheckBoxes?: boolean; + /** Specifies whether or not to select nodes recursively. */ + selectNodesRecursive?: boolean; + /** Specifies whether the "Select All" check box is displayed over the tree view. */ + selectAllEnabled?: boolean; + /** Specifies the text displayed at the "Select All" check box. */ + selectAllText?: string; + /** 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 is displayed by the widget. */ + displayExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is selected. */ + selectedExpr?: any; + /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is expanded. */ + expandedExpr?: 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 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 node is disabled. */ + disabledExpr?: any; + /** 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; + /** 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; + hoverStateEnabled?: boolean; + focusStateEnabled?: boolean; + } + /** A widget displaying specified data items as a tree. */ + export class dxTreeView extends CollectionWidget { + 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 CollectionWidgetOptions { + /** 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; + }; + }; + /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ + hoverStateEnabled?: boolean; + } + export class dxMenuBase extends CollectionWidget { + 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 of 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; + submenuHiddenAction?: Function; + /** A handler for the submenuHiding event. */ + onSubmenuHiding?: Function; + submenuHidingAction?: Function; + /** A handler for the submenuShowing event. */ + onSubmenuShowing?: Function; + submenuShowingAction?: Function; + /** A handler for the submenuShown event. */ + onSubmenuShown?: Function; + submenuShownAction?: 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; + } + 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 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 that defines filters for customary calculated grid cells. */ + calculateFilterExpression?: (filterValue: any, selectedFilterOperation: 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 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 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 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; + } + 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; + initNewRow?: (e: { data: Object }) => void; + /** A handler for the initNewRow event. */ + onInitNewRow?: (e: { data: Object }) => void; + rowInserted?: (e: { data: Object; key: any }) => void; + /** A handler for the rowInserted event. */ + onRowInserted?: (e: { data: Object; key: any }) => void; + rowInserting?: (e: { data: Object; cancel: boolean }) => void; + /** A handler for the rowInserting event. */ + onRowInserting?: (e: { data: Object; cancel: boolean }) => void; + rowRemoved?: (e: { data: Object; key: any }) => void; + /** A handler for the rowRemoved event. */ + onRowRemoved?: (e: { data: Object; key: any }) => void; + rowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; + /** A handler for the rowRemoving event. */ + onRowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; + rowUpdated?: (e: { data: Object; key: any }) => void; + /** A handler for the rowUpdated event. */ + onRowUpdated?: (e: { data: Object; key: any }) => void; + rowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => void; + /** A handler for the rowUpdating event. */ + onRowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => 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; + cellClick?: any; + /** A handler for the cellClick event. */ + onCellClick?: any; + cellHoverChanged?: (e: Object) => void; + /** A handler for the cellHoverChanged event. */ + onCellHoverChanged?: (e: Object) => void; + cellPrepared?: (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; + contentReadyAction?: Function; + /** Specifies a function that customizes grid columns after they are created. */ + customizeColumns?: (columns: Array) => void; + dataErrorOccurred?: (errorObject: Error) => void; + /** Specifies a data source for the grid. */ + dataSource?: any; + editingStart?: (e: { + data: Object; + key: any; + cancel: boolean; + column: dxDataGridColumn + }) => void; + /** A handler for the editingStart event. */ + onEditingStart?: (e: { + data: Object; + key: any; + cancel: boolean; + column: dxDataGridColumn + }) => void; + editorPrepared?: (e: Object) => void; + /** A handler for the editorPrepared event. */ + onEditorPrepared?: (e: Object) => void; + editorPreparing?: (e: Object) => void; + /** A handler for the editorPreparing event. */ + onEditorPreparing?: (e: Object) => void; + /** Contains options that specify how grid content can be changed. */ + editing?: { + /** Specifies whether or not grid records can be edited at runtime. */ + editEnabled?: boolean; + /** Specifies how grid values can be edited manually. */ + editMode?: string; + /** Specifies whether or not new records can be inserted into a grid. */ + insertEnabled?: boolean; + /** Specifies whether or not records can be deleted from a grid. */ + removeEnabled?: boolean; + /** 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 editEnabled 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 button that deletes a row from a grid. Setting this option makes sense only when the removeEnabled 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 insertEnabled 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 editEnabled 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 editEnabled 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 removeEnabled 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 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; + rowClick?: any; + /** A handler for the rowClick event. */ + onRowClick?: any; + rowPrepared?: (e: Object) => void; + /** 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 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 when this button exports to the XSLX format. */ + 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 whether the user can select all grid records at once. */ + allowSelectAll?: boolean; + /** Specifies the selection mode. */ + mode?: string; + }; + selectionChanged?: (e: { + currentSelectedRowKeys: Array; + currentDeselectedRowKeys: Array; + selectedRowKeys: Array; + selectedRowsData: Array; + }) => void; + /** 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; + format: string; + 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?: (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; + }; + /** 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 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; + }>; + /** 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; + /** Displays the load panel. */ + beginCustomLoading(messageText: string): void; + /** Discards changes made in a grid. */ + cancelEditData(): void; + /** 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, columnIndex: number): void; + /** Sets a specific row into the editing state. */ + editRow(rowIndex: number): 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. */ + 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. */ + 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; + /** Specifies whether or not the widget uses native scrolling. */ + useNativeScrolling?: 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; + /** 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 Load panel configuration options. */ + 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; + } + /** 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; + /** Updates the widget to the size of its content. */ + updateDimensions(): 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 { + action?: any; + /** 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 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; + 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: "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: "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: "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 legend's bottom margin in pixels. */ + bottom?: number; + /** Specifies the legend's left margin in pixels. */ + left?: number; + /** Specifies the legend's right margin in pixels. */ + right?: number; + /** Specifies the legend's bottom margin 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 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; + 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 { + drawn?: (widget: Object) => void; + /** A handler for the drawn event. */ + onDrawn?: (e: { + component: BaseWidget; + element: Element; + }) => void; + incidentOccured?: (incidentInfo: { + id: string; + type: string; + args: any; + text: string; + widget: string; + version: string; + }) => 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 a point from the series point collection based on the specified argument. + * @deprecated getPointsByArg(pointArg).md + */ + getPointByArg(pointArg: any): Object; + /** 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; + } + /** 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(): any; + /** Provides information about the selection state of a point. */ + isSelected(): any; + /** 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; + /** 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(): any; + /** Provides information about the selection state of a series. */ + isSelected(): any; + /** Provides information about the visibility state of a series. */ + isVisible(): boolean; + /** Makes a particular series visible. */ + show(): void; + 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; + /** 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(): any; + /** Provides information about the selection state of a series. */ + isSelected(): any; + /** Provides information about the visibility state of a series. */ + isVisible(): boolean; + /** Makes a particular series visible. */ + show(): void; + 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. */ + 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's series points are located. */ + 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. */ + 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 PieSeriesConfig extends CommonPieSeriesConfig { + /** Sets the series type. */ + type?: string; + } + 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 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; + }; + /** 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 a start angle for the argument axis in degrees. */ + startAngle?: number; + /** Specifies whether or not to display the first point at the angle specified by the startAngle option. */ + firstPointOnStartAngle?: boolean; + /** 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; + done?: Function; + /** 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; + pointClick?: any; + /** A handler for the pointHoverChanged event. */ + onPointHoverChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + pointHoverChanged?: (point: TPoint) => void; + /** A handler for the pointSelectionChanged event. */ + onPointSelectionChanged?: (e: { + component: BaseChart; + element: Element; + target: TPoint; + }) => void; + pointSelectionChanged?: (point: 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?: { + /** Specifies font options for the title. */ + font?: viz.core.Font; + /** Specifies the title's horizontal position in the chart. */ + horizontalAlignment?: string; + /** Specifies a title's position on the chart in the vertical direction. */ + verticalAlignment?: string; + /** Specifies the distance between the title and surrounding chart elements in pixels. */ + margin?: viz.core.Margins; + /** Specifies the height of the space reserved for the title. */ + placeholderSize?: number; + /** Specifies a text for the chart's title. */ + text?: string; + }; + /** 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; + tooltipHidden?: (point: TPoint) => void; + tooltipShown?: (point: TPoint) => 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 }; + /** 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; + } + 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 { + /** Specifies a value indicating 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?: any; + 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; + argumentAxisClick?: any; + /** 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 a default pane for the chart's 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; + legendClick?: any; + seriesClick?: any; + seriesHoverChanged?: (series: ChartSeries) => void; + seriesSelectionChanged?: (series: ChartSeries) => void; + /** 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); + /** 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): ChartSeries; + /** Gets a series within the chart's series collection by its position number. */ + getSeriesByPos(seriesIndex: number): ChartSeries; + /** 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; + } + } + export interface PolarChartTooltip extends BaseChartTooltip { + /** Specifies the kind of information to display in a tooltip. */ + shared?: boolean; + } + export interface dxPolarChartOptions extends AdvancedOptions { + /** Specifies a value indicating whether 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 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); + /** 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): PolarSeries; + /** Gets a series within the chart's series collection by its position number. */ + getSeriesByPos(seriesIndex: number): PolarSeries; + } + 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; + /** A handler for the legendClick event. */ + onLegendClick?: any; + legendClick?: any; + /** Specifies how a chart must behave when series point labels overlap. */ + resolveLabelOverlapping?: 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. */ + 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. */ + customTickValues?: Array; + /** Specifies the length of the scale's minor ticks. */ + length?: number; + /** Indicates whether automatically calculated minor ticks are visible or not. */ + showCalculatedTicks?: boolean; + /** Specifies an interval between minor ticks. */ + 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. */ + useTicksAutoArrangement?: boolean; + } + 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 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. */ + hideFirstLabel?: boolean; + /** Specifies whether or not to hide the first major tick on the scale. */ + hideFirstTick?: boolean; + /** Specifies whether or not to hide the last scale label. */ + hideLastLabel?: boolean; + /** Specifies whether or not to hide the last major tick on the scale. */ + hideLastTick?: boolean; + /** Specifies common options for scale labels. */ + label?: BaseScaleLabel; + /** Specifies options of the gauge's major ticks. */ + majorTick?: ScaleMajorTick; + /** Specifies options of the gauge's minor ticks. */ + minorTick?: ScaleTick; + /** 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 a gauge. */ + subtitle?: { + /** Specifies font options for the subtitle. */ + font?: viz.core.Font; + /** Specifies a text for the subtitle. */ + 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. */ + position?: string; + /** Specifies a text for the title. */ + 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 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 a value indicating 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?: any; + /** 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. */ + majorTickInterval?: 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. */ + 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 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; + }; + selectedRangeChanged?: (selectedRange: { startValue: any; endValue: any; }) => void; + /** 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 Area object. */ + export interface Area { + /** Contains the element type. */ + type: string; + /** Return the value of an attribute. */ + attribute(name: string): any; + /** Provides information about the selection state of an area. */ + selected(): boolean; + /** Sets a new selection state for an area. */ + selected(state: boolean): void; + /** Applies the area settings specified as a parameter and updates the area appearance. */ + applySettings(settings: any): void; + } + /** This section describes the fields and methods that can be used in code to manipulate the Markers object. */ + export interface Marker { + /** Contains the descriptive text accompanying the map marker. */ + text: string; + /** Contains the type of the element. */ + type: string; + /** Contains the URL of an image map marker. */ + url: string; + /** Contains the value of a bubble map marker. */ + value: number; + /** Contains the values of a pie map marker. */ + values: Array; + /** Returns the value of an attribute. */ + attribute(name: string): any; + /** Returns the coordinates of a specific marker. */ + coordinates(): Array; + /** Provides information about the selection state of a marker. */ + selected(): boolean; + /** Sets a new selection state for a marker. */ + selected(state: boolean): void; + /** Applies the marker settings specified as a parameter and updates the marker appearance. */ + applySettings(settings: any): void; + } + export interface AreaSettings { + /** Specifies the width of the area border in pixels. */ + borderWidth?: number; + /** Specifies a color for the area border. */ + borderColor?: string; + click?: any; + /** Specifies a color for an area. */ + color?: string; + /** Specifies the function that customizes each area individually. */ + customize?: (areaInfo: Area) => AreaSettings; + /** Specifies a color for the area border when the area is hovered over. */ + hoveredBorderColor?: string; + /** Specifies the pixel-measured width of the area border when the area is hovered over. */ + hoveredBorderWidth?: number; + /** Specifies a color for an area when this area is hovered over. */ + hoveredColor?: string; + /** Specifies whether or not to change the appearance of an area when it is hovered over. */ + hoverEnabled?: boolean; + /** Configures area labels. */ + label?: { + /** Specifies the data field that provides data for area labels. */ + dataField?: string; + /** Enables area labels. */ + enabled?: boolean; + /** Specifies font options for area labels. */ + font?: viz.core.Font; + }; + /** Specifies the name of the palette or a custom range of colors to be used for coloring a map. */ + palette?: any; + /** Specifies the number of colors in a palette. */ + paletteSize?: number; + /** Allows you to paint areas with similar attributes in the same color. */ + colorGroups?: Array; + /** Specifies the field that provides data to be used for coloring areas. */ + colorGroupingField?: string; + /** Specifies a color for the area border when the area is selected. */ + selectedBorderColor?: string; + /** Specifies a color for an area when this area is selected. */ + selectedColor?: string; + /** Specifies the pixel-measured width of the area border when the area is selected. */ + selectedBorderWidth?: number; + selectionChanged?: (area: Area) => void; + /** Specifies whether single or multiple areas can be selected on a vector map. */ + selectionMode?: string; + } + export interface MarkerSettings { + /** Specifies a color for the marker border. */ + borderColor?: string; + /** Specifies the width of the marker border in pixels. */ + borderWidth?: number; + click?: any; + /** Specifies a color for a marker of the dot or bubble type. */ + color?: string; + /** Specifies the function that customizes each marker individually. */ + customize?: (markerInfo: Marker) => MarkerSettings; + font?: Object; + /** Specifies the pixel-measured width of the marker border when the marker is hovered over. */ + hoveredBorderWidth?: number; + /** Specifies a color for the marker border when the marker is hovered over. */ + hoveredBorderColor?: string; + /** Specifies a color for a marker of the dot or bubble type when this marker is hovered over. */ + hoveredColor?: string; + /** Specifies whether or not to change the appearance of a marker when it is hovered over. */ + hoverEnabled?: boolean; + /** Specifies marker label options. */ + label?: { + /** Enables marker labels. */ + enabled?: boolean; + /** Specifies font options for marker labels. */ + 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. */ + 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. */ + minSize?: number; + /** Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. */ + opacity?: number; + /** Specifies the pixel-measured width of the marker border when the marker is selected. */ + selectedBorderWidth?: number; + /** Specifies a color for the marker border when the marker is selected. */ + selectedBorderColor?: string; + /** Specifies a color for a marker of the dot or bubble type when this marker is selected. */ + selectedColor?: string; + selectionChanged?: (marker: Marker) => void; + /** Specifies whether a single or multiple markers can be selected on a vector map. */ + selectionMode?: string; + /** Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. */ + size?: number; + /** Specifies the type of markers to be used on the map. */ + type?: string; + /** Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. */ + palette?: any; + /** Allows you to paint markers with similar attributes in the same color. */ + colorGroups?: Array; + /** Specifies the field that provides data to be used for coloring markers. */ + colorGroupingField?: string; + /** Allows you to display bubbles with similar attributes in the same size. */ + sizeGroups?: Array; + /** Specifies the field that provides data to be used for sizing bubble markers. */ + sizeGroupingField?: string; + } + export interface dxVectorMapOptions extends viz.core.BaseWidgetOptions { + /** An object specifying options for the map areas. */ + 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 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. */ + mapData?: any; + /** Specifies a data source for the map markers. */ + markers?: any; + /** An object specifying options for the map markers. */ + markerSettings?: MarkerSettings; + /** Specifies the size of the dxVectorMap widget. */ + size?: viz.core.Size; + /** 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; + centerChanged?: (center: Array) => void; + /** 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; + zoomFactorChanged?: (zoomFactor: number) => void; + /** A handler for the zoomFactorChanged event. */ + onZoomFactorChanged?: (e: { + zoomFactor: number; + component: dxVectorMap; + element: Element; + }) => void; + click?: any; + /** A handler for the click event. */ + onClick?: any; + /** A handler for the areaClick event. */ + onAreaClick?: any; + /** A handler for the areaSelectionChanged event. */ + onAreaSelectionChanged?: (e: { + target: Area; + component: dxVectorMap; + element: Element; + }) => void; + /** A handler for the markerClick event. */ + onMarkerClick?: any; + /** A handler for the markerSelectionChanged event. */ + onMarkerSelectionChanged?: (e: { + target: Marker; + component: dxVectorMap; + element: Element; + }) => void; + /** Disables the panning capability. */ + panningEnabled?: boolean; + } + export interface Legend extends viz.core.BaseLegend { + /** 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?: 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. */ + clearAreaSelection(): void; + /** Deselects all the selected markers on a map. The markers are displayed in their initial style after. */ + 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; + /** Returns an array with all the map areas. */ + getAreas(): Array; + /** Returns an array with all the map markers. */ + 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; + } +} +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; +} \ No newline at end of file diff --git a/devextreme/devextreme.d.ts b/devextreme/devextreme.d.ts index 83e69504be..706b4bded7 100644 --- a/devextreme/devextreme.d.ts +++ b/devextreme/devextreme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for DevExtreme 15.1.8 +// Type definitions for DevExtreme 15.2.3 // Project: http://js.devexpress.com/ // Definitions by: DevExpress Inc. // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -69,9 +69,7 @@ declare module DevExpress { 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; - /** Requests that the browser call a specified function to update animation before the next repaint. */ export function requestAnimationFrame(callback: Function): number; - /** Cancels an animation frame request scheduled with the requestAnimationFrame method. */ export function cancelAnimationFrame(requestID: number): void; /** Custom Knockout binding that links an HTML element with a specific action. */ export class Action { } @@ -128,6 +126,8 @@ declare module DevExpress { 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. */ @@ -163,8 +163,8 @@ declare module DevExpress { 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 Windows8. */ - win8?: boolean; + /** Indicates whether or not the device platform is Windows. */ + win?: boolean; /** Specifies a performance grade of the current device. */ grade?: string; } @@ -262,16 +262,6 @@ declare module DevExpress { errorDetails?: any; } export interface StoreOptions { - inserted?: (values: Object, key: any) => void; - inserting?: (values: Object) => void; - loaded?: (result: Array) => void; - loading?: (loadOptions: LoadOptions) => void; - modified?: () => void; - modifying?: () => void; - removed?: (key: any) => void; - removing?: (key: any) => void; - updated?: (key: any, values: Object) => void; - updating?: (key: any, values: Object) => void; /** A handler for the modified event. */ onModified?: () => void; /** A handler for the modifying event. */ @@ -310,16 +300,6 @@ declare module DevExpress { } /** The base class for all Stores. */ export class Store implements EventsMixin { - inserted: JQueryCallback; - inserting: JQueryCallback; - loaded: JQueryCallback; - loading: JQueryCallback; - modified: JQueryCallback; - modifying: JQueryCallback; - removed: JQueryCallback; - removing: JQueryCallback; - updated: JQueryCallback; - updating: JQueryCallback; constructor(options?: StoreOptions); /** Returns the data item specified by the key. */ byKey(key: any): JQueryPromise; @@ -450,9 +430,6 @@ declare module DevExpress { /** An object that provides access to a data web service or local data storage for collection container widgets. */ export class DataSource implements EventsMixin { constructor(options?: DataSourceOptions); - changed: JQueryCallback; - loadError: JQueryCallback; - loadingChanged: JQueryCallback; /** Disposes all resources associated with this DataSource. */ dispose(): void; /** Returns the current filter option value. */ @@ -583,6 +560,7 @@ declare module DevExpress { /** A function used to customize a web request before it is sent. */ beforeSend?: (request: { url: string; + async: boolean; method: string; timeout: number; params: Object; @@ -593,6 +571,8 @@ declare module DevExpress { 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. */ @@ -714,26 +694,16 @@ declare module DevExpress { export interface CollectionWidgetOptions extends WidgetOptions { /** A data source used to fetch data to be displayed by the widget. */ dataSource?: any; - itemClickAction?: any; - itemHoldAction?: Function; /** The time period in milliseconds before the onItemHold event is raised. */ itemHoldTimeout?: number; - itemRender?: any; - itemRenderedAction?: Function; /** An array of items displayed by the widget. */ items?: Array; - /** - * A function performed when a widget item is selected. - * @deprecated onSelectionChanged.md - */ - itemSelectAction?: Function; /** 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; - contentReadyAction?: any; /** A handler for the itemClick event. */ onItemClick?: any; /** A handler for the itemContextMenu event. */ @@ -774,7 +744,6 @@ declare module DevExpress { displayExpr?: any; /** Specifies the name of a data source item field whose value is held in the value configuration option. */ valueExpr?: any; - itemRender?: any; /** An array of items displayed by the widget. */ items?: Array; /** The template to be used for rendering items. */ @@ -787,7 +756,6 @@ declare module DevExpress { value?: Object; /** A handler for the valueChanged event. */ onValueChanged?: Function; - valueChangeAction?: 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. */ @@ -835,6 +803,10 @@ declare module DevExpress { 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 { @@ -927,6 +899,8 @@ declare module DevExpress.ui { 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. */ @@ -958,7 +932,6 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxDropDownListOptions); } export interface dxToolbarOptions extends CollectionWidgetOptions { - menuItemRender?: any; /** The template used to render menu items. */ menuItemTemplate?: any; /** Informs the widget about its location in a view HTML markup. */ @@ -982,6 +955,10 @@ declare module DevExpress.ui { 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 { @@ -991,37 +968,26 @@ declare module DevExpress.ui { export interface dxTextEditorOptions extends EditorOptions { /** A handler for the change event. */ onChange?: Function; - changeAction?: Function; /** A handler for the copy event. */ onCopy?: Function; - copyAction?: Function; /** A handler for the cut event. */ onCut?: Function; - cutAction?: Function; /** A handler for the enterKey event. */ onEnterKey?: Function; - enterKeyAction?: Function; /** A handler for the focusIn event. */ onFocusIn?: Function; - focusInAction?: Function; /** A handler for the focusOut event. */ onFocusOut?: Function; - focusOutAction?: Function; /** A handler for the input event. */ onInput?: Function; - inputAction?: Function; /** A handler for the keyDown event. */ onKeyDown?: Function; - keyDownAction?: Function; /** A handler for the keyPress event. */ onKeyPress?: Function; - keyPressAction?: Function; /** A handler for the keyUp event. */ onKeyUp?: Function; - keyUpAction?: Function; /** A handler for the paste event. */ onPaste?: Function; - pasteAction?: 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. */ @@ -1036,9 +1002,7 @@ declare module DevExpress.ui { attr?: Object; /** The read-only option that holds the text displayed by the widget input element. */ text?: string; - /** Specifies whether or not the widget supports the focused state and keyboard navigation. */ focusStateEnabled?: boolean; - /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ hoverStateEnabled?: boolean; /** The editor mask that specifies the format of the entered string. */ mask?: string; @@ -1048,6 +1012,8 @@ declare module DevExpress.ui { 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 { @@ -1100,9 +1066,14 @@ declare module DevExpress.ui { onTitleHold?: Function; /** A handler for the titleRendered event. */ onTitleRendered?: Function; - titleTemplate?: any; /** 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 { @@ -1110,6 +1081,8 @@ declare module DevExpress.ui { 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. */ @@ -1125,6 +1098,8 @@ declare module DevExpress.ui { 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 { @@ -1134,14 +1109,12 @@ declare module DevExpress.ui { export interface dxScrollViewOptions extends dxScrollableOptions { /** A handler for the pullDown event. */ onPullDown?: Function; - pullDownAction?: 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; - reachBottomAction?: 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. */ @@ -1171,12 +1144,10 @@ declare module DevExpress.ui { disabled?: boolean; /** A handler for the scroll event. */ onScroll?: Function; - scrollAction?: Function; /** Specifies when the widget shows the scrollbar. */ showScrollbar?: string; /** A handler for the update event. */ onUpdated?: Function; - updateAction?: Function; /** Indicates whether to use native or simulated scrolling. */ useNative?: boolean; /** A Boolean value specifying whether to enable or disable the bounce-back effect. */ @@ -1220,6 +1191,7 @@ declare module DevExpress.ui { update(): void; } export interface dxRadioGroupOptions extends CollectionWidgetOptions, DataExpressionMixinOptions { + activeStateEnabled?: boolean; /** Specifies the radio group layout. */ layout?: string; } @@ -1293,12 +1265,24 @@ declare module DevExpress.ui { 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; - hiddenAction?: 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; - hidingAction?: 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. */ @@ -1307,10 +1291,8 @@ declare module DevExpress.ui { shadingColor?: string; /** A handler for the showing event. */ onShowing?: Function; - showingAction?: Function; /** A handler for the shown event. */ onShown?: Function; - shownAction?: Function; /** A Boolean value specifying whether or not the widget is visible. */ visible?: boolean; /** The widget width in pixels. */ @@ -1379,7 +1361,6 @@ declare module DevExpress.ui { 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. */ autoAdjust?: boolean; - /** An object, a string, or an array specifying the location displayed at the center of the widget. */ center?: { /** The latitude location displayed in the center of the widget. */ lat?: number; @@ -1388,7 +1369,6 @@ declare module DevExpress.ui { }; /** A handler for the click event. */ onClick?: any; - clickAction?: any; /** Specifies whether or not map widget controls are available. */ controls?: boolean; /** Specifies the height of the widget. */ @@ -1404,25 +1384,20 @@ declare module DevExpress.ui { } /** A handler for the markerAdded event. */ onMarkerAdded?: Function; - markerAddedAction?: Function; /** A URL pointing to the custom icon to be used for map markers. */ markerIconSrc?: string; /** A handler for the markerRemoved event. */ onMarkerRemoved?: Function; - markerRemovedAction?: 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; - readyAction?: Function; /** A handler for the routeAdded event. */ onRouteAdded?: Function; - routeAddedAction?: Function; /** A handler for the routeRemoved event. */ onRouteRemoved?: Function; - routeRemovedAction?: Function; /** An array of routes shown on the map. */ routes?: Array; /** The type of a map to display. */ @@ -1463,7 +1438,6 @@ declare module DevExpress.ui { focusStateEnabled?: boolean; /** A Boolean value specifying whether or not to group widget items. */ grouped?: boolean; - groupRender?: any; /** 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. */ @@ -1472,7 +1446,6 @@ declare module DevExpress.ui { 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; - pageLoadingAction?: Function; /** 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. */ @@ -1489,14 +1462,12 @@ declare module DevExpress.ui { pullingDownText?: string; /** A handler for the pullRefresh event. */ onPullRefresh?: Function; - pullRefreshAction?: 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; - scrollAction?: 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. */ @@ -1520,8 +1491,6 @@ declare module DevExpress.ui { usePopover?: boolean; /** A handler for the valueChanged event. */ onValueChanged?: Function; - contentReadyAction?: Function; - titleRender?: any; /** A handler for the titleRendered event. */ onTitleRendered?: Function; /** A Boolean value specifying whether or not to display the title in the popup window. */ @@ -1568,7 +1537,6 @@ declare module DevExpress.ui { export interface dxListOptions extends CollectionWidgetOptions { /** A Boolean value specifying whether or not to display a grouped list. */ grouped?: boolean; - groupRender?: any; /** The template to be used for rendering item groups. */ groupTemplate?: any; onItemDeleting?: Function; @@ -1576,20 +1544,16 @@ declare module DevExpress.ui { onItemDeleted?: Function; /** A handler for the groupRendered event. */ onGroupRendered?: Function; - itemDeleteAction?: Function; /** A handler for the itemReordered event. */ onItemReordered?: Function; - itemReorderAction?: Function; /** A handler for the itemClick event. */ onItemClick?: any; /** A handler for the itemSwipe event. */ onItemSwipe?: Function; - itemSwipeAction?: 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; - pageLoadingAction?: 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. */ @@ -1598,14 +1562,12 @@ declare module DevExpress.ui { pullingDownText?: string; /** A handler for the pullRefresh event. */ onPullRefresh?: Function; - pullRefreshAction?: 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; - scrollAction?: Function; /** A Boolean value specifying whether to enable or disable list scrolling. */ scrollingEnabled?: boolean; /** Specifies when the widget shows the scrollbar. */ @@ -1618,7 +1580,6 @@ declare module DevExpress.ui { scrollByContent?: boolean; /** A Boolean value specifying if the list is scrolled using the scrollbar. */ scrollByThumb?: boolean; - itemUnselectAction?: Function; onItemContextMenu?: Function; onItemHold?: Function; /** Specifies whether or not an end-user can collapse groups. */ @@ -1630,6 +1591,7 @@ declare module DevExpress.ui { /** 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. */ @@ -1737,17 +1699,13 @@ declare module DevExpress.ui { onOpened?: Function; /** Specifies whether or not the drop-down editor is displayed. */ opened?: boolean; - closeAction?: Function; - openAction?: Function; - shownAction?: Function; - hiddenAction?: Function; /** Specifies whether or not the widget allows an end-user to enter a custom value. */ fieldEditEnabled?: boolean; - editEnabled?: 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 { @@ -1791,10 +1749,14 @@ declare module DevExpress.ui { 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. */ + /** 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; } /** A date box widget. */ export class dxDateBox extends dxDropDownEditor { @@ -1802,6 +1764,7 @@ declare module DevExpress.ui { 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. */ @@ -1813,6 +1776,7 @@ declare module DevExpress.ui { 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. */ @@ -1829,8 +1793,8 @@ declare module DevExpress.ui { maxZoomLevel?: string; /** Specifies the minimum zoom level of the calendar. */ minZoomLevel?: string; - /** The template to be used for rendering calendar cells. */ - cellTemplate?: any; + /** The template to be used for rendering calendar cells. */ + cellTemplate?: any; } /** A calendar widget. */ export class dxCalendar extends Editor { @@ -1842,7 +1806,6 @@ declare module DevExpress.ui { activeStateEnabled?: boolean; /** A handler for the click event. */ onClick?: any; - clickAction?: any; /** Specifies the icon to be displayed on the button. */ icon?: string; iconSrc?: string; @@ -2015,6 +1978,7 @@ declare module DevExpress.ui { constructor(element: Element, options?: dxProgressBarOptions); } export interface dxSliderOptions extends dxTrackBarOptions { + activeStateEnabled?: boolean; /** The slider step size. */ step?: number; /** The current slider value. */ @@ -2060,6 +2024,135 @@ declare module DevExpress.ui { 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 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; + /** Specifie 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; + } + 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 optional 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 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; + } + /** 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; @@ -2276,6 +2369,11 @@ interface JQuery { 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.dxForm): JQuery; } declare module DevExpress.ui { @@ -2286,6 +2384,8 @@ declare module DevExpress.ui { 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. */ @@ -2301,6 +2401,7 @@ declare module DevExpress.ui { 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. */ @@ -2314,6 +2415,8 @@ declare module DevExpress.ui { 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. */ @@ -2343,10 +2446,10 @@ declare module DevExpress.ui { activeStateEnabled?: boolean; /** A Boolean value specifying whether or not to display a grouped menu. */ menuGrouped?: boolean; - menuGroupRender?: any; + /** Specifies the current menu position. */ + menuPosition?: string; /** The name of the template used to display a group header. */ menuGroupTemplate?: any; - menuItemRender?: any; /** The template used to render menu items. */ menuItemTemplate?: any; /** A handler for the menuGroupRendered event. */ @@ -2409,18 +2512,15 @@ declare module DevExpress.ui { export interface dxDropDownMenuOptions extends WidgetOptions { /** A handler for the buttonClick event. */ onButtonClick?: any; - buttonClickAction?: any; /** The name of the icon to be displayed by the DropDownMenu button. */ buttonIcon?: string; - buttonIconSrc?: 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; - itemClickAction?: any; - itemRender?: any; /** An array of items displayed by the widget. */ items?: Array; /** The template to be used for rendering items. */ @@ -2433,7 +2533,6 @@ declare module DevExpress.ui { popupHeight?: any; /** Specifies whether or not the drop-down menu is displayed. */ opened?: boolean; - /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ hoverStateEnabled?: boolean; } /** A drop-down menu widget. */ @@ -2447,7 +2546,6 @@ declare module DevExpress.ui { close(): void; } export interface dxActionSheetOptions extends CollectionWidgetOptions { - cancelClickAction?: any; /** A handler for the cancelClick event. */ onCancelClick?: any; /** The text displayed in the button that closes the action sheet. */ @@ -2540,7 +2638,7 @@ declare module DevExpress.data { 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 th XmlaStore store type. */ + /** 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: { @@ -2594,18 +2692,60 @@ declare module DevExpress.data { 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. */ + /** Specifies data filtering conditions. Cannot be used for the XmlaStore store type. */ filter?: Object; /** An array of pivot grid fields. */ fields?: Array; - /** Indicates whether or not the local sorting of the XMLA data should be performed. */ - localSorting?: boolean; /** A handler for the changed event. */ onChanged?: () => void; /** A handler for the loadingChanged event. */ @@ -2618,7 +2758,9 @@ declare module DevExpress.data { /** An object that provides access to data for the dxPivotGrid widget. */ export class PivotGridDataSource implements EventsMixin { constructor(options?: PivotGridDataSource); - /** Starts loading data. */ + /** 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; @@ -2644,6 +2786,22 @@ declare module DevExpress.data { 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; @@ -2666,6 +2824,8 @@ declare module DevExpress.ui { 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. */ @@ -2674,14 +2834,36 @@ declare module DevExpress.ui { startDayHour?: number; /** Specifies an end hour in the scheduler view's time interval. */ endDayHour?: number; - /** Specifies whether the scheduler data can be edited at runtime. */ - editing?: boolean; + /** Specifies whether or not the "All-day" panel is visible. */ + showAllDayPanel?: boolean; + /** Specifies cell duration in minutes. */ + cellDuration?: number; + /** Specifies the edit mode for recurrent 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. */ + /** + * 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. */ @@ -2707,6 +2889,18 @@ declare module DevExpress.ui { 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; } /** A widget that displays scheduled data using different views and provides the capability to load, add and edit appointments. */ export class dxScheduler extends Widget { @@ -2720,6 +2914,8 @@ declare module DevExpress.ui { deleteAppointment(appointment: Object): void; /** Scrolls the scheduler work space to the specified time. */ scrollToTime(hours: number, minutes: number): void; + /** Displays the Appointment Details popup. */ + showAppointmentPopup(appointmentData: Object, createNewAppointment?: boolean): void; } export interface dxColorBoxOptions extends dxDropDownEditorOptions { /** Specifies the text displayed on the button that applies changes and closes the drop-down editor. */ @@ -2737,55 +2933,53 @@ declare module DevExpress.ui { constructor(element: JQuery, options?: dxColorBoxOptions); constructor(element: Element, options?: dxColorBoxOptions); } - export interface dxColorPickerOptions extends dxColorBoxOptions { } - /** - * A widget used to specify a color value. - * @deprecated Use the dxColorBox widget instead - */ - export class dxColorPicker extends dxColorBox { - constructor(element: JQuery, options?: dxColorPickerOptions); - constructor(element: Element, options?: dxColorPickerOptions); + 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 interface dxTreeViewOptions extends CollectionWidgetOptions { + 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; - /** - * An array of currently expanded item objects. - * @deprecated Use item.expanded field instead - */ - expandedItems?: Array; /** Specifies whether or not a check box is displayed at each tree view item. */ 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. */ selectAllEnabled?: boolean; /** Specifies the text displayed at the "Select All" check box. */ selectAllText?: string; - /** 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 is displayed by the widget. */ - displayExpr?: any; - /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is selected. */ - selectedExpr?: any; - /** Specifies the name of the data source item field whose value defines whether or not the corresponding node is expanded. */ - expandedExpr?: 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 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 node is disabled. */ - disabledExpr?: any; /** 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. */ @@ -2798,11 +2992,9 @@ declare module DevExpress.ui { onItemContextMenu?: Function; onItemRendered?: Function; onItemHold?: Function; - hoverStateEnabled?: boolean; - focusStateEnabled?: boolean; } /** A widget displaying specified data items as a tree. */ - export class dxTreeView extends CollectionWidget { + 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. */ @@ -2822,7 +3014,7 @@ declare module DevExpress.ui { /** Unselects all widget items. */ unselectAll(): void; } - export interface dxMenuBaseOptions extends CollectionWidgetOptions { + 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. */ @@ -2847,10 +3039,8 @@ declare module DevExpress.ui { hide?: number; }; }; - /** A Boolean value specifying whether or not the widget changes its state when being hovered by an end user. */ - hoverStateEnabled?: boolean; } - export class dxMenuBase extends CollectionWidget { + export class dxMenuBase extends HierarchicalCollectionWidget { constructor(element: JQuery, options?: dxMenuBaseOptions); constructor(element: Element, options?: dxMenuBaseOptions); /** Selects the specified item. */ @@ -2879,16 +3069,12 @@ declare module DevExpress.ui { submenuDirection?: string; /** A handler for the submenuHidden event. */ onSubmenuHidden?: Function; - submenuHiddenAction?: Function; /** A handler for the submenuHiding event. */ onSubmenuHiding?: Function; - submenuHidingAction?: Function; /** A handler for the submenuShowing event. */ onSubmenuShowing?: Function; - submenuShowingAction?: Function; /** A handler for the submenuShown event. */ onSubmenuShown?: Function; - submenuShownAction?: Function; } /** A menu widget. */ export class dxMenu extends dxMenuBase { @@ -2940,6 +3126,10 @@ declare module DevExpress.ui { 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 dxDataGridColumn { /** Specifies the content alignment within column cells. */ @@ -2948,6 +3138,8 @@ declare module DevExpress.ui { 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. */ @@ -2966,14 +3158,18 @@ declare module DevExpress.ui { 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) => Array; + 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. */ @@ -2986,6 +3182,8 @@ declare module DevExpress.ui { 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. */ @@ -3021,6 +3219,13 @@ declare module DevExpress.ui { /** 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 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. */ @@ -3047,6 +3252,8 @@ declare module DevExpress.ui { 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. */ @@ -3057,40 +3264,30 @@ declare module DevExpress.ui { onRowValidating?: (e: Object) => void; /** A handler for the contextMenuPreparing event. */ onContextMenuPreparing?: (e: Object) => void; - initNewRow?: (e: { data: Object }) => void; /** A handler for the initNewRow event. */ onInitNewRow?: (e: { data: Object }) => void; - rowInserted?: (e: { data: Object; key: any }) => void; /** A handler for the rowInserted event. */ onRowInserted?: (e: { data: Object; key: any }) => void; - rowInserting?: (e: { data: Object; cancel: boolean }) => void; /** A handler for the rowInserting event. */ - onRowInserting?: (e: { data: Object; cancel: boolean }) => void; - rowRemoved?: (e: { data: Object; key: any }) => void; + onRowInserting?: (e: { data: Object; cancel: any }) => void; /** A handler for the rowRemoved event. */ onRowRemoved?: (e: { data: Object; key: any }) => void; - rowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; /** A handler for the rowRemoving event. */ - onRowRemoving?: (e: { data: Object; key: any; cancel: boolean }) => void; - rowUpdated?: (e: { data: Object; key: any }) => void; + onRowRemoving?: (e: { data: Object; key: any; cancel: any }) => void; /** A handler for the rowUpdated event. */ onRowUpdated?: (e: { data: Object; key: any }) => void; - rowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => void; /** A handler for the rowUpdating event. */ - onRowUpdating?: (e: { oldData: Object; newData: Object; key: any; cancel: boolean }) => void; + 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; - cellClick?: any; /** A handler for the cellClick event. */ onCellClick?: any; - cellHoverChanged?: (e: Object) => void; /** A handler for the cellHoverChanged event. */ onCellHoverChanged?: (e: Object) => void; - cellPrepared?: (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. */ @@ -3145,18 +3342,12 @@ declare module DevExpress.ui { /** An array of grid columns. */ columns?: Array; onContentReady?: Function; - contentReadyAction?: Function; /** Specifies a function that customizes grid columns after they are created. */ customizeColumns?: (columns: Array) => void; - dataErrorOccurred?: (errorObject: Error) => void; /** Specifies a data source for the grid. */ dataSource?: any; - editingStart?: (e: { - data: Object; - key: any; - cancel: boolean; - column: dxDataGridColumn - }) => void; + /** Specifies whether or not to enable data caching. */ + cacheEnabled?: boolean; /** A handler for the editingStart event. */ onEditingStart?: (e: { data: Object; @@ -3164,27 +3355,31 @@ declare module DevExpress.ui { cancel: boolean; column: dxDataGridColumn }) => void; - editorPrepared?: (e: Object) => void; /** A handler for the editorPrepared event. */ onEditorPrepared?: (e: Object) => void; - editorPreparing?: (e: Object) => void; /** A handler for the editorPreparing event. */ onEditorPreparing?: (e: Object) => void; /** Contains options that specify how grid content can be changed. */ editing?: { - /** Specifies whether or not grid records can be edited at runtime. */ - editEnabled?: boolean; - /** Specifies how grid values can be edited manually. */ editMode?: string; - /** Specifies whether or not new records can be inserted into a grid. */ + editEnabled?: boolean; insertEnabled?: boolean; - /** Specifies whether or not records can be deleted from a grid. */ 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 editEnabled option is set to true. */ + /** 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; @@ -3192,15 +3387,17 @@ declare module DevExpress.ui { 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 button that deletes a row from a grid. Setting this option makes sense only when the removeEnabled option is set to true. */ + /** 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 insertEnabled option is true. */ + /** 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 editEnabled option is set to true. */ + /** 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 editEnabled option is set to true. */ + /** 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 removeEnabled option is set to true. */ + /** 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; }; }; @@ -3227,6 +3424,10 @@ declare module DevExpress.ui { 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. */ @@ -3297,10 +3498,8 @@ declare module DevExpress.ui { }; /** Specifies whether or not grid rows must be shaded in a different way. */ rowAlternationEnabled?: boolean; - rowClick?: any; /** A handler for the rowClick event. */ onRowClick?: any; - rowPrepared?: (e: Object) => void; /** A handler for the rowPrepared event. */ onRowPrepared?: (e: Object) => void; /** Specifies a custom template for grid rows. */ @@ -3311,6 +3510,14 @@ declare module DevExpress.ui { 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?: { @@ -3375,17 +3582,13 @@ declare module DevExpress.ui { 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; }; - selectionChanged?: (e: { - currentSelectedRowKeys: Array; - currentDeselectedRowKeys: Array; - selectedRowKeys: Array; - selectedRowsData: Array; - }) => void; /** A handler for the dataErrorOccured event. */ onDataErrorOccurred?: (e: { error: Error }) => void; /** A handler for the selectionChanged event. */ @@ -3435,7 +3638,7 @@ declare module DevExpress.ui { /** 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; + 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. */ @@ -3554,10 +3757,14 @@ declare module DevExpress.ui { 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. */ @@ -3577,9 +3784,19 @@ declare module DevExpress.ui { /** 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, columnIndex: number): void; + 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. */ @@ -3603,6 +3820,11 @@ declare module DevExpress.ui { /** 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; @@ -3617,6 +3839,11 @@ declare module DevExpress.ui { /** 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; @@ -3656,8 +3883,14 @@ declare module DevExpress.ui { onContentReady?: Function; /** Specifies a data source for the pivot grid. */ dataSource?: any; - /** Specifies whether or not the widget uses native scrolling. */ 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. */ @@ -3674,6 +3907,12 @@ declare module DevExpress.ui { 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. */ @@ -3720,6 +3959,8 @@ declare module DevExpress.ui { 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; }; /** The Load panel configuration options. */ loadPanel?: { @@ -3744,6 +3985,38 @@ declare module DevExpress.ui { 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; + format: string; + 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 { @@ -3751,8 +4024,12 @@ declare module DevExpress.ui { 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. */ @@ -3847,7 +4124,6 @@ declare module DevExpress.framework { setView(key: string, viewInfo: Object): void; } export interface dxCommandOptions extends DOMComponentOptions { - action?: any; /** 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. */ @@ -3933,6 +4209,8 @@ declare module DevExpress.framework { 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. */ @@ -3947,6 +4225,7 @@ declare module DevExpress.framework { navigating: JQueryCallback; navigatingBack: JQueryCallback; resolveLayoutController: JQueryCallback; + resolveViewCacheKey: JQueryCallback; viewDisposed: JQueryCallback; viewDisposing: JQueryCallback; viewHidden: JQueryCallback; @@ -4013,6 +4292,11 @@ declare module DevExpress.framework { 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; @@ -4041,6 +4325,7 @@ declare module DevExpress.framework { 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; @@ -4076,6 +4361,11 @@ declare module DevExpress.framework { 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; @@ -4169,13 +4459,13 @@ declare module DevExpress.viz.core { width?: number; } export interface Margins { - /** Specifies the legend's bottom margin in pixels. */ + /** Specifies the distance in pixels between the bottom side of the title and the surrounding widget elements. */ bottom?: number; - /** Specifies the legend's left margin in pixels. */ + /** Specifies the distance in pixels between the left side of the title and the surrounding widget elements. */ left?: number; - /** Specifies the legend's right margin in pixels. */ + /** Specifies the distance between the right side of the title and surrounding widget elements in pixels. */ right?: number; - /** Specifies the legend's bottom margin in pixels. */ + /** Specifies the distance between the top side of the title and surrounding widget elements in pixels. */ top?: number; } export interface Size { @@ -4184,6 +4474,27 @@ declare module DevExpress.viz.core { /** 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; @@ -4193,6 +4504,7 @@ declare module DevExpress.viz.core { 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 }; @@ -4283,32 +4595,23 @@ declare module DevExpress.viz.core { visible?: boolean; } export interface BaseWidgetOptions { - drawn?: (widget: Object) => void; /** A handler for the drawn event. */ onDrawn?: (e: { component: BaseWidget; element: Element; }) => void; - incidentOccured?: (incidentInfo: { + /** 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; - /** 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; @@ -4334,11 +4637,6 @@ declare module DevExpress.viz.charts { clearSelection(): void; /** Gets the color of a particular series. */ getColor(): string; - /** - * Gets a point from the series point collection based on the specified argument. - * @deprecated getPointsByArg(pointArg).md - */ - getPointByArg(pointArg: any): Object; /** 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. */ @@ -4353,6 +4651,20 @@ declare module DevExpress.viz.charts { 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 { @@ -4371,9 +4683,9 @@ declare module DevExpress.viz.charts { /** Hides the tooltip of the point. */ hideTooltip(): void; /** Provides information about the hover state of a point. */ - isHovered(): any; + isHovered(): boolean; /** Provides information about the selection state of a point. */ - isSelected(): any; + 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. */ @@ -4389,20 +4701,6 @@ declare module DevExpress.viz.charts { pane: string; /** Returns the name of the value axis of the series. */ axis: string; - /** 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(): any; - /** Provides information about the selection state of a series. */ - isSelected(): any; - /** Provides information about the visibility state of a series. */ - isVisible(): boolean; - /** Makes a particular series visible. */ - show(): void; selectPoint(point: ChartPoint): void; deselectPoint(point: ChartPoint): void; getAllPoints(): Array; @@ -4457,20 +4755,6 @@ declare module DevExpress.viz.charts { export interface PolarSeries extends BaseSeries { /** Returns the name of the value axis of the series. */ axis: string; - /** 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(): any; - /** Provides information about the selection state of a series. */ - isSelected(): any; - /** Provides information about the visibility state of a series. */ - isVisible(): boolean; - /** Makes a particular series visible. */ - show(): void; selectPoint(point: PolarPoint): void; deselectPoint(point: PolarPoint): void; getAllPoints(): Array; @@ -4819,7 +5103,10 @@ declare module DevExpress.viz.charts { /** 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. */ + /** + * 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; @@ -4827,7 +5114,10 @@ declare module DevExpress.viz.charts { maxLabelCount?: number; /** Specifies a minimal size of a displayed pie segment. */ minSegmentSize?: number; - /** Specifies the direction in which the dxPieChart's series points are located. */ + /** + * 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; @@ -4851,17 +5141,34 @@ declare module DevExpress.viz.charts { /** Specifies how many segments must not be grouped. */ topCount?: number; }; - /** Specifies a start angle for a pie chart in arc degrees. */ + /** + * 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 PieSeriesConfig extends CommonPieSeriesConfig { - /** Sets the series type. */ + export interface CommonPieSeriesSettings extends CommonPieSeriesConfig { + /** + * Sets a series type for all 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; @@ -4980,6 +5287,10 @@ declare module DevExpress.viz.charts { 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?: { @@ -4989,6 +5300,10 @@ declare module DevExpress.viz.charts { 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; @@ -5217,7 +5532,6 @@ declare module DevExpress.viz.charts { customizePoint?: (pointInfo: Object) => Object; /** Specifies a data source for the chart. */ dataSource?: any; - done?: Function; /** Specifies the appearance of the loading indicator. */ loadingIndicator?: viz.core.LoadingIndicator; /** Specifies options of a dxChart's (dxPieChart's) legend. */ @@ -5233,21 +5547,18 @@ declare module DevExpress.viz.charts { }) => void; /** A handler for the pointClick event. */ onPointClick?: any; - pointClick?: any; /** A handler for the pointHoverChanged event. */ onPointHoverChanged?: (e: { component: BaseChart; element: Element; target: TPoint; }) => void; - pointHoverChanged?: (point: TPoint) => void; /** A handler for the pointSelectionChanged event. */ onPointSelectionChanged?: (e: { component: BaseChart; element: Element; target: TPoint; }) => void; - pointSelectionChanged?: (point: 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. */ @@ -5257,20 +5568,7 @@ declare module DevExpress.viz.charts { /** Specifies the size of the widget in pixels. */ size?: viz.core.Size; /** Specifies a title for the chart. */ - title?: { - /** Specifies font options for the title. */ - font?: viz.core.Font; - /** Specifies the title's horizontal position in the chart. */ - horizontalAlignment?: string; - /** Specifies a title's position on the chart in the vertical direction. */ - verticalAlignment?: string; - /** Specifies the distance between the title and surrounding chart elements in pixels. */ - margin?: viz.core.Margins; - /** Specifies the height of the space reserved for the title. */ - placeholderSize?: number; - /** Specifies a text for the chart's title. */ - text?: string; - }; + title?: viz.core.Title; /** Specifies tooltip options. */ tooltip?: BaseChartTooltip; /** A handler for the tooltipShown event. */ @@ -5285,8 +5583,6 @@ declare module DevExpress.viz.charts { element: Element; target: BasePoint; }) => void; - tooltipHidden?: (point: TPoint) => void; - tooltipShown?: (point: TPoint) => void; } /** A base class for all chart widgets included in the ChartJS library. */ export class BaseChart extends viz.core.BaseWidget { @@ -5294,6 +5590,12 @@ declare module DevExpress.viz.charts { 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. */ @@ -5349,6 +5651,10 @@ declare module DevExpress.viz.charts { 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; } export interface Legend extends AdvancedLegend { /** Specifies whether the legend is located outside or inside the chart's plot. */ @@ -5361,8 +5667,6 @@ declare module DevExpress.viz.charts { shared?: boolean; } export interface dxChartOptions extends AdvancedOptions { - /** Specifies a value indicating 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?: any; adaptiveLayout?: { keepLabels?: boolean; }; @@ -5374,7 +5678,6 @@ declare module DevExpress.viz.charts { adjustOnZoom?: boolean; /** Specifies argument axis options for the dxChart widget. */ argumentAxis?: ChartArgumentAxis; - argumentAxisClick?: any; /** 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. */ @@ -5413,7 +5716,7 @@ declare module DevExpress.viz.charts { maxBubbleSize?: number; /** Specifies the diameter of the smallest bubble measured in pixels. */ minBubbleSize?: number; - /** Defines the dxChart widget's pane(s). */ + /** 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; @@ -5421,10 +5724,6 @@ declare module DevExpress.viz.charts { legend?: Legend; /** Specifies options for dxChart widget series. */ series?: Array; - legendClick?: any; - seriesClick?: any; - seriesHoverChanged?: (series: ChartSeries) => void; - seriesSelectionChanged?: (series: ChartSeries) => void; /** Defines options for the series template. */ seriesTemplate?: SeriesTemplate; /** Specifies tooltip options. */ @@ -5455,12 +5754,6 @@ declare module DevExpress.viz.charts { export class dxChart extends BaseChart { constructor(element: JQuery, options?: dxChartOptions); constructor(element: Element, options?: dxChartOptions); - /** 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): ChartSeries; - /** Gets a series within the chart's series collection by its position number. */ - getSeriesByPos(seriesIndex: number): ChartSeries; /** Sets the specified start and end values for the chart's argument axis. */ zoomArgument(startValue: any, endValue: any): void; } @@ -5480,8 +5773,6 @@ declare module DevExpress.viz.charts { shared?: boolean; } export interface dxPolarChartOptions extends AdvancedOptions { - /** Specifies a value indicating whether 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 adaptive layout options. */ adaptiveLayout?: { width?: number; @@ -5512,12 +5803,6 @@ declare module DevExpress.viz.charts { export class dxPolarChart extends BaseChart { constructor(element: JQuery, options?: dxPolarChartOptions); constructor(element: Element, options?: dxPolarChartOptions); - /** 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): PolarSeries; - /** Gets a series within the chart's series collection by its position number. */ - getSeriesByPos(seriesIndex: number): PolarSeries; } export interface PieLegend extends core.BaseLegend { /** Specifies what chart elements to highlight when a corresponding item in the legend is hovered over. */ @@ -5539,17 +5824,29 @@ declare module DevExpress.viz.charts { series?: Array; /** Specifies the diameter of the pie. */ diameter?: number; + /** Specifies the direction that the pie chart segments will occupy. */ + segmentsDirection?: string; + /** Specifies the starting angle in arc degrees for the first segment in a pie chart. */ + 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; - legendClick?: 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. */ + /** + * Provides access to the dxPieChart series. + * @deprecated ..\..\BaseChart\3 Methods\getAllSeries().md + */ getSeries(): PieSeries; } } @@ -5584,13 +5881,22 @@ declare module DevExpress.viz.gauges { export interface ScaleTick { /** Specifies the color of the scale's minor ticks. */ color?: string; - /** Specifies an array of custom minor ticks. */ + /** + * 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. */ + /** + * 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. */ + /** + * Specifies an interval between minor ticks. + * @deprecated ..\minorTickInterval.md + */ tickInterval?: number; /** Indicates whether scale minor ticks are visible or not. */ visible?: boolean; @@ -5598,14 +5904,28 @@ declare module DevExpress.viz.gauges { width?: number; } export interface ScaleMajorTick extends ScaleTick { - /** Specifies whether or not to expand the current major tick interval if labels overlap each other. */ + /** + * 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. */ @@ -5618,20 +5938,56 @@ declare module DevExpress.viz.gauges { 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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?: ScaleTick; + minorTick?: ScaleMinorTick; /** Specifies the start value for the scale of the gauge. */ startValue?: number; } @@ -5688,21 +6044,48 @@ declare module DevExpress.viz.gauges { redrawOnResize?: boolean; /** Specifies the size of the widget in pixels. */ size?: viz.core.Size; - /** Specifies a subtitle for a gauge. */ + /** + * Specifies a subtitle for the widget. + * @deprecated ..\..\..\BaseGauge\1 Configuration\title\subtitle\subtitle.md + */ subtitle?: { - /** Specifies font options for the subtitle. */ + /** + * Specifies font options for the subtitle. + * @deprecated ..\..\title\subtitle\font\font.md + */ font?: viz.core.Font; - /** Specifies a text for the subtitle. */ + /** + * 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. */ + /** + * Specifies a title's position on the gauge. + * @deprecated basegaugeoptions_title_verticalAlignment and basegaugeoptions_title_horizontalAlignment + */ position?: string; - /** Specifies a text for the title. */ + /** 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; @@ -5911,6 +6294,8 @@ declare module DevExpress.viz.rangeSelector { /** 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. */ @@ -5941,8 +6326,10 @@ declare module DevExpress.viz.rangeSelector { /** Specifies how to sort series points. */ sortingMethod?: any; }; - /** Specifies a value indicating 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?: 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; /** 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. */ @@ -6076,7 +6463,6 @@ declare module DevExpress.viz.rangeSelector { /** Specifies range selector's right indent. */ right?: number; }; - selectedRangeChanged?: (selectedRange: { startValue: any; endValue: any; }) => void; /** A handler for the selectedRangeChanged event. */ onSelectedRangeChanged?: (e: { startValue: any; @@ -6168,145 +6554,426 @@ interface JQuery { 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 Area object. */ + /** 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 the 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. */ + /** + * Contains the element type. + * @deprecated ..\..\Layer\2 Fields\type.md + */ type: string; - /** Return the value of an attribute. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * Contains the type of the element. + * @deprecated ..\..\Layer\2 Fields\type.md + */ type: string; - /** Contains the URL of an image map marker. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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 the marker appearance. */ + /** + * 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 AreaSettings { - /** Specifies the width of the area border in pixels. */ + 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 element. */ + data?: any; + /** Specifies the width of the layer elements border in pixels. */ borderWidth?: number; - /** Specifies a color for the area border. */ + /** Specifies a color for the border of the layer elements. */ borderColor?: string; - click?: any; - /** Specifies a color for an area. */ + /** Specifies a color for layer elements. */ color?: string; - /** Specifies the function that customizes each area individually. */ - customize?: (areaInfo: Area) => AreaSettings; - /** Specifies a color for the area border when the area is hovered over. */ + /** Specifies a color for the border of the layer element when it is hovered over. */ hoveredBorderColor?: string; - /** Specifies the pixel-measured width of the area border when the area is hovered over. */ + /** Specifies the pixel-measured width for the border of the layer element when it is hovered over. */ hoveredBorderWidth?: number; - /** Specifies a color for an area when this area is hovered over. */ + /** Specifies a color for a layer element when it is hovered over. */ hoveredColor?: string; - /** Specifies whether or not to change the appearance of an area when it is hovered over. */ + /** Specifies a pixel-measured 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; - /** Configures area labels. */ - label?: { - /** Specifies the data field that provides data for area labels. */ - dataField?: string; - /** Enables area labels. */ - enabled?: boolean; - /** Specifies font options for area labels. */ - font?: viz.core.Font; - }; - /** Specifies the name of the palette or a custom range of colors to be used for coloring a map. */ + /** 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 areas with similar attributes in the same color. */ + /** 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 areas. */ + /** Specifies the field that provides data to be used for coloring of layer elements. */ colorGroupingField?: string; - /** Specifies a color for the area border when the area is selected. */ - selectedBorderColor?: string; - /** Specifies a color for an area when this area is selected. */ - selectedColor?: string; - /** Specifies the pixel-measured width of the area border when the area is selected. */ - selectedBorderWidth?: number; - selectionChanged?: (area: Area) => void; - /** Specifies whether single or multiple areas can be selected on a vector map. */ - selectionMode?: string; - } - export interface MarkerSettings { - /** Specifies a color for the marker border. */ - borderColor?: string; - /** Specifies the width of the marker border in pixels. */ - borderWidth?: number; - click?: any; - /** Specifies a color for a marker of the dot or bubble type. */ - color?: string; - /** Specifies the function that customizes each marker individually. */ - customize?: (markerInfo: Marker) => MarkerSettings; - font?: Object; - /** Specifies the pixel-measured width of the marker border when the marker is hovered over. */ - hoveredBorderWidth?: number; - /** Specifies a color for the marker border when the marker is hovered over. */ - hoveredBorderColor?: string; - /** Specifies a color for a marker of the dot or bubble type when this marker is hovered over. */ - hoveredColor?: string; - /** Specifies whether or not to change the appearance of a marker when it is hovered over. */ - hoverEnabled?: boolean; + /** 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; }; - /** 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. */ - 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. */ - minSize?: number; - /** Specifies the opacity of markers. Setting this option makes sense only if you use markers of the bubble type. */ - opacity?: number; - /** Specifies the pixel-measured width of the marker border when the marker is selected. */ - selectedBorderWidth?: number; - /** Specifies a color for the marker border when the marker is selected. */ - selectedBorderColor?: string; - /** Specifies a color for a marker of the dot or bubble type when this marker is selected. */ - selectedColor?: string; - selectionChanged?: (marker: Marker) => void; - /** Specifies whether a single or multiple markers can be selected on a vector map. */ - selectionMode?: string; - /** Specifies the size of markers. Setting this option makes sense for any type of marker except bubble. */ - size?: number; - /** Specifies the type of markers to be used on the map. */ - type?: string; - /** Specifies the name of a palette or a custom set of colors to be used for coloring markers of the pie type. */ + } + 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; - /** Allows you to paint markers with similar attributes in the same color. */ + /** + * 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 markers. */ + /** + * Specifies the field that provides data to be used for coloring areas. + * @deprecated ..\layers\colorGroupingField.md + */ colorGroupingField?: string; - /** Allows you to display bubbles with similar attributes in the same size. */ + /** + * 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. */ + /** + * 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. */ + /** + * An object specifying options for the map areas. + * @deprecated Use the 'layers' option instead + */ areaSettings?: AreaSettings; /** Specifies the options for the map background. */ background?: { @@ -6315,6 +6982,10 @@ declare module DevExpress.viz.map { /** 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. */ @@ -6336,14 +7007,25 @@ declare module DevExpress.viz.map { }; /** Specifies the appearance of the loading indicator. */ loadingIndicator?: viz.core.LoadingIndicator; - /** Specifies a data source for the map area. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ @@ -6356,7 +7038,6 @@ declare module DevExpress.viz.map { zoomingEnabled?: boolean; /** Specifies the geographical coordinates of the center for a map. */ center?: Array; - centerChanged?: (center: Array) => void; /** A handler for the centerChanged event. */ onCenterChanged?: (e: { center: Array; @@ -6379,27 +7060,43 @@ declare module DevExpress.viz.map { zoomFactor?: number; /** Specifies a map's maximum zoom factor. */ maxZoomFactor?: number; - zoomFactorChanged?: (zoomFactor: number) => void; /** A handler for the zoomFactorChanged event. */ onZoomFactorChanged?: (e: { - zoomFactor: number; component: dxVectorMap; element: Element; + zoomFactor: number; }) => void; - click?: any; /** A handler for the click event. */ onClick?: any; - /** A handler for the areaClick event. */ + /** 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. */ + /** + * 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. */ + /** + * A handler for the markerClick event. + * @deprecated Use the 'onClick' option instead + */ onMarkerClick?: any; - /** A handler for the markerSelectionChanged event. */ + /** + * A handler for the markerSelectionChanged event. + * @deprecated Use the 'onSelecitonChanged' option instead + */ onMarkerSelectionChanged?: (e: { target: Marker; component: dxVectorMap; @@ -6409,12 +7106,19 @@ declare module DevExpress.viz.map { 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?: string; + 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 { @@ -6430,17 +7134,35 @@ declare module DevExpress.viz.map { 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. */ + /** + * 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. */ + /** + * 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; - /** Returns an array with all the map areas. */ + /** 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. */ + /** + * 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; @@ -6451,6 +7173,19 @@ declare module DevExpress.viz.map { /** 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; diff --git a/dhtmlxscheduler/dhtmlxscheduler.d.ts b/dhtmlxscheduler/dhtmlxscheduler.d.ts index c79ce78c9a..78537e3935 100644 --- a/dhtmlxscheduler/dhtmlxscheduler.d.ts +++ b/dhtmlxscheduler/dhtmlxscheduler.d.ts @@ -1165,11 +1165,22 @@ interface SchedulerStatic{ */ deleteEvent(id: any); + /** + * removes all blocking sets from the scheduler + */ + deleteMarkedTimespan(); + /** * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods * @param id the timespan id */ deleteMarkedTimespan(id: string); + + /** + * removes marking/blocking set by the addMarkedTimespan() and blockTime() methods + * @param configuration for deleting + */ + deleteMarkedTimespan(config: any); /** * deletes a section from the currently active view (if the opened view isn't Timeline in the 'Tree' mode - the method will be ignored) @@ -1212,6 +1223,13 @@ interface SchedulerStatic{ * 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); /** * gives access to the objects of lightbox's sections diff --git a/drop/drop.d.ts b/drop/drop.d.ts index a48cb8fb3c..1b994c9a1e 100644 --- a/drop/drop.d.ts +++ b/drop/drop.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Drop v0.5.7 +// Type definitions for Drop v1.3.0 // Project: http://github.hubspot.com/drop/ // Definitions by: Adi Dahiya // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -26,6 +26,7 @@ declare module drop { constrainToWindow?: boolean; constrainToScrollParent?: boolean; remove?: boolean; + beforeClose?: () => boolean; tetherOptions?: tether.ITetherOptions; } @@ -37,6 +38,7 @@ declare module drop { close(): void; remove(): void; toggle(): void; + isOpened(): boolean; position(): void; destroy(): void; /* diff --git a/easeljs/easeljs-tests.ts b/easeljs/easeljs-tests.ts index b036ae5702..c517dba2fb 100644 --- a/easeljs/easeljs-tests.ts +++ b/easeljs/easeljs-tests.ts @@ -42,6 +42,7 @@ function test_animation() { function test_graphics() { var g = new createjs.Graphics(); g.setStrokeStyle(1); + g.setStrokeDash([20, 10], 20); g.beginStroke(createjs.Graphics.getRGB(0, 0, 0)); g.beginFill(createjs.Graphics.getRGB(255, 0, 0)); g.drawCircle(0, 0, 3); diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index 73b45b8108..947c760e10 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -344,6 +344,7 @@ declare module createjs { quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): Graphics; rect(x: number, y: number, w: number, h: number): Graphics; setStrokeStyle(thickness: number, caps?: string | number, joints?: string | number, miterLimit?: number, ignoreScale?: boolean): Graphics; + setStrokeDash(segments?: number[], offset?: number): Graphics; store(): Graphics; toString(): string; unstore(): Graphics; @@ -377,6 +378,7 @@ declare module createjs { qt(cpx: number, cpy: number, x: number, y: number): Graphics; r(x: number, y: number, w: number, h: number): Graphics; ss(thickness: number, caps?: string | number, joints?: string | number, miterLimit?: number, ignoreScale?: boolean): Graphics; + sd(segments?: number[], offset?: number): Graphics; } diff --git a/email-addresses/email-addresses-tests.ts b/email-addresses/email-addresses-tests.ts new file mode 100644 index 0000000000..b43289d86c --- /dev/null +++ b/email-addresses/email-addresses-tests.ts @@ -0,0 +1,8 @@ +/// + +import addrs = require('email-addresses'); + +var result: Object; + +result = addrs.parseOneAddress('Jack Bowman '); +result = addrs.parseAddressList(['foo@bar.com', 'Foo Bar ']); diff --git a/email-addresses/email-addresses.d.ts b/email-addresses/email-addresses.d.ts new file mode 100644 index 0000000000..c8cd74d1a0 --- /dev/null +++ b/email-addresses/email-addresses.d.ts @@ -0,0 +1,9 @@ +// Type definitions for email-addresses 2.0.1 +// Project: https://github.com/jackbowman/email-addresses +// Definitions by: John Grimsey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "email-addresses" { + function parseOneAddress(opts: any): any; + function parseAddressList(opts: any): any; +} diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx new file mode 100644 index 0000000000..71e82351f7 --- /dev/null +++ b/enzyme/enzyme-tests.tsx @@ -0,0 +1,574 @@ +/// +/// + +import { shallow, mount, render, describeWithDOM, spyLifecycle } from "enzyme"; +import * as React from "react"; +import {Component, ReactElement} from "react"; +import {ShallowWrapper, ReactWrapper, CheerioWrapper} from "enzyme"; + + +// Help classes/interfaces +interface MyComponentProps { + propsProperty: any; +} + +interface MyComponentState { + stateProperty: any; +} + +class MyComponent extends Component { + setState(...args: any[]) { + } +} + +// API +module SpyLifecycleTest { + spyLifecycle(MyComponent); +} + +// ShallowWrapper +module ShallowWrapperTest { + var shallowWrapper: ShallowWrapper = + shallow(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String; + + function test_find() { + shallowWrapper = shallowWrapper.find('.selector'); + shallowWrapper = shallowWrapper.find(MyComponent); + } + + function test_findWhere() { + shallowWrapper = + shallowWrapper.findWhere((aShallowWrapper: ShallowWrapper) => true); + } + + function test_filter() { + shallowWrapper = shallowWrapper.filter('.selector'); + shallowWrapper = shallowWrapper.filter(MyComponent); + } + + function test_filterWhere() { + shallowWrapper = + shallowWrapper.filterWhere((aShallowWrapper: ShallowWrapper) => 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() { + shallowWrapper = shallowWrapper.find('.foo').not('.bar'); + } + + function test_children() { + shallowWrapper = shallowWrapper.children(); + } + + function test_parents() { + shallowWrapper = shallowWrapper.parents(); + } + + function test_parent() { + shallowWrapper = shallowWrapper.parent(); + } + + function test_closest() { + shallowWrapper = shallowWrapper.closest('.selector'); + shallowWrapper = shallowWrapper.closest(MyComponent); + } + + function test_shallow() { + shallowWrapper = shallowWrapper.shallow(); + } + + 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((aShallowWrapper: ShallowWrapper)=> { + }); + } + + function test_map() { + var arrayVal: Array = + shallowWrapper.map((aShallowWrapper: ShallowWrapper)=> { + }); + } + + function test_reduce() { + const total: number[] = + shallowWrapper.reduce( + (amount: number, n: ShallowWrapper) => amount + n.prop('amount') + ); + } + + 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 +module ReactWrapperTest { + var reactWrapper: ReactWrapper = + mount(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String; + + function test_find() { + reactWrapper = reactWrapper.find('.selector'); + reactWrapper = reactWrapper.find(MyComponent); + } + + function test_findWhere() { + reactWrapper = + reactWrapper.findWhere((aReactWrapper: ReactWrapper) => true); + } + + function test_filter() { + reactWrapper = reactWrapper.filter('.selector'); + reactWrapper = reactWrapper.filter(MyComponent); + } + + function test_filterWhere() { + reactWrapper = + reactWrapper.filterWhere((aReactWrapper: ReactWrapper) => 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() { + reactWrapper = 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() { + reactWrapper = 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((aReactWrapper: ReactWrapper)=> { + }); + } + + function test_map() { + var arrayVal: Array = + reactWrapper.map((aReactWrapper: ReactWrapper)=> { + }); + } + + 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 +module CheerioWrapperTest { + var cheerioWrapper: CheerioWrapper = + render(); + + var reactElement: ReactElement, + objectVal: Object, + boolVal: Boolean, + stringVal: String; + + function test_find() { + cheerioWrapper = cheerioWrapper.find('.selector'); + cheerioWrapper = cheerioWrapper.find(MyComponent); + } + + function test_findWhere() { + cheerioWrapper = + cheerioWrapper.findWhere((aCheerioWrapper: CheerioWrapper) => true); + } + + function test_filter() { + cheerioWrapper = cheerioWrapper.filter('.selector'); + cheerioWrapper = cheerioWrapper.filter(MyComponent); + } + + function test_filterWhere() { + cheerioWrapper = + cheerioWrapper.filterWhere((aCheerioWrapper: CheerioWrapper) => 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() { + cheerioWrapper = 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() { + cheerioWrapper = 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 arrayVal: Array = + cheerioWrapper.map((aCheerioWrapper: CheerioWrapper)=> { + }); + } + + 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.d.ts b/enzyme/enzyme.d.ts new file mode 100644 index 0000000000..dd0c996a7c --- /dev/null +++ b/enzyme/enzyme.d.ts @@ -0,0 +1,340 @@ +// 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} 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(selector: EnzymeSelector): T; + + /** + * Finds every node in the render tree that returns true for the provided predicate function. + * @param predicate + */ + findWhere(predicate: (shallowWrapper: ShallowWrapper) => Boolean): T; + + /** + * Removes nodes in the current wrapper that do not match the provided selector. + * @param selector The selector to match. + */ + filter(selector: EnzymeSelector): T; + + /** + * 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: (shallowWrapper: ShallowWrapper) => Boolean): T; + + /** + * 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): T; + + /** + * 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(selector?: EnzymeSelector): T; + + /** + * 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(selector?: EnzymeSelector): T; + + /** + * Returns a wrapper with the direct parent of the node in the current wrapper. + */ + parent(): T; + + /** + * 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(selector: EnzymeSelector): T; + + /** + * 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): T; + + /** + * Reduce the set of matched nodes to the first in the set. + */ + first(): T; + + /** + * Reduce the set of matched nodes to the last in the set. + */ + last(): T; + + /** + * 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(): Object; + + /** + * 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[]): T; + + /** + * 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): T; + + /** + * 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(state: Object): T; + + /** + * 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(state: Object): T; + + /** + * 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(): T; + + /** + * 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: ShallowWrapper) => void): T; + + /** + * 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: ShallowWrapper) => any): Array; + + /** + * 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: ShallowWrapper, 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: ShallowWrapper, 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: ShallowWrapper) => 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: ShallowWrapper) => Boolean): Boolean; + + length: number; + } + + export interface ShallowWrapper extends CommonWrapper, P, S> { + shallow(): ShallowWrapper; + + render(): CheerioWrapper; + } + + export interface ReactWrapper extends CommonWrapper, P, S> { + + } + + export interface CheerioWrapper extends CommonWrapper, P, S> { + + } + + /** + * 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/errorhandler/errorhandler-tests.ts b/errorhandler/errorhandler-tests.ts index 0ba9edb56f..1316888e32 100644 --- a/errorhandler/errorhandler-tests.ts +++ b/errorhandler/errorhandler-tests.ts @@ -1,7 +1,8 @@ /// -import express = require('express'); -import errorhandler = require('errorhandler'); +import * as express from 'express'; +import * as errorhandler from 'errorhandler'; + var app = express(); app.use(errorhandler()); @@ -14,4 +15,4 @@ app.use(errorhandler({ log: (err, str, req, res) => { const requestWasFresh = req && req.fresh; const responseContentType = res && res.contentType -}})) \ No newline at end of file +}})) diff --git a/errorhandler/errorhandler.d.ts b/errorhandler/errorhandler.d.ts index 8ae5e924ce..37d5c3c41d 100644 --- a/errorhandler/errorhandler.d.ts +++ b/errorhandler/errorhandler.d.ts @@ -6,19 +6,19 @@ /// declare module "errorhandler" { - import express = require('express'); - + import * as express from 'express'; + function errorHandler(options?: errorHandler.Options): express.ErrorRequestHandler; - + namespace errorHandler { interface LoggingCallback { (err: Error, str: string, req: express.Request, res: express.Response): void; } - + interface Options { /** * Defaults to true. - * + * * Possible values: * true : Log errors using console.error(str). * false : Only send the error back in the response. @@ -27,6 +27,6 @@ declare module "errorhandler" { log: boolean | LoggingCallback; } } - + export = errorHandler; } diff --git a/eventemitter3/eventemitter3-tests.ts b/eventemitter3/eventemitter3-tests.ts index da13434135..49ae0a24df 100644 --- a/eventemitter3/eventemitter3-tests.ts +++ b/eventemitter3/eventemitter3-tests.ts @@ -1,16 +1,44 @@ -/// +/// +/// +/// 'use strict'; import EventEmitter = require('eventemitter3'); +import util = require('util'); +import * as EventEmitter3ImportedAsES6Module from 'eventemitter3'; + +declare namespace Assume { + interface Class { + new(...args: any[]): T; + } + + interface Assume { + equals(compare: T): Assume; + equal(compare: T): Assume; + eqls(compare: T): Assume; + is: Assume; + deep: Assume; + to: Assume; + either(arr: T[]): Assume; + instanceOf(clazz: Class): Assume; + a(typeofString: string): Assume; + } + + export function assume(input: T): Assume; +} + +let assume = Assume.assume; class EventEmitterTest { - v: EventEmitter; + v: EventEmitter3.EventEmitter; constructor() { this.v = new EventEmitter(); - this.v = new EventEmitter.EventEmitter(); - this.v = new EventEmitter.EventEmitter2(); - this.v = new EventEmitter.EventEmitter3(); + this.v = new EventEmitter3ImportedAsES6Module(); + + // Some methods are missing or incompatible with current implementation (v4.2.x) of NodeJS.EventEmitter + // (e.g. getMaxListenters or listeners) + // var n: NodeJS.EventEmitter = this.v; } listeners() { @@ -27,39 +55,528 @@ class EventEmitterTest { on() { var fn = () => console.log(1); - var v1: EventEmitter = this.v.on('click', fn); - var v2: EventEmitter = this.v.on('click', fn, this); + var v1: EventEmitter3.EventEmitter = this.v.on('click', fn); + var v2: EventEmitter3.EventEmitter = this.v.on('click', fn, this); } once() { var fn = () => console.log(1); - var v1: EventEmitter = this.v.once('click', fn); - var v2: EventEmitter = this.v.once('click', fn, this); + var v1: EventEmitter3.EventEmitter = this.v.once('click', fn); + var v2: EventEmitter3.EventEmitter = this.v.once('click', fn, this); } removeListener() { var fn = () => console.log(1); - var v1: EventEmitter = this.v.removeListener('click', fn); - var v2: EventEmitter = this.v.removeListener('click', fn, true); + var v1: EventEmitter3.EventEmitter = this.v.removeListener('click', fn); + var v2: EventEmitter3.EventEmitter = this.v.removeListener('click', fn, true); } removeAllListeners() { - var v1: EventEmitter = this.v.removeAllListeners('click'); + var v1: EventEmitter3.EventEmitter = this.v.removeAllListeners('click'); } off() { var fn = () => console.log(1); - var v1: EventEmitter = this.v.off('click', fn); - var v2: EventEmitter = this.v.off('click', fn, true); + var v1: EventEmitter3.EventEmitter = this.v.off('click', fn); + var v2: EventEmitter3.EventEmitter = this.v.off('click', fn, true); } addListener() { var fn = () => console.log(1); - var v1: EventEmitter = this.v.addListener('click', fn); - var v2: EventEmitter = this.v.addListener('click', fn, this); + var v1: EventEmitter3.EventEmitter = this.v.addListener('click', fn); + var v2: EventEmitter3.EventEmitter = this.v.addListener('click', fn, this); } setMaxListeners() { - var v1: EventEmitter = this.v.setMaxListeners(); + var v1: EventEmitter3.EventEmitter = this.v.setMaxListeners(); } } + + +describe('EventEmitter', function tests() { + 'use strict'; + + it('exposes a `prefixed` property', function () { + assume(EventEmitter.prefixed).is.either([false, '~']); + }); + + it('inherits when used with require(util).inherits', function () { + class Beast extends EventEmitter { + /* rawr, i'm a beast */ + } + + util.inherits(Beast, EventEmitter); + + var moop = new Beast() + , meap = new Beast(); + + assume(moop).is.instanceOf(Beast); + assume(moop).is.instanceOf(EventEmitter); + + moop.listeners(); + meap.listeners(); + + moop.on('data', function () { + throw new Error('I should not emit'); + }); + + meap.emit('data', 'rawr'); + meap.removeListener('foo'); + meap.removeAllListeners(); + }); + + describe('EventEmitter#emit', function () { + it('should return false when there are not events to emit', function () { + var e = new EventEmitter(); + + assume(e.emit('foo')).equals(false); + assume(e.emit('bar')).equals(false); + }); + + it('emits with context', function (done) { + var context = { bar: 'baz' } + , e = new EventEmitter(); + + e.on('foo', function (bar: string) { + assume(bar).equals('bar'); + assume(this).equals(context); + + done(); + }, context).emit('foo', 'bar'); + }); + + it('emits with context, multiple arguments (force apply)', function (done) { + var context = { bar: 'baz' } + , e = new EventEmitter(); + + e.on('foo', function (bar: string) { + assume(bar).equals('bar'); + assume(this).equals(context); + + done(); + }, context).emit('foo', 'bar', 1,2,3,4,5,6,7,8,9,0); + }); + + it('can emit the function with multiple arguments', function () { + var e = new EventEmitter(); + + for(var i = 0; i < 100; i++) { + (function (j: number) { + for (var i = 0, args: number[] = []; i < j; i++) { + args.push(j); + } + + e.once('args', function () { + assume(arguments.length).equals(args.length); + }); + + e.emit.apply(e, (['args'] as any[]).concat(args)); + })(i); + } + }); + + it('can emit the function with multiple arguments, multiple listeners', function () { + var e = new EventEmitter(); + + for(var i = 0; i < 100; i++) { + (function (j: number) { + for (var i = 0, args: number[] = []; i < j; i++) { + args.push(j); + } + + e.once('args', function () { + assume(arguments.length).equals(args.length); + }); + + e.once('args', function () { + assume(arguments.length).equals(args.length); + }); + + e.once('args', function () { + assume(arguments.length).equals(args.length); + }); + + e.once('args', function () { + assume(arguments.length).equals(args.length); + }); + + e.emit.apply(e, (['args'] as any[]).concat(args)); + })(i); + } + }); + + it('emits with context, multiple listeners (force loop)', function () { + var e = new EventEmitter(); + + e.on('foo', function (bar: string) { + assume(this).eqls({ foo: 'bar' }); + assume(bar).equals('bar'); + }, { foo: 'bar' }); + + e.on('foo', function (bar: string) { + assume(this).eqls({ bar: 'baz' }); + assume(bar).equals('bar'); + }, { bar: 'baz' }); + + e.emit('foo', 'bar'); + }); + + it('emits with different contexts', function () { + var e = new EventEmitter() + , pattern = ''; + + function writer() { + pattern += this; + } + + e.on('write', writer, 'foo'); + e.on('write', writer, 'baz'); + e.once('write', writer, 'bar'); + e.once('write', writer, 'banana'); + + e.emit('write'); + assume(pattern).equals('foobazbarbanana'); + }); + + it('should return true when there are events to emit', function (done) { + var e = new EventEmitter(); + + e.on('foo', function () { + process.nextTick(done); + }); + + assume(e.emit('foo')).equals(true); + assume(e.emit('foob')).equals(false); + }); + + it('receives the emitted events', function (done) { + var e = new EventEmitter(); + + e.on('data', function (a: string, b: EventEmitter3.EventEmitter, c: Date, d: void, undef: void) { + assume(a).equals('foo'); + assume(b).equals(e); + assume(c).is.instanceOf(Date); + assume(undef).equals(undefined); + assume(arguments.length).equals(3); + + done(); + }); + + e.emit('data', 'foo', e, new Date()); + }); + + it('emits to all event listeners', function () { + var e = new EventEmitter() + , pattern: string[] = []; + + e.on('foo', function () { + pattern.push('foo1'); + }); + + e.on('foo', function () { + pattern.push('foo2'); + }); + + e.emit('foo'); + + assume(pattern.join(';')).equals('foo1;foo2'); + }); + + (function each(keys: string[]) { + var key = keys.shift(); + + if (!key) return; + + it('can store event which is a known property: '+ key, function (next) { + var e = new EventEmitter(); + + e.on(key, function (key: string) { + assume(key).equals(key); + next(); + }).emit(key, key); + }); + + each(keys); + })([ + 'hasOwnProperty', + 'constructor', + '__proto__', + 'toString', + 'toValue', + 'unwatch', + 'watch' + ]); + }); + + describe('EventEmitter#listeners', function () { + it('returns an empty array if no listeners are specified', function () { + var e = new EventEmitter(); + + assume(e.listeners('foo')).is.a('array'); + assume(e.listeners('foo').length).equals(0); + }); + + it('returns an array of function', function () { + var e = new EventEmitter(); + + function foo() {} + + e.on('foo', foo); + assume(e.listeners('foo')).is.a('array'); + assume(e.listeners('foo').length).equals(1); + assume(e.listeners('foo')).deep.equals([foo]); + }); + + it('is not vulnerable to modifications', function () { + var e = new EventEmitter(); + + function foo() {} + + e.on('foo', foo); + + assume(e.listeners('foo')).deep.equals([foo]); + + e.listeners('foo').length = 0; + assume(e.listeners('foo')).deep.equals([foo]); + }); + + it('can return a boolean as indication if listeners exist', function () { + var e = new EventEmitter(); + + function foo() {} + + e.once('once', foo); + e.once('multiple', foo); + e.once('multiple', foo); + e.on('on', foo); + e.on('multi', foo); + e.on('multi', foo); + + assume(e.listeners('foo', true)).equals(false); + assume(e.listeners('multiple', true)).equals(true); + assume(e.listeners('on', true)).equals(true); + assume(e.listeners('multi', true)).equals(true); + + e.removeAllListeners(); + + assume(e.listeners('multiple', true)).equals(false); + assume(e.listeners('on', true)).equals(false); + assume(e.listeners('multi', true)).equals(false); + }); + }); + + describe('EventEmitter#once', function () { + it('only emits it once', function () { + var e = new EventEmitter() + , calls = 0; + + e.once('foo', function () { + calls++; + }); + + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + + assume(e.listeners('foo').length).equals(0); + assume(calls).equals(1); + }); + + it('only emits once if emits are nested inside the listener', function () { + var e = new EventEmitter() + , calls = 0; + + e.once('foo', function () { + calls++; + e.emit('foo'); + }); + + e.emit('foo'); + assume(e.listeners('foo').length).equals(0); + assume(calls).equals(1); + }); + + it('only emits once for multiple events', function () { + var e = new EventEmitter() + , multi = 0 + , foo = 0 + , bar = 0; + + e.once('foo', function () { + foo++; + }); + + e.once('foo', function () { + bar++; + }); + + e.on('foo', function () { + multi++; + }); + + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + + assume(e.listeners('foo').length).equals(1); + assume(multi).equals(5); + assume(foo).equals(1); + assume(bar).equals(1); + }); + + it('only emits once with context', function (done) { + var context = { foo: 'bar' } + , e = new EventEmitter(); + + e.once('foo', function (bar: string) { + assume(this).equals(context); + assume(bar).equals('bar'); + + done(); + }, context).emit('foo', 'bar'); + }); + }); + + describe('EventEmitter#removeListener', function () { + it('should only remove the event with the specified function', function () { + var e = new EventEmitter(); + + function bar() {} + e.on('foo', function () {}); + e.on('bar', function () {}); + e.on('bar', bar); + + assume(e.removeListener('foo', bar)).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.listeners('bar').length).equals(2); + + assume(e.removeListener('foo')).equals(e); + assume(e.listeners('foo').length).equals(0); + assume(e.listeners('bar').length).equals(2); + + assume(e.removeListener('bar', bar)).equals(e); + assume(e.listeners('bar').length).equals(1); + assume(e.removeListener('bar')).equals(e); + assume(e.listeners('bar').length).equals(0); + }); + + it('should only remove once events when using the once flag', function () { + var e = new EventEmitter(); + + function foo() {} + e.on('foo', foo); + + assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.removeListener('foo', foo, undefined, true)).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.removeListener('foo', foo)).equals(e); + assume(e.listeners('foo').length).equals(0); + + e.on('foo', foo); + e.once('foo', foo); + + assume(e.removeListener('foo', function () {}, undefined, true)).equals(e); + assume(e.listeners('foo').length).equals(2); + assume(e.removeListener('foo', foo, undefined, true)).equals(e); + assume(e.listeners('foo').length).equals(1); + + e.once('foo', foo); + + assume(e.removeListener('foo', foo)).equals(e); + assume(e.listeners('foo').length).equals(0); + }); + + it('should only remove listeners matching the correct context', function () { + var e = new EventEmitter() + , context = { foo: 'bar' }; + + function foo() {} + function bar() {} + e.on('foo', foo, context); + + assume(e.listeners('foo').length).equals(1); + assume(e.removeListener('foo', function () {}, context)).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.removeListener('foo', foo, context)).equals(e); + assume(e.listeners('foo').length).equals(0); + + e.on('foo', foo, context); + e.on('foo', bar); + + assume(e.listeners('foo').length).equals(2); + assume(e.removeListener('foo', foo, { baz: 'quux' })).equals(e); + assume(e.listeners('foo').length).equals(2); + assume(e.removeListener('foo', foo, context)).equals(e); + assume(e.listeners('foo').length).equals(1); + assume(e.listeners('foo')[0]).equals(bar); + + e.on('foo', foo, context); + + assume(e.listeners('foo').length).equals(2); + assume(e.removeAllListeners('foo')).equals(e); + assume(e.listeners('foo').length).equals(0); + }); + }); + + describe('EventEmitter#removeAllListeners', function () { + it('removes all events for the specified events', function () { + var e = new EventEmitter(); + + e.on('foo', function () { throw new Error('oops'); }); + e.on('foo', function () { throw new Error('oops'); }); + e.on('bar', function () { throw new Error('oops'); }); + e.on('aaa', function () { throw new Error('oops'); }); + + assume(e.removeAllListeners('foo')).equals(e); + assume(e.listeners('foo').length).equals(0); + assume(e.listeners('bar').length).equals(1); + assume(e.listeners('aaa').length).equals(1); + + assume(e.removeAllListeners('bar')).equals(e); + assume(e.removeAllListeners('aaa')).equals(e); + + assume(e.emit('foo')).equals(false); + assume(e.emit('bar')).equals(false); + assume(e.emit('aaa')).equals(false); + }); + + it('just nukes the fuck out of everything', function () { + var e = new EventEmitter(); + + e.on('foo', function () { throw new Error('oops'); }); + e.on('foo', function () { throw new Error('oops'); }); + e.on('bar', function () { throw new Error('oops'); }); + e.on('aaa', function () { throw new Error('oops'); }); + + assume(e.removeAllListeners()).equals(e); + assume(e.listeners('foo').length).equals(0); + assume(e.listeners('bar').length).equals(0); + assume(e.listeners('aaa').length).equals(0); + + assume(e.emit('foo')).equals(false); + assume(e.emit('bar')).equals(false); + assume(e.emit('aaa')).equals(false); + }); + }); + + describe('#setMaxListeners', function () { + it('is a function', function () { + var e = new EventEmitter(); + + assume(e.setMaxListeners).is.a('function'); + }); + + it('returns self when called', function () { + var e = new EventEmitter(); + + assume(e.setMaxListeners()).to.equal(e); + }); + }); +}); diff --git a/eventemitter3/eventemitter3.d.ts b/eventemitter3/eventemitter3.d.ts index f5cf9bcb2d..0d692b8247 100644 --- a/eventemitter3/eventemitter3.d.ts +++ b/eventemitter3/eventemitter3.d.ts @@ -1,11 +1,14 @@ -// Type definitions for EventEmitter3 0.1.6 +// Type definitions for EventEmitter3 1.1.1 // Project: https://github.com/primus/eventemitter3 -// Definitions by: Yuichi Murata -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Yuichi Murata , Leon Yu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module EventEmitter3 { - // __Base is hack for https://github.com/Microsoft/TypeScript/issues/3602 - class __Base { +declare namespace EventEmitter3 { + interface EventEmitter3Static { + new (): EventEmitter; + prefixed: string | boolean; + } + class EventEmitter { /** * Minimal EventEmitter interface that is molded against the Node.js * EventEmitter interface. @@ -22,7 +25,17 @@ declare module EventEmitter3 { * @returns {Array} * @api public */ - listeners(event: string): Function[]; + listeners(event?: string): Function[]; + + /** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Boolean} + * @api public + */ + listeners(event: string, param: boolean): boolean; /** * Emit an event to all registered event listeners. @@ -37,8 +50,8 @@ declare module EventEmitter3 { * Register a new EventListener for the given event. * * @param {String} event Name of the event. - * @param {Functon} fn Callback function. - * @param {Mixed} context The context of the function. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. * @api public */ on(event: string, fn: Function, context?: any): EventEmitter; @@ -48,7 +61,7 @@ declare module EventEmitter3 { * * @param {String} event Name of the event. * @param {Function} fn Callback function. - * @param {Mixed} context The context of the function. + * @param {Mixed} [context=this] The context of the function. * @api public */ once(event: string, fn: Function, context?: any): EventEmitter; @@ -58,10 +71,11 @@ declare module EventEmitter3 { * * @param {String} event The event we want to remove. * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. * @param {Boolean} once Only remove once listeners. * @api public */ - removeListener(event: string, fn: Function, once?: boolean): EventEmitter; + removeListener(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; /** * Remove all listeners or only the listeners for the specified event. @@ -69,34 +83,41 @@ declare module EventEmitter3 { * @param {String} event The event want to remove all listeners for. * @api public */ - removeAllListeners(event: string): EventEmitter; + removeAllListeners(event?: string): EventEmitter; - // - // Alias methods names because people roll like that. - // - off(event: string, fn: Function, once?: boolean): EventEmitter; + /** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ + off(event: string, fn?: Function, context?: any, once?: boolean): EventEmitter; + + /** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} [context=this] The context of the function. + * @api public + */ addListener(event: string, fn: Function, context?: any): EventEmitter; - // - // This function doesn't apply anymore. - // + /** + * This function doesn't apply anymore. + * @deprecated + */ setMaxListeners(): EventEmitter; } - export class EventEmitter extends __Base { } - export module EventEmitter { - // - // Expose the module. - // - export class EventEmitter extends __Base {} - export class EventEmitter2 extends __Base {} - export class EventEmitter3 extends __Base {} - } } declare module 'eventemitter3' { // // Expose the module. // - class EventEmitter extends EventEmitter3.EventEmitter {} - export = EventEmitter; + var EventEmitter3: EventEmitter3.EventEmitter3Static; + export = EventEmitter3; } diff --git a/express-brute-mongo/express-brute-mongo-tests.ts b/express-brute-mongo/express-brute-mongo-tests.ts new file mode 100644 index 0000000000..a4512782be --- /dev/null +++ b/express-brute-mongo/express-brute-mongo-tests.ts @@ -0,0 +1,27 @@ +/// +/// +/// + +import express = require("express"); +import ExpressBrute = require("express-brute"); +import MongoStore = require("express-brute-mongo"); +import mongodb = require("mongodb"); +var MongoClient = mongodb.MongoClient; + +var store = new MongoStore(ready => { + MongoClient.connect("mongodb://127.0.0.1:27017/test", (err, db) => { + if (err) { + throw err; + } + + var collection = db.collection("bruteforce-store"); + ready(collection); + }); +}); + +var app = express(); +var bruteforce = new ExpressBrute(store); + +app.post("/auth", bruteforce.prevent, (req, res, next) => { + res.send("Success!"); +}); diff --git a/express-brute-mongo/express-brute-mongo.d.ts b/express-brute-mongo/express-brute-mongo.d.ts new file mode 100644 index 0000000000..bc4d5e43d3 --- /dev/null +++ b/express-brute-mongo/express-brute-mongo.d.ts @@ -0,0 +1,22 @@ +// Type definitions for express-brute-mongo +// Project: https://github.com/auth0/express-brute-mongo +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "express-brute-mongo" { + /** + * @summary MongoDB store adapter. + * @class + */ + export = class MongoStore { + /** + * @summary Constructor. + * @constructor + * @param {Function} getCollection The collection. + * @param {Object} options The otpions. + */ + constructor(getCollection: (collection: any) => void, options?: Object); + } +} diff --git a/express-brute/express-brute-tests.ts b/express-brute/express-brute-tests.ts new file mode 100644 index 0000000000..ea0f2f5b4d --- /dev/null +++ b/express-brute/express-brute-tests.ts @@ -0,0 +1,16 @@ +/// + +import express = require("express"); +import ExpressBrute = require("express-brute"); + +var store = new ExpressBrute.MemoryStore(); +store = new ExpressBrute.MemoryStore({ prefix: "prefix" }); +store.set("key", "value", 0, (error: any) => { }); +store.get("key", (error: any, data: Object) => { }); +store.reset("key", (error: any) => { }); + +var app = express(); +var bruteforce = new ExpressBrute(store); +app.post("/auth", bruteforce.prevent, (req, res, next) => { + res.send("Success!"); +}); diff --git a/express-brute/express-brute.d.ts b/express-brute/express-brute.d.ts new file mode 100644 index 0000000000..7242d44dc3 --- /dev/null +++ b/express-brute/express-brute.d.ts @@ -0,0 +1,129 @@ +// Type definitions for express-brute +// Project: https://github.com/AdamPflug/express-brute +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "express-brute" { + import express = require("express"); + + /** + * @summary Options for {@link MemoryStore} class. + * @interface + */ + interface MemoryStoreOptions { + /** + * @summary Key prefix. + * @type {string} + */ + prefix: string; + } + + /** + * @summary Options for {@link ExpressBrute#getMiddleware} class. + * @interface + */ + interface ExpressBruteMiddleware { + /** + * @summary Allows you to override the value of failCallback for this middleware. + * @type {Function} + */ + failCallback: Function; + + /** + * @summary Disregard IP address when matching requests if set to true. Defaults to false. + * @type {boolean} + */ + ignoreIP: boolean; + + /** + * @summary Key. + * @type {any} + */ + key: any; + } + + /** + * @summary Middleware. + * @class + */ + class ExpressBrute { + /** + * @summary Constructor. + * @constructor + * @param {any} store The store. + */ + constructor(store: any); + + /** + * @summary Generates middleware that will bounce requests with the same key and IP address that happen faster than the current wait time by calling failCallback. + * @param {Object} options The options. + */ + getMiddleware(options: ExpressBruteMiddleware): express.RequestHandler; + + /** + * @summary Uses the current proxy trust settings to get the current IP from a request object. + * @param {Request} request The HTTP request. + * @return {RequestHandler} The Request handler. + */ + getIPFromRequest(request: express.Request): express.RequestHandler; + + /** + * @summary Middleware that will bounce requests that happen faster than the current wait time by calling failCallback. + * @param {Request} request The HTTP request. + * @param {Response} response The HTTP response. + * @param {Function} next The next middleware. + * @return {RequestHandler} The Request handler. + */ + prevent(request: express.Request, response: express.Response, next: Function): express.RequestHandler; + + /** + * @summary Resets the wait time between requests back to its initial value. + * @param {string} ip The IP address. + * @param {string} key The key. response. + * @param {Function} next The next middleware. + * @return {RequestHandler} The Request handler. + */ + reset(ip: string, key: string, next: Function): express.RequestHandler; + } + + module ExpressBrute { + /** + * @summary In-memory store. + * @class + */ + export class MemoryStore { + /** + * @summary Constructor. + * @constructor + * @param {Object} options The options. + */ + constructor(options?: MemoryStoreOptions); + /** + * @summary Gets key value. + * @param {string} key The key name. + * @param {Function} callbck The callback. + */ + get(key: string, callback: (error: any, data: Object) => void): void; + + /** + * @summary Sets the key value. + * @param {string} key The name. + * @param {string} value The value. + * @param {number} lifetime The lifetime. + * @param {Function} callback The callback. + */ + set(key: string, value: any, lifetime: number, callback: (error: any) => void): void; + + /** + * @summary Deletes the key. + * @param {string} key The name. + * @param {Function} callback The callback. + */ + reset(key: string, callback: (error: any) => void): void; + } + } + + export = ExpressBrute; +} diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 428c90afd0..78073231be 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -66,12 +66,14 @@ declare module ExpressValidator { * Accepts http, https, ftp */ isUrl(): Validator; + /** * Combines isIPv4 and isIPv6 */ isIP(): Validator; isIPv4(): Validator; isIPv6(): Validator; + isMACAddress(): Validator; isAlpha(): Validator; isAlphanumeric(): Validator; isNumeric(): Validator; diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index d4ac5ad75b..248ee29f2c 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -345,7 +345,7 @@ declare module fabric { * @param eventName Event name (eg. 'after:render') or object with key/value pairs (eg. {'after:render': handler, 'selection:cleared': handler}) * @param handler Function to be deleted from EventListeners */ - off(eventName: string|any, handler: (e: IEvent) => any): T; + off(eventName?: string|any, handler?: (e: IEvent) => any): T; } // animation mixin diff --git a/fbemitter/fbemitter-tests.ts b/fbemitter/fbemitter-tests.ts new file mode 100644 index 0000000000..614d579634 --- /dev/null +++ b/fbemitter/fbemitter-tests.ts @@ -0,0 +1,349 @@ +/// +/// +/// +/// +'use strict'; + +/** + * The tests are adapted from ../eventemitter3/eventemitter3-tests.ts + */ + +import { EventEmitter, EventSubscription } from 'fbemitter'; +import * as util from 'util'; +import * as assert from 'assert'; + +describe('EventEmitter', function tests() { + 'use strict'; + + it('inherits when used with require(util).inherits', function () { + class Beast extends EventEmitter { + /* rawr, i'm a beast */ + } + + util.inherits(Beast, EventEmitter); + + var moop = new Beast() + , meap = new Beast(); + + assert.strictEqual(moop instanceof Beast, true); + assert.strictEqual(moop instanceof EventEmitter, true); + + moop.listeners('click'); + meap.listeners('click'); + + moop.addListener('data', function () { + throw new Error('I should not emit'); + }); + + meap.emit('data', 'rawr'); + meap.removeAllListeners(); + }); + + describe('EventEmitter#emit', function () { + it('emits with context', function (done) { + var context = { bar: 'baz' } + , e = new EventEmitter(); + + e.addListener('foo', function (bar: string) { + assert.strictEqual(bar, 'bar'); + assert.strictEqual(this, context); + + done(); + }, context); + + e.emit('foo', 'bar'); + }); + + it('can emit the function with multiple arguments', function () { + var e = new EventEmitter(); + + for(var i = 0; i < 100; i++) { + (function (j: number) { + for (var i = 0, args: number[] = []; i < j; i++) { + args.push(j); + } + + e.once('args', function () { + assert.strictEqual(arguments.length, args.length); + assert.deepStrictEqual(Array.prototype.slice.call(arguments), args); + }); + + e.emit.apply(e, (['args'] as any[]).concat(args)); + })(i); + } + }); + + it('can emit the function with multiple arguments, multiple listeners', function () { + var e = new EventEmitter(); + + for(var i = 0; i < 100; i++) { + (function (j: number) { + for (var i = 0, args: number[] = []; i < j; i++) { + args.push(j); + } + + e.once('args', function () { + assert.strictEqual(arguments.length, args.length); + assert.deepStrictEqual(Array.prototype.slice.call(arguments), args); + }); + + e.once('args', function () { + assert.strictEqual(arguments.length, args.length); + assert.deepStrictEqual(Array.prototype.slice.call(arguments), args); + }); + + e.once('args', function () { + assert.strictEqual(arguments.length, args.length); + assert.deepStrictEqual(Array.prototype.slice.call(arguments), args); + }); + + e.once('args', function () { + assert.strictEqual(arguments.length, args.length); + assert.deepStrictEqual(Array.prototype.slice.call(arguments), args); + }); + + e.emit.apply(e, (['args'] as any[]).concat(args)); + })(i); + } + }); + + it('emits with context, multiple listeners (force loop)', function () { + var e = new EventEmitter(); + + e.addListener('foo', function (bar: string) { + assert.deepStrictEqual(this, { foo: 'bar' }); + assert.strictEqual(bar, 'bar'); + }, { foo: 'bar' }); + + e.addListener('foo', function (bar: string) { + assert.deepStrictEqual(this, { bar: 'baz' }); + assert.strictEqual(bar, 'bar'); + }, { bar: 'baz' }); + + e.emit('foo', 'bar'); + }); + + it('emits with different contexts', function () { + var e = new EventEmitter() + , pattern = ''; + + function writer() { + pattern += this; + } + + e.addListener('write', writer, 'foo'); + e.addListener('write', writer, 'baz'); + e.once('write', writer, 'bar'); + e.once('write', writer, 'banana'); + + e.emit('write'); + assert.strictEqual(pattern, 'foobazbarbanana'); + }); + + it('receives the emitted events', function (done) { + var e = new EventEmitter(); + + e.addListener('data', function (a: string, b: EventEmitter, c: Date, d: void, undef: void) { + assert.strictEqual(a, 'foo'); + assert.strictEqual(b, e); + assert.strictEqual(c instanceof Date, true); + assert.strictEqual(undef, undefined); + assert.strictEqual(arguments.length, 3); + + done(); + }); + + e.emit('data', 'foo', e, new Date()); + }); + + it('emits to all event listeners', function () { + var e = new EventEmitter() + , pattern: string[] = []; + + e.addListener('foo', function () { + pattern.push('foo1'); + }); + + e.addListener('foo', function () { + pattern.push('foo2'); + }); + + e.emit('foo'); + + assert.strictEqual(pattern.join(';'), 'foo1;foo2'); + }); + + }); + + describe('EventEmitter#listeners', function () { + it('returns an empty array if no listeners are specified', function () { + var e = new EventEmitter(); + + assert.strictEqual(e.listeners('foo') instanceof Array, true); + assert.strictEqual(e.listeners('foo').length, 0); + }); + + it('returns an array of function', function () { + var e = new EventEmitter(); + + function foo() {} + + e.addListener('foo', foo); + assert.strictEqual(e.listeners('foo') instanceof Array, true); + assert.strictEqual(e.listeners('foo').length, 1); + console.log(e.listeners('foo')[0]); + assert.strictEqual(e.listeners('foo')[0], foo); + }); + + it('is not vulnerable to modifications', function () { + var e = new EventEmitter(); + + function foo() {} + + e.addListener('foo', foo); + + assert.strictEqual(e.listeners('foo')[0], foo); + + e.listeners('foo').length = 0; + assert.strictEqual(e.listeners('foo')[0], foo); + }); + }); + + describe('EventEmitter#once', function () { + it('only emits it once', function () { + var e = new EventEmitter() + , calls = 0; + + e.once('foo', function () { + calls++; + }); + + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(calls, 1); + }); + + it('only emits once if emits are nested inside the listener', function () { + var e = new EventEmitter() + , calls = 0; + + e.once('foo', function () { + calls++; + e.emit('foo'); + }); + + e.emit('foo'); + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(calls, 1); + }); + + it('only emits once for multiple events', function () { + var e = new EventEmitter() + , multi = 0 + , foo = 0 + , bar = 0; + + e.once('foo', function () { + foo++; + }); + + e.once('foo', function () { + bar++; + }); + + e.addListener('foo', function () { + multi++; + }); + + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + e.emit('foo'); + + assert.strictEqual(e.listeners('foo').length, 1); + assert.strictEqual(multi, 5); + assert.strictEqual(foo, 1); + assert.strictEqual(bar, 1); + }); + + it('only emits once with context', function (done) { + var context = { foo: 'bar' } + , e = new EventEmitter(); + + e.once('foo', function (bar: string) { + assert.strictEqual(this, context); + assert.strictEqual(bar, 'bar'); + done(); + }, context); + + e.emit('foo', 'bar'); + }); + }); + + describe('EventSubscription#remove', function () { + it('should only remove the event with the specified function', function () { + var e = new EventEmitter(); + + function bar() {} + var foo = e.addListener('foo', function () {}); + var bar1 = e.addListener('bar', function () {}); + var bar2 = e.addListener('bar', bar); + + assert.strictEqual(e.listeners('foo').length, 1); + assert.strictEqual(e.listeners('bar').length, 2); + + foo.remove(); + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(e.listeners('bar').length, 2); + + bar2.remove(); + assert.strictEqual(e.listeners('bar').length, 1); + + bar1.remove(); + assert.strictEqual(e.listeners('bar').length, 0); + }); + }); + + describe('EventEmitter#removeAllListeners', function () { + it('removes all events for the specified events', function () { + var e = new EventEmitter(); + + e.addListener('foo', function () { throw new Error('oops'); }); + e.addListener('foo', function () { throw new Error('oops'); }); + e.addListener('bar', function () { throw new Error('oops'); }); + e.addListener('aaa', function () { throw new Error('oops'); }); + + e.removeAllListeners('foo'); + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(e.listeners('bar').length, 1); + assert.strictEqual(e.listeners('aaa').length, 1); + + e.removeAllListeners('bar'); + e.removeAllListeners('aaa'); + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(e.listeners('bar').length, 0); + assert.strictEqual(e.listeners('aaa').length, 0); + }); + + it('just nukes the fuck out of everything', function () { + var e = new EventEmitter(); + + e.addListener('foo', function () { throw new Error('oops'); }); + e.addListener('foo', function () { throw new Error('oops'); }); + e.addListener('bar', function () { throw new Error('oops'); }); + e.addListener('aaa', function () { throw new Error('oops'); }); + + e.removeAllListeners(); + assert.strictEqual(e.listeners('foo').length, 0); + assert.strictEqual(e.listeners('bar').length, 0); + assert.strictEqual(e.listeners('aaa').length, 0); + }); + }); + +}); diff --git a/fbemitter/fbemitter.d.ts b/fbemitter/fbemitter.d.ts new file mode 100644 index 0000000000..b26b1a3162 --- /dev/null +++ b/fbemitter/fbemitter.d.ts @@ -0,0 +1,67 @@ +// Type definitions for Facebook's EventEmitter 2.0.0 +// Project: https://github.com/facebook/emitter +// Definitions by: kmxz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'fbemitter' { + + export class EventSubscription { + + listener: Function; + context: any; + + /** + * Removes this subscription from the subscriber that controls it. + */ + remove(): void; + + } + + export class EventEmitter { + + constructor(); + + /** + * Adds a listener to be invoked when events of the specified type are + * emitted. An optional calling context may be provided. The data arguments + * emitted will be passed to the listener function. + */ + addListener(eventType: string, listener: Function, context?: any): EventSubscription; + + /** + * Similar to addListener, except that the listener is removed after it is + * invoked once. + */ + once(eventType: string, listener: Function, context?: any): EventSubscription; + + /** + * Removes all of the registered listeners, including those registered as + * listener maps. + */ + removeAllListeners(eventType?: string): void; + + /** + * Provides an API that can be called during an eventing cycle to remove the + * last listener that was invoked. This allows a developer to provide an event + * object that can remove the listener (or listener map) during the + * invocation. + * + * If it is called when not inside of an emitting cycle it will throw. + */ + removeCurrentListener(): void; + + /** + * Returns an array of listeners that are currently registered for the given + * event. + */ + listeners(eventType: string): Function[]; + + /** + * Emits an event of the given type with the given data. All handlers of that + * particular type will be notified. + */ + emit(eventType: string, ...data: any[]): void; + + } + +} \ No newline at end of file diff --git a/field/field-test.ts b/field/field-test.ts new file mode 100644 index 0000000000..d99dfee8a5 --- /dev/null +++ b/field/field-test.ts @@ -0,0 +1,28 @@ +// From https://github.com/jprichardson/field/blob/e968fd979ba1a06e35571695ddfdad513e516eae/README.md + +/// + +// get + +const config = { + environment: { + production: { + port: 80 + } + } +} + +console.log(field.get(config, 'environment:production:port')) +// => 80 + +// set + +var database: any = {} + +console.log(field.get(database, 'production.port')) +// => undefined + +// will return undefined since it never existed before +field.set(database, 'production.port', 27017) +console.log(database.production.port) +// => 27017 diff --git a/field/field.d.ts b/field/field.d.ts new file mode 100644 index 0000000000..0ffe08a01e --- /dev/null +++ b/field/field.d.ts @@ -0,0 +1,9 @@ +// Type definitions for field 1.0.1 +// Project: https://www.npmjs.com/package/field +// Definitions by: Leo Liang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module field { + export function get(topObj: any, fields: string): any; + export function set(topObj: any, fields: string, value: any): any; +} diff --git a/firebase/firebase.d.ts b/firebase/firebase.d.ts index 0c316b638a..58d7cd8742 100644 --- a/firebase/firebase.d.ts +++ b/firebase/firebase.d.ts @@ -143,6 +143,7 @@ interface FirebaseQuery { */ equalTo(value: string, key?: string): FirebaseQuery; equalTo(value: number, key?: string): FirebaseQuery; + equalTo(value: boolean, key?: string): FirebaseQuery; /** * Generates a new Query object limited to the first certain number of children. */ diff --git a/fixed-data-table/fixed-data-table-0.4.7-tests.tsx b/fixed-data-table/fixed-data-table-0.4.7-tests.tsx new file mode 100644 index 0000000000..641487ff68 --- /dev/null +++ b/fixed-data-table/fixed-data-table-0.4.7-tests.tsx @@ -0,0 +1,39 @@ +/// +/// +/// + +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as FixedDataTable from "fixed-data-table"; + +var rows = [ + ['a1', 'b1', 'c1'], + ['a2', 'b2', 'c2'], + ['a3', 'b3', 'c3'], + // .... and more +]; + +function rowGetter(rowIndex: number) { + return rows[rowIndex]; +} + + var table = + + + + +ReactDOM.render(table, document.body); diff --git a/fixed-data-table/fixed-data-table-0.4.7.d.ts b/fixed-data-table/fixed-data-table-0.4.7.d.ts new file mode 100644 index 0000000000..1dc22dc3de --- /dev/null +++ b/fixed-data-table/fixed-data-table-0.4.7.d.ts @@ -0,0 +1,402 @@ +// Type definitions for fixed-data-table 0.4.7 +// Project: https://github.com/facebook/fixed-data-table +// Definitions by: Petar Paar +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module FixedDataTable { + export var version: string; + + export interface TableProps extends __React.Props { + /** + * Pixel width of table. If all columns do not fit, + * a horizontal scrollbar will appear. + */ + width: number; + + /** + * Pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + height?: number; + + /** + * Maximum pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either `height` or `maxHeight` must be specified. + */ + maxHeight?: number; + + /** + * Pixel height of table's owner, this is used in a managed scrolling + * situation when you want to slide the table up from below the fold + * without having to constantly update the height on every scroll tick. + * Instead, vary this property on scroll. By using `ownerHeight`, we + * over-render the table while making sure the footer and horizontal + * scrollbar of the table are visible when the current space for the table + * in view is smaller than the final, over-flowing height of table. It + * allows us to avoid resizing and reflowing table when it is moving in the + * view. + * + * This is used if `ownerHeight < height` (or `maxHeight`). + */ + ownerHeight?: number; + + /** + * hidden or auto + */ + overflowX?: string; + overflowY?: string; + + /** + * Number of rows in the table. + */ + rowsCount: number; + + /** + * Pixel height of rows unless `rowHeightGetter` is specified and returns + * different value. + */ + rowHeight: number; + + /** + * If specified, `rowHeightGetter(index)` is called for each row and the + * returned value overrides `rowHeight` for particular row. + */ + rowHeightGetter?: Function; + + /** + * To get rows to display in table, `rowGetter(index)` + * is called. `rowGetter` should be smart enough to handle async + * fetching of data and return temporary objects + * while data is being fetched. + */ + rowGetter: Function; + + /** + * To get any additional CSS classes that should be added to a row, + * `rowClassNameGetter(index)` is called. + */ + rowClassNameGetter?: Function; + + /** + * Pixel height of the column group header. + */ + groupHeaderHeight?: number; + + /** + * Pixel height of header. + */ + headerHeight: number; + + /** + * Function that is called to get the data for the header row. + * If the function returns null, the header will be set to the + * Column's label property. + */ + headerDataGetter?: Function; + + /** + * Pixel height of footer. + */ + footerHeight?: number; + + /** + * DEPRECATED - use footerDataGetter instead. + * Data that will be passed to footer cell renderers. + */ + footerData?: any; + + /** + * Function that is called to get the data for the footer row. + */ + footerDataGetter?: Function; + + /** + * Value of horizontal scroll. + */ + scrollLeft?: number; + + /** + * Index of column to scroll to. + */ + scrollToColumn?: number; + + /** + * Value of vertical scroll. + */ + scrollTop?: number; + + /** + * Index of row to scroll to. + */ + scrollToRow?: number; + + /** + * Callback that is called when scrolling starts with current horizontal + * and vertical scroll values. + */ + onScrollStart?: Function; + + /** + * Callback that is called when scrolling ends or stops with new horizontal + * and vertical scroll values. + */ + onScrollEnd?: Function; + + /** + * Callback that is called when `rowHeightGetter` returns a different height + * for a row than the `rowHeight` prop. This is necessary because initially + * table estimates heights of some parts of the content. + */ + onContentHeightChange?: Function; + + /** + * Callback that is called when a row is clicked. + */ + onRowClick?: Function; + + /** + * Callback that is called when a row is double clicked. + */ + onRowDoubleClick?: Function; + + /** + * Callback that is called when a mouse-down event happens on a row. + */ + onRowMouseDown?: Function; + + /** + * Callback that is called when a mouse-enter event happens on a row. + */ + onRowMouseEnter?: Function; + + /** + * Callback that is called when a mouse-leave event happens on a row. + */ + onRowMouseLeave?: Function; + + /** + * Callback that is called when resizer has been released + * and column needs to be updated. + * + * Required if the isResizable property is true on any column. + * + * ``` + * function( + * newColumnWidth: number, + * dataKey: string, + * ) + * ``` + */ + onColumnResizeEndCallback?: Function; + + /** + * Whether a column is currently being resized. + */ + isColumnResizing?: boolean + } + + interface ColumnProps { + /** + * The horizontal alignment of the table cell content. + * 'left', 'center', 'right' + */ + align?: string; + + /** + * className for this column's header cell. + */ + headerClassName?: string; + + /** + * className for this column's footer cell. + */ + footerClassName?: string; + + /** + * className for each of this column's data cells. + */ + cellClassName?: string; + + /** + * The cell renderer that returns React-renderable content for table cell. + * ``` + * function( + * cellData: any, + * cellDataKey: string, + * rowData: object, + * rowIndex: number, + * columnData: any, + * width: number + * ): ?$jsx + * ``` + */ + cellRenderer?: Function; + + /** + * The getter `function(string_cellDataKey, object_rowData)` that returns + * the cell data for the `cellRenderer`. + * If not provided, the cell data will be collected from + * `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns + * will be used to determine whether the cell should re-render. + */ + cellDataGetter?: Function; + + /** + * The key to retrieve the cell data from the data row. Provided key type + * must be either `string` or `number`. Since we use this + * for keys, it must be specified for each column. + */ + dataKey: string|number; + + /** + * Controls if the column is fixed when scrolling in the X axis. + */ + fixed?: boolean; + + /** + * The cell renderer that returns React-renderable content for table column + * header. + * ``` + * function( + * label: ?string, + * cellDataKey: string, + * columnData: any, + * rowData: array, + * width: number + * ): ?$jsx + * ``` + */ + headerRenderer?: Function; + + /** + * The cell renderer that returns React-renderable content for table column + * footer. + * ``` + * function( + * label: ?string, + * cellDataKey: string, + * columnData: any, + * rowData: array, + * width: number + * ): ?$jsx + * ``` + */ + footerRenderer?: Function; + + /** + * Bucket for any data to be passed into column renderer functions. + */ + columnData?: any; + + /** + * The column's header label. + */ + label: string; + + /** + * The pixel width of the column. + */ + width: number; + + /** + * If this is a resizable column this is its minimum pixel width. + */ + minWidth?: number; + + /** + * If this is a resizable column this is its maximum pixel width. + */ + maxWidth?: number; + + /** + * The grow factor relative to other columns. Same as the flex-grow API + * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available + * extra width and distribute it proportionally according to all columns' + * flexGrow values. Defaults to zero (no-flexing). + */ + flexGrow?: number; + + /** + * Whether the column can be resized with the + * FixedDataTableColumnResizeHandle. Please note that if a column + * has a flex grow, once you resize the column this will be set to 0. + * + * This property only provides the UI for the column resizing. If this + * is set to true, you will need ot se the onColumnResizeEndCallback table + * property and render your columns appropriately. + */ + isResizable?: boolean; + + /** + * Experimental feature + * Whether cells in this column can be removed from document when outside + * of viewport as a result of horizontal scrolling. + * Setting this property to true allows the table to not render cells in + * particular column that are outside of viewport for visible rows. This + * allows to create table with many columns and not have vertical scrolling + * performance drop. + * Setting the property to false will keep previous behaviour and keep + * cell rendered if the row it belongs to is visible. + */ + allowCellsRecycling?: boolean; + } + + export interface ColumnGroupProps { + /** + * The horizontal alignment of the table cell content. + * 'left', 'center', 'right' + */ + align?: string; + + /** + * Controls if the column group is fixed when scrolling in the X axis. + */ + fixed?: boolean; + + /** + * Bucket for any data to be passed into column group renderer functions. + */ + columnGroupData?: any; + + /** + * The column group's header label. + */ + label?: string; + + /** + * The cell renderer that returns React-renderable content for a table + * column group header. If it's not specified, the label from props will + * be rendered as header content. + * ``` + * function( + * label: ?string, + * cellDataKey: string, + * columnGroupData: any, + * rowData: array, // array of labels of all columnGroups + * width: number + * ): ?$jsx + * ``` + */ + groupHeaderRenderer?: Function; + } + + export class Table extends __React.Component { + render(): __React.DOMElement + } + export class Column extends __React.Component { + render(): __React.DOMElement + } + export class ColumnGroup extends __React.Component { + render(): __React.DOMElement + } +} + +declare module "fixed-data-table" { + export = FixedDataTable; +} \ No newline at end of file diff --git a/fixed-data-table/fixed-data-table-tests.tsx b/fixed-data-table/fixed-data-table-tests.tsx index 28dae2890f..1f10a9fdb5 100644 --- a/fixed-data-table/fixed-data-table-tests.tsx +++ b/fixed-data-table/fixed-data-table-tests.tsx @@ -1,39 +1,163 @@ -/// +/// /// -/// import * as React from "react"; -import * as ReactDOM from "react-dom"; -import * as FixedDataTable from "fixed-data-table"; +import {Table, Cell, Column, CellProps} from "fixed-data-table"; -var rows = [ - ['a1', 'b1', 'c1'], - ['a2', 'b2', 'c2'], - ['a3', 'b3', 'c3'], - // .... and more -]; - -function rowGetter(rowIndex: number) { - return rows[rowIndex]; +// create your Table +class MyTable1 extends React.Component<{}, {}> { + render(): React.ReactElement { + return ( +
+ // add columns +
+ ); + } } - var table = { + render(): React.ReactElement { + return ( + - - - + width={1000} + height={500}> + Basic content} + width={200} + /> +
+ ); + } +} -ReactDOM.render(table, document.body); +// provide Custom Data +interface MyTable3State { + myTableData: [{name: string}]; +} + +class MyTable3 extends React.Component<{}, MyTable3State> { + + constructor(props: {}) { + super(props); + + this.state = { + myTableData: [ + {name: "Rylan"}, + {name: "Amelia"}, + {name: "Estevan"}, + {name: "Florence"}, + {name: "Tressa"}, + ] + }; + } + + render(): React.ReactElement { + return ( + + Name} + cell={(props: CellProps) => ( + + {this.state.myTableData[props.rowIndex].name} + + )} + width={200} + /> +
+ ); + } +} + +// Create Reusable Cells +interface RowData { + [field: string]: string; +} + +interface MyCellProps extends CellProps { + rowIndex?: number; + field: string; + data: RowData[]; +} + +class MyTextCell extends React.Component { + render(): React.ReactElement { + const {rowIndex, field, data} = this.props; + + return ( + + {data[rowIndex][field]} + + ); + } +} + +class MyLinkCell extends React.Component { + render(): React.ReactElement { + const {rowIndex, field, data} = this.props; + const link: string = data[rowIndex][field]; + + return ( + + {link} + + ); + } +} + +interface MyTable4State { + tableData: RowData[]; +} + +class MyTable4 extends React.Component<{}, MyTable4State> { + + constructor(props: {}) { + super(props); + this.state = { + tableData: [ + {name: "Rylan", email: "Angelita_Weimann42@gmail.com"}, + {name: "Amelia", email: "Dexter.Trantow57@hotmail.com"}, + {name: "Estevan", email: "Aimee7@hotmail.com"}, + {name: "Florence", email: "Jarrod.Bernier13@yahoo.com"}, + {name: "Tressa", email: "Yadira1@hotmail.com"} + ] + }; + } + + render(): React.ReactElement { + return ( + + { + ["name", "email"].map(field => + {field}} + cell={ + + } + width={200}/> + ) + } +
+ ); + } +} diff --git a/fixed-data-table/fixed-data-table.d.ts b/fixed-data-table/fixed-data-table.d.ts index 1dc22dc3de..219b7e39ff 100644 --- a/fixed-data-table/fixed-data-table.d.ts +++ b/fixed-data-table/fixed-data-table.d.ts @@ -1,6 +1,6 @@ -// Type definitions for fixed-data-table 0.4.7 +// Type definitions for fixed-data-table 0.6.0 // Project: https://github.com/facebook/fixed-data-table -// Definitions by: Petar Paar +// Definitions by: Petar Paar , Stephen Jelfs // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -8,345 +8,396 @@ declare module FixedDataTable { export var version: string; + /** + * Data grid component with fixed or scrollable header and columns. + * + * The layout of the data table is as follows: + * + * + * +---------------------------------------------------+ + * | Fixed Column Group | Scrollable Column Group | + * | Header | Header | + * | | | + * +---------------------------------------------------+ + * | | | + * | Fixed Header Columns | Scrollable Header Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Body Columns | Scrollable Body Columns | + * | | | + * +-----------------------+---------------------------+ + * | | | + * | Fixed Footer Columns | Scrollable Footer Columns | + * | | | + * +-----------------------+---------------------------+ + * + * Fixed Column Group Header: + * + * These are the headers for a group of columns if included in + * the table that do not scroll vertically or horizontally. + * + * Scrollable Column Group Header: + * + * The header for a group of columns that do not move while + * scrolling vertically, but move horizontally with the + * horizontal scrolling. + * + * Fixed Header Columns: + * + * The header columns that do not move while scrolling + * vertically or horizontally. + * + * Scrollable Header Columns: + * + * The header columns that do not move while scrolling + * vertically, but move horizontally with the horizontal scrolling. + * + * Fixed Body Columns: + * + * The body columns that do not move while scrolling + * horizontally, but move vertically with the vertical scrolling. + * + * Scrollable Body Columns: + * + * The body columns that move while scrolling vertically or + * horizontally. + * + */ export interface TableProps extends __React.Props { + /** + * Pixel width of table. If all columns do not fit, a + * horizontal scrollbar will appear. + */ + width: number; + + /** + * Pixel height of table. If all rows do not fit, a + * vertical scrollbar will appear. + * + * Either height or maxHeight must be specified. + */ + height?: number; + + /** + * Maximum pixel height of table. If all rows do not fit, + * a vertical scrollbar will appear. + * + * Either height or maxHeight must be specified. + */ + maxHeight?: number; + + /** + * Pixel height of table's owner, this is used in a managed + * scrolling situation when you want to slide the table up + * from below the fold without having to constantly update + * the height on every scroll tick. Instead, vary this + * property on scroll. By using ownerHeight, we over-render + * the table while making sure the footer and horizontal + * scrollbar of the table are visible when the current space + * for the table in view is smaller than the final, + * over-flowing height of table. It allows us to avoid + * resizing and reflowing table when it is moving in the + * view. + * + * This is used if ownerHeight < height (or maxHeight). + */ + ownerHeight?: number; + + /** + * 'hidden'|'auto' + */ + overflowX?: string; + + /** + * 'hidden'|'auto' + */ + overflowY?: string; + + /** + * Number of rows in the table. + */ + rowsCount: number; + + /** + * Pixel height of rows unless rowHeightGetter is specified + * and returns different value. + */ + rowHeight: number; + + /** + * If specified, rowHeightGetter(index) is called for each + * row and the returned value overrides rowHeight for + * particular row. + */ + rowHeightGetter?: (index: number) => number; + + /** + * To get any additional CSS classes that should be added to + * a row, rowClassNameGetter(index) is called. + */ + rowClassNameGetter?: (index: number) => string; + + /** + * Pixel height of the column group header. + * + * defaultValue: 0 + */ + groupHeaderHeight?: number; + + /** + * Pixel height of the header. + * + * defaultValue: 0 + */ + headerHeight?: number; + + /** + * Pixel height of the footer. + * + * defaultValue: 0 + */ + footerHeight?: number; + + /** + * Value of horizontal scroll. + * + * defaultValue: 0 + */ + scrollLeft?: number; + + /** + * Index of column to scroll to. + */ + scrollToColumn?: number; + + /** + * Value of vertical scroll. + * + * defaultValue: 0 + */ + scrollTop?: number; + + /** + * Index of row to scroll to. + */ + scrollToRow?: number; + + /** + * Callback that is called when scrolling starts with + * current horizontal and vertical scroll values. + */ + onScrollStart?: (horizontalScroll: number, verticalScroll: number) => void; + + /** + * Callback that is called when scrolling ends or stops with + * new horizontal and vertical scroll values. + */ + onScrollEnd?: (horizontalScroll: number, verticalScroll: number) => void; + + /** + * Callback that is called when rowHeightGetter returns a + * different height for a row than the rowHeight prop. This + * is necessary because initially table estimates heights + * of some parts of the content. + */ + onContentHeightChange?: (height: number) => void; + + /** + * Callback that is called when a row is clicked. + */ + onRowClick?: (index: number) => void; + + /** + * Callback that is called when a row is double clicked. + */ + onRowDoubleClick?: (index: number) => void; + + /** + * Callback that is called when a mouse-down event happens + * on a row. + */ + onRowMouseDown?: (index: number) => void; + + /** + * Callback that is called when a mouse-enter event happens + * on a row. + */ + onRowMouseEnter?: (index: number) => void; + + /** + * Callback that is called when a mouse-leave event happens + * on a row. + */ + onRowMouseLeave?: (index: number) => void; + + /** + * Callback that is called when resizer has been released + * and column needs to be updated. + * + * Required if the isResizable property is true on any + * column. + */ + onColumnResizeEndCallback?: (newColumnWidth: number, columnKey: string) => void; + + /** + * Whether a column is currently being resized. + */ + isColumnResizing?: boolean; + } + + /** + * Component that defines the attributes of table column. + */ + interface ColumnProps extends __React.Props { + /** + * The horizontal alignment of the table cell content. + * + * 'left'|'center'|'right' + */ + align?: string; + + /** + * Controls if the column is fixed when scrolling in the X + * axis. + * + * defaultValue: false + */ + fixed?: boolean; + + /** + * The header cell for this column. This can either be a + * string. a React element, or a function that generates a + * React Element. Passing in a string will render a default + * header cell with that string. By default, the React + * element passed in can expect to receive the following + * props: + * + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * + * Because you are passing in your own React element, you + * can feel free to pass in whatever props you may want or need. + * + * If you pass in a function, you will receive the same props object as the first argument. + */ + header?: string | __React.ReactElement | ((props: CellProps) => (string | __React.ReactElement)); + + /** + * This is the body cell that will be cloned for this + * column. This can either be a string a React element, + * or a function that generates a React Element. Passing + * in a string will render a default cell with that + * string. By default, the React element passed in can + * expect to receive the following props: + * + * props: { + * rowIndex; number // (the row index of the cell) + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * + * Because you are passing in your own React element, you + * can feel free to pass in whatever props you may want or + * need. + * + * If you pass in a function, you will receive the same + * props object as the first argument. + */ + cell?: string | __React.ReactElement | ((props: CellProps) => (string | __React.ReactElement)); + /** - * Pixel width of table. If all columns do not fit, - * a horizontal scrollbar will appear. - */ - width: number; - - /** - * Pixel height of table. If all rows do not fit, - * a vertical scrollbar will appear. - * - * Either `height` or `maxHeight` must be specified. - */ - height?: number; - - /** - * Maximum pixel height of table. If all rows do not fit, - * a vertical scrollbar will appear. - * - * Either `height` or `maxHeight` must be specified. - */ - maxHeight?: number; - - /** - * Pixel height of table's owner, this is used in a managed scrolling - * situation when you want to slide the table up from below the fold - * without having to constantly update the height on every scroll tick. - * Instead, vary this property on scroll. By using `ownerHeight`, we - * over-render the table while making sure the footer and horizontal - * scrollbar of the table are visible when the current space for the table - * in view is smaller than the final, over-flowing height of table. It - * allows us to avoid resizing and reflowing table when it is moving in the - * view. - * - * This is used if `ownerHeight < height` (or `maxHeight`). - */ - ownerHeight?: number; + * The footer cell for this column. This can either be a + * string. a React element, or a function that generates a + * React Element. Passing in a string will render a default + * header cell with that string. By default, the React + * element passed in can expect to receive the following + * props: + * + * props: { + * columnKey: string // (of the column, if given) + * height: number // (supplied from the Table or rowHeightGetter) + * width: number // (supplied from the Column) + * } + * + * Because you are passing in your own React element, you + * can feel free to pass in whatever props you may want or + * need. + * + * If you pass in a function, you will receive the same + * props object as the first argument. + */ + footer?: string | __React.ReactElement | ((props: CellProps) => (string | __React.ReactElement)); /** - * hidden or auto + * This is used to uniquely identify the column, and is not + * required unless you a resizing columns. This will be the + * key given in the onColumnResizeEndCallback on the Table. + */ + columnKey?: string | number; + + /** + * The pixel width of the column. + */ + width: number; + + /** + * If this is a resizable column this is its minimum pixel + * width. + */ + minWidth?: number; + + /** + * If this is a resizable column this is its maximum pixel + * width. + */ + maxWidth?: number; + + /** + * The grow factor relative to other columns. Same as the + * flex-grow API from http://www.w3.org/TR/css3-flexbox/. + * Basically, take any available extra width and distribute + * it proportionally according to all columns' flexGrow + * values. Defaults to zero (no-flexing). + */ + flexGrow?: number; + + /** + * Whether the column can be resized with the + * FixedDataTableColumnResizeHandle. Please note that if a + * column has a flex grow, once you resize the column this + * will be set to 0. + * + * This property only provides the UI for the column + * resizing. If this is set to true, you will need to set the + * onColumnResizeEndCallback table property and render your + * columns appropriately. */ - overflowX?: string; - overflowY?: string; + isResizable?: boolean; - /** - * Number of rows in the table. - */ - rowsCount: number; - - /** - * Pixel height of rows unless `rowHeightGetter` is specified and returns - * different value. - */ - rowHeight: number; - - /** - * If specified, `rowHeightGetter(index)` is called for each row and the - * returned value overrides `rowHeight` for particular row. - */ - rowHeightGetter?: Function; - - /** - * To get rows to display in table, `rowGetter(index)` - * is called. `rowGetter` should be smart enough to handle async - * fetching of data and return temporary objects - * while data is being fetched. - */ - rowGetter: Function; - - /** - * To get any additional CSS classes that should be added to a row, - * `rowClassNameGetter(index)` is called. - */ - rowClassNameGetter?: Function; - - /** - * Pixel height of the column group header. - */ - groupHeaderHeight?: number; - - /** - * Pixel height of header. - */ - headerHeight: number; - - /** - * Function that is called to get the data for the header row. - * If the function returns null, the header will be set to the - * Column's label property. - */ - headerDataGetter?: Function; - - /** - * Pixel height of footer. - */ - footerHeight?: number; - - /** - * DEPRECATED - use footerDataGetter instead. - * Data that will be passed to footer cell renderers. - */ - footerData?: any; - - /** - * Function that is called to get the data for the footer row. - */ - footerDataGetter?: Function; - - /** - * Value of horizontal scroll. - */ - scrollLeft?: number; - - /** - * Index of column to scroll to. - */ - scrollToColumn?: number; - - /** - * Value of vertical scroll. - */ - scrollTop?: number; - - /** - * Index of row to scroll to. - */ - scrollToRow?: number; - - /** - * Callback that is called when scrolling starts with current horizontal - * and vertical scroll values. - */ - onScrollStart?: Function; - - /** - * Callback that is called when scrolling ends or stops with new horizontal - * and vertical scroll values. - */ - onScrollEnd?: Function; - - /** - * Callback that is called when `rowHeightGetter` returns a different height - * for a row than the `rowHeight` prop. This is necessary because initially - * table estimates heights of some parts of the content. - */ - onContentHeightChange?: Function; - - /** - * Callback that is called when a row is clicked. - */ - onRowClick?: Function; - - /** - * Callback that is called when a row is double clicked. - */ - onRowDoubleClick?: Function; - - /** - * Callback that is called when a mouse-down event happens on a row. - */ - onRowMouseDown?: Function; - - /** - * Callback that is called when a mouse-enter event happens on a row. - */ - onRowMouseEnter?: Function; - - /** - * Callback that is called when a mouse-leave event happens on a row. - */ - onRowMouseLeave?: Function; - - /** - * Callback that is called when resizer has been released - * and column needs to be updated. - * - * Required if the isResizable property is true on any column. - * - * ``` - * function( - * newColumnWidth: number, - * dataKey: string, - * ) - * ``` - */ - onColumnResizeEndCallback?: Function; - - /** - * Whether a column is currently being resized. - */ - isColumnResizing?: boolean + /** + * Whether cells in this column can be removed from document + * when outside of viewport as a result of horizontal + * scrolling. Setting this property to true allows the table + * to not render cells in particular column that are outside + * of viewport for visible rows. This allows to create table + * with many columns and not have vertical scrolling + * performance drop. Setting the property to false will keep + * previous behaviour and keep cell rendered if the row it + * belongs to is visible. + * + * defaultValue: false + */ + allowCellsRecycling?: boolean; } - - interface ColumnProps { - /** - * The horizontal alignment of the table cell content. - * 'left', 'center', 'right' - */ - align?: string; - - /** - * className for this column's header cell. - */ - headerClassName?: string; - - /** - * className for this column's footer cell. - */ - footerClassName?: string; - - /** - * className for each of this column's data cells. - */ - cellClassName?: string; - - /** - * The cell renderer that returns React-renderable content for table cell. - * ``` - * function( - * cellData: any, - * cellDataKey: string, - * rowData: object, - * rowIndex: number, - * columnData: any, - * width: number - * ): ?$jsx - * ``` - */ - cellRenderer?: Function; - - /** - * The getter `function(string_cellDataKey, object_rowData)` that returns - * the cell data for the `cellRenderer`. - * If not provided, the cell data will be collected from - * `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns - * will be used to determine whether the cell should re-render. - */ - cellDataGetter?: Function; - - /** - * The key to retrieve the cell data from the data row. Provided key type - * must be either `string` or `number`. Since we use this - * for keys, it must be specified for each column. - */ - dataKey: string|number; - - /** - * Controls if the column is fixed when scrolling in the X axis. - */ - fixed?: boolean; - - /** - * The cell renderer that returns React-renderable content for table column - * header. - * ``` - * function( - * label: ?string, - * cellDataKey: string, - * columnData: any, - * rowData: array, - * width: number - * ): ?$jsx - * ``` - */ - headerRenderer?: Function; - - /** - * The cell renderer that returns React-renderable content for table column - * footer. - * ``` - * function( - * label: ?string, - * cellDataKey: string, - * columnData: any, - * rowData: array, - * width: number - * ): ?$jsx - * ``` - */ - footerRenderer?: Function; - - /** - * Bucket for any data to be passed into column renderer functions. - */ - columnData?: any; - - /** - * The column's header label. - */ - label: string; - - /** - * The pixel width of the column. - */ - width: number; - - /** - * If this is a resizable column this is its minimum pixel width. - */ - minWidth?: number; - - /** - * If this is a resizable column this is its maximum pixel width. - */ - maxWidth?: number; - - /** - * The grow factor relative to other columns. Same as the flex-grow API - * from http://www.w3.org/TR/css3-flexbox/. Basically, take any available - * extra width and distribute it proportionally according to all columns' - * flexGrow values. Defaults to zero (no-flexing). - */ - flexGrow?: number; - - /** - * Whether the column can be resized with the - * FixedDataTableColumnResizeHandle. Please note that if a column - * has a flex grow, once you resize the column this will be set to 0. - * - * This property only provides the UI for the column resizing. If this - * is set to true, you will need ot se the onColumnResizeEndCallback table - * property and render your columns appropriately. - */ - isResizable?: boolean; - - /** - * Experimental feature - * Whether cells in this column can be removed from document when outside - * of viewport as a result of horizontal scrolling. - * Setting this property to true allows the table to not render cells in - * particular column that are outside of viewport for visible rows. This - * allows to create table with many columns and not have vertical scrolling - * performance drop. - * Setting the property to false will keep previous behaviour and keep - * cell rendered if the row it belongs to is visible. - */ - allowCellsRecycling?: boolean; - } - + + /** + * Component that defines the attributes of a table column group. + */ export interface ColumnGroupProps { /** * The horizontal alignment of the table cell content. @@ -355,35 +406,80 @@ declare module FixedDataTable { align?: string; /** - * Controls if the column group is fixed when scrolling in the X axis. + * Controls if the column group is fixed when scrolling in the X + * axis. + * + * defaultValue: false */ fixed?: boolean; - /** - * Bucket for any data to be passed into column group renderer functions. - */ - columnGroupData?: any; + /** + * The header cell for this column group. This can either be + * a string. a React element, or a function that generates a + * React Element. Passing in a string will render a default + * header cell with that string. By default, the React + * element passed in can expect to receive the following + * props: + * + * props: { + * height: number // (supplied from the groupHeaderHeight) + * width: number // (supplied from the Column) + * } + * + * Because you are passing in your own React element, you + * can feel free to pass in whatever props you may want or + * need. + * + * If you pass in a function, you will receive the same props + * object as the first argument. + */ + header: string | __React.ReactElement | ((props: CellProps) => (string | __React.ReactElement)); + } + + /** + * Component that handles default cell layout and styling. + * + * All props unless specified below will be set onto the top + * level div rendered by the cell. + * + * Example usage via from a Column: + * + * const MyColumn = ( + * ( + * + * Cell number: {rowIndex} + * + * )} + * width={100} + * /> + * ); + */ + export interface CellProps { + /** + * The row index of the cell. + */ + rowIndex?: number - /** - * The column group's header label. - */ - label?: string; + /** + * Outer height of the cell. + */ + height?: number; - /** - * The cell renderer that returns React-renderable content for a table - * column group header. If it's not specified, the label from props will - * be rendered as header content. - * ``` - * function( - * label: ?string, - * cellDataKey: string, - * columnGroupData: any, - * rowData: array, // array of labels of all columnGroups - * width: number - * ): ?$jsx - * ``` - */ - groupHeaderRenderer?: Function; + /** + * Outer width of the cell. + */ + width?: number; + + /** + * Optional prop that if specified on the Column will be + * passed to the cell. It can be used to uniquely identify + * which column is the cell is in. + */ + columnKey?: string | number; } export class Table extends __React.Component { @@ -395,8 +491,11 @@ declare module FixedDataTable { export class ColumnGroup extends __React.Component { render(): __React.DOMElement } + export class Cell extends __React.Component { + render(): __React.DOMElement + } } declare module "fixed-data-table" { export = FixedDataTable; -} \ No newline at end of file +} diff --git a/flot/jquery.flot.d.ts b/flot/jquery.flot.d.ts index 027330eee8..c45558b870 100644 --- a/flot/jquery.flot.d.ts +++ b/flot/jquery.flot.d.ts @@ -92,6 +92,8 @@ declare module jquery.flot { interface axisOptions { show?: boolean; // null or true/false position?: string; // "bottom" or "top" or "left" or "right" + mode?: string; // "time" + monthNames?: string[]; // array of month names color?: any; // null or color spec tickColor?: any; // null or color spec diff --git a/flux/flux.d.ts b/flux/flux.d.ts index c65892321c..13d7163116 100644 --- a/flux/flux.d.ts +++ b/flux/flux.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve Baker , Giedrius Grabauskas // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module Flux { @@ -70,6 +70,7 @@ declare module "flux" { declare module FluxUtils { + import React = __React; export class Container { constructor(); /** diff --git a/fontoxml/fontoxml-tests.ts b/fontoxml/fontoxml-tests.ts index 7821806cf2..11d47db895 100644 --- a/fontoxml/fontoxml-tests.ts +++ b/fontoxml/fontoxml-tests.ts @@ -25,4 +25,11 @@ var simpleinit:com.fontoxml.IInvocator = { documentIds: ["11-22-33","44-55-66"], cmsBaseUrl: "/test/", editSessionToken: "aa-bb-cc-dd-ee" +} + +var eventData:com.fontoxml.IFontoMessageEventData = { + command: "test-command", + type: "test-type", + scope: init, + metadata: {} } \ No newline at end of file diff --git a/fontoxml/fontoxml.d.ts b/fontoxml/fontoxml.d.ts index 4d621c234c..8e6a0a2c76 100644 --- a/fontoxml/fontoxml.d.ts +++ b/fontoxml/fontoxml.d.ts @@ -37,4 +37,13 @@ declare module com.fontoxml roleId:string; } + //This is describes the object that is assigned to the MessageEvent.data + //property after the FontoXML editor posts a message + export interface IFontoMessageEventData { + command: string; + type: string; + scope: com.fontoxml.IInvocator; + metadata: any; + } + } \ No newline at end of file diff --git a/freedom/freedom.d.ts b/freedom/freedom.d.ts index fa80a530c3..c69b800e9c 100644 --- a/freedom/freedom.d.ts +++ b/freedom/freedom.d.ts @@ -497,6 +497,7 @@ declare module freedom.Social { interface UserProfile { userId: string; name: string; + status?: number; url?: string; // Image URI (e.g. data:image/png;base64,adkwe329...) imageData?: string; diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 6400dba7e0..7415bdd73c 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -247,6 +247,7 @@ declare module FullCalendar { backgroundColor?: string; borderColor?: string; textColor?: string; + rendering?: string; } export interface ViewObject extends Timespan { diff --git a/fullname/fullname-tests.ts b/fullname/fullname-tests.ts new file mode 100644 index 0000000000..a037f2634e --- /dev/null +++ b/fullname/fullname-tests.ts @@ -0,0 +1,5 @@ +/// + +import fullname = require("fullname"); + +fullname().then(function(name) { name === "string"; }); diff --git a/fullname/fullname.d.ts b/fullname/fullname.d.ts new file mode 100644 index 0000000000..a1d44f1672 --- /dev/null +++ b/fullname/fullname.d.ts @@ -0,0 +1,11 @@ +// Type definitions for fullname v2.1.0 +// Project: https://www.npmjs.com/package/fullname +// Definitions by: Klaus Reimer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "fullname" { + function fullname(): Promise; + export = fullname; +} diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bafbaa49f7..55588681fa 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -1,21 +1,25 @@ -/// -import app = require('app'); -import AutoUpdater = require('auto-updater'); -import BrowserWindow = require('browser-window'); -import ContentTracing = require('content-tracing'); -import Dialog = require('dialog'); -import GlobalShortcut = require('global-shortcut'); -import ipc = require('ipc'); -import Menu = require('menu'); -import MenuItem = require('menu-item'); -import PowerMonitor = require('power-monitor'); -import Protocol = require('protocol'); -import Tray = require('tray'); -import Clipboard = require('clipboard'); -import CrashReporter = require('crash-reporter'); -import NativeImage = require('native-image'); -import Screen = require('screen'); -import Shell = require('shell'); +/// +import { + app, + autoUpdater, + BrowserWindow, + contentTracing, + dialog, + globalShortcut, + ipcMain, + Menu, + MenuItem, + powerMonitor, + protocol, + Tray, + clipboard, + crashReporter, + nativeImage, + screen, + shell +} from 'electron'; + +require('electron').hideInternalModules(); import path = require('path'); @@ -39,8 +43,8 @@ app.on('window-all-closed', () => { var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) { // Someone tried to run a second instance, we should focus our window if (mainWindow) { - if (mainWindow.isMinimized()) mainWindow.restore(); - mainWindow.focus(); + if (mainWindow.isMinimized()) mainWindow.restore(); + mainWindow.focus(); } return true; }); @@ -125,7 +129,40 @@ var dockMenu = Menu.buildFromTemplate([ { label: 'Pro' } ] }, - { label: 'New Command...' } + { label: 'New Command...' }, + { + label: 'Edit', + submenu: [ + { + label: 'Undo', + accelerator: 'CmdOrCtrl+Z', + role: 'undo' + }, + { + label: 'Redo', + accelerator: 'Shift+CmdOrCtrl+Z', + role: 'redo' + }, + { + type: 'separator' + }, + { + label: 'Cut', + accelerator: 'CmdOrCtrl+X', + role: 'cut' + }, + { + label: 'Copy', + accelerator: 'CmdOrCtrl+C', + role: 'copy' + }, + { + label: 'Paste', + accelerator: 'CmdOrCtrl+V', + role: 'paste' + }, + ] + }, ]); app.dock.setMenu(dockMenu); @@ -156,7 +193,7 @@ app.on('ready', () => { onlineStatusWindow.loadURL(`file://${__dirname}/online-status.html`); }); -ipc.on('online-status-changed', (event: any, status: any) => { +ipcMain.on('online-status-changed', (event: any, status: any) => { console.log(status); }); @@ -166,8 +203,8 @@ ipc.on('online-status-changed', (event: any, status: any) => { app.on('ready', () => { window = new BrowserWindow({ width: 800, - height: 600, - 'title-bar-style': 'hidden-inset', + height: 600, + titleBarStyle: 'hidden-inset', }); window.loadURL('https://github.com'); }); @@ -183,7 +220,7 @@ app.commandLine.appendSwitch('vmodule', 'console=0'); // auto-updater // https://github.com/atom/electron/blob/master/docs/api/auto-updater.md -AutoUpdater.setFeedURL('http://mycompany.com/myapp/latest?version=' + app.getVersion()); +autoUpdater.setFeedURL('http://mycompany.com/myapp/latest?version=' + app.getVersion()); // browser-window // https://github.com/atom/electron/blob/master/docs/api/browser-window.md @@ -199,11 +236,11 @@ win.show(); // content-tracing // https://github.com/atom/electron/blob/master/docs/api/content-tracing.md -ContentTracing.startRecording('*', ContentTracing.DEFAULT_OPTIONS, () => { +contentTracing.startRecording('*', contentTracing.DEFAULT_OPTIONS, () => { console.log('Tracing started'); setTimeout(() => { - ContentTracing.stopRecording('', path => { + contentTracing.stopRecording('', path => { console.log('Tracing data recorded to ' + path); }); }, 5000); @@ -212,7 +249,7 @@ ContentTracing.startRecording('*', ContentTracing.DEFAULT_OPTIONS, () => { // dialog // https://github.com/atom/electron/blob/master/docs/api/dialog.md -console.log(Dialog.showOpenDialog({ +console.log(dialog.showOpenDialog({ properties: ['openFile', 'openDirectory', 'multiSelections'] })); @@ -220,30 +257,30 @@ console.log(Dialog.showOpenDialog({ // https://github.com/atom/electron/blob/master/docs/api/global-shortcut.md // Register a 'ctrl+x' shortcut listener. -var ret = GlobalShortcut.register('ctrl+x', () => { +var ret = globalShortcut.register('ctrl+x', () => { console.log('ctrl+x is pressed'); }); if (!ret) console.log('registerion fails'); // Check whether a shortcut is registered. -console.log(GlobalShortcut.isRegistered('ctrl+x')); +console.log(globalShortcut.isRegistered('ctrl+x')); // Unregister a shortcut. -GlobalShortcut.unregister('ctrl+x'); +globalShortcut.unregister('ctrl+x'); // Unregister all shortcuts. -GlobalShortcut.unregisterAll(); +globalShortcut.unregisterAll(); -// ipc +// ipcMain // https://github.com/atom/electron/blob/master/docs/api/ipc-main-process.md -ipc.on('asynchronous-message', (event: any, arg: any) => { +ipcMain.on('asynchronous-message', (event: GitHubElectron.IPCMainEvent, arg: any) => { console.log(arg); // prints "ping" event.sender.send('asynchronous-reply', 'pong'); }); -ipc.on('synchronous-message', (event: any, arg: any) => { +ipcMain.on('synchronous-message', (event: GitHubElectron.IPCMainEvent, arg: any) => { console.log(arg); // prints "ping" event.returnValue = 'pong'; }); @@ -405,7 +442,7 @@ Menu.buildFromTemplate([ // https://github.com/atom/electron/blob/master/docs/api/power-monitor.md app.on('ready', () => { - PowerMonitor.on('suspend', () => { + powerMonitor.on('suspend', () => { console.log('The system is going to sleep'); }); }); @@ -414,9 +451,9 @@ app.on('ready', () => { // https://github.com/atom/electron/blob/master/docs/api/protocol.md app.on('ready', () => { - Protocol.registerProtocol('atom', (request: any) => { + protocol.registerProtocol('atom', (request: any) => { var url = request.url.substr(7); - return new Protocol.RequestFileJob(path.normalize(`${__dirname}/${url}`)); + return new protocol.RequestFileJob(path.normalize(`${__dirname}/${url}`)); }); }); @@ -440,26 +477,26 @@ app.on('ready', () => { // clipboard // https://github.com/atom/electron/blob/master/docs/api/clipboard.md -Clipboard.writeText('Example String'); -Clipboard.writeText('Example String', 'selection'); -console.log(Clipboard.readText('selection')); +clipboard.writeText('Example String'); +clipboard.writeText('Example String', 'selection'); +console.log(clipboard.readText('selection')); // crash-reporter // https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md -CrashReporter.start({ +crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', submitURL: 'https://your-domain.com/url-to-submit', autoSubmit: true }); -// NativeImage +// nativeImage // https://github.com/atom/electron/blob/master/docs/api/native-image.md var appIcon2 = new Tray('/Users/somebody/images/icon.png'); var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); -var image = Clipboard.readImage(); +var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); @@ -467,12 +504,12 @@ var appIcon4 = new Tray('/Users/somebody/images/icon.png'); // https://github.com/atom/electron/blob/master/docs/api/screen.md app.on('ready', () => { - var size = Screen.getPrimaryDisplay().workAreaSize; + var size = screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width: size.width, height: size.height }); }); app.on('ready', () => { - var displays = Screen.getAllDisplays(); + var displays = screen.getAllDisplays(); var externalDisplay: any = null; for (var i in displays) { if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { @@ -492,4 +529,4 @@ app.on('ready', () => { // shell // https://github.com/atom/electron/blob/master/docs/api/shell.md -Shell.openExternal('https://github.com'); +shell.openExternal('https://github.com'); diff --git a/github-electron/github-electron-main.d.ts b/github-electron/github-electron-main.d.ts deleted file mode 100644 index a133155a93..0000000000 --- a/github-electron/github-electron-main.d.ts +++ /dev/null @@ -1,270 +0,0 @@ -// Type definitions for the Electron 0.25.2 main process -// Project: http://electron.atom.io/ -// Definitions by: jedmao -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module GitHubElectron { - interface ContentTracing { - /** - * Get a set of category groups. The category groups can change as new code paths are reached. - * @param callback Called once all child processes have acked to the getCategories request. - */ - getCategories(callback: (categoryGroups: any[]) => void): void; - /** - * Start recording on all processes. Recording begins immediately locally, and asynchronously - * on child processes as soon as they receive the EnableRecording request. - * @param categoryFilter A filter to control what category groups should be traced. - * A filter can have an optional "-" prefix to exclude category groups that contain - * a matching category. Having both included and excluded category patterns in the - * same list would not be supported. - * @param options controls what kind of tracing is enabled, it could be a OR-ed - * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING - * and tracing.RECORD_CONTINUOUSLY. - * @param callback Called once all child processes have acked to the startRecording request. - */ - startRecording(categoryFilter: string, options: number, callback: Function): void; - /** - * Stop recording on all processes. Child processes typically are caching trace data and - * only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid - * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all - * child processes to flush any pending trace data. - * @param resultFilePath Trace data will be written into this file if it is not empty, - * or into a temporary file. - * @param callback Called once all child processes have acked to the stopRecording request. - */ - stopRecording(resultFilePath: string, callback: - /** - * @param filePath A file that contains the traced data. - */ - (filePath: string) => void - ): void; - /** - * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously - * on child processes as soon as they receive the startMonitoring request. - * @param callback Called once all child processes have acked to the startMonitoring request. - */ - startMonitoring(categoryFilter: string, options: number, callback: Function): void; - /** - * Stop monitoring on all processes. - * @param callback Called once all child processes have acked to the stopMonitoring request. - */ - stopMonitoring(callback: Function): void; - /** - * Get the current monitoring traced data. Child processes typically are caching trace data - * and only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid much - * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child - * processes to flush any pending trace data. - * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request. - */ - captureMonitoringSnapshot(resultFilePath: string, callback: - /** - * @param filePath A file that contains the traced data - * @returns {} - */ - (filePath: string) => void - ): void; - /** - * Get the maximum across processes of trace buffer percent full state. - * @param callback Called when the TraceBufferUsage value is determined. - */ - getTraceBufferUsage(callback: Function): void; - /** - * @param callback Called every time the given event occurs on any process. - */ - setWatchEvent(categoryName: string, eventName: string, callback: Function): void; - /** - * Cancel the watch event. If tracing is enabled, this may race with the watch event callback. - */ - cancelWatchEvent(): void; - DEFAULT_OPTIONS: number; - ENABLE_SYSTRACE: number; - ENABLE_SAMPLING: number; - RECORD_CONTINUOUSLY: number; - } - - interface Dialog { - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns an array of file paths chosen by the user, - * otherwise returns undefined. - */ - showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog; - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns the path of file chosen by the user, otherwise - * returns undefined. - */ - showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog; - /** - * Shows a message box. It will block until the message box is closed. It returns . - * @param callback If supplied, the API call will be asynchronous. - * @returns The index of the clicked button. - */ - showMessageBox: typeof GitHubElectron.Dialog.showMessageBox; - - /** - * Runs a modal dialog that shows an error message. This API can be called safely - * before the ready event of app module emits, it is usually used to report errors - * in early stage of startup. - */ - showErrorBox(title: string, content: string): void; - } - - interface GlobalShortcut { - /** - * Registers a global shortcut of accelerator. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @param callback Called when the registered shortcut is pressed by the user. - * @returns {} - */ - register(accelerator: string, callback: Function): void; - /** - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @returns Whether the accelerator is registered. - */ - isRegistered(accelerator: string): boolean; - /** - * Unregisters the global shortcut of keycode. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - */ - unregister(accelerator: string): void; - /** - * Unregisters all the global shortcuts. - */ - unregisterAll(): void; - } - - class RequestFileJob { - /** - * Create a request job which would query a file of path and set corresponding mime types. - */ - constructor(path: string); - } - - class RequestStringJob { - /** - * Create a request job which sends a string as response. - */ - constructor(options?: { - /** - * Default is "text/plain". - */ - mimeType?: string; - /** - * Default is "UTF-8". - */ - charset?: string; - data?: string; - }); - } - - class RequestBufferJob { - /** - * Create a request job which accepts a buffer and sends a string as response. - */ - constructor(options?: { - /** - * Default is "application/octet-stream". - */ - mimeType?: string; - /** - * Default is "UTF-8". - */ - encoding?: string; - data?: Buffer; - }); - } - - interface Protocol { - registerProtocol(scheme: string, handler: (request: any) => void): void; - unregisterProtocol(scheme: string): void; - isHandledProtocol(scheme: string): boolean; - interceptProtocol(scheme: string, handler: (request: any) => void): void; - uninterceptProtocol(scheme: string): void; - RequestFileJob: typeof RequestFileJob; - RequestStringJob: typeof RequestStringJob; - RequestBufferJob: typeof RequestBufferJob; - } -} - -declare module 'app' { - var _app: GitHubElectron.App; - export = _app; -} - -declare module 'auto-updater' { - var _autoUpdater: GitHubElectron.AutoUpdater; - export = _autoUpdater; -} - -declare module 'browser-window' { - var BrowserWindow: typeof GitHubElectron.BrowserWindow; - export = BrowserWindow; -} - -declare module 'content-tracing' { - var contentTracing: GitHubElectron.ContentTracing - export = contentTracing; -} - -declare module 'dialog' { - var dialog: GitHubElectron.Dialog - export = dialog; -} - -declare module 'global-shortcut' { - var globalShortcut: GitHubElectron.GlobalShortcut; - export = globalShortcut; -} - -declare module 'ipc' { - var ipc: NodeJS.EventEmitter; - export = ipc; -} - -declare module 'menu' { - var Menu: typeof GitHubElectron.Menu; - export = Menu; -} - -declare module 'menu-item' { - var MenuItem: typeof GitHubElectron.MenuItem; - export = MenuItem; -} - -declare module 'power-monitor' { - var powerMonitor: NodeJS.EventEmitter; - export = powerMonitor; -} - -declare module 'protocol' { - var protocol: GitHubElectron.Protocol; - export = protocol; -} - -declare module 'tray' { - var Tray: typeof GitHubElectron.Tray; - export = Tray; -} - -interface NodeRequireFunction { - (id: 'app'): GitHubElectron.App - (id: 'auto-updater'): GitHubElectron.AutoUpdater - (id: 'browser-window'): typeof GitHubElectron.BrowserWindow - (id: 'content-tracing'): GitHubElectron.ContentTracing - (id: 'dialog'): GitHubElectron.Dialog - (id: 'global-shortcut'): GitHubElectron.GlobalShortcut - (id: 'ipc'): NodeJS.EventEmitter - (id: 'menu'): typeof GitHubElectron.Menu - (id: 'menu-item'): typeof GitHubElectron.MenuItem - (id: 'power-monitor'): NodeJS.EventEmitter - (id: 'protocol'): GitHubElectron.Protocol - (id: 'tray'): typeof GitHubElectron.Tray -} diff --git a/github-electron/github-electron-renderer-tests.ts b/github-electron/github-electron-renderer-tests.ts index 86680600fc..cf610718ce 100644 --- a/github-electron/github-electron-renderer-tests.ts +++ b/github-electron/github-electron-renderer-tests.ts @@ -1,23 +1,25 @@ -/// -import ipc = require('ipc'); -import remote = require('remote'); -import WebFrame = require('web-frame'); -import Clipboard = require('clipboard'); -import CrashReporter = require('crash-reporter'); -import NativeImage = require('native-image'); -import Screen = require('screen'); -import Shell = require('shell'); +/// +import { + ipcRenderer, + remote, + webFrame, + clipboard, + crashReporter, + nativeImage, + screen, + shell +} from 'electron'; import fs = require('fs'); // In renderer process (web page). // https://github.com/atom/electron/blob/master/docs/api/ipc-renderer.md -console.log(ipc.sendSync('synchronous-message', 'ping')); // prints "pong" +console.log(ipcRenderer.sendSync('synchronous-message', 'ping')); // prints "pong" -ipc.on('asynchronous-reply', (arg: any) => { +ipcRenderer.on('asynchronous-reply', (arg: any) => { console.log(arg); // prints "pong" }); -ipc.send('asynchronous-message', 'ping'); +ipcRenderer.send('asynchronous-message', 'ping'); // remote // https://github.com/atom/electron/blob/master/docs/api/remote.md @@ -45,9 +47,9 @@ remote.getCurrentWindow().capturePage(buf => { // web-frame // https://github.com/atom/electron/blob/master/docs/api/web-frame.md -WebFrame.setZoomFactor(2); +webFrame.setZoomFactor(2); -WebFrame.setSpellCheckProvider('en-US', true, { +webFrame.setSpellCheckProvider('en-US', true, { spellCheck: text => { return !(require('spellchecker').isMisspelled(text)); } @@ -56,27 +58,27 @@ WebFrame.setSpellCheckProvider('en-US', true, { // clipboard // https://github.com/atom/electron/blob/master/docs/api/clipboard.md -Clipboard.writeText('Example String'); -Clipboard.writeText('Example String', 'selection'); -console.log(Clipboard.readText('selection')); +clipboard.writeText('Example String'); +clipboard.writeText('Example String', 'selection'); +console.log(clipboard.readText('selection')); // crash-reporter // https://github.com/atom/electron/blob/master/docs/api/crash-reporter.md -CrashReporter.start({ +crashReporter.start({ productName: 'YourName', companyName: 'YourCompany', submitURL: 'https://your-domain.com/url-to-submit', autoSubmit: true }); -// NativeImage +// nativeImage // https://github.com/atom/electron/blob/master/docs/api/native-image.md var Tray: typeof GitHubElectron.Tray = remote.require('Tray'); var appIcon2 = new Tray('/Users/somebody/images/icon.png'); var window2 = new BrowserWindow({ icon: '/Users/somebody/images/window.png' }); -var image = Clipboard.readImage(); +var image = clipboard.readImage(); var appIcon3 = new Tray(image); var appIcon4 = new Tray('/Users/somebody/images/icon.png'); @@ -88,12 +90,12 @@ var app: GitHubElectron.App = remote.require('app'); var mainWindow: GitHubElectron.BrowserWindow = null; app.on('ready', () => { - var size = Screen.getPrimaryDisplay().workAreaSize; + var size = screen.getPrimaryDisplay().workAreaSize; mainWindow = new BrowserWindow({ width: size.width, height: size.height }); }); app.on('ready', () => { - var displays = Screen.getAllDisplays(); + var displays = screen.getAllDisplays(); var externalDisplay: any = null; for (var i in displays) { if (displays[i].bounds.x > 0 || displays[i].bounds.y > 0) { @@ -113,4 +115,4 @@ app.on('ready', () => { // shell // https://github.com/atom/electron/blob/master/docs/api/shell.md -Shell.openExternal('https://github.com'); +shell.openExternal('https://github.com'); diff --git a/github-electron/github-electron-renderer.d.ts b/github-electron/github-electron-renderer.d.ts deleted file mode 100644 index 62b29d9cd6..0000000000 --- a/github-electron/github-electron-renderer.d.ts +++ /dev/null @@ -1,116 +0,0 @@ -// Type definitions for the Electron 0.25.2 renderer process (web page) -// Project: http://electron.atom.io/ -// Definitions by: jedmao -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare module GitHubElectron { - export class InProcess implements NodeJS.EventEmitter { - addListener(event: string, listener: Function): InProcess; - on(event: string, listener: Function): InProcess; - once(event: string, listener: Function): InProcess; - removeListener(event: string, listener: Function): InProcess; - removeAllListeners(event?: string): InProcess; - setMaxListeners(n: number): void; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - /** - * Send ...args to the renderer via channel in asynchronous message, the main - * process can handle it by listening to the channel event of ipc module. - */ - send(channel: string, ...args: any[]): void; - /** - * Send ...args to the renderer via channel in synchronous message, and returns - * the result sent from main process. The main process can handle it by listening - * to the channel event of ipc module, and returns by setting event.returnValue. - * Note: Usually developers should never use this API, since sending synchronous - * message would block the whole renderer process. - * @returns The result sent from the main process. - */ - sendSync(channel: string, ...args: any[]): string; - /** - * Like ipc.send but the message will be sent to the host page instead of the main process. - * This is mainly used by the page in to communicate with host page. - */ - sendToHost(channel: string, ...args: any[]): void; - } - - interface Remote { - /** - * @returns The object returned by require(module) in the main process. - */ - require(module: string): any; - /** - * @returns The BrowserWindow object which this web page belongs to. - */ - getCurrentWindow(): BrowserWindow - /** - * @returns The global variable of name (e.g. global[name]) in the main process. - */ - getGlobal(name: string): any; - /** - * Returns the process object in the main process. This is the same as - * remote.getGlobal('process'), but gets cached. - */ - process: any; - } - - interface WebFrame { - /** - * Changes the zoom factor to the specified factor, zoom factor is - * zoom percent / 100, so 300% = 3.0. - */ - setZoomFactor(factor: number): void; - /** - * @returns The current zoom factor. - */ - getZoomFactor(): number; - /** - * Changes the zoom level to the specified level, 0 is "original size", and each - * increment above or below represents zooming 20% larger or smaller to default - * limits of 300% and 50% of original size, respectively. - */ - setZoomLevel(level: number): void; - /** - * @returns The current zoom level. - */ - getZoomLevel(): number; - /** - * Sets a provider for spell checking in input fields and text areas. - */ - setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { - /** - * @returns Whether the word passed is correctly spelled. - */ - spellCheck: (text: string) => boolean; - }): void; - /** - * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content - * warnings. For example, https and data are secure schemes because they cannot be - * corrupted by active network attackers. - */ - registerURLSchemeAsSecure(scheme: string): void; - } -} - -declare module 'ipc' { - var inProcess: GitHubElectron.InProcess; - export = inProcess; -} - -declare module 'remote' { - var remote: GitHubElectron.Remote; - export = remote; -} - -declare module 'web-frame' { - var webframe: GitHubElectron.WebFrame; - export = webframe; -} - -interface NodeRequireFunction { - (id: 'ipc'): GitHubElectron.InProcess - (id: 'remote'): GitHubElectron.Remote - (id: 'web-frame'): GitHubElectron.WebFrame -} diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index d4ab0099f0..b1df3bccce 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Electron 0.25.2 (shared between main and rederer processes) +// Type definitions for Electron v0.35.0 // Project: http://electron.atom.io/ -// Definitions by: jedmao -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: jedmao , rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -70,9 +70,11 @@ declare module GitHubElectron { once(event: string, listener: Function): Screen; removeListener(event: string, listener: Function): Screen; removeAllListeners(event?: string): Screen; - setMaxListeners(n: number): void; + setMaxListeners(n: number): Screen; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; /** * @returns The current absolute position of the mouse pointer. */ @@ -108,9 +110,11 @@ declare module GitHubElectron { once(event: string, listener: Function): WebContents; removeListener(event: string, listener: Function): WebContents; removeAllListeners(event?: string): WebContents; - setMaxListeners(n: number): void; + setMaxListeners(n: number): WebContents; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; constructor(options?: BrowserWindowOptions); /** * @returns All opened browser windows. @@ -447,54 +451,63 @@ declare module GitHubElectron { isVisibleOnAllWorkspaces(): boolean; } + interface WebPreferences { + nodeIntegration?: boolean; + preload?: string; + partition?: string; + zoomFactor?: number; + javascript?: boolean; + webSecurity?: boolean; + allowDisplayingInsecureContent?: boolean; + allowRunningInsecureContent?: boolean; + images?: boolean; + textAreasAreResizable?: boolean; + webgl?: boolean; + webaudio?: boolean; + plugins?: boolean; + experimentalFeatures?: boolean; + experimentalCanvasFeatures?: boolean; + overlayScrollbars?: boolean; + sharedWorker?: boolean; + directWrite?: boolean; + pageVisibility?: boolean; + } + // Includes all options BrowserWindow can take as of this writing // http://electron.atom.io/docs/v0.29.0/api/browser-window/ interface BrowserWindowOptions extends Rectangle { show?: boolean; - 'use-content-size'?: boolean; + useContentSize?: boolean; center?: boolean; - 'min-width'?: number; - 'min-height'?: number; - 'max-width'?: number; - 'max-height'?: number; + minWidth?: number; + minHeight?: number; + maxWidth?: number; + maxHeight?: number; resizable?: boolean; - 'always-on-top'?: boolean; + alwaysOnTop?: boolean; fullscreen?: boolean; - 'skip-taskbar'?: boolean; - 'zoom-factor'?: number; + skipTaskbar?: boolean; + zoomFactor?: number; kiosk?: boolean; title?: string; icon?: NativeImage|string; frame?: boolean; - 'node-integration'?: boolean; - 'accept-first-mouse'?: boolean; - 'disable-auto-hide-cursor'?: boolean; - 'auto-hide-menu-bar'?: boolean; - 'enable-larger-than-screen'?: boolean; - 'dark-theme'?: boolean; + acceptFirstMouse?: boolean; + disableAutoHideCursor?: boolean; + autoHideMenuBar?: boolean; + enableLargerThanScreen?: boolean; + darkTheme?: boolean; preload?: string; transparent?: boolean; type?: string; - 'standard-window'?: boolean; - 'web-preferences'?: any; // Object - javascript?: boolean; - 'web-security'?: boolean; - images?: boolean; + standardWindow?: boolean; + webPreferences?: WebPreferences; java?: boolean; - 'text-areas-are-resizable'?: boolean; - webgl?: boolean; - webaudio?: boolean; - plugins?: boolean; - 'extra-plugin-dirs'?: string[]; - 'experimental-features'?: boolean; - 'experimental-canvas-features'?: boolean; - 'subpixel-font-scaling'?: boolean; - 'overlay-scrollbars'?: boolean; - 'overlay-fullscreen-video'?: boolean; - 'shared-worker'?: boolean; - 'direct-write'?: boolean; - 'page-visibility'?: boolean; - 'title-bar-style'?: string; + textAreasAreResizable?: boolean; + extraPluginDirs?: string[]; + subpixelFontScaling?: boolean; + overlayFullscreenVideo?: boolean; + titleBarStyle?: string; } interface Rectangle { @@ -513,9 +526,11 @@ declare module GitHubElectron { once(event: string, listener: Function): WebContents; removeListener(event: string, listener: Function): WebContents; removeAllListeners(event?: string): WebContents; - setMaxListeners(n: number): void; + setMaxListeners(n: number): WebContents; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; /** * Loads the url in the window. * @param url Must contain the protocol prefix (e.g., the http:// or file://). @@ -880,6 +895,10 @@ declare module GitHubElectron { * a given menu. */ position?: string; + /** + * Define the action of the menu item, when specified the click property will be ignored + */ + role?: string; } class BrowserWindowProxy { @@ -917,9 +936,11 @@ declare module GitHubElectron { once(event: string, listener: Function): App; removeListener(event: string, listener: Function): App; removeAllListeners(event?: string): App; - setMaxListeners(n: number): void; + setMaxListeners(n: number): App; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; /** * Try to close all windows. The before-quit event will first be emitted. * If all windows are successfully closed, the will-quit event will be emitted @@ -1100,7 +1121,7 @@ declare module GitHubElectron { * Note: This API is only available on Mac. */ setMenu(menu: Menu): void; - } + }; } class AutoUpdater implements NodeJS.EventEmitter { @@ -1109,9 +1130,11 @@ declare module GitHubElectron { once(event: string, listener: Function): AutoUpdater; removeListener(event: string, listener: Function): AutoUpdater; removeAllListeners(event?: string): AutoUpdater; - setMaxListeners(n: number): void; + setMaxListeners(n: number): AutoUpdater; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; /** * Set the url and initialize the auto updater. * The url cannot be changed once it is set. @@ -1170,8 +1193,12 @@ declare module GitHubElectron { /** * File types that can be displayed, see dialog.showOpenDialog for an example. */ - filters?: string[]; - }, callback?: (fileName: string) => void): void; + + filters?: { + name: string; + extensions: string[]; + }[] + }, callback?: (fileName: string) => void): string; /** * Shows a message box. It will block until the message box is closed. It returns . @@ -1219,9 +1246,11 @@ declare module GitHubElectron { once(event: string, listener: Function): Tray; removeListener(event: string, listener: Function): Tray; removeAllListeners(event?: string): Tray; - setMaxListeners(n: number): void; + setMaxListeners(n: number): Tray; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; /** * Creates a new tray icon associated with the image. */ @@ -1299,7 +1328,7 @@ declare module GitHubElectron { */ read(format: string, type?: string): any; } - + interface CrashReporterStartOptions { /** * Default: Electron @@ -1328,9 +1357,9 @@ declare module GitHubElectron { * Only string properties are send correctly. * Nested objects are not supported. */ - extra?: {} + extra?: {}; } - + interface CrashReporterPayload extends Object { /** * E.g., "electron-crash-service". @@ -1370,18 +1399,18 @@ declare module GitHubElectron { */ upload_file_minidump: File; } - + interface CrashReporter { start(options?: CrashReporterStartOptions): void; - + /** * @returns The date and ID of the last crash report. When there was no crash report * sent or the crash reporter is not started, null will be returned. */ getLastCrashReport(): CrashReporterPayload; } - - interface Shell{ + + interface Shell { /** * Show the given file in a file manager. If possible, select the file. */ @@ -1404,31 +1433,393 @@ declare module GitHubElectron { */ beep(): void; } -} -declare module 'clipboard' { - var clipboard: GitHubElectron.Clipboard - export = clipboard; -} + // Type definitions for renderer process -declare module 'crash-reporter' { - var crashReporter: GitHubElectron.CrashReporter - export = crashReporter; -} + export class IpcRenderer implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): IpcRenderer; + on(event: string, listener: Function): IpcRenderer; + once(event: string, listener: Function): IpcRenderer; + removeListener(event: string, listener: Function): IpcRenderer; + removeAllListeners(event?: string): IpcRenderer; + setMaxListeners(n: number): IpcRenderer; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + /** + * Send ...args to the renderer via channel in asynchronous message, the main + * process can handle it by listening to the channel event of ipc module. + */ + send(channel: string, ...args: any[]): void; + /** + * Send ...args to the renderer via channel in synchronous message, and returns + * the result sent from main process. The main process can handle it by listening + * to the channel event of ipc module, and returns by setting event.returnValue. + * Note: Usually developers should never use this API, since sending synchronous + * message would block the whole renderer process. + * @returns The result sent from the main process. + */ + sendSync(channel: string, ...args: any[]): string; + /** + * Like ipc.send but the message will be sent to the host page instead of the main process. + * This is mainly used by the page in to communicate with host page. + */ + sendToHost(channel: string, ...args: any[]): void; + } -declare module 'native-image' { - var nativeImage: typeof GitHubElectron.NativeImage; - export = nativeImage; -} + class IPCMain implements NodeJS.EventEmitter { + addListener(event: string, listener: Function): IPCMain; + once(event: string, listener: Function): IPCMain; + removeListener(event: string, listener: Function): IPCMain; + removeAllListeners(event?: string): IPCMain; + setMaxListeners(n: number): IPCMain; + getMaxListeners(): number; + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; + on(event: string, listener: (event: IPCMainEvent, ...args: any[]) => any): IPCMain; + } -declare module 'screen' { - var screen: GitHubElectron.Screen; - export = screen; -} + interface IPCMainEvent { + returnValue?: any; + sender: WebContents; + } -declare module 'shell' { - var shell: GitHubElectron.Shell; - export = shell; + interface Remote extends CommonElectron { + /** + * @returns The object returned by require(module) in the main process. + */ + require(module: string): any; + /** + * @returns The BrowserWindow object which this web page belongs to. + */ + getCurrentWindow(): BrowserWindow; + /** + * @returns The global variable of name (e.g. global[name]) in the main process. + */ + getGlobal(name: string): any; + /** + * Returns the process object in the main process. This is the same as + * remote.getGlobal('process'), but gets cached. + */ + process: NodeJS.Process; + } + + interface WebFrame { + /** + * Changes the zoom factor to the specified factor, zoom factor is + * zoom percent / 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * @returns The current zoom factor. + */ + getZoomFactor(): number; + /** + * Changes the zoom level to the specified level, 0 is "original size", and each + * increment above or below represents zooming 20% larger or smaller to default + * limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * @returns The current zoom level. + */ + getZoomLevel(): number; + /** + * Sets a provider for spell checking in input fields and text areas. + */ + setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { + /** + * @returns Whether the word passed is correctly spelled. + */ + spellCheck: (text: string) => boolean; + }): void; + /** + * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content + * warnings. For example, https and data are secure schemes because they cannot be + * corrupted by active network attackers. + */ + registerURLSchemeAsSecure(scheme: string): void; + } + + // Type definitions for main process + + interface ContentTracing { + /** + * Get a set of category groups. The category groups can change as new code paths are reached. + * @param callback Called once all child processes have acked to the getCategories request. + */ + getCategories(callback: (categoryGroups: any[]) => void): void; + /** + * Start recording on all processes. Recording begins immediately locally, and asynchronously + * on child processes as soon as they receive the EnableRecording request. + * @param categoryFilter A filter to control what category groups should be traced. + * A filter can have an optional "-" prefix to exclude category groups that contain + * a matching category. Having both included and excluded category patterns in the + * same list would not be supported. + * @param options controls what kind of tracing is enabled, it could be a OR-ed + * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING + * and tracing.RECORD_CONTINUOUSLY. + * @param callback Called once all child processes have acked to the startRecording request. + */ + startRecording(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop recording on all processes. Child processes typically are caching trace data and + * only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid + * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all + * child processes to flush any pending trace data. + * @param resultFilePath Trace data will be written into this file if it is not empty, + * or into a temporary file. + * @param callback Called once all child processes have acked to the stopRecording request. + */ + stopRecording(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data. + */ + (filePath: string) => void + ): void; + /** + * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously + * on child processes as soon as they receive the startMonitoring request. + * @param callback Called once all child processes have acked to the startMonitoring request. + */ + startMonitoring(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop monitoring on all processes. + * @param callback Called once all child processes have acked to the stopMonitoring request. + */ + stopMonitoring(callback: Function): void; + /** + * Get the current monitoring traced data. Child processes typically are caching trace data + * and only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid much + * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child + * processes to flush any pending trace data. + * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request. + */ + captureMonitoringSnapshot(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data + * @returns {} + */ + (filePath: string) => void + ): void; + /** + * Get the maximum across processes of trace buffer percent full state. + * @param callback Called when the TraceBufferUsage value is determined. + */ + getTraceBufferUsage(callback: Function): void; + /** + * @param callback Called every time the given event occurs on any process. + */ + setWatchEvent(categoryName: string, eventName: string, callback: Function): void; + /** + * Cancel the watch event. If tracing is enabled, this may race with the watch event callback. + */ + cancelWatchEvent(): void; + DEFAULT_OPTIONS: number; + ENABLE_SYSTRACE: number; + ENABLE_SAMPLING: number; + RECORD_CONTINUOUSLY: number; + } + + interface Dialog { + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog; + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog; + /** + * Shows a message box. It will block until the message box is closed. It returns . + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + showMessageBox: typeof GitHubElectron.Dialog.showMessageBox; + + /** + * Runs a modal dialog that shows an error message. This API can be called safely + * before the ready event of app module emits, it is usually used to report errors + * in early stage of startup. + */ + showErrorBox(title: string, content: string): void; + } + + interface GlobalShortcut { + /** + * Registers a global shortcut of accelerator. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @param callback Called when the registered shortcut is pressed by the user. + * @returns {} + */ + register(accelerator: string, callback: Function): void; + /** + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @returns Whether the accelerator is registered. + */ + isRegistered(accelerator: string): boolean; + /** + * Unregisters the global shortcut of keycode. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + */ + unregister(accelerator: string): void; + /** + * Unregisters all the global shortcuts. + */ + unregisterAll(): void; + } + + class RequestFileJob { + /** + * Create a request job which would query a file of path and set corresponding mime types. + */ + constructor(path: string); + } + + class RequestStringJob { + /** + * Create a request job which sends a string as response. + */ + constructor(options?: { + /** + * Default is "text/plain". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + charset?: string; + data?: string; + }); + } + + class RequestBufferJob { + /** + * Create a request job which accepts a buffer and sends a string as response. + */ + constructor(options?: { + /** + * Default is "application/octet-stream". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + encoding?: string; + data?: Buffer; + }); + } + + interface Protocol { + registerProtocol(scheme: string, handler: (request: any) => void): void; + unregisterProtocol(scheme: string): void; + isHandledProtocol(scheme: string): boolean; + interceptProtocol(scheme: string, handler: (request: any) => void): void; + uninterceptProtocol(scheme: string): void; + RequestFileJob: typeof RequestFileJob; + RequestStringJob: typeof RequestStringJob; + RequestBufferJob: typeof RequestBufferJob; + } + + interface PowerSaveBlocker { + start(type: string): number; + stop(id: number): void; + isStarted(id: number): boolean; + } + + interface ClearStorageDataOptions { + origin?: string; + storages?: string[]; + quotas?: string[]; + } + + interface NetworkEmulationOptions { + offline?: boolean; + latency?: number; + downloadThroughput?: number; + uploadThroughput?: number; + } + + interface CertificateVerifyProc { + (hostname: string, cert: any, callback: (accepted: boolean) => any): any; + } + + class Session { + static fromPartition(partition: string): Session; + static defaultSession: Session; + + cookies: any; + clearCache(callback: Function): void; + clearStorageData(callback: Function): void; + clearStorageData(options: ClearStorageDataOptions, callback: Function): void; + setProxy(config: string, callback: Function): void; + resolveProxy(url: URL, callback: (proxy: any) => any): void; + setDownloadPath(path: string): void; + enableNetworkEmulation(options: NetworkEmulationOptions): void; + disableNetworkEmulation(): void; + setCertificateVerifyProc(proc: CertificateVerifyProc): void; + webRequest: any; + } + + interface CommonElectron { + clipboard: GitHubElectron.Clipboard; + crashReporter: GitHubElectron.CrashReporter; + nativeImage: typeof GitHubElectron.NativeImage; + shell: GitHubElectron.Shell; + + app: GitHubElectron.App; + autoUpdater: GitHubElectron.AutoUpdater; + BrowserWindow: typeof GitHubElectron.BrowserWindow; + contentTracing: GitHubElectron.ContentTracing; + dialog: GitHubElectron.Dialog; + ipcMain: GitHubElectron.IPCMain; + globalShortcut: GitHubElectron.GlobalShortcut; + Menu: typeof GitHubElectron.Menu; + MenuItem: typeof GitHubElectron.MenuItem; + powerMonitor: NodeJS.EventEmitter; + powerSaveBlocker: GitHubElectron.PowerSaveBlocker; + protocol: GitHubElectron.Protocol; + screen: GitHubElectron.Screen; + session: GitHubElectron.Session; + Tray: typeof GitHubElectron.Tray; + hideInternalModules(): void; + } + + interface DesktopCapturerOptions { + types?: string[]; + thumbnailSize?: { + width: number; + height: number; + }; + } + + interface DesktopCapturerSource { + id: string; + name: string; + thumbnail: NativeImage; + } + + interface DesktopCapturer { + getSources(options: any, callback: (error: Error, sources: DesktopCapturerSource[]) => any): void; + } + + interface Electron extends CommonElectron { + desktopCapturer: GitHubElectron.DesktopCapturer; + ipcRenderer: GitHubElectron.IpcRenderer; + remote: GitHubElectron.Remote; + webFrame: GitHubElectron.WebFrame; + } } interface Window { @@ -1446,10 +1837,11 @@ interface File { path: string; } +declare module 'electron' { + var electron: GitHubElectron.Electron; + export = electron; +} + interface NodeRequireFunction { - (id: 'clipboard'): GitHubElectron.Clipboard - (id: 'crash-reporter'): GitHubElectron.CrashReporter - (id: 'native-image'): typeof GitHubElectron.NativeImage - (id: 'screen'): GitHubElectron.Screen - (id: 'shell'): GitHubElectron.Shell + (id: 'electron'): GitHubElectron.Electron; } diff --git a/google-maps/google-maps-tests.ts b/google-maps/google-maps-tests.ts new file mode 100644 index 0000000000..50f8489360 --- /dev/null +++ b/google-maps/google-maps-tests.ts @@ -0,0 +1,27 @@ +/// + +import GoogleMapsLoader = require('google-maps'); + +GoogleMapsLoader.load(function(google) { + var loadedMap = google.maps.Map; +}); + +GoogleMapsLoader.KEY = 'qwertyuiopasdfghjklzxcvbnm'; + +GoogleMapsLoader.CLIENT = 'yourclientkey'; +GoogleMapsLoader.VERSION = '3.14'; + +GoogleMapsLoader.SENSOR = true; + +GoogleMapsLoader.LIBRARIES = ['geometry', 'places']; + +GoogleMapsLoader.LANGUAGE = 'fr'; + +GoogleMapsLoader.release(function() { + console.log('No google maps api around'); +}); + +GoogleMapsLoader.onLoad(function(google) { + var loadedMap = google.maps.Map; + console.log('I just loaded google maps api'); +}); diff --git a/google-maps/google-maps.d.ts b/google-maps/google-maps.d.ts new file mode 100644 index 0000000000..edc37822c8 --- /dev/null +++ b/google-maps/google-maps.d.ts @@ -0,0 +1,26 @@ +// Type definitions for google-maps 3.1.0 +// Project: https://www.npmjs.com/package/google-maps +// Definitions by: Deividas Bakanas , Giedrius Grabauskas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace GoogleMapsLoader { + interface CallBack { + (google: { maps: { Map: google.maps.Map } }): void; + } + export var KEY: string; + export var CLIENT: string; + export var VERSION: string; + export var SENSOR: boolean; + export var LIBRARIES: Array; + export var LANGUAGE: string; + export function release(callBack: Function): void; + export function onLoad(callBack?: CallBack): void; + export function load(callBack?: CallBack): void; + export function isLoaded(): boolean; + +} +declare module 'google-maps' { + export = GoogleMapsLoader; +} diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 222faec1d1..f1ef8278c3 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -365,6 +365,7 @@ declare module google { export interface TransitionAnimation { duration?: number; easing?: string; // linear, in, out, inAndOut + startup?: boolean; } export interface ChartAxis { diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 3ac35b0482..699115473b 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -911,10 +911,10 @@ declare module google.maps { avoidFerries?: boolean; avoidHighways?: boolean; avoidTolls?: boolean; - destination?: LatLng|string; + destination?: LatLng|LatLngLiteral|string; durationInTraffic?: boolean; optimizeWaypoints?: boolean; - origin?: LatLng|string; + origin?: LatLng|LatLngLiteral|string; provideRouteAlternatives?: boolean; region?: string; transitOptions?: TransitOptions; @@ -959,7 +959,7 @@ declare module google.maps { export interface TransitFare { } export interface DirectionsWaypoint { - location: LatLng|string; + location: LatLng|LatLngLiteral|string; stopover: boolean; } @@ -1917,16 +1917,16 @@ declare module google.maps { } export interface PlaceSearchRequest { - bounds: LatLngBounds; - keyword: string; - location: LatLng|LatLngLiteral; + bounds?: LatLngBounds; + keyword?: string; + location?: LatLng|LatLngLiteral; maxPriceLevel?: number; minPriceLevel?: number; - name: string; - openNow: boolean; - radius: number; - rankBy: RankBy; - types: string[]; + name?: string; + openNow?: boolean; + radius?: number; + rankBy?: RankBy; + types?: string[]; } export class PlacesService { @@ -1963,11 +1963,11 @@ declare module google.maps { export interface RadarSearchRequest { bounds?: LatLngBounds; - keyword: string; - location: LatLng|LatLngLiteral; - name: string; - radius: number; - types: string[]; + keyword?: string; + location?: LatLng|LatLngLiteral; + name?: string; + radius?: number; + types?: string[]; } export enum RankBy { @@ -1988,10 +1988,10 @@ declare module google.maps { export interface TextSearchRequest { bounds?: LatLngBounds; - location: LatLng|LatLngLiteral; + location?: LatLng|LatLngLiteral; query: string; - radius: number; - types: string[]; + radius?: number; + types?: string[]; } } diff --git a/graham_scan/graham_scan.d.ts b/graham_scan/graham_scan.d.ts index 617df2e7e8..dbc30517b2 100644 --- a/graham_scan/graham_scan.d.ts +++ b/graham_scan/graham_scan.d.ts @@ -6,3 +6,7 @@ declare class ConvexHullGrahamScan { addPoint(x: number, y: number): void; getHull(): {x: number, y: number}[]; } + +declare module 'graham_scan' { + export = ConvexHullGrahamScan; +} diff --git a/gulp-autoprefixer/gulp-autoprefixer-tests.ts b/gulp-autoprefixer/gulp-autoprefixer-tests.ts index 9fca0fa69c..1b3ba0d535 100644 --- a/gulp-autoprefixer/gulp-autoprefixer-tests.ts +++ b/gulp-autoprefixer/gulp-autoprefixer-tests.ts @@ -1,7 +1,7 @@ /// /// -import gulp = require("gulp"); -import autoprefixer = require("gulp-autoprefixer"); +import * as gulp from "gulp"; +import * as autoprefixer from "gulp-autoprefixer"; gulp.src("test.css") .pipe(autoprefixer()) @@ -17,4 +17,4 @@ gulp.src("test.css") gulp.src("test.css") .pipe(autoprefixer({remove: false})) - .pipe(gulp.dest("build")); \ No newline at end of file + .pipe(gulp.dest("build")); diff --git a/gulp-autoprefixer/gulp-autoprefixer.d.ts b/gulp-autoprefixer/gulp-autoprefixer.d.ts index 5abfdc6283..4ab8cf40d8 100644 --- a/gulp-autoprefixer/gulp-autoprefixer.d.ts +++ b/gulp-autoprefixer/gulp-autoprefixer.d.ts @@ -14,5 +14,7 @@ declare module "gulp-autoprefixer" { function autoPrefixer(opts?: Options): NodeJS.ReadWriteStream; + namespace autoPrefixer {} + export = autoPrefixer; } diff --git a/gulp-babel/gulp-babel.d.ts b/gulp-babel/gulp-babel.d.ts index 98d33881cf..632cb86f96 100644 --- a/gulp-babel/gulp-babel.d.ts +++ b/gulp-babel/gulp-babel.d.ts @@ -36,5 +36,7 @@ declare module 'gulp-babel' { retainLines?: boolean }): NodeJS.ReadWriteStream; + module babel { } + export = babel; } diff --git a/gulp-csso/gulp-csso-tests.ts b/gulp-csso/gulp-csso-tests.ts index 5f61d4871f..0ddf457c7d 100644 --- a/gulp-csso/gulp-csso-tests.ts +++ b/gulp-csso/gulp-csso-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require('gulp'); -import csso = require('gulp-csso'); +import * as gulp from 'gulp'; +import * as csso from 'gulp-csso'; gulp.task('default', () => gulp.src('./main.css') diff --git a/gulp-csso/gulp-csso.d.ts b/gulp-csso/gulp-csso.d.ts index d5d338c4ac..c2b58777a8 100644 --- a/gulp-csso/gulp-csso.d.ts +++ b/gulp-csso/gulp-csso.d.ts @@ -7,6 +7,6 @@ declare module 'gulp-csso' { function csso(structureMinimization?: boolean): NodeJS.ReadWriteStream; - + namespace csso {} export = csso; } diff --git a/gulp-debug/gulp-debug-tests.ts b/gulp-debug/gulp-debug-tests.ts index e6485d8da9..9701074101 100644 --- a/gulp-debug/gulp-debug-tests.ts +++ b/gulp-debug/gulp-debug-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require('gulp'); -import debug = require('gulp-debug'); +import * as gulp from 'gulp'; +import * as debug from 'gulp-debug'; gulp.task('default', () => gulp.src('foo.js') diff --git a/gulp-debug/gulp-debug.d.ts b/gulp-debug/gulp-debug.d.ts index 743f5f5eb1..d7ade91ac8 100644 --- a/gulp-debug/gulp-debug.d.ts +++ b/gulp-debug/gulp-debug.d.ts @@ -13,5 +13,7 @@ declare module 'gulp-debug' { function debug(options?: IOptions): NodeJS.ReadWriteStream; + namespace debug {} + export = debug; } diff --git a/gulp-dtsm/gulp-dtsm-tests.ts b/gulp-dtsm/gulp-dtsm-tests.ts index f97f8705e4..1eb5057380 100644 --- a/gulp-dtsm/gulp-dtsm-tests.ts +++ b/gulp-dtsm/gulp-dtsm-tests.ts @@ -2,10 +2,9 @@ /// /// -import dtsm = require('gulp-dtsm'); -import gulp = require('gulp'); +import * as dtsm from 'gulp-dtsm'; +import * as gulp from 'gulp'; var stream: NodeJS.WritableStream = dtsm(); gulp.task('dtsm', () => gulp.src('./dtsm.json').pipe(dtsm())); - diff --git a/gulp-dtsm/gulp-dtsm.d.ts b/gulp-dtsm/gulp-dtsm.d.ts index a8fe7878f5..63f01e1f59 100644 --- a/gulp-dtsm/gulp-dtsm.d.ts +++ b/gulp-dtsm/gulp-dtsm.d.ts @@ -8,6 +8,7 @@ declare module "gulp-dtsm" { function dtsm(): NodeJS.WritableStream; + namespace dtsm {} + export = dtsm; } - diff --git a/gulp-flatten/gulp-flatten-tests.ts b/gulp-flatten/gulp-flatten-tests.ts index ee56225644..5a476195d0 100644 --- a/gulp-flatten/gulp-flatten-tests.ts +++ b/gulp-flatten/gulp-flatten-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require("gulp"); -import flatten = require("gulp-flatten"); +import * as gulp from "gulp"; +import * as flatten from "gulp-flatten"; gulp.task("flatten:simple", () => { gulp.src(["files/**/*.txt"]) diff --git a/gulp-flatten/gulp-flatten.d.ts b/gulp-flatten/gulp-flatten.d.ts index ccd9cedf10..2992aff4f7 100644 --- a/gulp-flatten/gulp-flatten.d.ts +++ b/gulp-flatten/gulp-flatten.d.ts @@ -13,5 +13,7 @@ declare module "gulp-flatten" { function flatten(options?: IOptions): NodeJS.ReadWriteStream; + namespace flatten {} + export = flatten; } diff --git a/gulp-gh-pages/gulp-gh-pages-tests.ts b/gulp-gh-pages/gulp-gh-pages-tests.ts index a8633c0519..0d12c7329a 100644 --- a/gulp-gh-pages/gulp-gh-pages-tests.ts +++ b/gulp-gh-pages/gulp-gh-pages-tests.ts @@ -1,7 +1,7 @@ /// /// -import gulp = require("gulp"); -import ghPages = require("gulp-gh-pages"); +import * as gulp from "gulp"; +import * as ghPages from "gulp-gh-pages"; gulp.src("test.css") .pipe(ghPages()); @@ -22,4 +22,4 @@ gulp.src("test.css") .pipe(ghPages({push: false})); gulp.src("test.css") - .pipe(ghPages({message: "master"})); \ No newline at end of file + .pipe(ghPages({message: "master"})); diff --git a/gulp-gh-pages/gulp-gh-pages.d.ts b/gulp-gh-pages/gulp-gh-pages.d.ts index ef71465644..228589914e 100644 --- a/gulp-gh-pages/gulp-gh-pages.d.ts +++ b/gulp-gh-pages/gulp-gh-pages.d.ts @@ -17,5 +17,7 @@ declare module "gulp-gh-pages" { function ghPages(opts?: Options): NodeJS.ReadWriteStream; + namespace ghPages {} + export = ghPages; } diff --git a/gulp-inject/gulp-inject-tests.ts b/gulp-inject/gulp-inject-tests.ts index 804e6f9b55..4f535c8d64 100644 --- a/gulp-inject/gulp-inject-tests.ts +++ b/gulp-inject/gulp-inject-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require("gulp"); -import inject = require("gulp-inject"); +import * as gulp from "gulp"; +import * as inject from "gulp-inject"; gulp.task("inject:simple", () => { gulp.src("src/index.html") diff --git a/gulp-inject/gulp-inject.d.ts b/gulp-inject/gulp-inject.d.ts index fb2668a1f7..5e72e06738 100644 --- a/gulp-inject/gulp-inject.d.ts +++ b/gulp-inject/gulp-inject.d.ts @@ -35,5 +35,7 @@ declare module "gulp-inject" { function inject(sources: NodeJS.ReadableStream, options?: IOptions): NodeJS.ReadWriteStream; + namespace inject {} + export = inject; } diff --git a/gulp-less/gulp-less-tests.ts b/gulp-less/gulp-less-tests.ts index a0671e7665..ba9758649a 100644 --- a/gulp-less/gulp-less-tests.ts +++ b/gulp-less/gulp-less-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require("gulp"); -import less = require("gulp-less"); +import * as gulp from "gulp"; +import * as less from "gulp-less"; // Without options gulp.task("less", () => { diff --git a/gulp-less/gulp-less.d.ts b/gulp-less/gulp-less.d.ts index 84adca370b..8ee0a9b485 100644 --- a/gulp-less/gulp-less.d.ts +++ b/gulp-less/gulp-less.d.ts @@ -15,5 +15,7 @@ declare module "gulp-less" { function less(options?: IOptions): NodeJS.ReadWriteStream; + namespace less {} + export = less; } diff --git a/gulp-load-plugins/gulp-load-plugins-tests.ts b/gulp-load-plugins/gulp-load-plugins-tests.ts index f479be00cd..50930358f0 100644 --- a/gulp-load-plugins/gulp-load-plugins-tests.ts +++ b/gulp-load-plugins/gulp-load-plugins-tests.ts @@ -3,9 +3,9 @@ /// /// -import gulp = require('gulp'); -import gulpConcat = require('gulp-concat'); -import gulpLoadPlugins = require('gulp-load-plugins'); +import * as gulp from 'gulp'; +import * as gulpConcat from 'gulp-concat'; +import * as gulpLoadPlugins from 'gulp-load-plugins'; interface GulpPlugins extends IGulpPlugins { concat: typeof gulpConcat; @@ -29,8 +29,8 @@ gulp.task('taskName', () => { }); /* - * From 0.8.0, you can pass in an object of mappings for renaming plugins. For example, - * imagine you want to load the gulp-ruby-sass plugin, but want to refer to it as just + * From 0.8.0, you can pass in an object of mappings for renaming plugins. For example, + * imagine you want to load the gulp-ruby-sass plugin, but want to refer to it as just * sass : */ plugins = gulpLoadPlugins({ @@ -39,9 +39,9 @@ plugins = gulpLoadPlugins({ } }); /* - * gulp-load-plugins comes with npm scope support. The major difference is that scoped - * plugins are accessible through an object on plugins that represents the scope. For - * example, if the plugin is @myco/gulp-test-plugin then you can access the plugin as + * gulp-load-plugins comes with npm scope support. The major difference is that scoped + * plugins are accessible through an object on plugins that represents the scope. For + * example, if the plugin is @myco/gulp-test-plugin then you can access the plugin as * shown in the following example: */ interface GulpPlugins { @@ -49,5 +49,5 @@ interface GulpPlugins { testPlugin(): NodeJS.ReadWriteStream; } } - + plugins.myco.testPlugin(); diff --git a/gulp-load-plugins/gulp-load-plugins.d.ts b/gulp-load-plugins/gulp-load-plugins.d.ts index c8a11091d2..d72ca87c41 100644 --- a/gulp-load-plugins/gulp-load-plugins.d.ts +++ b/gulp-load-plugins/gulp-load-plugins.d.ts @@ -7,7 +7,7 @@ /** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */ declare module 'gulp-load-plugins' { - + interface IOptions { /** the glob(s) to search for, default ['gulp-*', 'gulp.*'] */ pattern?: string[]; @@ -24,14 +24,16 @@ declare module 'gulp-load-plugins' { /** a mapping of plugins to rename, the key being the NPM name of the package, and the value being an alias you define */ rename?: IPluginNameMappings; } - + interface IPluginNameMappings { [npmPackageName: string]: string } - + /** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */ function gulpLoadPlugins(options?: IOptions): T; - + + namespace gulpLoadPlugins {} + export = gulpLoadPlugins; } diff --git a/gulp-minify-css/gulp-minify-css-tests.ts b/gulp-minify-css/gulp-minify-css-tests.ts index 1375042dd2..d8ac4d9dfc 100644 --- a/gulp-minify-css/gulp-minify-css-tests.ts +++ b/gulp-minify-css/gulp-minify-css-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require("gulp"); -import minifyCSS = require("gulp-minify-css"); +import * as gulp from "gulp"; +import * as minifyCSS from "gulp-minify-css"; gulp.task("minify-css", () => { gulp.src("css/**/*.css") diff --git a/gulp-minify-css/gulp-minify-css.d.ts b/gulp-minify-css/gulp-minify-css.d.ts index be6d45b8b1..bc990a6e0e 100644 --- a/gulp-minify-css/gulp-minify-css.d.ts +++ b/gulp-minify-css/gulp-minify-css.d.ts @@ -27,5 +27,7 @@ declare module "gulp-minify-css" { function minifyCSS(options?: IOptions): NodeJS.ReadWriteStream; + namespace minifyCSS {} + export = minifyCSS; } diff --git a/gulp-minify-html/gulp-minify-html-tests.ts b/gulp-minify-html/gulp-minify-html-tests.ts index 9714818f53..2ec41e556a 100644 --- a/gulp-minify-html/gulp-minify-html-tests.ts +++ b/gulp-minify-html/gulp-minify-html-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require('gulp'); -import minifyHtml = require('gulp-minify-html'); +import * as gulp from 'gulp'; +import * as minifyHtml from 'gulp-minify-html'; minifyHtml(); minifyHtml({conditionals: true, loose: true}); diff --git a/gulp-minify-html/gulp-minify-html.d.ts b/gulp-minify-html/gulp-minify-html.d.ts index 7471040847..11ce298a49 100644 --- a/gulp-minify-html/gulp-minify-html.d.ts +++ b/gulp-minify-html/gulp-minify-html.d.ts @@ -31,5 +31,7 @@ declare module 'gulp-minify-html' { function minifyHtml(options?: IOptions): NodeJS.ReadWriteStream; + namespace minifyHtml {} + export = minifyHtml; } diff --git a/gulp-mocha/gulp-mocha-tests.ts b/gulp-mocha/gulp-mocha-tests.ts index 09f62b83d9..8d3eda4ea3 100644 --- a/gulp-mocha/gulp-mocha-tests.ts +++ b/gulp-mocha/gulp-mocha-tests.ts @@ -1,9 +1,9 @@ /// /// -import gulp = require("gulp"); -import mocha = require("gulp-mocha"); +import * as gulp from "gulp"; +import * as mocha from "gulp-mocha"; gulp.task('default', function () { return gulp.src('test.js', {read: false}) .pipe(mocha({reporter: 'nyan'})); -}); \ No newline at end of file +}); diff --git a/gulp-mocha/gulp-mocha.d.ts b/gulp-mocha/gulp-mocha.d.ts index 8d21b1323d..b63714b773 100644 --- a/gulp-mocha/gulp-mocha.d.ts +++ b/gulp-mocha/gulp-mocha.d.ts @@ -8,5 +8,6 @@ declare module "gulp-mocha" { function mocha(setupOptions?: MochaSetupOptions): NodeJS.ReadWriteStream; + namespace mocha {} export = mocha; -} \ No newline at end of file +} diff --git a/gulp-ruby-sass/gulp-ruby-sass-tests.ts b/gulp-ruby-sass/gulp-ruby-sass-tests.ts index cba0c4c60d..5237527a45 100644 --- a/gulp-ruby-sass/gulp-ruby-sass-tests.ts +++ b/gulp-ruby-sass/gulp-ruby-sass-tests.ts @@ -1,7 +1,7 @@ /// /// -import gulp = require("gulp"); -import sass = require("gulp-ruby-sass"); +import * as gulp from "gulp"; +import * as sass from "gulp-ruby-sass"; gulp.task('sass', function () { sass('./scss/*.scss') diff --git a/gulp-ruby-sass/gulp-ruby-sass.d.ts b/gulp-ruby-sass/gulp-ruby-sass.d.ts index bb0c56328d..2b0d26fdfa 100644 --- a/gulp-ruby-sass/gulp-ruby-sass.d.ts +++ b/gulp-ruby-sass/gulp-ruby-sass.d.ts @@ -64,5 +64,7 @@ declare module "gulp-ruby-sass" { */ function sass(source: string, options?: Options): NodeJS.ReadableStream; + namespace sass {} + export = sass; } diff --git a/gulp-size/gulp-size-tests.ts b/gulp-size/gulp-size-tests.ts index bfa2c6a04b..8981960f20 100644 --- a/gulp-size/gulp-size-tests.ts +++ b/gulp-size/gulp-size-tests.ts @@ -2,9 +2,9 @@ /// /// -import gulp = require('gulp'); -import size = require('gulp-size'); -import debug = require('gulp-debug'); +import * as gulp from 'gulp'; +import * as size from 'gulp-size'; +import * as debug from 'gulp-debug'; gulp.task('default', () => gulp.src('fixture.js') diff --git a/gulp-size/gulp-size.d.ts b/gulp-size/gulp-size.d.ts index d25f6ed94b..022e9b1713 100644 --- a/gulp-size/gulp-size.d.ts +++ b/gulp-size/gulp-size.d.ts @@ -19,5 +19,7 @@ declare module 'gulp-size' { function size(options?: IOptions): ISizeStream; + namespace size {} + export = size; } diff --git a/gulp-sort/gulp-sort-tests.ts b/gulp-sort/gulp-sort-tests.ts index 12685c0859..d94f5cfdcb 100644 --- a/gulp-sort/gulp-sort-tests.ts +++ b/gulp-sort/gulp-sort-tests.ts @@ -3,9 +3,9 @@ /// /// -import gulp = require('gulp'); -import sort = require('gulp-sort'); -import gulpUtil = require('gulp-util'); +import * as gulp from 'gulp'; +import * as sort from 'gulp-sort'; +import * as gulpUtil from 'gulp-util'; // default sort gulp.src('./src/js/**/*.js') @@ -38,7 +38,7 @@ gulp.src('./src/js/**/*.js') } })) .pipe(gulp.dest('./build/js')); - + function customComparator(file1: gulpUtil.File, file2: gulpUtil.File) { if (file1.path.indexOf('build') > -1) { return 1; @@ -47,4 +47,4 @@ function customComparator(file1: gulpUtil.File, file2: gulpUtil.File) { return -1; } return 0; -} \ No newline at end of file +} diff --git a/gulp-sort/gulp-sort.d.ts b/gulp-sort/gulp-sort.d.ts index c06b9c3e07..d4e740fc59 100644 --- a/gulp-sort/gulp-sort.d.ts +++ b/gulp-sort/gulp-sort.d.ts @@ -8,11 +8,11 @@ /** Sort files in stream by path or any custom sort comparator */ declare module 'gulp-sort' { - + import gulpUtil = require('gulp-util'); - + interface IOptions { - /** + /** * A function to compare two files. * Returns: * -1 if file1 should be before file2, @@ -23,9 +23,9 @@ declare module 'gulp-sort' { /** Whether to sort in ascending order, default is true */ asc?: boolean; } - + interface IComparatorFunction { - /** + /** * A function to compare two files. * Returns: * -1 if file1 should be before file2, @@ -34,11 +34,13 @@ declare module 'gulp-sort' { */ (file1: gulpUtil.File, file2: gulpUtil.File): number; } - + /** Sort files in stream by path or any custom sort comparator */ function gulpSort(): NodeJS.ReadWriteStream; function gulpSort(comparator: IComparatorFunction): NodeJS.ReadWriteStream; function gulpSort(options: IOptions): NodeJS.ReadWriteStream; - + + namespace gulpSort {} + export = gulpSort; } diff --git a/gulp-tsd/gulp-tsd-tests.ts b/gulp-tsd/gulp-tsd-tests.ts index a7c20519cd..734db65e81 100644 --- a/gulp-tsd/gulp-tsd-tests.ts +++ b/gulp-tsd/gulp-tsd-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require("gulp"); -import tsd = require("gulp-tsd"); +import * as gulp from "gulp"; +import * as tsd from "gulp-tsd"; gulp.task("tsd", () => { gulp.src("gulp_tsd.json") diff --git a/gulp-tsd/gulp-tsd.d.ts b/gulp-tsd/gulp-tsd.d.ts index 816d50d25b..4e9380ebf2 100644 --- a/gulp-tsd/gulp-tsd.d.ts +++ b/gulp-tsd/gulp-tsd.d.ts @@ -18,5 +18,7 @@ declare module "gulp-tsd" { function tsd(opts?: IOptions, callback?: gulp.TaskCallback): NodeJS.ReadWriteStream; + namespace tsd {} + export = tsd; } diff --git a/gulp-typescript/gulp-typescript-tests.ts b/gulp-typescript/gulp-typescript-tests.ts index 5abd5a1523..ab40e478d8 100644 --- a/gulp-typescript/gulp-typescript-tests.ts +++ b/gulp-typescript/gulp-typescript-tests.ts @@ -60,3 +60,7 @@ gulp.task('default', function () { .pipe(typescript()) .pipe(gulp.dest('built/local')); }); + +var compilerOptions = tsProject.config.compilerOptions; +var exclude = tsProject.config.exclude; +var files = tsProject.config.files; diff --git a/gulp-typescript/gulp-typescript.d.ts b/gulp-typescript/gulp-typescript.d.ts index 84d4b5d9ce..d51a3122e0 100644 --- a/gulp-typescript/gulp-typescript.d.ts +++ b/gulp-typescript/gulp-typescript.d.ts @@ -20,14 +20,32 @@ declare module "gulp-typescript" { noImplicitAny?: boolean; noLib?: boolean; removeComments?: boolean; - sourceRoot?: string; + sourceRoot?: string; // use gulp-sourcemaps instead sortOutput?: boolean; target?: string; typescript?: any; + outFile?: string; + outDir?: string; + suppressImplicitAnyIndexErrors?: boolean; + jsx?: string; + declaration?: boolean; + emitDecoratorMetadata?: boolean; + experimentalAsyncFunctions?: boolean; + moduleResolution?: string; + noEmitHelpers?: boolean; + preserveConstEnums?: boolean; + isolatedModules?: boolean; + } + + interface TsConfig { + files?: string[]; + exclude?: string[]; + compilerOptions?: any; } interface Project { - src(): NodeJS.ReadWriteStream + config: TsConfig; + src(): NodeJS.ReadWriteStream; } interface FilterSettings { @@ -51,4 +69,4 @@ declare module "gulp-typescript" { } export = GulpTypescript; -} \ No newline at end of file +} diff --git a/gulp-watch/gulp-watch-tests.ts b/gulp-watch/gulp-watch-tests.ts index dd237dccc2..d912199fdd 100644 --- a/gulp-watch/gulp-watch-tests.ts +++ b/gulp-watch/gulp-watch-tests.ts @@ -1,8 +1,8 @@ /// /// -import gulp = require('gulp'); -import watch = require('gulp-watch'); +import * as gulp from 'gulp'; +import * as watch from 'gulp-watch'; gulp.task('stream', () => gulp.src('css/**/*.css') diff --git a/gulp-watch/gulp-watch.d.ts b/gulp-watch/gulp-watch.d.ts index 35fb7de955..74af525477 100644 --- a/gulp-watch/gulp-watch.d.ts +++ b/gulp-watch/gulp-watch.d.ts @@ -22,6 +22,6 @@ declare module 'gulp-watch' { } function watch(glob: string | Array, options?: IOptions, callback?: Function): IWatchStream; - + namespace watch {} export = watch; } diff --git a/hammerjs/hammerjs.d.ts b/hammerjs/hammerjs.d.ts index 0df86dfc67..e2d4a8c528 100644 --- a/hammerjs/hammerjs.d.ts +++ b/hammerjs/hammerjs.d.ts @@ -107,7 +107,7 @@ interface HammerManager emit( event:string, data:any ):void; get( recogniser:Recognizer ):Recognizer; get( recogniser:string ):Recognizer; - off( events:string, handler:( event:HammerInput ) => void ):void; + off( events:string, handler?:( event:HammerInput ) => void ):void; on( events:string, handler:( event:HammerInput ) => void ):void; recognize( inputData:any ):void; remove( recogniser:Recognizer ):HammerManager; diff --git a/handlebars/handlebars.d.ts b/handlebars/handlebars.d.ts index 9a0aa510ac..54dc7e9aef 100644 --- a/handlebars/handlebars.d.ts +++ b/handlebars/handlebars.d.ts @@ -7,6 +7,8 @@ declare module Handlebars { export function registerHelper(name: string, fn: Function, inverse?: boolean): void; export function registerPartial(name: string, str: any): void; + export function unregisterHelper(name: string): void; + export function unregisterPartial(name: string): void; export function K(): void; export function createFrame(object: any): any; export function Exception(message: string): void; diff --git a/hopscotch/hopscotch-tests.ts b/hopscotch/hopscotch-tests.ts new file mode 100644 index 0000000000..fb1d1c68a5 --- /dev/null +++ b/hopscotch/hopscotch-tests.ts @@ -0,0 +1,55 @@ +/// + +var tourDefinition: TourDefinition = { + id: 'intro-tour', + steps: [ + { + target: '.popupTarget', + placement: 'bottom', + title: 'A tour step', + content: 'A tour message' + }, + { + target: [".aSelector"], + placement: 'bottom', + + yOffset: 10, + width: 400, + xOffset: -420, + arrowOffset: 380 + }, + { + target: '.domainPatterns form', + placement: 'right', + title: 'A question?', + content: "Hello!", + onShow: function () { } + }, + { + target: '.home-button', + placement: 'left', + title: "Let's get started", + content: "Content", + + multipage: true, + nextOnTargetClick: true, + showNextButton: false + }, + { + target: '.buttons', + placement: 'top', + + title: 'Another title', + content: "A message", + + showNextButton: false, + nextOnTargetClick: true, + onShow: function () { } + } + ], + skipIfNoElement: false, + onClose: function () { }, + onEnd: function () { } +}; + +hopscotch.startTour(tourDefinition); diff --git a/hopscotch/hopscotch.d.ts b/hopscotch/hopscotch.d.ts new file mode 100644 index 0000000000..46fdf17c6d --- /dev/null +++ b/hopscotch/hopscotch.d.ts @@ -0,0 +1,165 @@ +// Type definitions for Hopscotch v0.2.5 +// Project: http://linkedin.github.io/hopscotch/ +// Definitions by: Tim Perry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare type CallbackNameNamesOrDefinition = string | string[] | (() => void); + +interface HopscotchConfiguration { + bubbleWidth?: number; + buddleHeight?: number; + + smoothScroll?: boolean; + scrollDuration?: number; + scrollTopMargin?: number; + + showCloseButton?: boolean; + showNextButton?: boolean; + showPrevButton?: boolean; + + arrowWidth?: number; + skipIfNoElement?: boolean; + nextOnTargetClick?: boolean; + + onNext?: CallbackNameNamesOrDefinition; + onPrev?: CallbackNameNamesOrDefinition; + onStart?: CallbackNameNamesOrDefinition; + onEnd?: CallbackNameNamesOrDefinition; + onClose?: CallbackNameNamesOrDefinition; + onError?: CallbackNameNamesOrDefinition; + + i18n?: { + nextBtn?: string; + prevBtn?: string; + doneBtn?: string; + skipBtn?: string; + closeTooltip?: string; + stepNums?: string[]; + } +} + +interface TourDefinition extends HopscotchConfiguration { + id: string; + steps: StepDefinition[]; +} + +interface StepDefinition { + placement: string; + target: string | HTMLElement | Array + + title?: string; + content?: string; + + width?: number; + padding?: number; + + xOffset?: number; + yOffset?: number; + arrowOffset?: number; + + delay?: number; + zIndex?: number; + + showNextButton?: boolean; + showPrevButton?: boolean; + showCTAButton?: boolean; + + ctaLabel?: string; + multipage?: boolean; + showSkip?: boolean; + fixedElement?: boolean; + nextOnTargetClick?: boolean; + + onPrev?: CallbackNameNamesOrDefinition; + onNext?: CallbackNameNamesOrDefinition; + onShow?: CallbackNameNamesOrDefinition; + onCTA?: CallbackNameNamesOrDefinition; +} + +interface HopscotchStatic { + /** + * Actually starts the tour. Optional stepNum argument specifies what step to start at. + */ + startTour(tour: TourDefinition, stepNum?: number): void; + + /** + * Skips to a given step in the tour + */ + showStep(id: number): void; + + /** + * Goes back one step in the tour + */ + prevStep(): void; + + /** + * Goes forward one step in the tour + */ + nextStep(): void; + + /** + * Ends the current tour. If clearCookie is set to false, the tour state is preserved. + * Otherwise, if clearCookie is set to true or is not provided, the tour state is cleared. + */ + endTour(clearCookie: boolean): void; + + /** + * Sets options for running the tour. + */ + configure(options: HopscotchConfiguration): void; + + /** + * Returns the currently running tour. + */ + getCurrTour(): TourDefinition; + + /** + * Returns the currently running tour. + */ + getCurrStepNum(): number; + + /** + * Checks for tour state saved in sessionStorage/cookies and returns the state if + * it exists. Use this method to determine whether or not you should resume a tour. + */ + getState(): string; + + /** + * Adds a callback for one of the event types. Valid event types are: + * *start*, *end*, *next*, *prev*, *show*, *close*, *error* + */ + listen(eventName: string, callback: () => void): void; + + /** + * Removes a callback for one of the event types. + */ + unlisten(eventName: string, callback: () => void): void; + + /** + * Remove callbacks for hopscotch events. If tourOnly is set to true, only removes + * callbacks specified by a tour (callbacks set by hopscotch.configure or hopscotch.listen + * will remain). If eventName is null or undefined, callbacks for all events will be removed. + */ + removeCallbacks(eventName?: string, tourOnly?: boolean): void; + + /** + * Registers a callback helper. See the section about Helpers below. + */ + registerHelper(id: string, helper: (...args: any[]) => void): void; + + /** + * Resets i18n strings to original default values. + */ + resetDefaultI18N(): void; + + /** + * Resets all config options to original values. + */ + resetDefaultOptions(): void; +} + +declare var hopscotch: HopscotchStatic; + +declare module "hopscotch" { + export = hopscotch; +} diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 06b91f13b6..4403259008 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -1,8 +1,8 @@ /// /// -import createError = require('http-errors'); -import express = require('express'); +import * as createError from 'http-errors'; +import * as express from 'express'; var app = express(); @@ -67,3 +67,5 @@ var err = new createError['404'](); //createError['404'](); // TypeScript should fail with "Did you mean to include 'new'?" //new createError(); // TypeScript should fail with "Only a void function can be called with the 'new' keyword" + +let error: createError.HttpError; diff --git a/http-errors/http-errors.d.ts b/http-errors/http-errors.d.ts index 6f78ff6a73..e15a7cb4e1 100644 --- a/http-errors/http-errors.d.ts +++ b/http-errors/http-errors.d.ts @@ -4,82 +4,86 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'http-errors' { - interface HttpError extends Error { - status: number; - statusCode: number; - expose: boolean; + namespace createHttpError { + + // See https://github.com/jshttp/http-errors/blob/1.3.1/index.js#L42 + interface HttpError extends Error { + status: number; + statusCode: number; + expose: boolean; + } + + interface CreateHttpError { + // See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674 + [code: string]: new() => HttpError; + + (...args: Array): HttpError; + + Continue: new() => HttpError; + SwitchingProtocols: new() => HttpError; + Processing: new() => HttpError; + OK: new() => HttpError; + Created: new() => HttpError; + Accepted: new() => HttpError; + NonAuthoritativeInformation: new() => HttpError; + NoContent: new() => HttpError; + ResetContent: new() => HttpError; + PartialContent: new() => HttpError; + MultiStatus: new() => HttpError; + AlreadyReported: new() => HttpError; + IMUsed: new() => HttpError; + MultipleChoices: new() => HttpError; + MovedPermanently: new() => HttpError; + Found: new() => HttpError; + SeeOther: new() => HttpError; + NotModified: new() => HttpError; + UseProxy: new() => HttpError; + Unused: new() => HttpError; + TemporaryRedirect: new() => HttpError; + PermanentRedirect: new() => HttpError; + BadRequest: new() => HttpError; + Unauthorized: new() => HttpError; + PaymentRequired: new() => HttpError; + Forbidden: new() => HttpError; + NotFound: new() => HttpError; + MethodNotAllowed: new() => HttpError; + NotAcceptable: new() => HttpError; + ProxyAuthenticationRequired: new() => HttpError; + RequestTimeout: new() => HttpError; + Conflict: new() => HttpError; + Gone: new() => HttpError; + LengthRequired: new() => HttpError; + PreconditionFailed: new() => HttpError; + PayloadTooLarge: new() => HttpError; + URITooLong: new() => HttpError; + UnsupportedMediaType: new() => HttpError; + RangeNotSatisfiable: new() => HttpError; + ExpectationFailed: new() => HttpError; + ImATeapot: new() => HttpError; + UnprocessableEntity: new() => HttpError; + Locked: new() => HttpError; + FailedDependency: new() => HttpError; + UnorderedCollection: new() => HttpError; + UpgradeRequired: new() => HttpError; + PreconditionRequired: new() => HttpError; + TooManyRequests: new() => HttpError; + RequestHeaderFieldsTooLarge: new() => HttpError; + UnavailableForLegalReasons: new() => HttpError; + InternalServerError: new() => HttpError; + NotImplemented: new() => HttpError; + BadGateway: new() => HttpError; + ServiceUnavailable: new() => HttpError; + GatewayTimeout: new() => HttpError; + HTTPVersionNotSupported: new() => HttpError; + VariantAlsoNegotiates: new() => HttpError; + InsufficientStorage: new() => HttpError; + LoopDetected: new() => HttpError; + BandwidthLimitExceeded: new() => HttpError; + NotExtended: new() => HttpError; + NetworkAuthenticationRequired: new() => HttpError; + } } - interface CreateHttpError { - // See https://github.com/Microsoft/TypeScript/issues/227#issuecomment-50092674 - [code: string]: new() => HttpError; - - (...args: Array): HttpError; - - Continue: new() => HttpError; - SwitchingProtocols: new() => HttpError; - Processing: new() => HttpError; - OK: new() => HttpError; - Created: new() => HttpError; - Accepted: new() => HttpError; - NonAuthoritativeInformation: new() => HttpError; - NoContent: new() => HttpError; - ResetContent: new() => HttpError; - PartialContent: new() => HttpError; - MultiStatus: new() => HttpError; - AlreadyReported: new() => HttpError; - IMUsed: new() => HttpError; - MultipleChoices: new() => HttpError; - MovedPermanently: new() => HttpError; - Found: new() => HttpError; - SeeOther: new() => HttpError; - NotModified: new() => HttpError; - UseProxy: new() => HttpError; - Unused: new() => HttpError; - TemporaryRedirect: new() => HttpError; - PermanentRedirect: new() => HttpError; - BadRequest: new() => HttpError; - Unauthorized: new() => HttpError; - PaymentRequired: new() => HttpError; - Forbidden: new() => HttpError; - NotFound: new() => HttpError; - MethodNotAllowed: new() => HttpError; - NotAcceptable: new() => HttpError; - ProxyAuthenticationRequired: new() => HttpError; - RequestTimeout: new() => HttpError; - Conflict: new() => HttpError; - Gone: new() => HttpError; - LengthRequired: new() => HttpError; - PreconditionFailed: new() => HttpError; - PayloadTooLarge: new() => HttpError; - URITooLong: new() => HttpError; - UnsupportedMediaType: new() => HttpError; - RangeNotSatisfiable: new() => HttpError; - ExpectationFailed: new() => HttpError; - ImATeapot: new() => HttpError; - UnprocessableEntity: new() => HttpError; - Locked: new() => HttpError; - FailedDependency: new() => HttpError; - UnorderedCollection: new() => HttpError; - UpgradeRequired: new() => HttpError; - PreconditionRequired: new() => HttpError; - TooManyRequests: new() => HttpError; - RequestHeaderFieldsTooLarge: new() => HttpError; - UnavailableForLegalReasons: new() => HttpError; - InternalServerError: new() => HttpError; - NotImplemented: new() => HttpError; - BadGateway: new() => HttpError; - ServiceUnavailable: new() => HttpError; - GatewayTimeout: new() => HttpError; - HTTPVersionNotSupported: new() => HttpError; - VariantAlsoNegotiates: new() => HttpError; - InsufficientStorage: new() => HttpError; - LoopDetected: new() => HttpError; - BandwidthLimitExceeded: new() => HttpError; - NotExtended: new() => HttpError; - NetworkAuthenticationRequired: new() => HttpError; - } - - var httpError: CreateHttpError; - export = httpError; + var createHttpError: createHttpError.CreateHttpError; + export = createHttpError; } diff --git a/icepick/icepick-tests.ts b/icepick/icepick-tests.ts new file mode 100644 index 0000000000..350e5f2dc8 --- /dev/null +++ b/icepick/icepick-tests.ts @@ -0,0 +1,177 @@ +/// +/// + + +import i = require("icepick"); + +"use strict"; // so attempted modifications of frozen objects will throw errors + +// freeze(collection) +{ + let coll = { + a: "foo", + b: [1, 2, 3], + c: { + d: "bar" + } + }; + + i.freeze(coll); +} + +// thaw(collection) +class Foo {} + +{ + let coll = i.freeze({ a: "foo", b: [1, 2, 3], c: { d: "bar" }, e: new Foo() }); + let thawed = i.thaw(coll); +} + +// assoc(collection, key, value) +{ + let coll = { a: 1, b: 2 }; + let newColl = i.assoc(coll, "b", 3); // {a: 1, b: 3} + + let arr = ["a", "b", "c"]; + let newArr = i.assoc(arr, 2, "d"); // ["a", "b", "d"] +} + +// alias: set(collection, key, value) +{ + let coll = { a: 1, b: 2 }; + let newColl = i.set(coll, "b", 3); // {a: 1, b: 3} + + let arr = ["a", "b", "c"]; + let newArr = i.set(arr, 2, "d"); // ["a", "b", "d"] +} + +// dissoc(collection, key) +{ + let coll = { a: 1, b: 2, c: 3 }; + let newColl = i.dissoc(coll, "b"); // {a: 1, c: 3} + + let arr = ["a", "b", "c"]; + let newArr = i.dissoc(arr, 2); // ["a", , "c"] +} + +// alias: unset(collection, key) +{ + let coll = { a: 1, b: 2, c: 3 }; + let newColl = i.unset(coll, "b"); // {a: 1, c: 3} + + let arr = ["a", "b", "c"]; + let newArr = i.unset(arr, 2); // ["a", , "c"] +} + +// assocIn(collection, path, value) +{ + let coll = { + a: "foo", + b: [1, 2, 3], + c: { + d: "bar" + } + }; + + let newColl = i.assocIn(coll, ["c", "d"], "baz"); + + let coll2 = {}; + let newColl2 = i.assocIn(coll2, ["a", "b", "c"], 1); +} + +// alias: setIn(collection, path, value) +{ + let coll = { + a: "foo", + b: [1, 2, 3], + c: { + d: "bar" + } + }; + + let newColl = i.setIn(coll, ["c", "d"], "baz"); + + let coll2 = {}; + let newColl2 = i.setIn(coll2, ["a", "b", "c"], 1); +} + +// getIn(collection, path) +{ + let coll = i.freeze([ + { a: 1 }, + { b: 2 } + ]); + + let result = i.getIn(coll, [1, "b"]); // 2 +} + +// updateIn(collection, path, callback) +{ + let coll = i.freeze([ + { a: 1 }, + { b: 2 } + ]); + + let newColl = i.updateIn(coll, [1, "b"], function(val: number) { + return val * 2; + }); // [ {a: 1}, {b: 4} ] +} + +// assign(coll1, coll2, ...) +{ + let obj1 = { a: 1, b: 2, c: 3 }; + let obj2 = { c: 4, d: 5 }; + + let result = i.assign(obj1, obj2); // {a: 1, b: 2, c: 4, d: 5} +} + +// merge(target, source) +{ + let defaults = { a: 1, c: { d: 1, e: [1, 2, 3], f: { g: 1 } } }; + let obj = { c: { d: 2, e: [2], f: null as any } }; + + let result1 = i.merge(defaults, obj); // {a: 1, c: {d: 2, e: [2]}, f: null} + + let obj2 = { c: { d: 2 } }; + let result2 = i.merge(result1, obj2); + + (result1 === result2); // true +} + +// arrays +{ + var a = [1]; + a = i.push(a, 2); // [1, 2]; + a = i.unshift(a, 0); // [0, 1, 2]; + a = i.pop(a); // [0, 1]; + a = i.shift(a); // [1]; +} +{ + i.map(function(v) { return v * 2 }, [1, 2, 3]); // [2, 4, 6] + + var removeEvens = _.partial(i.filter, function(v: number) { return v % 2; }); + + removeEvens([1, 2, 3]); // [1, 3] +} +{ + var arr = i.freeze([{ a: 1 }, { b: 2 }]); + + //ECMAScript 2015 + //arr.find(function(item) { return item.b != null; }); // {b: 2} +} + +// chain(coll) - not defined +{ + let o = { + a: [1, 2, 3], + b: { c: 1 }, + d: 4 + }; + + let result = i.chain(o) + .assocIn(["a", 2], 4) + .merge({ b: { c: 2, c2: 3 } }) + .assoc("e", 2) + .dissoc("d") + .value(); +} diff --git a/icepick/icepick.d.ts b/icepick/icepick.d.ts new file mode 100644 index 0000000000..85bbf0ae3d --- /dev/null +++ b/icepick/icepick.d.ts @@ -0,0 +1,72 @@ +// Type definitions for icepick v1.1.0 +// Project: https://github.com/aearly/icepick +// Definitions by: Nathan Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "icepick" { + export function freeze(collection: T): T; + export function thaw(collection: T): T; + export function assoc(collection: T, key: number | string, value: any): T; + export function dissoc(collection: T, key: number | string): T; + export function assocIn(collection: T, path: Array, value: any): T; + export function getIn(collection: any, path: Array): Result; + export function updateIn(collection: T, path: Array, callback: (value: V) => V): T; + + export {assoc as set}; + export {dissoc as unset}; + export {assocIn as setIn}; + + export function assign(target: T): T; + export function assign(target: T, source1: S1): (T & S1); + export function assign(target: T, s1: S1, s2: S2): (T & S1 & S2); + export function assign(target: T, s1: S1, s2: S2, s3: S3): (T & S1 & S2 & S3); + export function assign(target: T, s1: S1, s2: S2, s3: S3, s4: S4): (T & S1 & S2 & S3 & S4); + + export {assign as extend}; + + export function merge(target: T, source: S1): (T & S1); + + export function push(array: T[], element: T): T[]; + export function pop(array: T[]): T[]; + export function shift(array: T[]): T[]; + export function unshift(array: T[], element: T): T[]; + export function reverse(array: T[]): T[]; + export function sort(array: T[], compareFunction?: (a:T, b:T) => number): T[]; + export function splice(array: T[], start: number, deleteCount: number, ...items: T[]): T[]; + export function slice(array: T[], begin?: number, end?: number): T[]; + + export function map(fn: (value: T) => U, array: T[]): U[]; + export function filter(fn: (value: T) => boolean, array: T[]): T[]; + + interface IcepickWrapper { + value(): T; + + freeze(): IcepickWrapper; + thaw(): IcepickWrapper; + + assoc(key: number | string, value: any): IcepickWrapper; + set(key: number | string, value: any): IcepickWrapper; + + dissoc(key: number | string): IcepickWrapper; + unset(key: number | string): IcepickWrapper; + + assocIn(path: Array, value: any): IcepickWrapper; + setIn(path: Array, value: any): IcepickWrapper; + + getIn(collection: any, path: Array): IcepickWrapper; + updateIn(collection: T, path: Array, callback: (value: V) => V): IcepickWrapper; + + assign(source1: S1): IcepickWrapper; + assign(s1: S1, s2: S2): IcepickWrapper; + assign(s1: S1, s2: S2, s3: S3): IcepickWrapper; + assign(s1: S1, s2: S2, s3: S3, s4: S4): IcepickWrapper; + extend(source1: S1): IcepickWrapper; + extend(s1: S1, s2: S2): IcepickWrapper; + extend(s1: S1, s2: S2, s3: S3): IcepickWrapper; + extend(s1: S1, s2: S2, s3: S3, s4: S4): IcepickWrapper; + + merge(source: S1): IcepickWrapper; + } + + export function chain(target: T): IcepickWrapper; +} diff --git a/imap/imap-tests.ts b/imap/imap-tests.ts index 23f5f8f17e..8d9ce6cce8 100644 --- a/imap/imap-tests.ts +++ b/imap/imap-tests.ts @@ -124,7 +124,7 @@ var fs = require('fs'); openInbox(function(err : Error, box : IMAP.Box) { if (err) throw err; - imap.search([ 'UNSEEN', ['SINCE', 'May 20, 2010'] ], function(err : Error, results : string[]) { + imap.search([ 'UNSEEN', ['SINCE', 'May 20, 2010'] ], function(err : Error, results : number[]) { if (err) throw err; var f = imap.fetch(results, { bodies: '' }); f.on('message', function(msg : IMAP.ImapMessage, seqno : number) { diff --git a/imap/imap.d.ts b/imap/imap.d.ts index 1284919556..4b88279aef 100644 --- a/imap/imap.d.ts +++ b/imap/imap.d.ts @@ -5,32 +5,46 @@ /// - declare module IMAP { - + // The property names of these interfaces match the documentation (where type names were given). export interface Config { - user: string; // Username for plain-text authentication. - password: string; // Password for plain-text authentication. - xoauth?: string; // Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string). - xoauth2?: string; // Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string). - host?: string; // Hostname or IP address of the IMAP server. Default: "localhost" - port?: number; // Port number of the IMAP server. Default: 143 - tls?: boolean; // Perform implicit TLS connection? Default: false - tlsOptions?: Object; // Options object to pass to tls.connect() Default: (none) - autotls?: string; // Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never' - connTimeout?: number; // Number of milliseconds to wait for a connection to be established. Default: 10000 - authTimeout?: number; // Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000 - keepalive?: any; /* boolean|KeepAlive */ // Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true - debug?: Function; // If set, the function will be called with one argument, a string containing some debug info Default: (no debug output) + /** Username for plain-text authentication. */ + user: string; + /** Password for plain-text authentication. */ + password: string; + /** Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string). */ + xoauth?: string; + /** Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string). */ + xoauth2?: string; + /** Hostname or IP address of the IMAP server. Default: "localhost" */ + host?: string; + /** Port number of the IMAP server. Default: 143 */ + port?: number; + /** Perform implicit TLS connection? Default: false */ + tls?: boolean; + /** Options object to pass to tls.connect() Default: (none) */ + tlsOptions?: Object; + /** Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never' */ + autotls?: string; + /** Number of milliseconds to wait for a connection to be established. Default: 10000 */ + connTimeout?: number; + /** Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000 */ + authTimeout?: number; + /** Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true */ + keepalive?: any; /* boolean|KeepAlive */ + /** If set, the function will be called with one argument, a string containing some debug info Default: (no debug output) */ + debug?: Function; } - export interface KeepAlive { - interval?: number; // This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000 - idleInterval?: number; // This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins) - forceNoop?: boolean; // Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false + /** This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000 */ + interval?: number; + /** This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins) */ + idleInterval?: number; + /** Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false */ + forceNoop?: boolean; } // One of: @@ -41,69 +55,119 @@ declare module IMAP { // type MessageSource = string | string[] - - - export interface Box { - name: string; // The name of this mailbox. - readOnly?: boolean; // True if this mailbox was opened in read-only mode. (Only available with openBox() calls) - newKeywords: boolean; //True if new keywords can be added to messages in this mailbox. - uidvalidity: number; // A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened. - uidnext: number; // The uid that will be assigned to the next message that arrives at this mailbox. - flags: string[]; // array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available. - permFlags: string[]; // A list of flags that can be permanently added/removed to/from messages in this mailbox. - persistentUIDs: boolean; // Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible. - messages: { //Contains various message counts for this mailbox: - total: number; // Total number of messages in this mailbox. - new: number; // Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages). - unseen: number; // (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read). + /** The name of this mailbox. */ + name: string; + /** True if this mailbox was opened in read-only mode. (Only available with openBox() calls) */ + readOnly?: boolean; + /** True if new keywords can be added to messages in this mailbox. */ + newKeywords: boolean; + /** A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened. */ + uidvalidity: number; + /** The uid that will be assigned to the next message that arrives at this mailbox. */ + uidnext: number; + /** array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available. */ + flags: string[]; + /** A list of flags that can be permanently added/removed to/from messages in this mailbox. */ + permFlags: string[]; + /** Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible. */ + persistentUIDs: boolean; + /** Contains various message counts for this mailbox: */ + messages: { + /** Total number of messages in this mailbox. */ + total: number; + /** Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages). */ + new: number; + /** (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read). */ + unseen: number; }; } - - // Given in a 'message' event from ImapFetch - export interface ImapMessage extends NodeJS.EventEmitter { + export interface ImapMessageBodyInfo { + /** The specifier for this body (e.g. 'TEXT', 'HEADER.FIELDS (TO FROM SUBJECT)', etc). */ + which: string; + /** The size of this body in bytes. */ + size: number; } + export interface ImapMessageAttributes { + /** A 32-bit ID that uniquely identifies this message within its mailbox. */ + uid: number; + /** A list of flags currently set on this message. */ + flags: string[]; + /** The internal server date for the message. */ + date: Date; + /** The message's body structure (only set if requested with fetch()). */ + struct?: any[]; + /** The RFC822 message size (only set if requested with fetch()). */ + size?: number; + } + + /** Given in a 'message' event from ImapFetch */ + export interface ImapMessage extends NodeJS.EventEmitter { + on(event: string, listener: Function): this; + on(event: 'body', listener: (stream: NodeJS.ReadableStream, info: ImapMessageBodyInfo) => void): this; + on(event: 'attributes', listener: (attrs: ImapMessageAttributes) => void): this; + on(event: 'end', listener: () => void): this; + } export interface FetchOptions { - markSeen?: boolean; // Mark message(s) as read when fetched. Default: false - struct?: boolean; // Fetch the message structure. Default: false - envelope?: boolean; // Fetch the message envelope. Default: false - size?: boolean; // Fetch the RFC822 size. Default: false - modifiers?: Object; // Fetch modifiers defined by IMAP extensions. Default: (none) - bodies?: any; /* string|string[] */ // A string or Array of strings containing the body part section to fetch. Default: (none) Example sections: + /** Mark message(s) as read when fetched. Default: false */ + markSeen?: boolean; + /** Fetch the message structure. Default: false */ + struct?: boolean; + /** Fetch the message envelope. Default: false */ + envelope?: boolean; + /** Fetch the RFC822 size. Default: false */ + size?: boolean; + /** Fetch modifiers defined by IMAP extensions. Default: (none) */ + modifiers?: Object; + /** A string or Array of strings containing the body part section to fetch. Default: (none) Example sections: */ + bodies?: string | string[]; } - // Returned from fetch() + /** Returned from fetch() */ export interface ImapFetch extends NodeJS.EventEmitter { + on(event: string, listener: Function): this; + on(event: 'message', listener: (message: ImapMessage, seqno: number) => void): this; + on(event: 'error', listener: (error: Error) => void): this; + once(event: string, listener: Function): this; + once(event: 'error', listener: (error: Error) => void): this; } - + export interface Folder { - attribs: string[]; - delimiter: string; - children: Folder[]; - parent: Folder; + /** mailbox attributes. An attribute of 'NOSELECT' indicates the mailbox cannot be opened */ + attribs: string[]; + /** hierarchy delimiter for accessing this mailbox's direct children. */ + delimiter: string; + /** an object containing another structure similar in format to this top level, otherwise null if no children */ + children: MailBoxes; + /** pointer to parent mailbox, null if at the top level */ + parent: Folder; } export interface MailBoxes { - [name: string] : Folder; + [name: string]: Folder; } export interface AppendOptions { - mailbox?: string; // The name of the mailbox to append the message to. Default: the currently open mailbox - flags?: any; /* string|string[] */ // A single flag (e.g. 'Seen') or an array of flags (e.g. ['Seen', 'Flagged']) to append to the message. Default: (no flags) - date?: Date; // What to use for message arrival date/time. Default: (current date/time) + /** The name of the mailbox to append the message to. Default: the currently open mailbox */ + mailbox?: string; + /** A single flag (e.g. 'Seen') or an array of flags (e.g. ['Seen', 'Flagged']) to append to the message. Default: (no flags) */ + flags?: any; /* string|string[] */ + /** What to use for message arrival date/time. Default: (current date/time) */ + date?: Date; } + export interface MessageFunctions { + /** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. + + The following message flags are valid types that do not have arguments: - // search() criteria - /** - // The following message flags are valid types that do not have arguments: ALL: void; // All messages. ANSWERED: void; // Messages with the Answered flag set. DELETED: void; // Messages with the Deleted flag set. @@ -118,8 +182,8 @@ declare module IMAP { UNDRAFT: void; // Messages that do not have the Draft flag set. UNFLAGGED: void; // Messages that do not have the Flagged flag set. UNSEEN: void; // Messages that do not have the Seen flag set. - - // The following are valid types that require string value(s): + + The following are valid types that require string value(s): BCC: any; // Messages that contain the specified string in the BCC field. CC: any; // Messages that contain the specified string in the CC field. @@ -130,143 +194,149 @@ declare module IMAP { TEXT: any; // Messages that contain the specified string in the header OR the message body. KEYWORD: any; // Messages with the specified keyword set. HEADER: any; // Requires two string values, with the first being the header name and the second being the value to search for. If this second string is empty, all messages that contain the given header name will be returned. - // The following are valid types that require a string parseable by JavaScripts Date object OR a Date instance: + + The following are valid types that require a string parseable by JavaScripts Date object OR a Date instance: + BEFORE: any; // Messages whose internal date (disregarding time and timezone) is earlier than the specified date. ON: any; // Messages whose internal date (disregarding time and timezone) is within the specified date. SINCE: any; // Messages whose internal date (disregarding time and timezone) is within or later than the specified date. SENTBEFORE: any; // Messages whose Date header (disregarding time and timezone) is earlier than the specified date. SENTON: any; // Messages whose Date header (disregarding time and timezone) is within the specified date. SENTSINCE: any; // Messages whose Date header (disregarding time and timezone) is within or later than the specified date. - //The following are valid types that require one Integer value: + + The following are valid types that require one Integer value: + LARGER: number; // Messages with a size larger than the specified number of bytes. SMALLER: number; // Messages with a size smaller than the specified number of bytes. - // The following are valid criterion that require one or more Integer values: + + The following are valid criterion that require one or more Integer values: + UID: any; // Messages with UIDs corresponding to the specified UID set. Ranges are permitted (e.g. '2504:2507' or '*' or '2504:*'). - */ - - - export interface MessageFunctions { - // Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. - search(criteria : any[], callback : (error : Error, uids : string[]) => void) : void; - // Fetches message(s) in the currently open mailbox. - fetch(source : any /* MessageSource */, options : FetchOptions) : ImapFetch; - // Copies message(s) in the currently open mailbox to another mailbox. - copy(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void; - // Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. - move(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void; - // Adds flag(s) to message(s). - addFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Removes flag(s) from message(s). - delFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Sets the flag(s) for message(s). - setFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. - addKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - //Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. - delKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - // Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. - setKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - // Checks if the server supports the specified capability. - serverSupports(capability : string) : boolean; + */ + search(criteria: any[], callback: (error: Error, uids: number[]) => void): void; + /** Fetches message(s) in the currently open mailbox; source can be a single message identifier, a message identifier range (e.g. '2504:2507' or '*' or '2504:*'), an array of message identifiers, or an array of message identifier ranges. */ + fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch; + /** Copies message(s) in the currently open mailbox to another mailbox. */ + copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void; + /** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */ + move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void; + /** Adds flag(s) to message(s). */ + addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Removes flag(s) from message(s). */ + delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Sets the flag(s) for message(s). */ + setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */ + addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */ + delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */ + setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Checks if the server supports the specified capability. */ + serverSupports(capability: string): boolean; } - - - export class Connection implements NodeJS.EventEmitter, MessageFunctions { /** @constructor */ - constructor(config : Config); - + constructor(config: Config); + // from NodeJS.EventEmitter - addListener(event: string, listener: Function): NodeJS.EventEmitter; - on(event: string, listener: Function): NodeJS.EventEmitter; - once(event: string, listener: Function): NodeJS.EventEmitter; - removeListener(event: string, listener: Function): NodeJS.EventEmitter; - removeAllListeners(event?: string): NodeJS.EventEmitter; - setMaxListeners(n: number): void; + addListener(event: string, listener: Function): this; + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + removeListener(event: string, listener: Function): this; + removeAllListeners(event?: string): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; - + listenerCount(type: string): number; + // from MessageFunctions - // Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. - search(criteria : any[], callback : (error : Error, uids : string[]) => void) : void; - // Fetches message(s) in the currently open mailbox. - fetch(source : any /* MessageSource */, options : FetchOptions) : ImapFetch; - // Copies message(s) in the currently open mailbox to another mailbox. - copy(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void; - // Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. - move(source : any /* MessageSource */, mailboxName : string, callback : (error : Error) => void) : void; - // Adds flag(s) to message(s). - addFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Removes flag(s) from message(s). - delFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Sets the flag(s) for message(s). - setFlags(source : any /* MessageSource */, flags : any, callback : (error : Error) => void) : void; - // Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. - addKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - //Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. - delKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - // Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. - setKeywords(source : any /* MessageSource */, keywords : any /* string|string[] */, callback : (error : Error) => void) : void; - // Checks if the server supports the specified capability. - serverSupports(capability : string) : boolean; - - // Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values. - static parseHeader(rawHeader: string, disableAutoDecode? : boolean) : any; - - state: string; // The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated'). - delimiter: string; // The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey. - namespaces: { // Contains information about each namespace type (if supported by the server) with the following properties: - personal: any[]; // Mailboxes that belong to the logged in user. - other: any[]; // Mailboxes that belong to other users that the logged in user has access to. - shared: any[]; // Mailboxes that are accessible by any logged in user. + /** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. */ + search(criteria: any[], callback: (error: Error, uids: number[]) => void): void; + /** Fetches message(s) in the currently open mailbox. */ + fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch; + /** Copies message(s) in the currently open mailbox to another mailbox. */ + copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void; + /** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */ + move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void; + /** Adds flag(s) to message(s). */ + addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Removes flag(s) from message(s). */ + delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Sets the flag(s) for message(s). */ + setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void; + /** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */ + addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */ + delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */ + setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void; + /** Checks if the server supports the specified capability. */ + serverSupports(capability: string): boolean; + + /** Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values. */ + static parseHeader(rawHeader: string, disableAutoDecode?: boolean): {[index: string]: string[]}; + + /** The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated'). */ + state: string; + /** The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey. */ + delimiter: string; + /** Contains information about each namespace type (if supported by the server) with the following properties: */ + namespaces: { + /** Mailboxes that belong to the logged in user. */ + personal: any[]; + /** Mailboxes that belong to other users that the logged in user has access to. */ + other: any[]; + /** Mailboxes that are accessible by any logged in user. */ + shared: any[]; }; + /** + seq exposes the search() ... serverSupports() set of commands, but returns sequence number(s) instead of UIDs. + */ seq: MessageFunctions; /** Attempts to connect and authenticate with the IMAP server. */ - connect() : void; + connect(): void; /** Closes the connection to the server after all requests in the queue have been sent. */ - end() : void; + end(): void; /** Immediately destroys the connection to the server. */ - destroy() : void; + destroy(): void; /** Opens a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. modifiers is used by IMAP extensions. */ - openBox(mailboxName : string, callback : (error : Error, mailbox: Box) => void) : void; - openBox(mailboxName : string, openReadOnly : boolean, callback : (error : Error, mailbox: Box) => void) : void; - openBox(mailboxName : string, openReadOnly : boolean, modifiers : Object, callback : (error : Error, mailbox: Box) => void) : void; + openBox(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void; + openBox(mailboxName: string, openReadOnly: boolean, callback: (error: Error, mailbox: Box) => void): void; + openBox(mailboxName: string, openReadOnly: boolean, modifiers: Object, callback: (error: Error, mailbox: Box) => void): void; /** Closes the currently open mailbox. If autoExpunge is true, any messages marked as Deleted in the currently open mailbox will be removed if the mailbox was NOT opened in read-only mode. If autoExpunge is false, you disconnect, or you open another mailbox, messages marked as Deleted will NOT be removed from the currently open mailbox. */ - closeBox(callback : (error : Error) => void) : void; - closeBox(autoExpunge : boolean, callback : (error : Error) => void) : void; + closeBox(callback: (error: Error) => void): void; + closeBox(autoExpunge: boolean, callback: (error: Error) => void): void; /** Creates a new mailbox on the server. mailboxName should include any necessary prefix/path. */ - addBox(mailboxName : string, callback : (error : Error) => void) : void; + addBox(mailboxName: string, callback: (error: Error) => void): void; /** Removes a specific mailbox that exists on the server. mailboxName should including any necessary prefix/path. */ - delBox(mailboxName : string, callback : (error : Error, uids : string[]) => void) : void; + delBox(mailboxName: string, callback: (error: Error) => void): void; /** Renames a specific mailbox that exists on the server. Both oldMailboxName and newMailboxName should include any necessary prefix/path. Note: Renaming the 'INBOX' mailbox will instead cause all messages in 'INBOX' to be moved to the new mailbox. */ - renameBox(oldMailboxName : string, newMailboxName : string, callback : (error : Error, mailbox: Box) => void) : void; + renameBox(oldMailboxName: string, newMailboxName: string, callback: (error: Error, mailbox: Box) => void): void; /** Subscribes to a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */ - subscribeBox(mailboxName : string, callback : (error : Error) => void) : void; + subscribeBox(mailboxName: string, callback: (error: Error) => void): void; /** Unsubscribes from a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */ - unsubscribeBox(mailboxName : string, callback : (error : Error) => void) : void; + unsubscribeBox(mailboxName: string, callback: (error: Error) => void): void; /** Fetches information about a mailbox other than the one currently open. Note: There is no guarantee that this will be a fast operation on the server. Also, do not call this on the currently open mailbox. */ - status(mailboxName : string, callback : (error : Error, mailbox: Box) => void) : void; + status(mailboxName: string, callback: (error: Error, mailbox: Box) => void): void; /** Obtains the full list of mailboxes. If nsPrefix is not specified, the main personal namespace is used. */ - getBoxes(callback : (error : Error, mailboxes: MailBoxes) => void) : void; - getBoxes(nsPrefix : string, callback : (error : Error, mailboxes: MailBoxes) => void) : void; + getBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void; + getBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void; /** Obtains the full list of subscribed mailboxes. If nsPrefix is not specified, the main personal namespace is used. */ - getSubscribedBoxes(callback : (error : Error, mailboxes: MailBoxes) => void) : void; - getSubscribedBoxes(nsPrefix : string, callback : (error : Error, mailboxes: MailBoxes) => void) : void; + getSubscribedBoxes(callback: (error: Error, mailboxes: MailBoxes) => void): void; + getSubscribedBoxes(nsPrefix: string, callback: (error: Error, mailboxes: MailBoxes) => void): void; /** Permanently removes all messages flagged as Deleted in the currently open mailbox. If the server supports the 'UIDPLUS' capability, uids can be supplied to only remove messages that both have their uid in uids and have the \Deleted flag set. Note: At least on Gmail, performing this operation with any currently open mailbox that is not the Spam or Trash mailbox will merely archive any messages marked as Deleted (by moving them to the 'All Mail' mailbox). */ - expunge(callback : (error : Error) => void) : void; - expunge(uids : any /* MessageSource */, callback : (error : Error) => void) : void; - // Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are: - append(msgData : any, callback : (error : Error) => void) : void; - append(msgData : any, options : AppendOptions, callback : (error : Error) => void) : void; + expunge(callback: (error: Error) => void): void; + expunge(uids: any /* MessageSource */, callback: (error: Error) => void): void; + /** Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are: */ + append(msgData: any, callback: (error: Error) => void): void; + append(msgData: any, options: AppendOptions, callback: (error: Error) => void): void; } - } - declare module "imap" { - var out: typeof IMAP.Connection; - export = out; } diff --git a/intro.js/intro.js-tests.ts b/intro.js/intro.js-tests.ts index b8e8126ae9..0ec5938f5c 100644 --- a/intro.js/intro.js-tests.ts +++ b/intro.js/intro.js-tests.ts @@ -3,6 +3,8 @@ var intro = introJs(); intro.setOption('doneLabel', 'Next page'); +intro.setOption('overlayOpacity', 50); +intro.setOption('showProgress', true); intro.setOptions({ steps: [ { diff --git a/intro.js/intro.js.d.ts b/intro.js/intro.js.d.ts index 15a73f5178..6763124ba9 100644 --- a/intro.js/intro.js.d.ts +++ b/intro.js/intro.js.d.ts @@ -1,20 +1,13 @@ -// Type definitions for intro.js 1.0.0 +// Type definitions for intro.js 1.1.1 // Project: https://github.com/usablica/intro.js // Definitions by: Maxime Fabre // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module IntroJs { - enum Positions { - top, - left, - right, - bottom - } - interface Step { intro: string; - element?: string|HTMLElement; - position?: string|Positions; + element?: string|HTMLElement|Element; + position?: string; } interface Options { @@ -49,7 +42,7 @@ declare module IntroJs { refresh(): IntroJs; - setOption(option: string, value: string|number): IntroJs; + setOption(option: string, value: string|number|boolean): IntroJs; setOptions(options: Options): IntroJs; onexit(callback: Function): IntroJs; diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index c68846715e..8491fc13f8 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -149,6 +149,7 @@ class IonicTestController { ionicModalController.initialize(modalOptions); ionicModalController.show().then(() => console.log("shown modal")) ionicModalController.hide().then(() => console.log("hid modal")) + ionicModalController.remove().then(() => console.log("removed modal")) var isShown: boolean = ionicModalController.isShown(); this.$ionicModal.fromTemplateUrl("templateUrl", modalOptions) @@ -199,8 +200,9 @@ class IonicTestController { }; var ionicPopoverController: ionic.popover.IonicPopoverController = this.$ionicPopover.fromTemplate("template", popoverOptions); ionicPopoverController.initialize(popoverOptions); - ionicPopoverController.show(angular.element("body")).then(() => console.log("shown popover")) - ionicPopoverController.hide().then(() => console.log("hid popover")) + ionicPopoverController.show(angular.element("body")).then(() => console.log("shown popover")); + ionicPopoverController.hide().then(() => console.log("hid popover")); + ionicPopoverController.remove().then(() => console.log("removed popover")); var isShown: boolean = ionicPopoverController.isShown(); this.$ionicPopover.fromTemplateUrl("templateUrl", popoverOptions) @@ -360,6 +362,8 @@ class IonicTestController { this.$ionicTabsDelegate.select(1); var selectedIndex: number = this.$ionicTabsDelegate.selectedIndex(); var ionicTabsDelegate: ionic.tabs.IonicTabsDelegate = this.$ionicTabsDelegate.$getByHandle("handle"); + this.$ionicTabsDelegate.showBar(true); + var isBarShown: boolean = this.$ionicTabsDelegate.showBar(); } private testUtility(): void { var {top: number, left: number, width: number, height: number} = this.$ionicPositionService.position(angular.element("body")); diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index bb009df513..a767b851bf 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -174,6 +174,7 @@ declare module ionic { initialize(options: IonicModalOptions): void; show(): ng.IPromise; hide(): ng.IPromise; + remove(): ng.IPromise; isShown(): boolean; } @@ -237,6 +238,7 @@ declare module ionic { show($event?: any): ng.IPromise; hide(): ng.IPromise; isShown(): boolean; + remove(): ng.IPromise; } interface IonicPopoverOptions { scope?: any; @@ -343,6 +345,7 @@ declare module ionic { select(index: number): void; selectedIndex(): number; $getByHandle(handle: string): IonicTabsDelegate; + showBar(show?: boolean): boolean; } } module utility { diff --git a/jade/jade-tests.ts b/jade/jade-tests.ts index 8a2b6b48de..6b4774021f 100644 --- a/jade/jade-tests.ts +++ b/jade/jade-tests.ts @@ -1,10 +1,10 @@ /// -import jade from 'jade'; +import * as jade from 'jade'; jade.compile("b")(); jade.compileFile("foo.jade", {})(); jade.compileClient("a")({ a: 1 }); jade.compileClientWithDependenciesTracked("test").body(); jade.render("h1",{}); -jade.renderFile("foo.jade"); \ No newline at end of file +jade.renderFile("foo.jade"); diff --git a/jade/jade.d.ts b/jade/jade.d.ts index 9615fa8c87..0764006e56 100644 --- a/jade/jade.d.ts +++ b/jade/jade.d.ts @@ -4,16 +4,13 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module 'jade' { - module jade { - function compile(template: string, options?: any): (locals?: any) => string; - function compileFile(path: string, options?: any): (locals?: any) => string; - function compileClient(template: string, options?: any): (locals?: any) => string; - function compileClientWithDependenciesTracked(template: string, options?: any): { - body: (locals?: any) => string; - dependencies: string[]; - }; - function render(template: string, options?: any): string; - function renderFile(path: string, options?: any): string; - } - export default jade; + export function compile(template: string, options?: any): (locals?: any) => string; + export function compileFile(path: string, options?: any): (locals?: any) => string; + export function compileClient(template: string, options?: any): (locals?: any) => string; + export function compileClientWithDependenciesTracked(template: string, options?: any): { + body: (locals?: any) => string; + dependencies: string[]; + }; + export function render(template: string, options?: any): string; + export function renderFile(path: string, options?: any): string; } diff --git a/jake/jake.d.ts b/jake/jake.d.ts index 95614374cc..84d5c50790 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -231,9 +231,11 @@ declare module jake{ once(event: string, listener: Function): NodeJS.EventEmitter; removeListener(event: string, listener: Function): NodeJS.EventEmitter; removeAllListeners(event?: string): NodeJS.EventEmitter; - setMaxListeners(n: number): void; + setMaxListeners(n: number): NodeJS.EventEmitter; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; value: any; } diff --git a/jasmine-jquery/jasmine-jquery.d.ts b/jasmine-jquery/jasmine-jquery.d.ts index 903e3f7e29..0e1f2b82b1 100644 --- a/jasmine-jquery/jasmine-jquery.d.ts +++ b/jasmine-jquery/jasmine-jquery.d.ts @@ -195,8 +195,8 @@ declare module jasmine { * // returns true * expect($('

    header

    ')).toContainHtml('
      ') */ - //toContainHtml(html: string): boolean; - + toContainHtml(html: string): boolean; + /** * Check if DOM element has the given Text. * @param text Accepts a string or regular expression @@ -213,8 +213,8 @@ declare module jasmine { * // returns true * expect($('

        header

        ')).toContainText('header') */ - //toContainText(text: string): boolean; - + toContainText(text: string): boolean; + /** * Check if DOM element has the given value. * This can only be applied for element on with jQuery val() can be called. diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index ed85914884..46a1937f43 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -281,7 +281,7 @@ declare module jasmine { toBe(expected: any, expectationFailOutput?: any): boolean; toEqual(expected: any, expectationFailOutput?: any): boolean; - toMatch(expected: any, expectationFailOutput?: any): boolean; + toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean; toBeDefined(expectationFailOutput?: any): boolean; toBeUndefined(expectationFailOutput?: any): boolean; toBeNull(expectationFailOutput?: any): boolean; @@ -291,13 +291,12 @@ declare module jasmine { toHaveBeenCalled(): boolean; toHaveBeenCalledWith(...params: any[]): boolean; toContain(expected: any, expectationFailOutput?: any): boolean; - toBeLessThan(expected: any, expectationFailOutput?: any): boolean; - toBeGreaterThan(expected: any, expectationFailOutput?: any): boolean; - toBeCloseTo(expected: any, precision: any, expectationFailOutput?: any): boolean; - toContainHtml(expected: string): boolean; - toContainText(expected: string): boolean; + toBeLessThan(expected: number, expectationFailOutput?: any): boolean; + toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean; + toBeCloseTo(expected: number, precision: any, expectationFailOutput?: any): boolean; toThrow(expected?: any): boolean; - toThrowError(expected?: any, message?: string): boolean; + toThrowError(message?: string | RegExp): boolean; + toThrowError(expected?: Error, message?: string | RegExp): boolean; not: Matchers; Any: Any; diff --git a/javascript-bignum/javascript-bignum-tests.ts b/javascript-bignum/javascript-bignum-tests.ts new file mode 100644 index 0000000000..57555fcce2 --- /dev/null +++ b/javascript-bignum/javascript-bignum-tests.ts @@ -0,0 +1,21 @@ +/// +let m = SchemeNumber("1"); +let n = SchemeNumber(2); + +let sum: SchemeNumber = SchemeNumber.fn["+"](m, n); +sum = SchemeNumber.fn["+"](m, 1); +sum = SchemeNumber.fn["+"](m, "12"); +sum = SchemeNumber.fn["+"]("12", "25"); + +let floored: SchemeNumber = SchemeNumber.fn.floor(m); + +let str: string = floored.toString(16); +str = floored.toExponential(2); +str = floored.toPrecision(2); +str = floored.toFixed(2); + +let num: number = maxIntegerDigits; +num = VERSION[0]; +num = VERSION.length; + +raise("fake error", "This is not really an error", m); diff --git a/javascript-bignum/javascript-bignum.d.ts b/javascript-bignum/javascript-bignum.d.ts new file mode 100644 index 0000000000..a088837d10 --- /dev/null +++ b/javascript-bignum/javascript-bignum.d.ts @@ -0,0 +1,53 @@ +// Type definitions for javascript-bignum +// Project: https://github.com/jtobey/javascript-bignum +// Definitions by: Nathan Shively-Sanders +// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Documentation: http://john-edwin-tobey.org/Scheme/javascript-bignum/docs/files/schemeNumber-js.html + +// This version only includes typing for schemeNumber, not the full library +declare type SchemeOperator = (...args: (string | SchemeNumber | number)[]) => SchemeNumber; +declare var VERSION: number[]; +declare function raise(conditionType: string, message: string, ...irritants: any[]): void; +declare var maxIntegerDigits: number; +declare interface SchemeFn { + [opname: string]: SchemeOperator; + inexact: SchemeOperator; + exact: SchemeOperator; + max: SchemeOperator; + min: SchemeOperator; + abs: SchemeOperator; + div: SchemeOperator; + mod: SchemeOperator; + div0: SchemeOperator; + mod0: SchemeOperator; + gcd: SchemeOperator; + lcm: SchemeOperator; + numerator: SchemeOperator; + denominator: SchemeOperator; + floor: SchemeOperator; + ceiling: SchemeOperator; + truncate: SchemeOperator; + round: SchemeOperator; + rationalize: SchemeOperator; + exp: SchemeOperator; + log: SchemeOperator; + sin: SchemeOperator; + cos: SchemeOperator; + tan: SchemeOperator; + asin: SchemeOperator; + acos: SchemeOperator; + atan: SchemeOperator; + sqrt: SchemeOperator; + expt: SchemeOperator; + magnitude: SchemeOperator; + angle: SchemeOperator; +} +declare interface SchemeNumber { + (value: string | number): SchemeNumber; + toString(radix: number): string; + toFixed(fractionDigits: number): string; + toExponential(fractionDigits: number): string; + toPrecision(precision: number): string; + fn: SchemeFn; +} +declare var SchemeNumber: SchemeNumber; diff --git a/jee-jsf/jsf-tests.ts b/jee-jsf/jsf-tests.ts new file mode 100644 index 0000000000..76815bf9ee --- /dev/null +++ b/jee-jsf/jsf-tests.ts @@ -0,0 +1,27 @@ +/// + +function callbackWithoutData() { + +} + +function callback(data:jsf.ajax.RequestData) { + +} + +class RequestOptionsImpl implements jsf.ajax.RequestOptions { + execute = "@all"; + render = "@none"; +} + + +jsf.ajax.addOnEvent(callbackWithoutData); +jsf.ajax.addOnEvent(callback); + +jsf.ajax.addOnError(callbackWithoutData); +jsf.ajax.addOnError(callback); + +jsf.ajax.request("someSource"); +jsf.ajax.request("someSource", "change"); +jsf.ajax.request("someSource", "change", new RequestOptionsImpl()); + +jsf.ajax.response("someRequestObject", {context: "someContextObject"}); diff --git a/jee-jsf/jsf.d.ts b/jee-jsf/jsf.d.ts new file mode 100644 index 0000000000..d19dafe0eb --- /dev/null +++ b/jee-jsf/jsf.d.ts @@ -0,0 +1,72 @@ +// Type definitions for for the JSF 2.0 Ajax request API +// Project: https://docs.oracle.com/cd/E17802_01/j2ee/javaee/javaserverfaces/2.0/docs/js-api/symbols/jsf.ajax.html +// Definitions by: Lars Michaelis and Stephan Zerhusen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module jsf { + module ajax { + + interface RequestData { + status: string; + description: string; + } + + interface RequestOptions { + /** + * space seperated list of client identifiers + */ + execute?: String; + + /** + * space seperated list of client identifiers + */ + render?: String; + + /** + * function to callback for event + * @param callback the callback function + */ + onevent?(callback:(data:RequestData) => void): void; + + /** + * function to callback for error + * @param callback the callback function + */ + onerror?(callback:(data:RequestData) => void): void; + + /** + * object containing parameters to include in the request + */ + params?: any; + } + + /** + * Register a callback for event handling. + * @param callback a reference to a function to call on an event + */ + function addOnEvent(callback:(data:RequestData) => void):void; + + /** + * Register a callback for error handling. + * @param callback a reference to a function to call on an error + */ + function addOnError(callback:(data:RequestData) => void):void; + + /** + * Send an asynchronous Ajax request to the server. + * @param source The DOM element that triggered this Ajax request, or an id string of the element to use as the triggering element. + * @param event The DOM event that triggered this Ajax request. The event argument is optional. + * @param options The set of available options that can be sent as request parameters to control client and/or server side request processing. + */ + function request(source:any, event?:String, options?:RequestOptions):void; + + /** + * Receive an Ajax response from the server. + * @param request The XMLHttpRequest instance that contains the status code and response message from the server. + * @param context An object containing the request context, including the following properties: the source element, per call onerror callback function, and per call onevent callback function. + * @throws EmptyResponse error if request contains no data + */ + function response(request:any, context:any):void; + + } +} diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 9e631e3e37..c8c05bf872 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -579,7 +579,9 @@ 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(); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 2e230dcb86..c774b36ab4 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -1,6 +1,6 @@ // Type definitions for joi v4.6.0 // Project: https://github.com/spumko/joi -// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig +// Definitions by: Bart van der Schoor , Laurence Dougal Myers , Christopher Glantschnig , David Broder-Rodgers // Definitions: https://github.com/borisyankov/DefinitelyTyped // TODO express type of Schema in a type-parameter (.default, .valid, .example etc) @@ -584,8 +584,8 @@ declare module 'joi' { /** * Verifies an assertion where. */ - assert(ref: string, schema: Schema, message: string): ObjectSchema; - assert(ref: Reference, schema: Schema, message: string): ObjectSchema; + 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). diff --git a/jointjs/jointjs.d.ts b/jointjs/jointjs.d.ts index 1c7e915715..cbabf0095a 100644 --- a/jointjs/jointjs.d.ts +++ b/jointjs/jointjs.d.ts @@ -60,12 +60,12 @@ declare module joint { } interface IOptions { - width: number; - height: number; - gridSize: number; - perpendicularLinks: boolean; - elementView: ElementView; - linkView: LinkView; + width?: number; + height?: number; + gridSize?: number; + perpendicularLinks?: boolean; + elementView?: ElementView; + linkView?: LinkView; } class Paper extends Backbone.View { diff --git a/jquery-cropbox/jquery-cropbox-tests.ts b/jquery-cropbox/jquery-cropbox-tests.ts index e8db3847c6..6e54848af8 100644 --- a/jquery-cropbox/jquery-cropbox-tests.ts +++ b/jquery-cropbox/jquery-cropbox-tests.ts @@ -37,3 +37,9 @@ cropboxWithOptions.update(); cropboxWithOptions.getDataURL(); cropboxWithOptions.getBlob(); cropboxWithOptions.remove(); + +cropboxWithOptions.on("cropbox",(e: Event, data: any, img: jQueryCropBox.Cropbox) => { + + //DoStuff + +}); diff --git a/jquery-cropbox/jquery-cropbox.d.ts b/jquery-cropbox/jquery-cropbox.d.ts index 82b550bf30..3f7c57a20e 100644 --- a/jquery-cropbox/jquery-cropbox.d.ts +++ b/jquery-cropbox/jquery-cropbox.d.ts @@ -103,7 +103,14 @@ declare module jQueryCropBox { * Remove the cropbox functionality from the image. */ remove(): void; + + /** + * Attach an event handler function for one event on the Crop Box + */ + on(event: string, callback: jQueryCropBox.EventCallback): void; } + + type EventCallback = (e: Event, data: any, img: jQueryCropBox.Cropbox) => void; } interface JQuery { diff --git a/jquery.mmenu/jquery.mmenu-tests.ts b/jquery.mmenu/jquery.mmenu-tests.ts new file mode 100644 index 0000000000..ae52793d62 --- /dev/null +++ b/jquery.mmenu/jquery.mmenu-tests.ts @@ -0,0 +1,85 @@ +/// +/// + + +// -------------------------------------------------------- +// ---------------- TEST DEFAULT OPTIONS ------------------ +// -------------------------------------------------------- + +var menu: JQuery = $("#my-menu"); +menu.mmenu( + // options + { + extensions: [], + navbar: { + add: true, + title: "Menu", + titleLink: "parent" + }, + onClick: { + close: true, + preventDefault: false, + setSelected: false + }, + slidingSubmenus: true + }, + // configurations + { + classNames: { + divider: "Divider", + inset: "Inset", + panel: "Panel", + selected: "Selected", + vertical: "vertical" + }, + clone: false, + openingInterval: 25, + panelNodetype: "div, ul, ol", + transitionDuration: 400 + } +); + + +// -------------------------------------------------------- +// ------------------- TEST MMENU API --------------------- +// -------------------------------------------------------- + +var api = menu.data("mmenu"); +var myPanel: JQuery = $("#panel"); +var listItem: JQuery = $(".list-item"); + +api.closeAllPanels(); +api.bind("closeAllPanels", function() { + console.log("close all opened panels and go back to the first panel."); +}); + +api.closePanel(myPanel); +api.bind("closePanel", function(panel) { + console.log("close this ", panel); +}); + +api.getInstance(); +api.bind("getInstance", function() { + console.log("get the class instance for the menu."); +}); + +api.init(myPanel); +api.bind("init", function(panel) { + console.log("method to (re)initialize a newly added ", panel); +}); + +api.openPanel(myPanel); +api.bind("openPanel", function(panel) { + console.log("This panel is now opened ", panel); +}); + +api.setSelected(listItem, true); +api.bind("setSelected", function(listItem, selected) { + console.log("set or unset a list item as selected ", listItem); + console.log("has selected ", selected); +}); + +api.update(); +api.bind("update", function() { + console.log("update the appearance for the menu"); +}); diff --git a/jquery.mmenu/jquery.mmenu.d.ts b/jquery.mmenu/jquery.mmenu.d.ts new file mode 100644 index 0000000000..a502c37cdb --- /dev/null +++ b/jquery.mmenu/jquery.mmenu.d.ts @@ -0,0 +1,242 @@ +// Type definitions for jQuery mmenu v5.5.3 +// Project: http://mmenu.frebsite.nl/ +// Definitions by: John Gouigouix +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module JQueryMmenu { + + interface NavbarOptions { + + /** + * Whether or not to add a navbar above the panels. + * Default: true + */ + add?: boolean; + + /** + * The title above the main panel. + * Default: "Menu" + */ + title?: string; + + /** + * The type of link to set for the title. + * Possible values: "parent", "anchor" or "none". + * Default: "parent" + */ + titleLink?: string; + + } + + interface OnclickOptions { + + /** + * Whether or not the menu should close after clicking a link inside it. + * The default value varies per link: true if the default behavior for + * the clicked link is prevented, false otherwise. + * Default: null + */ + close?: boolean | any; + + /** + * Whether or not to prevent the default behavior for the clicked link. + * The default value varies per link: true if its href is equal to + * or starts with a hash (#), false otherwise. + * Default: null + */ + preventDefault?: boolean | any; + + /** + * Whether or not the clicked link should be visibly "selected". + * Default: true + */ + setSelected?: boolean | any; + + } + + interface Options { + + /** + * A collection of extension names to enable for the menu. + * You'll need this option when using the extensions. + * Default: [] + */ + extensions?: Array; + + /** + * navbar options + */ + navbar?: NavbarOptions; + + /** + * onClick options + */ + onClick?: OnclickOptions; + + /** + * Whether or not submenus should come sliding in from the right. + * If false, submenus expand below their parent. + * To expand a single submenu below its parent item, add the class "Vertical" to it. + * Default: true + */ + slidingSubmenus?: boolean; + + } + + interface ClassnamesConfigurations { + + /** + * The classname on a LI that should be displayed as a divider. + * Default: "Divider" + */ + divider?: string; + + /** + * The classname on a submenu (a nested UL) that should be displayed as a default list. + * Default: "Inset" + */ + inset?: string; + + /** + * The classname on an element (for example a DIV) that should be considered to be a panel. + * Only applies if the "isMenu" option is set to false. + * Default: "Panel" + */ + panel?: string; + + /** + * The classname on the LI that should be displayed as selected. + * Default: "Selected" + */ + selected?: string; + + /** + * The classname on a submenu (a nested UL) that should expand below + * their parent instead of slide in from the right. + * Default: "vertical" + */ + vertical?: string; + + } + + interface Configurations { + + /** + * the CSS class names object + */ + classNames?: ClassnamesConfigurations; + + /** + * Whether or not the menu should be cloned (and the original menu kept intact). + * Default: false + */ + clone?: boolean; + + /** + * The number of milliseconds between opening/closing the menu and panels, + * needed to force CSS transitions. + * Default: 25 + */ + openingInterval?: number; + + /** + * jQuery selector containing the node-type of panels. + * Default: "div, ul, ol" + */ + panelNodetype?: string; + + /** + * The number of milliseconds used in the CSS transitions. + * Default: 400 (The value should match the associated CSS value.) + */ + transitionDuration?: number; + + } + + interface API { + + /** + * Trigger non-specialized signature method + * @param methodName + * @param callback + */ + bind(methodName: string, callback: (...args: any[]) => void): any; + + /** + * Trigger this method to close all opened panels and go back to the first panel. + */ + closeAllPanels(): JQuery; + /** @see closeAllPanels() */ + bind(methodName: "closeAllPanels", callback: () => void): JQuery; + + /** + * Trigger this method to close a panel + * (only available if the "slidingSubmenus" option is set to false). + * @param panel + */ + closePanel(panel: JQuery): void; + /** @see closePanel() */ + bind(methodName: "closePanel", callback: (panel: JQuery) => void): void; + + /** + * Trigger this method to get the class instance for the menu. + */ + getInstance(): void; + /** @see getInstance() */ + bind(methodName: "getInstance", callback: () => void): void; + + /** + * Trigger this method to (re)initialize a newly added panel. + * @param panel The panel to (re)initialize. + */ + init(panel: JQuery): void; + /** @see init() */ + bind(methodName: "init", callback: (panel: JQuery) => void): void; + + /** + * Trigger this method to open a panel. + * @param panel The panel to open. + */ + openPanel(panel: JQuery): void; + /** @see openPanel() */ + bind(methodName: "openPanel", callback: (panel: JQuery) => void): void; + + /** + * Trigger this method to set or unset a list item as "selected". + * @param li The list item to set or unset as "selected". + * @param selected Whether to set or unset the list item as "selected". Default: true + */ + setSelected(li: JQuery, selected?: boolean): void; + /** @see setSelected() */ + bind(methodName: "setSelected", callback: (li: JQuery, selected?: boolean) => void): void; + + /** + * Trigger this method to update the appearance for the menu. + */ + update(): void; + /** @see update() */ + bind(methodName: "update", callback: () => void): void; + + } + +} + + +interface JQuery { + + /** + * Create mmenu component + */ + mmenu(): JQuery; + mmenu(options: JQueryMmenu.Options): JQuery; + mmenu(options: JQueryMmenu.Options, configurations: JQueryMmenu.Configurations): JQuery; + + /** + * Return the mmenu object + * @param element + */ + data(element: "mmenu"): JQueryMmenu.API; + +} diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index d9a33ed4fc..ade8eb735d 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -49,7 +49,7 @@ declare module JQueryUI { delay?: number; disabled?: boolean; minLength?: number; - position?: string; + position?: any; // object source?: any; // [], string or () } @@ -362,7 +362,8 @@ declare module JQueryUI { title?: string; width?: any; // number or string zIndex?: number; - + + open?: DialogEvent; close?: DialogEvent; } diff --git a/jssha/jssha-1.6.0-tests.ts b/jssha/jssha-1.6.0-tests.ts new file mode 100755 index 0000000000..67e1ec026c --- /dev/null +++ b/jssha/jssha-1.6.0-tests.ts @@ -0,0 +1,15 @@ +/// +/// + +var imported = require("jssha"); + +var shaObj1:jsSHA.jsSHA = new jsSHA("This is a Test", "TEXT", "UTF8"); +var shaObj2 = new imported("This is a Test", "TEXT"); + +var hash1:string = shaObj2.getHash("SHA-512", "HEX"); +var hash2:string = shaObj2.getHash("SHA-512", "HEX", 2); +var hash3:string = shaObj2.getHash("SHA-512", "HEX", 2, {outputUpper: false, b64Pad: "foobar"}); + +var format:jsSHA.OutputFormatOptions = {outputUpper: false, b64Pad: "foobar"}; +var hmac1 = shaObj2.getHMAC("SecretKey", "TEXT", "SHA-512", "HEX"); +var hmac2 = shaObj2.getHMAC("SecretKey", "TEXT", "SHA-512", "HEX", format); diff --git a/jssha/jssha-1.6.0.d.ts b/jssha/jssha-1.6.0.d.ts new file mode 100755 index 0000000000..b6dcef80fa --- /dev/null +++ b/jssha/jssha-1.6.0.d.ts @@ -0,0 +1,65 @@ +// Type definitions for jsSHA-1.6.0 +// Project: https://github.com/Caligatio/jsSHA +// Definitions by: David Li +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +declare module jsSHA { + export interface OutputFormatOptions { + outputUpper? : boolean; + b64Pad? : string; + } + + export interface jsSHA { + /** + * jsSHA is the workhorse of the library. Instantiate it with the string to + * be hashed as the parameter + * + * @constructor + * @this {jsSHA} + * @param {string} srcString The string to be hashed + * @param {string} inputFormat The format of srcString, HEX, TEXT, B64, or BYTES + * @param {string=} encoding The text encoding to use to encode the source + * string + */ + new (srcString:string, inputFormat:string, encoding?:string):jsSHA; + + /** + * Returns the desired SHA hash of the string specified at instantiation + * using the specified parameters + * + * @param {string} variant The desired SHA variant (SHA-1, SHA-224, + * SHA-256, SHA-384, or SHA-512) + * @param {string} format The desired output formatting (B64, HEX, or BYTES) + * @param {number=} numRounds The number of rounds of hashing to be + * executed + * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts + * Hash list of output formatting options + * @return {string} The string representation of the hash in the format + * specified + */ + getHash(variant:string, format:string, numRounds?:number, outputFormatOpts?:OutputFormatOptions):string; + + /** + * Returns the desired HMAC of the string specified at instantiation + * using the key and variant parameter + * + * @param {string} key The key used to calculate the HMAC + * @param {string} inputFormat The format of key, HEX, TEXT, B64, or BYTES + * @param {string} variant The desired SHA variant (SHA-1, SHA-224, + * SHA-256, SHA-384, or SHA-512) + * @param {string} outputFormat The desired output formatting + * (B64, HEX, or BYTES) + * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts + * associative array of output formatting options + * @return {string} The string representation of the hash in the format + * specified + */ + getHMAC(key:string, inputFormat:string, variant:string, outputFormat:string, outputFormatOpts?:OutputFormatOptions):string; + } +} + +declare var jsSHA: jsSHA.jsSHA; +declare module 'jssha' { + export = jsSHA; +} diff --git a/jssha/jssha-tests.ts b/jssha/jssha-tests.ts old mode 100755 new mode 100644 index 8d6eec5a64..e5a83b14a8 --- a/jssha/jssha-tests.ts +++ b/jssha/jssha-tests.ts @@ -1,15 +1,56 @@ /// /// -var imported = require("jssha"); +import imported = require("jssha"); -var shaObj1:jsSHA.jsSHA = new jsSHA("This is a Test", "TEXT", "UTF8"); -var shaObj2 = new imported("This is a Test", "TEXT"); +// constructor +let shaObj1:jsSHA.jsSHA = new imported("SHA-512", "TEXT"); +let shaObj2:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { }); +let shaObj3:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { encoding: "UTF8" }); +let shaObj4:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { numRounds: 1 }); +let shaObj5:jsSHA.jsSHA = new imported("SHA-512", "TEXT", { encoding: "UTF8", numRounds: 1 }); -var hash1:string = shaObj2.getHash("SHA-512", "HEX"); -var hash2:string = shaObj2.getHash("SHA-512", "HEX", 2); -var hash3:string = shaObj2.getHash("SHA-512", "HEX", 2, {outputUpper: false, b64Pad: "foobar"}); +// setHMACKey +shaObj1.setHMACKey("key", "TEXT"); +shaObj2.setHMACKey("key", "TEXT", { }); +shaObj3.setHMACKey("key", "TEXT", { encoding: "UTF8" }); -var format:jsSHA.OutputFormatOptions = {outputUpper: false, b64Pad: "foobar"}; -var hmac1 = shaObj2.getHMAC("SecretKey", "TEXT", "SHA-512", "HEX"); -var hmac2 = shaObj2.getHMAC("SecretKey", "TEXT", "SHA-512", "HEX", format); +// update +shaObj1.update("This is a test"); + +// getHash +let hash1:string = shaObj4.getHash("HEX"); +let hash2:string = shaObj4.getHash("HEX", {}); +let hash3:string = shaObj4.getHash("HEX", { b64Pad: "=" }); +let hash4:string = shaObj4.getHash("HEX", { outputUpper: true }); +let hash5:string = shaObj4.getHash("HEX", { outputUpper: true, b64Pad: '=' }); + +// getHMAC +let hmac1:string = shaObj1.getHMAC("HEX"); +let hmac2:string = shaObj1.getHMAC("HEX", {}); +let hmac3:string = shaObj1.getHMAC("HEX", { b64Pad: "=" }); +let hmac4:string = shaObj1.getHMAC("HEX", { outputUpper: true }); +let hmac5:string = shaObj1.getHMAC("HEX", { outputUpper: true, b64Pad: '=' }); + + +// examples from the readme.md (https://github.com/Caligatio/jsSHA/blob/v2.0.2/README.md) +{ + var shaObj = new imported("SHA-512", "TEXT"); + shaObj.update("This is a test"); + var hash = shaObj.getHash("HEX"); +} + + +{ + let shaObj = new imported("SHA-256", "TEXT"); + shaObj.setHMACKey("abc", "TEXT"); + shaObj.update("This is a test"); + let hmac = shaObj.getHMAC("HEX"); +} + +// Browser global test +{ + var shaObj = new jsSHA("SHA-512", "TEXT"); + shaObj.update("This is a test"); + var hash = shaObj.getHash("HEX"); +} \ No newline at end of file diff --git a/jssha/jssha.d.ts b/jssha/jssha.d.ts old mode 100755 new mode 100644 index 1c75c38620..f695a66700 --- a/jssha/jssha.d.ts +++ b/jssha/jssha.d.ts @@ -1,13 +1,22 @@ // Type definitions for jsSHA // Project: https://github.com/Caligatio/jsSHA -// Definitions by: David Li -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: David Li , Tobias Kahlert +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module jsSHA { + + export interface EncodingOptions { + encoding? : string; + } + + export interface Options extends EncodingOptions { + numRounds? : number; + } + export interface OutputFormatOptions { - outputUpper : boolean; - b64Pad : string; + outputUpper? : boolean; + b64Pad? : string; } export interface jsSHA { @@ -15,47 +24,58 @@ declare module jsSHA { * jsSHA is the workhorse of the library. Instantiate it with the string to * be hashed as the parameter * - * @constructor - * @this {jsSHA} - * @param {string} srcString The string to be hashed - * @param {string} inputFormat The format of srcString, HEX, TEXT, B64, or BYTES - * @param {string=} encoding The text encoding to use to encode the source - * string + * @param {string} variant The desired SHA variant (SHA-1, SHA-224, SHA-256, + * SHA-384, or SHA-512) + * @param {string} inputFormat The format of srcString: HEX, TEXT, B64, or BYTES + * @param {{encoding: (string|undefined), numRounds: (string|undefined)}=} + * options Optional values */ - new (srcString:string, inputFormat:string, encoding?:string):jsSHA; + new (variant:string, inputFormat:string, options?:Options):jsSHA; /** - * Returns the desired SHA hash of the string specified at instantiation - * using the specified parameters - * - * @param {string} variant The desired SHA variant (SHA-1, SHA-224, - * SHA-256, SHA-384, or SHA-512) - * @param {string} format The desired output formatting (B64, HEX, or BYTES) - * @param {number=} numRounds The number of rounds of hashing to be - * executed - * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts - * Hash list of output formatting options - * @return {string} The string representation of the hash in the format - * specified - */ - getHash(variant:string, format:string, numRounds?:number, outputFormatOpts?:OutputFormatOptions):string; + * Sets the HMAC key for an eventual getHMAC call. Must be called + * immediately after jsSHA object instantiation + * + * @param {string} key The key used to calculate the HMAC + * @param {string} inputFormat The format of key, HEX, TEXT, B64, or BYTES + * @param {{encoding : (string|undefined)}=} encodingOpts Associative array + * of input format options + */ + setHMACKey(key:string, inputFormat:string, encodingOpts?:EncodingOptions):void; + + /** + * Takes strString and hashes as many blocks as possible. Stores the + * rest for either a future update or getHash call. + * + * @param {string} srcString The string to be hashed + */ + update(srcString:string):void; + /** - * Returns the desired HMAC of the string specified at instantiation - * using the key and variant parameter - * - * @param {string} key The key used to calculate the HMAC - * @param {string} inputFormat The format of key, HEX, TEXT, B64, or BYTES - * @param {string} variant The desired SHA variant (SHA-1, SHA-224, - * SHA-256, SHA-384, or SHA-512) - * @param {string} outputFormat The desired output formatting - * (B64, HEX, or BYTES) - * @param {{outputUpper : boolean, b64Pad : string}=} outputFormatOpts - * associative array of output formatting options - * @return {string} The string representation of the hash in the format - * specified - */ - getHMAC(key:string, inputFormat:string, variant:string, outputFormat:string, outputFormatOpts?:OutputFormatOptions):string; + * Returns the desired SHA hash of the string specified at instantiation + * using the specified parameters + * + * @param {string} format The desired output formatting (B64, HEX, or BYTES) + * @param {{outputUpper : (boolean|undefined), b64Pad : (string|undefined)}=} + * outputFormatOpts Hash list of output formatting options + * @return {string} The string representation of the hash in the format + * specified + */ + getHash(format:string, outputFormatOpts?:OutputFormatOptions):string; + + /** + * Returns the the HMAC in the specified format using the key given by + * a previous setHMACKey call. + * + * @param {string} format The desired output formatting + * (B64, HEX, or BYTES) + * @param {{outputUpper : (boolean|undefined), b64Pad : (string|undefined)}=} + * outputFormatOpts associative array of output formatting options + * @return {string} The string representation of the hash in the format + * specified + */ + getHMAC(format:string, outputFormatOpts?:OutputFormatOptions):string; } } diff --git a/jsurl/jsurl-tests.ts b/jsurl/jsurl-tests.ts new file mode 100644 index 0000000000..a10d0a763e --- /dev/null +++ b/jsurl/jsurl-tests.ts @@ -0,0 +1,80 @@ +/// + +interface UModel extends UrlQuery { + a: any; + b: string; +} + +interface U2Model extends UrlQuery { + a: any; +} + +interface U3Model extends UrlQuery { + foo: string; +} + +var u = new Url(); // curent document URL will be used +// or we can instantiate as +var u2 = new Url("http://example.com/some/path?a=b&c=d#someAnchor"); +// it should support relative URLs also +var u3 = new Url("/my/site/doc/path?foo=bar#baz"); + +// get the value of some query string parameter +alert(u2.query.a); +// or +alert(u3.query["foo"]); + +// Manupulating query string parameters +u.query.a = [1, 2, 3]; // adds/replaces in query string params a=1&a=2&a=3 +u.query.b = 'woohoo'; // adds/replaces in query string param b=woohoo + +if (u.query.a instanceof Array) { // the way to add a parameter + u.query.a.push(4); // now it's "a=1&a=2&a=3&a=4&b=woohoo" +} + +else { // if not an array but scalar value here is a way how to convert to array + u.query.a = [u.query.a]; + u.query.a.push(8) +} + + +// The way to remove the parameter: +delete u.query.a +// or: +delete u.query["a"] + +// If you need to remove all query string params: +u.query.clear(); +alert(u); + +// Lookup URL parts: +alert( + 'protocol = ' + u.protocol + '\n' + + 'user = ' + u.user + '\n' + + 'pass = ' + u.pass + '\n' + + 'host = ' + u.host + '\n' + + 'port = ' + u.port + '\n' + + 'path = ' + u.path + '\n' + + 'query = ' + u.query + '\n' + + 'hash = ' + u.hash +); + +// Manipulating URL parts +u.path = '/some/new/path'; // the way to change URL path +u.protocol = 'https' // the way to force https protocol on the source URL + +// inject into string +var str = 'My Cool Link'; + +// or use in DOM context +var a = document.createElement('a'); +a.href = u.toString(); +a.innerHTML = 'test'; +document.body.appendChild(a); + +// Stringify +var su1 = u + ''; +var su2 = String(u); +var su3 = u.toString(); +// NOTE, that usually it will be done automatically, so only in special +// cases direct stringify is required \ No newline at end of file diff --git a/jsurl/jsurl.d.ts b/jsurl/jsurl.d.ts new file mode 100644 index 0000000000..cbe9858518 --- /dev/null +++ b/jsurl/jsurl.d.ts @@ -0,0 +1,23 @@ +// Type definitions for jsurl 1.2.7 +// Project: https://github.com/Mikhus/jsurl +// Definitions by: Alexey Gorshkov +// Definitions: https://github.com/agorshkov23/DefinitelyTyped + +interface UrlQuery { + clear: () => void; +} + +declare class Url { + constructor(); + constructor(url: string); + query: T; + protocol: string; + user: string; + pass: string; + host: string; + port: string; + path: string; + hash: string; + href: string; + toString: () => string; +} \ No newline at end of file diff --git a/kefir/kefir-tests.ts b/kefir/kefir-tests.ts index a0d0a96186..94300550b4 100644 --- a/kefir/kefir-tests.ts +++ b/kefir/kefir-tests.ts @@ -30,7 +30,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke let stream10: Stream = Kefir.stream(emitter => { let count = 0; emitter.emit(count); - + let intervalId = setInterval(() => { count++; if (count < 4) { @@ -39,7 +39,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke emitter.end(); } }, 1000); - + return () => clearInterval(intervalId); }); } @@ -77,6 +77,7 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke let observable01: Stream = Kefir.sequentially(100, [1, 2, 3]).map(x => x + 1); let observable02: Stream = Kefir.sequentially(100, [1, 2, 3]).filter(x => x > 1); let observable03: Stream = Kefir.sequentially(100, [1, 2, 3]).take(2); + let observable29: Stream = Kefir.sequentially(100, [1, 2, 3]).takeErrors(2); let observable04: Stream = Kefir.sequentially(100, [1, 2, 3]).takeWhile(x => x < 3); let observable05: Stream = Kefir.sequentially(100, [1, 2, 3]).last(); let observable06: Stream = Kefir.sequentially(100, [1, 2, 3]).skip(2); @@ -103,14 +104,16 @@ import { Observable, ObservablePool, Stream, Property, Event, Emitter } from 'ke }).endOnError(); let observable22: Stream = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors(x => { return {convert: x < 0, error: x}; - }).skipValues(); + }).ignoreValues(); let observable23: Stream = Kefir.sequentially(100, [0, -1, 2, -3]).valuesToErrors(x => { return {convert: x < 0, error: x}; - }).skipErrors(); - let observable24: Stream = Kefir.sequentially(100, [1, 2, 3]).skipEnd(); + }).ignoreErrors(); + let observable24: Stream = Kefir.sequentially(100, [1, 2, 3]).ignoreEnd(); let ovservable25: Stream = Kefir.sequentially(100, [1, 2, 3]).beforeEnd(() => 0); let observable26: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5]).slidingWindow(3, 2) let observable27: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5]).bufferWhile(x => x !== 3); + let observable30: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5]).bufferWithCount(2); + let observable31: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5]).bufferWithTimeOrCount(330, 10); { var myTransducer: any; let observable28: Stream = Kefir.sequentially(100, [1, 2, 3, 4, 5, 6]).transduce(myTransducer); diff --git a/kefir/kefir.d.ts b/kefir/kefir.d.ts index 9e3303f01e..a95b12a887 100644 --- a/kefir/kefir.d.ts +++ b/kefir/kefir.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Kefir 2.8.1 +// Type definitions for Kefir 3.2.0 // Project: http://rpominov.github.io/kefir/ // Definitions by: Aya Morisawa // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,7 +6,7 @@ /// declare module "kefir" { - + export interface Observable { // Subscribe / add side effects onValue(callback: (value: T) => void): void; @@ -19,12 +19,14 @@ declare module "kefir" { offAny(callback: (event: Event) => void): void; log(name?: string): void; offLog(name?: string): void; + flatten(transformer?: (value: T) => U[]): Stream; toPromise(PromiseConstructor?: any): any; + toESObservable(): any; } - + export interface Stream extends Observable { toProperty(getCurrent?: () => T): Property; - + // Modify an stream map(fn: (value: T) => U): Stream; filter(predicate?: (value: T) => boolean): Stream; @@ -36,24 +38,26 @@ declare module "kefir" { skipDuplicates(comparator?: (a: T, b: T) => boolean): Stream; diff(fn?: (prev: T, next: T) => T, seed?: T): Stream; scan(fn: (prev: T, next: T) => T, seed?: T): Stream; - flatten(transformer?: (value: T) => U[]): Stream; delay(wait: number): Stream; - throttle(wait: number, options?: {leading: boolean, trailing: boolean}): Stream; + throttle(wait: number, options?: {leading?: boolean, trailing?: boolean}): Stream; debounce(wait: number, options?: {immediate: boolean}): Stream; valuesToErrors(handler?: (value: T) => {convert: boolean, error: U}): Stream; errorsToValues(handler?: (error: S) => {convert: boolean, value: U}): Stream; mapErrors(fn: (error: S) => U): Stream; filterErrors(predicate?: (error: S) => boolean): Stream; endOnError(): Stream; - skipValues(): Stream; - skipErrors(): Stream; - skipEnd(): Stream; + takeErrors(n: number): Stream; + ignoreValues(): Stream; + ignoreErrors(): Stream; + ignoreEnd(): Stream; beforeEnd(fn: () => U): Stream; slidingWindow(max: number, mix?: number): Stream; bufferWhile(predicate: (value: T) => boolean): Stream; + bufferWithCount(count: number, options?: {flushOnEnd: boolean}): Stream; + bufferWithTimeOrCount(interval: number, count: number, options?: {flushOnEnd: boolean}): Stream; transduce(transducer: any): Stream; withHandler(handler: (emitter: Emitter, event: Event) => void): Stream; - + // Combine streams combine(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; zip(otherObs: Stream, combinator?: (value: T, ...values: U[]) => W): Stream; @@ -65,20 +69,20 @@ declare module "kefir" { flatMapConcat(fn: (value: T) => Stream): Stream; flatMapConcurLimit(fn: (value: T) => Stream, limit: number): Stream; flatMapErrors(transform: (error: S) => Stream): Stream; - + // Combine two streams filterBy(otherObs: Observable): Stream; sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Stream; skipUntilBy(otherObs: Observable): Stream; takeUntilBy(otherObs: Observable): Stream; bufferBy(otherObs: Observable, options?: {flushOnEnd: boolean}): Stream; - bufferWhileBy(otherObs: Observable): Stream; + bufferWhileBy(otherObs: Observable, options?: {flushOnEnd?: boolean, flushOnChange?: boolean}): Stream; awaiting(otherObs: Observable): Stream; } - + export interface Property extends Observable { changes(): Stream; - + // Modify an property map(fn: (value: T) => U): Property; filter(predicate?: (value: T) => boolean): Property; @@ -90,24 +94,26 @@ declare module "kefir" { skipDuplicates(comparator?: (a: T, b: T) => boolean): Property; diff(fn?: (prev: T, next: T) => T, seed?: T): Property; scan(fn: (prev: T, next: T) => T, seed?: T): Property; - flatten(transformer?: (value: T) => U[]): Property; delay(wait: number): Property; - throttle(wait: number, options?: {leading: boolean, trailing: boolean}): Property; + throttle(wait: number, options?: {leading?: boolean, trailing?: boolean}): Property; debounce(wait: number, options?: {immediate: boolean}): Property; valuesToErrors(handler?: (value: T) => {convert: boolean, error: U}): Property; errorsToValues(handler?: (error: S) => {convert: boolean, value: U}): Property; mapErrors(fn: (error: S) => U): Property; filterErrors(predicate?: (error: S) => boolean): Property; endOnError(): Property; - skipValues(): Property; - skipErrors(): Property; - skipEnd(): Property; + takeErrors(n: number): Stream; + ignoreValues(): Property; + ignoreErrors(): Property; + ignoreEnd(): Property; beforeEnd(fn: () => U): Property; slidingWindow(max: number, mix?: number): Property; bufferWhile(predicate: (value: T) => boolean): Property; + bufferWithCount(count: number, options?: {flushOnEnd: boolean}): Property; + bufferWithTimeOrCount(interval: number, count: number, options?: {flushOnEnd: boolean}): Property; transduce(transducer: any): Property; withHandler(handler: (emitter: Emitter, event: Event) => void): Property; - + // Combine properties combine(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; zip(otherObs: Property, combinator?: (value: T, ...values: U[]) => W): Property; @@ -119,35 +125,34 @@ declare module "kefir" { flatMapConcat(fn: (value: T) => Property): Property; flatMapConcurLimit(fn: (value: T) => Property, limit: number): Property; flatMapErrors(transform: (error: S) => Property): Property; - + // Combine two properties filterBy(otherObs: Observable): Property; sampledBy(otherObs: Observable, combinator?: (a: T, b: U) => W): Property; skipUntilBy(otherObs: Observable): Property; takeUntilBy(otherObs: Observable): Property; bufferBy(otherObs: Observable, options?: {flushOnEnd: boolean}): Property; - bufferWhileBy(otherObs: Observable): Property; + bufferWhileBy(otherObs: Observable, options?: {flushOnEnd?: boolean, flushOnChange?: boolean}): Property; awaiting(otherObs: Observable): Property; } - + export interface ObservablePool extends Observable { plug(obs: Observable): void; unPlug(obs: Observable): void; } - + export interface Event { type: string; value: T; - current: boolean; } - + export interface Emitter { emit(value: T): void; error(error: S): void; end(): void; emitEvent(event: {type: string, value: T | S}): void; } - + // Create a stream export function never(): Stream; export function later(wait: number, value: T): Stream; @@ -159,12 +164,13 @@ declare module "kefir" { export function fromNodeCallback(fn: (callback: (error: S, result: T) => void) => void): Stream; export function fromEvents(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream; export function stream(subscribe: (emitter: Emitter) => Function | void): Stream; - + export function fromESObservable(observable: any): Stream + // Create a property export function constant(value: T): Property; export function constantError(error: T): Property; export function fromPromise(promise: any): Property; - + // Combine observables export function combine(obss: Observable[], passiveObss: Observable[], combinator?: (...values: T[]) => U): Observable; export function combine(obss: Observable[], combinator?: (...values: T[]) => U): Observable; diff --git a/knex/knex.d.ts b/knex/knex.d.ts index d2afc4aa82..49fb30ae02 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -39,7 +39,7 @@ declare module "knex" { // // QueryInterface // - + interface QueryInterface { select: Select; as: As; @@ -49,7 +49,7 @@ declare module "knex" { into: Table; table: Table; distinct: Distinct; - + // Joins join: Join; joinRaw: JoinRaw; @@ -61,7 +61,7 @@ declare module "knex" { outerJoin: Join; fullOuterJoin: Join; crossJoin: Join; - + // Wheres where: Where; andWhere: Where; @@ -86,29 +86,29 @@ declare module "knex" { whereNotBetween: WhereBetween; orWhereBetween: WhereBetween; orWhereNotBetween: WhereBetween; - + // Group by groupBy: GroupBy; groupByRaw: RawQueryBuilder; - + // Order by orderBy: OrderBy; orderByRaw: RawQueryBuilder; - + // Union union: Union; unionAll(callback: Function): QueryBuilder; - + // Having having: Having; havingRaw: RawQueryBuilder; orHaving: Having; orHavingRaw: RawQueryBuilder; - + // Paging offset(offset: number): QueryBuilder; limit(limit: number): QueryBuilder; - + // Aggregation count(columnName?: string): QueryBuilder; min(columnName: string): QueryBuilder; @@ -117,43 +117,43 @@ declare module "knex" { avg(columnName: string): QueryBuilder; increment(columnName: string, amount?: number): QueryBuilder; decrement(columnName: string, amount?: number): QueryBuilder; - + // Others first(...columns: string[]): QueryBuilder; - + debug(enabled?: boolean): QueryBuilder; pluck(column: string): QueryBuilder; - + 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; - + del(returning?: string | string[]): QueryBuilder; delete(returning?: string | string[]): QueryBuilder; truncate(): QueryBuilder; - + transacting(trx: Transaction): QueryBuilder; connection(connection: any): QueryBuilder; clone(): QueryBuilder; } - + interface As { (columnName: string): QueryBuilder; } - + interface Select extends ColumnNameQueryBuilder { } - + interface Table { (tableName: string): QueryBuilder; (callback: Function): QueryBuilder; } - + interface Distinct extends ColumnNameQueryBuilder { } - + interface Join { (raw: Raw): QueryBuilder; (tableName: string, callback: Function): QueryBuilder; @@ -161,126 +161,126 @@ declare module "knex" { (tableName: string, column1: string, raw: Raw): QueryBuilder; (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; } - + interface JoinRaw { (tableName: string, binding?: Value): QueryBuilder; } - + interface Where extends WhereRaw, WhereWrapped, WhereNull { (object: Object): QueryBuilder; (columnName: string, value: Value): QueryBuilder; (columnName: string, operator: string, value: Value): QueryBuilder; (columnName: string, operator: string, query: QueryBuilder): QueryBuilder; } - + interface WhereRaw extends RawQueryBuilder { (condition: boolean): QueryBuilder; } - + interface WhereWrapped { (callback: Function): QueryBuilder; } - + interface WhereNull { (columnName: string): QueryBuilder; } - + interface WhereIn { (columnName: string, values: Value[]): QueryBuilder; (columnName: string, callback: Function): QueryBuilder; (columnName: string, query: QueryBuilder): QueryBuilder; } - + interface WhereBetween { (columnName: string, range: [Value, Value]): QueryBuilder; } - + interface WhereExists { (callback: Function): QueryBuilder; (query: QueryBuilder): QueryBuilder; } - + interface WhereNull { (columnName: string): QueryBuilder; } - + interface WhereIn { (columnName: string, values: Value[]): QueryBuilder; } - + interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { } - + interface OrderBy { (columnName: string, direction?: string): QueryBuilder; } - + interface Union { (callback: Function, wrap?: boolean): QueryBuilder; (callbacks: Function[], wrap?: boolean): QueryBuilder; (...callbacks: Function[]): QueryBuilder; // (...callbacks: Function[], wrap?: boolean): QueryInterface; } - + interface Having extends RawQueryBuilder, WhereWrapped { (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; } - + // commons - + interface ColumnNameQueryBuilder { (...columnNames: ColumnName[]): QueryBuilder; (columnNames: ColumnName[]): QueryBuilder; } - + interface RawQueryBuilder { (sql: string, ...bindings: Value[]): QueryBuilder; (sql: string, bindings: Value[]): QueryBuilder; (raw: Raw): QueryBuilder; } - + // Raw - + interface Raw extends events.EventEmitter, ChainableInterface { wrap(before: string, after: string): Raw; } - + interface RawBuilder { (value: Value): Raw; (sql: string, ...bindings: Value[]): Raw; (sql: string, bindings: Value[]): Raw; } - + // // QueryBuilder // - + interface QueryBuilder extends QueryInterface, ChainableInterface { or: QueryBuilder; and: QueryBuilder; - + //TODO: Promise? columnInfo(column?: string): Promise; - + forUpdate(): QueryBuilder; forShare(): QueryBuilder; - + toSQL(): Sql; - + on(event: string, callback: Function): QueryBuilder; } - + interface Sql { method: string; options: any; bindings: Value[]; sql: string; } - + // // Chainable interface // - + interface ChainableInterface extends Promise { toQuery(): string; options(options: any): QueryBuilder; @@ -289,16 +289,16 @@ declare module "knex" { pipe(writable: any): QueryBuilder; exec(callback: Function): QueryBuilder; } - + interface Transaction extends QueryBuilder { commit: any; rollback: any; } - + // // Schema builder // - + interface SchemaBuilder { createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): Promise; renameTable(oldTableName: string, newTableName: string): Promise; @@ -309,7 +309,7 @@ declare module "knex" { dropTableIfExists(tableName: string): Promise; raw(statement: string): SchemaBuilder; } - + interface TableBuilder { increments(columnName?: string): ColumnBuilder; dropColumn(columnName: string): TableBuilder; @@ -336,24 +336,24 @@ declare module "knex" { specificType(columnName: string, type: string): ColumnBuilder; primary(columnNames: string[]) : TableBuilder; index(columnNames: string[], indexName?: string, indexType?: string) : TableBuilder; - unique(columnNames: string[], indexName?: string) : TableBuilder; + unique(columnNames: string[], indexName?: string) : TableBuilder; } - + interface CreateTableBuilder extends TableBuilder { } - + interface MySqlTableBuilder extends CreateTableBuilder { engine(val: string): CreateTableBuilder; charset(val: string): CreateTableBuilder; collate(val: string): CreateTableBuilder; } - + interface AlterTableBuilder extends TableBuilder { } - + interface MySqlAlterTableBuilder extends AlterTableBuilder { } - + interface ColumnBuilder { index(indexName?: string): ColumnBuilder; primary(): ColumnBuilder; @@ -367,34 +367,34 @@ declare module "knex" { nullable(): ColumnBuilder; comment(value: string): ColumnBuilder; } - + interface PostgreSqlColumnBuilder extends ColumnBuilder { index(indexName?: string, indexType?: string): ColumnBuilder; } - + interface ReferencingColumnBuilder { inTable(tableName: string): ColumnBuilder; } - + interface AlterColumnBuilder extends ColumnBuilder { } - + interface MySqlAlterColumnBuilder extends AlterColumnBuilder { first(): AlterColumnBuilder; after(columnName: string): AlterColumnBuilder; } - + // // Configurations // - + interface ColumnInfo { defaultValue: Value; type: string; maxLength: number; nullable: boolean; } - + interface Config { debug?: boolean; client?: string; @@ -404,7 +404,7 @@ declare module "knex" { pool?: PoolConfig; migrations?: MigrationConfig; } - + interface ConnectionConfig { host: string; user: string; @@ -412,13 +412,13 @@ declare module "knex" { database: string; debug?: boolean; } - + /** Used with SQLite3 adapter */ interface Sqlite3ConnectionConfig { filename: string; debug?: boolean; } - + interface SocketConnectionConfig { socketPath: string; user: string; @@ -426,7 +426,7 @@ declare module "knex" { database: string; debug?: boolean; } - + interface PoolConfig { name?: string; create?: Function; @@ -443,7 +443,7 @@ declare module "knex" { validate?: Function; log?: boolean; } - + interface MigrationConfig { database?: string; directory?: string; diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 8f5d6fef4a..ea5cc33cd6 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -30,9 +30,9 @@ interface KnockoutObservableArrayFunctions { push(...items: T[]): void; shift(): T; unshift(...items: T[]): number; - reverse(): T[]; - sort(): void; - sort(compareFunction: (left: T, right: T) => number): void; + reverse(): KnockoutObservableArray; + sort(): KnockoutObservableArray; + sort(compareFunction: (left: T, right: T) => number): KnockoutObservableArray; // Ko specific [key: string]: KnockoutBindingHandler; @@ -562,6 +562,7 @@ declare module KnockoutComponentTypes { } interface ComponentConfig { + viewModel?: ViewModelFunction | ViewModelSharedInstance | ViewModelFactoryFunction | AMDModule; template: any; createViewModel?: any; } diff --git a/knockout/tests/jasmine.extensions.d.ts b/knockout/tests/jasmine.extensions.d.ts new file mode 100644 index 0000000000..c3b12213f0 --- /dev/null +++ b/knockout/tests/jasmine.extensions.d.ts @@ -0,0 +1,10 @@ +// Knockout specs depend on custom Jasmine matchers +// See https://github.com/knockout/knockout/blob/v3.4.0/spec/lib/jasmine.extensions.js +// FYI jasmine-jquery.d.ts (https://github.com/velesin/jasmine-jquery) also defines toContainHtml() and toContainText() + +declare module jasmine { + interface Matchers { + toContainHtml(expected: string): boolean; + toContainText(expected: string): boolean; + } +} diff --git a/knockout/tests/knockout-templatingBehaviors-tests.ts b/knockout/tests/knockout-templatingBehaviors-tests.ts index 50ec275724..cd86465b23 100644 --- a/knockout/tests/knockout-templatingBehaviors-tests.ts +++ b/knockout/tests/knockout-templatingBehaviors-tests.ts @@ -1,4 +1,5 @@ /// +/// /// /// diff --git a/lazy.js/lazy.js-tests.ts b/lazy.js/lazy.js-tests.ts index 5e45ccf135..57d1ef37e8 100644 --- a/lazy.js/lazy.js-tests.ts +++ b/lazy.js/lazy.js-tests.ts @@ -28,6 +28,7 @@ var anyObjectSeq: LazyJS.ObjectLikeSequence; var fooAsyncSeq: LazyJS.AsyncSequence; var strSequence: LazyJS.Sequence; +var anySequence: LazyJS.Sequence; var stringSeq: LazyJS.StringLikeSequence; var obj: Object; @@ -44,7 +45,6 @@ function fnCallback(): void { } function fnErrorCallback(error: any): void { - } function fnValueCallback(value: Foo): void { @@ -108,8 +108,8 @@ fooSequence = fooSequence.dropWhile(fnTestCallback); fooSequence = fooSequence.each(fnValueCallback); bool = fooSequence.every(fnTestCallback); fooSequence = fooSequence.filter(fnTestCallback); -fooSequence = fooSequence.find(fnTestCallback); -fooSequence = fooSequence.findWhere(obj); +foo = fooSequence.find(fnTestCallback); +foo = fooSequence.findWhere(obj); x = fooSequence.first(); fooSequence = fooSequence.first(num); @@ -134,7 +134,7 @@ foo = fooSequence.max(); foo = fooSequence.max(fnNumberCallback); foo = fooSequence.min(); foo = fooSequence.min(fnNumberCallback); -fooSequence = fooSequence.pluck(str); +anySequence = fooSequence.pluck(str); bar = fooSequence.reduce(fnMemoCallback); bar = fooSequence.reduce(fnMemoCallback, bar); bar = fooSequence.reduceRight(fnMemoCallback, bar); @@ -152,8 +152,8 @@ fooSequence = fooSequence.sortBy(str, bool); fooSequence = fooSequence.sortBy(fnNumberCallback); fooSequence = fooSequence.sortBy(fnNumberCallback, bool); fooSequence = fooSequence.sortedIndex(foo); -fooSequence = fooSequence.sum(); -fooSequence = fooSequence.sum(fnNumberCallback); +foo = fooSequence.sum(); +foo = fooSequence.sum(fnNumberCallback); fooSequence = fooSequence.takeWhile(fnTestCallback); fooSequence = fooSequence.union(fooArr); fooSequence = fooSequence.uniq(); diff --git a/lazy.js/lazy.js.d.ts b/lazy.js/lazy.js.d.ts index 02cf1833b5..55406d5c50 100644 --- a/lazy.js/lazy.js.d.ts +++ b/lazy.js/lazy.js.d.ts @@ -135,8 +135,8 @@ declare module LazyJS { dropWhile(predicateFn: TestCallback): Sequence; every(predicateFn: TestCallback): boolean; filter(predicateFn: TestCallback): Sequence; - find(predicateFn: TestCallback): Sequence; - findWhere(properties: Object): Sequence; + find(predicateFn: TestCallback): T; + findWhere(properties: Object): T; flatten(): Sequence; groupBy(keyFn: GetKeyCallback): ObjectLikeSequence; @@ -150,7 +150,7 @@ declare module LazyJS { max(valueFn?: NumberCallback): T; min(valueFn?: NumberCallback): T; none(valueFn?: TestCallback): boolean; - pluck(propertyName: string): Sequence; + pluck(propertyName: string): Sequence; reduce(aggregatorFn: MemoCallback, memo?: U): U; reduceRight(aggregatorFn: MemoCallback, memo: U): U; reject(predicateFn: TestCallback): Sequence; @@ -162,7 +162,7 @@ declare module LazyJS { sortBy(sortFn: NumberCallback, descending?: boolean): Sequence; sortedIndex(value: T): Sequence; size(): number; - sum(valueFn?: NumberCallback): Sequence; + sum(valueFn?: NumberCallback): T; takeWhile(predicateFn: TestCallback): Sequence; union(var_args: T[]): Sequence; uniq(): Sequence; diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index 0ea66d32e0..2a7e418f71 100755 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -131,6 +131,7 @@ var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); map.addLayer(layer); map.addLayer(layer, false); +map.eachLayer(l => {}); map.removeLayer(layer); map.hasLayer(layer); @@ -423,4 +424,4 @@ var zoomCtrl = L.control.zoom({ position: "topleft", zoomInText: '+', zoomOutText: '-' -}); +}); \ No newline at end of file diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 565a3c25de..94e6ab51c3 100755 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -516,7 +516,7 @@ declare module L { function (options?: ControlOptions): Control; } - namespace control { + export namespace control { /** * Creates a zoom control. @@ -2441,6 +2441,12 @@ declare namespace L { */ options: Map.MapOptions; + /** + * Iterates over the layers of the map, optionally specifying context + * of the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): Map; + //////////////// //////////////// addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; @@ -3261,7 +3267,7 @@ declare namespace L { off(eventMap?: any, context?: any): Path; } - namespace Path { + export namespace Path { /** * True if SVG is used for vector rendering (true for most modern browsers). */ diff --git a/lestate/lestate-tests.ts b/lestate/lestate-tests.ts new file mode 100644 index 0000000000..9a007c68d2 --- /dev/null +++ b/lestate/lestate-tests.ts @@ -0,0 +1,20 @@ +/// + +let State = LeState.createState() + +State.set({ + test : {} +}) + +let currentState = State.get() + +State.insert({ + test : {} +}) + +let currentDescription = State.getDescription() + +State.createListener({ + id : 0, + selector : state => ({ test : state.test }) +}) diff --git a/lestate/lestate.d.ts b/lestate/lestate.d.ts new file mode 100644 index 0000000000..d36a137eb4 --- /dev/null +++ b/lestate/lestate.d.ts @@ -0,0 +1,27 @@ +// Type definitions for LeState v0.1.3 +// Project: https://github.com/LeTools/LeState +// Definitions by: Hadrian Oliveira +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare let LeState : { + createState: (props?: { + initialState: {}; + }) => { + set(newValue: {}): [{ + id: number; + state: {}; + }]; + get(): any; + insert(newValue: {}): void; + getDescription(): {}; + createListener({ id, selector, force }: { + id: number; + selector: (state :any) => {}; + force?: boolean; + }): void; + }; +}; + +declare module "lestate" { + export default LeState; +} diff --git a/lime-js/lime-js-tests.ts b/lime-js/lime-js-tests.ts new file mode 100644 index 0000000000..aa73444b17 --- /dev/null +++ b/lime-js/lime-js-tests.ts @@ -0,0 +1,35 @@ +/// + +var transport = new Lime.WebSocketTransport(true); +var clientChannel = new Lime.ClientChannel(transport, true, true); + +clientChannel.onMessage = (m) => { + // message received callback +}; +clientChannel.onNotification = (n) => { + // notification received callback +}; +clientChannel.onCommand = (c) => { + // command received callback +}; + +transport.onOpen = () => { + var authentication: Lime.Authentication = new Lime.GuestAuthentication(); + Lime.ClientChannelExtensions.establishSession(clientChannel, "none", "none", "test@msging.net", authentication, "test", (err, session) => { + var message: Lime.Message = { + id: "123", + to: "someone@test.net", + type: "text/plain", + content: "Hello, world!" + }; + clientChannel.sendMessage(message); + }); +}; +transport.onClose = () => { + // transport closed callback +}; +transport.onError = (err) => { + // transport error callback +}; + +transport.open("ws://test.net"); diff --git a/lime-js/lime-js.d.ts b/lime-js/lime-js.d.ts new file mode 100644 index 0000000000..7e26733d36 --- /dev/null +++ b/lime-js/lime-js.d.ts @@ -0,0 +1,200 @@ +// Type definitions for lime-js 0.0.3 +// Project: https://github.com/takenet/lime-js +// Definitions by: Arthur Xavier +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare namespace Lime { + + interface Envelope { + id?: string; + from?: string; + to?: string; + pp?: string; + metadata?: any; + } + interface Reason { + code: number; + description?: string; + } + + interface Message extends Envelope { + type: string; + content: any; + } + + interface Notification extends Envelope { + event: string; + reason?: Reason; + } + class NotificationEvent { + static accepted: string; + static validated: string; + static authorized: string; + static dispatched: string; + static received: string; + static consumed: string; + } + + interface Command extends Envelope { + uri?: string; + type?: string; + resource?: any; + method: string; + status?: string; + reason?: Reason; + } + class CommandMethod { + static get: string; + static set: string; + static delete: string; + static observe: string; + static subscribe: string; + } + class CommandStatus { + static success: string; + static failure: string; + } + + interface Session extends Envelope { + state: string; + encryptionOptions?: string[]; + encryption?: string; + compressionOptions?: string[]; + compression?: string; + scheme?: string; + authentication?: any; + reason?: Reason; + } + class SessionState { + static new: string; + static negotiating: string; + static authenticating: string; + static established: string; + static finishing: string; + static finished: string; + static failed: string; + } + class SessionEncryption { + static none: string; + static tls: string; + } + class SessionCompression { + static none: string; + static gzip: string; + } + + class Authentication { + scheme: string; + static guest: string; + static plain: string; + static transport: string; + static key: string; + } + class GuestAuthentication extends Authentication { + scheme: string; + } + class TransportAuthentication extends Authentication { + scheme: string; + } + class PlainAuthentication extends Authentication { + scheme: string; + password: string; + } + class KeyAuthentication extends Authentication { + scheme: string; + key: string; + } + + class Channel { + constructor(transport: Transport, autoReplyPings: boolean, autoNotifyReceipt: boolean); + sendMessage(message: Message): void; + onMessage(message: Message): void; + sendCommand(command: Command): void; + onCommand(command: Command): void; + sendNotification(notification: Notification): void; + onNotification(notification: Notification): void; + sendSession(session: Session): void; + onSession(session: Session): void; + transport: Transport; + remoteNode: string; + localNode: string; + sessionId: string; + state: string; + } + + class ClientChannel extends Channel { + constructor(transport: Transport, autoReplyPings?: boolean, autoNotifyReceipt?: boolean); + startNewSession(): void; + negotiateSession(sessionCompression: string, sessionEncryption: string): void; + authenticateSession(identity: string, authentication: Authentication, instance: string): void; + sendFinishingSession(): void; + onSessionNegotiating(session: Session): void; + onSessionAuthenticating(session: Session): void; + onSessionEstablished(session: Session): void; + onSessionFinished(session: Session): void; + onSessionFailed(session: Session): void; + } + + class ClientChannelExtensions { + static establishSession(clientChannel: ClientChannel, compression: string, encryption: string, identity: string, authentication: Authentication, instance: string, callback: (error: Error, session: Session) => any): void; + } + + interface IMessageChannel { + sendMessage(message: Message): void; + onMessage: (message: Message) => any; + } + interface ICommandChannel { + sendCommand(command: Command): void; + onCommand: (command: Command) => any; + } + interface INotificationChannel { + sendNotification(notification: Notification): void; + onNotification: (notification: Notification) => any; + } + interface ISessionChannel { + sendSession(session: Session): void; + onSession: (session: Session) => any; + } + interface ISessionListener { + (session: Session): void; + } + + interface Transport extends ITransportStateListener { + send(envelope: Envelope): void; + onEnvelope: (envelope: Envelope) => any; + open(uri: string): void; + close(): void; + getSupportedCompression(): string[]; + setCompression(compression: string): void; + compression: string; + getSupportedEncryption(): string[]; + setEncryption(encryption: string): void; + encryption: string; + } + interface ITransportEnvelopeListener { + (envelope: Envelope): void; + } + interface ITransportStateListener { + onOpen: () => void; + onClose: () => void; + onError: (error: string) => void; + } + + class WebSocketTransport implements Transport { + webSocket: WebSocket; + constructor(traceEnabled?: boolean); + send(envelope: Envelope): void; + onEnvelope(envelope: Envelope): void; + open(uri: string): void; + close(): void; + getSupportedCompression(): string[]; + setCompression(compression: string): void; + compression: string; + getSupportedEncryption(): string[]; + setEncryption(encryption: string): void; + encryption: string; + onOpen(): void; + onClose(): void; + onError(error: string): void; + } +} diff --git a/lobibox/lobibox-tests.ts b/lobibox/lobibox-tests.ts new file mode 100644 index 0000000000..78637114a1 --- /dev/null +++ b/lobibox/lobibox-tests.ts @@ -0,0 +1,144 @@ +/** + * Created by itboy on 11/22/2015. + */ + /// + /// + + + //Run test : LobiboxTest.test() after window load event +class LobiboxTest { + static test() { + // extending default parameters + Lobibox.notify.DEFAULTS = $.extend({}, Lobibox.notify.DEFAULTS, { + //override any options from default options + delay: false, + soundPath: '/libraries/lobibox/sounds/', + size: 'mini' + }); + +// notify + Lobibox.notify("error", {msg: "Hello world"}); + Lobibox.notify("success", {msg: "Hello world"}); + Lobibox.notify("warning", {msg: "Hello world"}); + Lobibox.notify("info", {msg: "Hello world"}); + +// alert + Lobibox.alert("error", {msg: "Hello world"}); + Lobibox.alert("success", {msg: "Hello world"}); + Lobibox.alert("warning", {msg: "Hello world"}); + Lobibox.alert("info", {msg: "Hello world"}); + +//alert with more options + Lobibox.alert('error', { + msg: 'This is an error message', + //buttons: ['ok', 'cancel', 'yes', 'no'], + //Or more powerfull way + buttons: { + ok: { + 'class': 'btn btn-info', + closeOnClick: false + }, + cancel: { + 'class': 'btn btn-danger', + closeOnClick: false + }, + yes: { + 'class': 'btn btn-success', + closeOnClick: false + }, + no: { + 'class': 'btn btn-warning', + closeOnClick: false + }, + custom: { + 'class': 'btn btn-default', + text: 'Custom' + } + }, + callback: function (lobibox:any, type:string):any { + let btnType:string = ""; + if (type === 'no') { + btnType = 'warning'; + } else if (type === 'yes') { + btnType = 'success'; + } else if (type === 'ok') { + btnType = 'info'; + } else if (type === 'cancel') { + btnType = 'error'; + } + Lobibox.notify(btnType, { + size: 'mini', + msg: 'This is ' + btnType + ' message' + }); + } + }); + +// confirm + Lobibox.confirm({ + msg: "Are you ok", + }); + +// prompt + Lobibox.prompt("text", { + title: 'Please enter username', + //Attributes of + attrs: { + placeholder: "Username" + } + }); + +// progress + Lobibox.progress({ + title: 'Please wait', + label: 'Uploading files...', + onShow: function ($this:any):void { + var i = 0; + var inter = setInterval(function ():void { + window.console.log(i); + if (i > 100) { + clearInterval(inter); + } + i = i + 0.1; + $this.setProgress(i); + }, 10); + } + }); + +// window + Lobibox.window({ + title: 'Window title', + //Available types: string, jquery object, function + content: function ():any { + return $('.container'); + }, + url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.css', + autoload: false, + loadMethod: 'GET', + //Load parameters + params: { + param1: 'Lorem', + param2: 'Ipsum' + }, + buttons: { + load: { + text: 'Load from url' + }, + close: { + text: 'Close', + closeOnClick: true + } + }, + callback: function ($this:any, type:string, ev:any):void { + if (type === 'load') { + $this.load(function ():any { + //Do something when content is loaded + }); + } + } + }); + } +} + +window.onload = (): void => { + LobiboxTest.test(); +}; diff --git a/lobibox/lobibox.d.ts b/lobibox/lobibox.d.ts new file mode 100644 index 0000000000..d8a7588d51 --- /dev/null +++ b/lobibox/lobibox.d.ts @@ -0,0 +1,197 @@ +// Type definitions for lobibox 1.0.1 +// Project: https://github.com/arboshiki/lobibox +// Definitions by: Sabeeh Ul Hussnain +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var Lobibox: LobiboxModule.LobiboxStatic; +declare module "Lobibox" { + export = Lobibox; +} +declare module LobiboxModule { + interface MessageBoxesDefault { + title? : string; + horizontalOffset?: number; + width? : number; + height? : string; // Height is automatically given calculated by width + closeButton? : boolean; // Show close button or not + draggable? : boolean; // Make messagebox draggable + customBtnClass? : string; // Class for custom buttons + modal? : boolean; + debug? : boolean; + buttonsAlign? : string; // Position where buttons should be aligned + closeOnEsc? : boolean; // Close messagebox on Esc press + delayToRemove? : number; + baseClass? : string; + showClass? : string; + hideClass? : string; + msg? : string; + + // methods + hide? (): MessageBoxesDefault; + show? (): MessageBoxesDefault; + setWidth? (width?: number): MessageBoxesDefault; + setHeight? (height?: number): MessageBoxesDefault; + setSize? (width?: number, height?: number): MessageBoxesDefault; + setPosition? (left?: number|string, top?: number): MessageBoxesDefault; + setTitle? (title?: string): MessageBoxesDefault; + getTitle? (): string; + + // events + // when messagebox show is called but before it is actually shown + onShow? (lobibox:any): void ; + // after messagebox is shown + shown? (lobibox:any): void; + // when messagebox remove method is called but before it is actually hidden + beforeClose? (lobibox:any): void; + // after messagebox is hidden + closed? (lobibox:any): void; + } + + interface MessageBoxesOptions extends MessageBoxesDefault { + bodyClass? : string; + modalClasses? : { + 'error'? : string, + 'success'? : string, + 'info'? : string, + 'warning'? : string, + 'confirm'? : string, + 'progress'? : string, + 'prompt'? : string, + 'default'? : string, + 'window'? : string + }, + buttonsAlign?: any; + buttons?: { + ok?: { + 'class'?: string, + text?: string, + closeOnClick?: boolean + }, + cancel?: { + 'class'?: string, + text?: string, + closeOnClick?: boolean + }, + yes?: { + 'class'?: string, + text?: string, + closeOnClick?: boolean + }, + no?: { + 'class'?: string, + text?: string, + closeOnClick?: boolean + }, + }|any; + callback? (lobibox:any, type?:string, ev?: any): void; + } + interface ConfirmOptions extends MessageBoxesOptions { + title? : string; + width? : number; + iconClass? : string; + } + + interface PromptOptions extends MessageBoxesOptions, PromptMethods { + width?: number; + attrs?: any; // Object of any valid attribute of input field + value?: string; // Value which is given to textfield when messagebox is created + multiline?: boolean; // Set this true for multiline prompt + lines?: number; // This works only for multiline prompt. Number of lines + type?: string; // Prompt type. Available types (text|number|color) + label?: string; // Set some text which will be shown exactly on top of textfield + } + interface AlertOptions extends MessageBoxesOptions { + warning?: { + title?: string, + iconClass?: string // Change warning alert icon globally + }; + info?:{ + title?: string, + iconClass?: string // Change info alert icon globally + }; + success?: { + title?: string, + iconClass?: string // Change success alert icon globally + }; + error?: { + title?: string, + iconClass?: string // Change error alert icon globally + }; + } + interface ProgressOptions extends MessageBoxesOptions, ProgressMethods, ProgressEvents { + width? : number; + showProgressLabel? : boolean; // Show percentage of progress + label? : string; // Show progress label + progressTpl? : boolean; //Template of progress bar + + //Events + progressUpdated? : any; + progressCompleted? : any; + } + interface WindowOptions extends MessageBoxesOptions { + width? : number; + height? : any; + content? : any; // HTML Content of window + url? : string; // URL which will be used to load content + draggable? : boolean; // Override default option + autoload? : boolean; // Auto load from given url when window is created + loadMethod? : string; // Ajax method to load content + showAfterLoad? : boolean; // Show window after content is loaded or show and then load content + params? : {}; // Parameters which will be send by ajax for loading content + } + interface ProgressEvents { + progressUpdated? (lobibox:LobiboxStatic): void; + progressComplete? (lobibox:LobiboxStatic): void; + } + interface PromptMethods { + setValue? (val?:string): PromptMethods; + getValue? (): string; + } + interface ProgressMethods { + setProgress? (progress:number): ProgressMethods; + getProgress? (): number; + } + + interface NotifyDefault { + title?: boolean; // Title of notification. If you do not include the title in options it will automatically takes its value + //from Lobibox.notify.OPTIONS object depending of the type of the notifications or set custom string. Set this false to disable title + size?: string; // normal, mini, large + soundPath?: string; // The folder path where sounds are located + soundExt?: string; // Default extension for all sounds + showClass?: string; // Show animation class. + hideClass?: string; // Hide animation class. + icon?: boolean; // Icon of notification. Leave as is for default icon or set custom string + msg?: string; // Message of notification + img?: string; // Image source string + closable?: boolean; // Make notifications closable + delay?: number; // Hide notification after this time (in miliseconds) + delayIndicator?: boolean; // Show timer indicator + closeOnClick?: boolean; // Close notifications by clicking on them + width?: number; // Width of notification box + sound?: boolean; // Sound of notification. Set this false to disable sound. Leave as is for default sound or set custom soud path + position?: string; // Place to show notification. Available options: "top left", "top right", "bottom left", "bottom right" + } + interface NotifyOptions extends NotifyDefault, NotifyMethods { + 'class'?: string; //You can override options for large notifications from here + large?: {width?: number}; //You can override options for small notifications from here + mini?: {'class'?: string}; //Default options of different style notifications + success?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string}; + error?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string}; + warning?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string}; + info?: {'class'?: string, 'title'?: string,'icon'?: string,sound?: string}; + } + + interface NotifyMethods { + remove? (): any; + } + + interface LobiboxStatic { + base: {OPTIONS: MessageBoxesOptions, DEFAULTS: MessageBoxesDefault}; + alert: {(type: string, options?: T): LobiboxStatic, DEFAULTS: AlertOptions}; + prompt: {(type: string, options?: T): LobiboxStatic, DEFAULTS: PromptOptions}; + confirm: {(options?: ConfirmOptions): T, DEFAULTS: ConfirmOptions}; + progress: {(options: ProgressOptions): T, DEFAULTS: ProgressOptions}; + window: {(options: WindowOptions): T, DEFAULTS: WindowOptions}; + notify: {(type: string, options?: NotifyOptions): T, DEFAULTS?: NotifyDefault,OPTIONS?:NotifyOptions}; + } +} diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9cae2a8721..77a20e2e2b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1315,17 +1315,86 @@ module TestSortedIndex { // _.sortedLastIndex module TestSortedLastIndex { - result = _.sortedLastIndex([20, 30, 50], 40); - result = _.sortedLastIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); - var sortedLastIndexDict: { wordToNumber: { [idx: string]: number } } = { - 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } - }; - result = _.sortedLastIndex(['twenty', 'thirty', 'fifty'], 'fourty', function (word: string) { - return sortedLastIndexDict.wordToNumber[word]; - }); - result = _.sortedLastIndex(['twenty', 'thirty', 'fifty'], 'fourty', function (word: string) { - return this.wordToNumber[word]; - }, sortedLastIndexDict); + type SampleType = {a: number; b: string; c: boolean;}; + + let array: SampleType[]; + let list: _.List; + + let value: SampleType; + + let stringIterator: (x: string) => number; + let arrayIterator: (x: SampleType) => number; + let listIterator: (x: SampleType) => number; + + { + let result: number; + + result = _.sortedLastIndex('', ''); + result = _.sortedLastIndex('', '', stringIterator); + result = _.sortedLastIndex('', '', stringIterator, any); + result = _.sortedLastIndex('', '', stringIterator); + result = _.sortedLastIndex('', '', stringIterator, any); + + result = _.sortedLastIndex(array, value); + result = _.sortedLastIndex(array, value, arrayIterator); + result = _.sortedLastIndex(array, value, arrayIterator, any); + result = _.sortedLastIndex(array, value, ''); + result = _.sortedLastIndex(array, value, {a: 42}); + result = _.sortedLastIndex(array, value, arrayIterator); + result = _.sortedLastIndex(array, value, arrayIterator, any); + result = _.sortedLastIndex<{a: number}, SampleType>(array, value, {a: 42}); + + result = _.sortedLastIndex(list, value); + result = _.sortedLastIndex(list, value, listIterator); + result = _.sortedLastIndex(list, value, listIterator, any); + result = _.sortedLastIndex(list, value, ''); + result = _.sortedLastIndex(list, value, {a: 42}); + result = _.sortedLastIndex(list, value, listIterator); + result = _.sortedLastIndex(list, value, listIterator, any); + result = _.sortedLastIndex<{a: number}, SampleType>(list, value, {a: 42}); + + result = _('').sortedLastIndex(''); + result = _('').sortedLastIndex('', stringIterator); + result = _('').sortedLastIndex('', stringIterator, any); + + result = _(array).sortedLastIndex(value); + result = _(array).sortedLastIndex(value, arrayIterator); + result = _(array).sortedLastIndex(value, arrayIterator, any); + result = _(array).sortedLastIndex(value, ''); + result = _(array).sortedLastIndex<{a: number}>(value, {a: 42}); + + result = _(list).sortedLastIndex(value); + result = _(list).sortedLastIndex(value, listIterator); + result = _(list).sortedLastIndex(value, listIterator, any); + result = _(list).sortedLastIndex(value, ''); + result = _(list).sortedLastIndex(value, {a: 42}); + result = _(list).sortedLastIndex(value, listIterator); + result = _(list).sortedLastIndex(value, listIterator, any); + result = _(list).sortedLastIndex<{a: number}, SampleType>(value, {a: 42}); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _('').chain().sortedLastIndex(''); + result = _('').chain().sortedLastIndex('', stringIterator); + result = _('').chain().sortedLastIndex('', stringIterator, any); + + result = _(array).chain().sortedLastIndex(value); + result = _(array).chain().sortedLastIndex(value, arrayIterator); + result = _(array).chain().sortedLastIndex(value, arrayIterator, any); + result = _(array).chain().sortedLastIndex(value, ''); + result = _(array).chain().sortedLastIndex<{a: number}>(value, {a: 42}); + + result = _(list).chain().sortedLastIndex(value); + result = _(list).chain().sortedLastIndex(value, listIterator); + result = _(list).chain().sortedLastIndex(value, listIterator, any); + result = _(list).chain().sortedLastIndex(value, ''); + result = _(list).chain().sortedLastIndex(value, {a: 42}); + result = _(list).chain().sortedLastIndex(value, listIterator); + result = _(list).chain().sortedLastIndex(value, listIterator, any); + result = _(list).chain().sortedLastIndex<{a: number}, SampleType>(value, {a: 42}); + } } // _.tail @@ -1602,37 +1671,329 @@ module TestUnion { } } -result = _.uniq([1, 2, 1, 3, 1]); -result = _.uniq([1, 1, 2, 2, 3], true); -result = _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function (letter) { - return letter.toLowerCase(); -}); -result = _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function (num) { return this.floor(num); }, Math); -result = <{ x: number; }[]>_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); +// _.uniq +module TestUniq { + type SampleObject = {a: number; b: string; c: boolean}; -result = _.unique([1, 2, 1, 3, 1]); -result = _.unique([1, 1, 2, 2, 3], true); -result = _.unique(['A', 'b', 'C', 'a', 'B', 'c'], function (letter) { - return letter.toLowerCase(); -}); -result = _.unique([1, 2.5, 3, 1.5, 2, 3.5], function (num) { return this.floor(num); }, Math); -result = <{ x: number; }[]>_.unique([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + let array: SampleObject[]; + let list: _.List; -result = _([1, 2, 1, 3, 1]).uniq().value(); -result = _([1, 1, 2, 2, 3]).uniq(true).value(); -result = _(['A', 'b', 'C', 'a', 'B', 'c']).uniq(function (letter) { - return letter.toLowerCase(); -}).value(); -result = _([1, 2.5, 3, 1.5, 2, 3.5]).uniq(function (num) { return this.floor(num); }, Math).value(); -result = <{ x: number; }[]>_([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }]).uniq('x').value(); + let stringIterator: (value: string, index: number, collection: string) => string; + let listIterator: (value: SampleObject, index: number, collection: _.List) => number; -result = _([1, 2, 1, 3, 1]).unique().value(); -result = _([1, 1, 2, 2, 3]).unique(true).value(); -result = _(['A', 'b', 'C', 'a', 'B', 'c']).unique(function (letter) { - return letter.toLowerCase(); -}).value(); -result = _([1, 2.5, 3, 1.5, 2, 3.5]).unique(function (num) { return this.floor(num); }, Math).value(); -result = <{ x: number; }[]>_([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }]).unique('x').value(); + { + let result: string[]; + + result = _.uniq('abc'); + result = _.uniq('abc', true); + result = _.uniq('abc', true, stringIterator); + result = _.uniq('abc', true, stringIterator, any); + result = _.uniq('abc', true, stringIterator); + result = _.uniq('abc', true, stringIterator, any); + result = _.uniq('abc', stringIterator); + result = _.uniq('abc', stringIterator, any); + result = _.uniq('abc', stringIterator); + result = _.uniq('abc', stringIterator, any); + } + + { + let result: SampleObject[]; + + result = _.uniq(array); + result = _.uniq(array, true); + result = _.uniq(array, true, listIterator); + result = _.uniq(array, true, listIterator, any); + result = _.uniq(array, true, listIterator); + result = _.uniq(array, true, listIterator, any); + result = _.uniq(array, listIterator); + result = _.uniq(array, listIterator, any); + result = _.uniq(array, listIterator); + result = _.uniq(array, listIterator, any); + result = _.uniq(array, true, 'a'); + result = _.uniq(array, true, 'a', any); + result = _.uniq(array, 'a'); + result = _.uniq(array, 'a', any); + result = _.uniq(array, true, {a: 42}); + result = _.uniq<{a: number}, SampleObject>(array, true, {a: 42}); + result = _.uniq(array, {a: 42}); + result = _.uniq<{a: number}, SampleObject>(array, {a: 42}); + + result = _.uniq(list); + result = _.uniq(list, true); + result = _.uniq(list, true, listIterator); + result = _.uniq(list, true, listIterator, any); + result = _.uniq(list, true, listIterator); + result = _.uniq(list, true, listIterator, any); + result = _.uniq(list, listIterator); + result = _.uniq(list, listIterator, any); + result = _.uniq(list, listIterator); + result = _.uniq(list, listIterator, any); + result = _.uniq(list, true, 'a'); + result = _.uniq(list, true, 'a', any); + result = _.uniq(list, 'a'); + result = _.uniq(list, 'a', any); + result = _.uniq(list, true, {a: 42}); + result = _.uniq<{a: number}, SampleObject>(list, true, {a: 42}); + result = _.uniq(list, {a: 42}); + result = _.uniq<{a: number}, SampleObject>(list, {a: 42}); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('abc').uniq(); + result = _('abc').uniq(true); + result = _('abc').uniq(true, stringIterator); + result = _('abc').uniq(true, stringIterator, any); + result = _('abc').uniq(stringIterator); + result = _('abc').uniq(stringIterator, any); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(array).uniq(); + result = _(array).uniq(true); + result = _(array).uniq(true, listIterator); + result = _(array).uniq(true, listIterator, any); + result = _(array).uniq(listIterator); + result = _(array).uniq(listIterator, any); + result = _(array).uniq(true, 'a'); + result = _(array).uniq(true, 'a', any); + result = _(array).uniq('a'); + result = _(array).uniq('a', any); + result = _(array).uniq<{a: number}>(true, {a: 42}); + result = _(array).uniq<{a: number}>({a: 42}); + + result = _(list).uniq(); + result = _(list).uniq(true); + result = _(list).uniq(true, listIterator); + result = _(list).uniq(true, listIterator, any); + result = _(list).uniq(true, listIterator); + result = _(list).uniq(true, listIterator, any); + result = _(list).uniq(listIterator); + result = _(list).uniq(listIterator, any); + result = _(list).uniq(listIterator); + result = _(list).uniq(listIterator, any); + result = _(list).uniq(true, 'a'); + result = _(list).uniq(true, 'a', any); + result = _(list).uniq('a'); + result = _(list).uniq('a', any); + result = _(list).uniq(true, {a: 42}); + result = _(list).uniq<{a: number}, SampleObject>(true, {a: 42}); + result = _(list).uniq({a: 42}); + result = _(list).uniq<{a: number}, SampleObject>({a: 42}); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _('abc').chain().uniq(); + result = _('abc').chain().uniq(true); + result = _('abc').chain().uniq(true, stringIterator); + result = _('abc').chain().uniq(true, stringIterator, any); + result = _('abc').chain().uniq(stringIterator); + result = _('abc').chain().uniq(stringIterator, any); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().uniq(); + result = _(array).chain().uniq(true); + result = _(array).chain().uniq(true, listIterator); + result = _(array).chain().uniq(true, listIterator, any); + result = _(array).chain().uniq(listIterator); + result = _(array).chain().uniq(listIterator, any); + result = _(array).chain().uniq(true, 'a'); + result = _(array).chain().uniq(true, 'a', any); + result = _(array).chain().uniq('a'); + result = _(array).chain().uniq('a', any); + result = _(array).chain().uniq<{a: number}>(true, {a: 42}); + result = _(array).chain().uniq<{a: number}>({a: 42}); + + result = _(list).chain().uniq(); + result = _(list).chain().uniq(true); + result = _(list).chain().uniq(true, listIterator); + result = _(list).chain().uniq(true, listIterator, any); + result = _(list).chain().uniq(true, listIterator); + result = _(list).chain().uniq(true, listIterator, any); + result = _(list).chain().uniq(listIterator); + result = _(list).chain().uniq(listIterator, any); + result = _(list).chain().uniq(listIterator); + result = _(list).chain().uniq(listIterator, any); + result = _(list).chain().uniq(true, 'a'); + result = _(list).chain().uniq(true, 'a', any); + result = _(list).chain().uniq('a'); + result = _(list).chain().uniq('a', any); + result = _(list).chain().uniq(true, {a: 42}); + result = _(list).chain().uniq<{a: number}, SampleObject>(true, {a: 42}); + result = _(list).chain().uniq({a: 42}); + result = _(list).chain().uniq<{a: number}, SampleObject>({a: 42}); + } +} + +// _.unique +module TestUnique { + type SampleObject = {a: number; b: string; c: boolean}; + + let array: SampleObject[]; + let list: _.List; + + let stringIterator: (value: string, index: number, collection: string) => string; + let listIterator: (value: SampleObject, index: number, collection: _.List) => number; + + { + let result: string[]; + + result = _.unique('abc'); + result = _.unique('abc', true); + result = _.unique('abc', true, stringIterator); + result = _.unique('abc', true, stringIterator, any); + result = _.unique('abc', true, stringIterator); + result = _.unique('abc', true, stringIterator, any); + result = _.unique('abc', stringIterator); + result = _.unique('abc', stringIterator, any); + result = _.unique('abc', stringIterator); + result = _.unique('abc', stringIterator, any); + } + + { + let result: SampleObject[]; + + result = _.unique(array); + result = _.unique(array, true); + result = _.unique(array, true, listIterator); + result = _.unique(array, true, listIterator, any); + result = _.unique(array, true, listIterator); + result = _.unique(array, true, listIterator, any); + result = _.unique(array, listIterator); + result = _.unique(array, listIterator, any); + result = _.unique(array, listIterator); + result = _.unique(array, listIterator, any); + result = _.unique(array, true, 'a'); + result = _.unique(array, true, 'a', any); + result = _.unique(array, 'a'); + result = _.unique(array, 'a', any); + result = _.unique(array, true, {a: 42}); + result = _.unique<{a: number}, SampleObject>(array, true, {a: 42}); + result = _.unique(array, {a: 42}); + result = _.unique<{a: number}, SampleObject>(array, {a: 42}); + + result = _.unique(list); + result = _.unique(list, true); + result = _.unique(list, true, listIterator); + result = _.unique(list, true, listIterator, any); + result = _.unique(list, true, listIterator); + result = _.unique(list, true, listIterator, any); + result = _.unique(list, listIterator); + result = _.unique(list, listIterator, any); + result = _.unique(list, listIterator); + result = _.unique(list, listIterator, any); + result = _.unique(list, true, 'a'); + result = _.unique(list, true, 'a', any); + result = _.unique(list, 'a'); + result = _.unique(list, 'a', any); + result = _.unique(list, true, {a: 42}); + result = _.unique<{a: number}, SampleObject>(list, true, {a: 42}); + result = _.unique(list, {a: 42}); + result = _.unique<{a: number}, SampleObject>(list, {a: 42}); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('abc').unique(); + result = _('abc').unique(true); + result = _('abc').unique(true, stringIterator); + result = _('abc').unique(true, stringIterator, any); + result = _('abc').unique(stringIterator); + result = _('abc').unique(stringIterator, any); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _(array).unique(); + result = _(array).unique(true); + result = _(array).unique(true, listIterator); + result = _(array).unique(true, listIterator, any); + result = _(array).unique(listIterator); + result = _(array).unique(listIterator, any); + result = _(array).unique(true, 'a'); + result = _(array).unique(true, 'a', any); + result = _(array).unique('a'); + result = _(array).unique('a', any); + result = _(array).unique<{a: number}>(true, {a: 42}); + result = _(array).unique<{a: number}>({a: 42}); + + result = _(list).unique(); + result = _(list).unique(true); + result = _(list).unique(true, listIterator); + result = _(list).unique(true, listIterator, any); + result = _(list).unique(true, listIterator); + result = _(list).unique(true, listIterator, any); + result = _(list).unique(listIterator); + result = _(list).unique(listIterator, any); + result = _(list).unique(listIterator); + result = _(list).unique(listIterator, any); + result = _(list).unique(true, 'a'); + result = _(list).unique(true, 'a', any); + result = _(list).unique('a'); + result = _(list).unique('a', any); + result = _(list).unique(true, {a: 42}); + result = _(list).unique<{a: number}, SampleObject>(true, {a: 42}); + result = _(list).unique({a: 42}); + result = _(list).unique<{a: number}, SampleObject>({a: 42}); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _('abc').chain().unique(); + result = _('abc').chain().unique(true); + result = _('abc').chain().unique(true, stringIterator); + result = _('abc').chain().unique(true, stringIterator, any); + result = _('abc').chain().unique(stringIterator); + result = _('abc').chain().unique(stringIterator, any); + } + + { + let result: _.LoDashExplicitArrayWrapper; + + result = _(array).chain().unique(); + result = _(array).chain().unique(true); + result = _(array).chain().unique(true, listIterator); + result = _(array).chain().unique(true, listIterator, any); + result = _(array).chain().unique(listIterator); + result = _(array).chain().unique(listIterator, any); + result = _(array).chain().unique(true, 'a'); + result = _(array).chain().unique(true, 'a', any); + result = _(array).chain().unique('a'); + result = _(array).chain().unique('a', any); + result = _(array).chain().unique<{a: number}>(true, {a: 42}); + result = _(array).chain().unique<{a: number}>({a: 42}); + + result = _(list).chain().unique(); + result = _(list).chain().unique(true); + result = _(list).chain().unique(true, listIterator); + result = _(list).chain().unique(true, listIterator, any); + result = _(list).chain().unique(true, listIterator); + result = _(list).chain().unique(true, listIterator, any); + result = _(list).chain().unique(listIterator); + result = _(list).chain().unique(listIterator, any); + result = _(list).chain().unique(listIterator); + result = _(list).chain().unique(listIterator, any); + result = _(list).chain().unique(true, 'a'); + result = _(list).chain().unique(true, 'a', any); + result = _(list).chain().unique('a'); + result = _(list).chain().unique('a', any); + result = _(list).chain().unique(true, {a: 42}); + result = _(list).chain().unique<{a: number}, SampleObject>(true, {a: 42}); + result = _(list).chain().unique({a: 42}); + result = _(list).chain().unique<{a: number}, SampleObject>({a: 42}); + } +} // _.upzip module TestUnzip { @@ -2625,9 +2986,11 @@ module TestAny { let array: TResult[]; let list: _.List; let dictionary: _.Dictionary; + let numericDictionary: _.NumericDictionary; let listIterator: (value: TResult, index: number, collection: _.List) => boolean; let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => boolean; + let numericDictionaryIterator: (value: TResult, key: number, collection: _.NumericDictionary) => boolean; { let result: boolean; @@ -2650,6 +3013,12 @@ module TestAny { result = _.any(dictionary, ''); result = _.any<{a: number}, TResult>(dictionary, {a: 42}); + result = _.any(numericDictionary); + result = _.any(numericDictionary, numericDictionaryIterator); + result = _.any(numericDictionary, numericDictionaryIterator, any); + result = _.any(numericDictionary, ''); + result = _.any<{a: number}, TResult>(numericDictionary, {a: 42}); + result = _(array).any(); result = _(array).any(listIterator); result = _(array).any(listIterator, any); @@ -2667,6 +3036,12 @@ module TestAny { result = _(dictionary).any(dictionaryIterator, any); result = _(dictionary).any(''); result = _(dictionary).any<{a: number}>({a: 42}); + + result = _(numericDictionary).any(); + result = _(numericDictionary).any(numericDictionaryIterator); + result = _(numericDictionary).any(numericDictionaryIterator, any); + result = _(numericDictionary).any(''); + result = _(numericDictionary).any<{a: number}>({a: 42}); } { @@ -2689,6 +3064,12 @@ module TestAny { result = _(dictionary).chain().any(dictionaryIterator, any); result = _(dictionary).chain().any(''); result = _(dictionary).chain().any<{a: number}>({a: 42}); + + result = _(numericDictionary).chain().any(); + result = _(numericDictionary).chain().any(numericDictionaryIterator); + result = _(numericDictionary).chain().any(numericDictionaryIterator, any); + result = _(numericDictionary).chain().any(''); + result = _(numericDictionary).chain().any<{a: number}>({a: 42}); } } @@ -4309,9 +4690,11 @@ module TestSome { let array: TResult[]; let list: _.List; let dictionary: _.Dictionary; + let numericDictionary: _.NumericDictionary; let listIterator: (value: TResult, index: number, collection: _.List) => boolean; let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => boolean; + let numericDictionaryIterator: (value: TResult, key: number, collection: _.NumericDictionary) => boolean; { let result: boolean; @@ -4334,6 +4717,12 @@ module TestSome { result = _.some(dictionary, ''); result = _.some<{a: number}, TResult>(dictionary, {a: 42}); + result = _.some(numericDictionary); + result = _.some(numericDictionary, numericDictionaryIterator); + result = _.some(numericDictionary, numericDictionaryIterator, any); + result = _.some(numericDictionary, ''); + result = _.some<{a: number}, TResult>(numericDictionary, {a: 42}); + result = _(array).some(); result = _(array).some(listIterator); result = _(array).some(listIterator, any); @@ -4351,6 +4740,12 @@ module TestSome { result = _(dictionary).some(dictionaryIterator, any); result = _(dictionary).some(''); result = _(dictionary).some<{a: number}>({a: 42}); + + result = _(numericDictionary).some(); + result = _(numericDictionary).some(numericDictionaryIterator); + result = _(numericDictionary).some(numericDictionaryIterator, any); + result = _(numericDictionary).some(''); + result = _(numericDictionary).some<{a: number}>({a: 42}); } { @@ -4373,6 +4768,12 @@ module TestSome { result = _(dictionary).chain().some(dictionaryIterator, any); result = _(dictionary).chain().some(''); result = _(dictionary).chain().some<{a: number}>({a: 42}); + + result = _(numericDictionary).chain().some(); + result = _(numericDictionary).chain().some(numericDictionaryIterator); + result = _(numericDictionary).chain().some(numericDictionaryIterator, any); + result = _(numericDictionary).chain().some(''); + result = _(numericDictionary).chain().some<{a: number}>({a: 42}); } } @@ -4589,22 +4990,31 @@ module TestBackflow { } // _.before -var testBeforeFn = ((n: number) => () => ++n)(0); -var testBeforeResultFn = <() => number>_.before<() => number>(3, testBeforeFn); -result = testBeforeResultFn(); -// → 1 -result = testBeforeResultFn(); -// → 2 -result = testBeforeResultFn(); -// → 2 -var testBeforeFn = ((n: number) => () => ++n)(0); -var testBeforeResultFn = <() => number>_(3).before<() => number>(testBeforeFn); -result = testBeforeResultFn(); -// → 1 -result = testBeforeResultFn(); -// → 2 -result = testBeforeResultFn(); -// → 2 +module TestBefore { + interface Func { + (a: string, b: number): boolean; + } + + let func: Func; + + { + let result: Func; + + _.before(42, func); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + _(42).before(func); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + _(42).chain().before(func); + } +} var funcBind = function(greeting: string, punctuation: string) { return greeting + ' ' + this.user + punctuation; }; var funcBound1: (punctuation: string) => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); @@ -4617,16 +5027,43 @@ var addTwoNumbers = function (x: number, y: number) { return x + y }; var plusTwo = _.bind(addTwoNumbers, null, 2); plusTwo(100); -var view = { - 'label': 'docs', - 'onClick': function () { console.log('clicked ' + this.label); } -}; +// _.bindAll +module TestBindAll { + interface SampleObject { + a: Function; + b: Function; + c: Function; + } -view = _.bindAll(view); -jQuery('#docs').on('click', view.onClick); + let object: SampleObject; -view = _(view).bindAll().value(); -jQuery('#docs').on('click', view.onClick); + { + let result: SampleObject; + + result = _.bindAll(object); + result = _.bindAll(object, 'c'); + result = _.bindAll(object, ['b'], 'c'); + result = _.bindAll(object, 'a', ['b'], 'c'); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(object).bindAll(); + result = _(object).bindAll('c'); + result = _(object).bindAll(['b'], 'c'); + result = _(object).bindAll('a', ['b'], 'c'); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(object).chain().bindAll(); + result = _(object).chain().bindAll('c'); + result = _(object).chain().bindAll(['b'], 'c'); + result = _(object).chain().bindAll('a', ['b'], 'c'); + } +} var objectBindKey = { 'name': 'moe', @@ -4733,28 +5170,50 @@ curryResult7 = _.curryRight(testCurry2)(true)(2); curryResult8 = _.curryRight(testCurry2)(true); curryResult9 = _.curryRight(testCurry2); -declare var source: any; -result = _.debounce(function () { }, 150); +// _.debounce +module TestDebounce { + interface SampleFunc { + (n: number, s: string): boolean; + } -jQuery('#postbox').on('click', _.debounce(function () { }, 300, { - 'leading': true, - 'trailing': false -})); + interface Options { + leading?: boolean; + maxWait?: number; + trailing?: boolean; + } -source.addEventListener('message', _.debounce(function () { }, 250, { - 'maxWait': 1000 -}), false); + interface ResultFunc { + (n: number, s: string): boolean; + cancel(): void; + } -result = <_.LoDashImplicitObjectWrapper>_(function () { }).debounce(150); + let func: SampleFunc; + let options: Options; -jQuery('#postbox').on('click', <_.LoDashImplicitObjectWrapper>_(function () { }).debounce(300, { - 'leading': true, - 'trailing': false -})); + { + let result: ResultFunc; -source.addEventListener('message', <_.LoDashImplicitObjectWrapper>_(function () { }).debounce(250, { - 'maxWait': 1000 -}), false); + result = _.debounce(func); + result = _.debounce(func, 42); + result = _.debounce(func, 42, options); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(func).debounce(); + result = _(func).debounce(42); + result = _(func).debounce(42, options); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(func).chain().debounce(); + result = _(func).chain().debounce(42); + result = _(func).chain().debounce(42, options); + } +} // _.defer module TestDefer { @@ -4822,10 +5281,34 @@ module TestDelay { } // _.flow -var testFlowSquareFn = (n: number) => n * n; -var testFlowAddFn = (n: number, m: number) => n + m; -result = _.flow<(n: number, m: number) => number>(testFlowAddFn, testFlowSquareFn)(1, 2); -result = _(testFlowAddFn).flow<(n: number, m: number) => number>(testFlowSquareFn).value()(1, 2); +module TestFlow { + let Fn1: (n: number) => number; + let Fn2: (m: number, n: number) => number; + + { + let result: (m: number, n: number) => number; + + result = _.flow<(m: number, n: number) => number>(Fn1, Fn2); + result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + result = _.flow<(m: number, n: number) => number>(Fn1, Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashImplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).flow<(m: number, n: number) => number>(Fn2); + result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } + + { + let result: _.LoDashExplicitObjectWrapper<(m: number, n: number) => number>; + + result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn2); + result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn2); + result = _(Fn1).chain().flow<(m: number, n: number) => number>(Fn1, Fn1, Fn2); + } +} // _.flowRight module TestFlowRight { @@ -4925,17 +5408,38 @@ module TestModArgs { } // _.negate -interface TestNegatePredicate { - (a1: number, a2: number): boolean; +module TestNegate { + interface PredicateFn { + (a1: number, a2: number): boolean; + } + + interface ResultFn { + (a1: number, a2: number): boolean; + } + + var predicate = (a1: number, a2: number) => a1 > a2; + + { + let result: ResultFn; + + result = _.negate(predicate); + result = _.negate(predicate); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _(predicate).negate(); + result = _(predicate).negate(); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _(predicate).chain().negate(); + result = _(predicate).chain().negate(); + } } -interface TestNegateResult { - (a1: number, a2: number): boolean; -} -var testNegatePredicate = (a1: number, a2: number) => a1 > a2; -result = _.negate(testNegatePredicate); -result = _.negate(testNegatePredicate); -result = _(testNegatePredicate).negate().value(); -result = _(testNegatePredicate).negate().value(); // _.once module TestOnce { @@ -5250,53 +5754,101 @@ result = _({}).isArguments(); } // _.isArray -result = _.isArray(any); -result = _(1).isArray(); -result = _([]).isArray(); -result = _({}).isArray(); -{ - let value: number[]|string = [1, 3, 5]; - if (_.isArray(value)) { - let length: number[] = value.concat(4); - // compile error - // let char: string = value.charAt(0); - } else { - let char: string = value.charAt(0); - // compile error - // let length: number[] = value.concat(4); - } +module TestIsArray { + { + let value: number|string[]|boolean[]; + + if (_.isArray(value)) { + let result: string[] = value; + } + else { + if (_.isArray(value)) { + let result: boolean[] = value; + } + else { + let result: number = value; + } + } + } + + { + let result: boolean; + + result = _.isArray(any); + result = _(1).isArray(); + result = _([]).isArray(); + result = _({}).isArray(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isArray(); + result = _([]).chain().isArray(); + result = _({}).chain().isArray(); + } } // _.isBoolean -result = _.isBoolean(any); -result = _(1).isBoolean(); -result = _([]).isBoolean(); -result = _({}).isBoolean(); -{ - let value: number[]|boolean = [1, 3, 5]; - if (_.isBoolean(value)) { - let b: boolean = value; - // compile error - // let length: number = value.length; - } else { - let length: number = value.length; - // compile error - // let b: boolean = value; +module TestIsBoolean { + { + let value: number|boolean; + + if (_.isBoolean(value)) { + let result: boolean = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isBoolean(any); + result = _(1).isBoolean(); + result = _([]).isBoolean(); + result = _({}).isBoolean(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isBoolean(); + result = _([]).chain().isBoolean(); + result = _({}).chain().isBoolean(); } } // _.isDate -result = _.isDate(any); -result = _(42).isDate(); -result = _([]).isDate(); -result = _({}).isDate(); -{ - let value: Date|string = "foo"; - if (_.isDate(value)) { - value.toTimeString(); - } else { - value.charAt(0); - } +module TestIsBoolean { + { + let value: number|Date; + + if (_.isDate(value)) { + let result: Date = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isDate(any); + result = _(42).isDate(); + result = _([]).isDate(); + result = _({}).isDate(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(42).chain().isDate(); + result = _([]).chain().isDate(); + result = _({}).chain().isDate(); + } } // _.isElement @@ -5368,23 +5920,54 @@ result = _({}).isError(); } // _.isFinite -result = _.isFinite(any); -result = _(1).isFinite(); -result = _([]).isFinite(); -result = _({}).isFinite(); +module TestIsFinite { + { + let result: boolean; + + result = _.isFinite(any); + result = _(1).isFinite(); + result = _([]).isFinite(); + result = _({}).isFinite(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isFinite(); + result = _([]).chain().isFinite(); + result = _({}).chain().isFinite(); + } +} // _.isFunction -result = _.isFunction(any); -result = _(1).isFunction(); -result = _([]).isFunction(); -result = _({}).isFunction(); -{ - let value: Function|string = "foo"; - if (_.isFunction(value)) { - value(); - } else { - let result: string = value; - } +module TestIsFunction { + { + let value: number|Function; + + if (_.isFunction(value)) { + let result: Function = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isFunction(any); + result = _(1).isFunction(); + result = _([]).isFunction(); + result = _({}).isFunction(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isFunction(); + result = _([]).chain().isFunction(); + result = _({}).chain().isFunction(); + } } // _.isMatch @@ -5397,23 +5980,56 @@ result = _({}).isMatch({}, testIsMatchCustiomizerFn); result = _({}).isMatch({}, testIsMatchCustiomizerFn, {}); // _.isNaN -result = _.isNaN(NaN); -result = _.isNaN(new Number(NaN)); -result = _.isNaN(undefined); -result = _(NaN).isNaN(); -result = _(new Number(NaN)).isNaN(); -result = _(undefined).isNaN(); +module TestIsNaN { + { + let result: boolean; + + result = _.isNaN(any); + + result = _(1).isNaN(); + result = _([]).isNaN(); + result = _({}).isNaN(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isNaN(); + result = _([]).chain().isNaN(); + result = _({}).chain().isNaN(); + } +} // _.isNative -result = _.isNative(Array.prototype.push); -result = _(Array.prototype.push).isNative(); -{ - let value: Function|string = "foo"; - if (_.isNative(value)) { - value(); - } else { - let result: string = value; - } +module TestIsNative { + { + let value: number|Function; + + if (_.isNative(value)) { + let result: Function = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isNative(any); + + result = _(1).isNative(); + result = _([]).isNative(); + result = _({}).isNative(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isNative(); + result = _([]).chain().isNative(); + result = _({}).chain().isNative(); + } } // _.isNull @@ -5438,24 +6054,56 @@ module TestIsNull { } // _.isNumber -result = _.isNumber(any); -result = _(1).isNumber(); -result = _([]).isNumber(); -result = _({}).isNumber(); -{ - let value: number|string = "foo"; - if (_.isNumber(value)) { - let result: number = value * 42; - } else { - let result: string = value; - } +module TestIsNumber { + { + let value: string|number; + + if (_.isNumber(value)) { + let result: number = value; + } + else { + let result: string = value; + } + } + + { + let result: boolean; + + result = _.isNumber(any); + + result = _(1).isNumber(); + result = _([]).isNumber(); + result = _({}).isNumber(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isNumber(); + result = _([]).chain().isNumber(); + result = _({}).chain().isNumber(); + } } // _.isObject -result = _.isObject(any); -result = _(1).isObject(); -result = _([]).isObject(); -result = _({}).isObject(); +module TestIsObject { + { + let result: boolean; + + result = _.isObject(any); + result = _(1).isObject(); + result = _([]).isObject(); + result = _({}).isObject(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isObject(); + result = _([]).chain().isObject(); + result = _({}).chain().isObject(); + } +} // _.isPlainObject result = _.isPlainObject(any); @@ -5464,32 +6112,65 @@ result = _([]).isPlainObject(); result = _({}).isPlainObject(); // _.isRegExp -result = _.isRegExp(any); -result = _(1).isRegExp(); -result = _([]).isRegExp(); -result = _({}).isRegExp(); -{ - let value: RegExp|string = /^foo$/g; - if (_.isRegExp(value)) { - let regex: RegExp = value; - let index: number = value.exec("foo").index; - } else { - let result: string = value; - } +module TestIsRegExp { + { + let value: number|RegExp; + + if (_.isRegExp(value)) { + let result: RegExp = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isRegExp(any); + result = _(1).isRegExp(); + result = _([]).isRegExp(); + result = _({}).isRegExp(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isRegExp(); + result = _([]).chain().isRegExp(); + result = _({}).chain().isRegExp(); + } } // _.isString -result = _.isString(any); -result = _(1).isString(); -result = _([]).isString(); -result = _({}).isString(); -{ - let value: string|number = "foo"; - if (_.isString(value)) { - let result: string = value; - } else { - let result: number = value * 42; - } +module TestIsString { + { + let value: number|string; + + if (_.isString(value)) { + let result: string = value; + } + else { + let result: number = value; + } + } + + { + let result: boolean; + + result = _.isString(any); + result = _(1).isString(); + result = _([]).isString(); + result = _({}).isString(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isString(); + result = _([]).chain().isString(); + result = _({}).chain().isString(); + } } // _.isTypedArray @@ -5509,10 +6190,25 @@ module TestIsTypedArray { } // _.isUndefined -result = _.isUndefined(any); -result = _(1).isUndefined(); -result = _([]).isUndefined(); -result = _({}).isUndefined(); +module TestIsUndefined { + { + let result: boolean; + + result = _.isUndefined(any); + + result = _(1).isUndefined(); + result = _([]).isUndefined(); + result = _({}).isUndefined(); + } + + { + let result: _.LoDashExplicitWrapper; + + result = _(1).chain().isUndefined(); + result = _([]).chain().isUndefined(); + result = _({}).chain().isUndefined(); + } +} // _.lt module TestLt { @@ -6991,19 +7687,43 @@ module TestFunctions { } } -interface HasName { - name: string; +// _.omit +module TestOmit { + let predicate: (element: any, key: string, collection: any) => boolean; + + { + let result: TResult; + + result = _.omit({}, 'a'); + result = _.omit({}, 0, 'a'); + result = _.omit({}, true, 0, 'a'); + result = _.omit({}, ['b', 1, false], true, 0, 'a'); + result = _.omit({}, predicate); + result = _.omit({}, predicate, any); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _({}).omit('a'); + result = _({}).omit(0, 'a'); + result = _({}).omit(true, 0, 'a'); + result = _({}).omit(['b', 1, false], true, 0, 'a'); + result = _({}).omit(predicate); + result = _({}).omit(predicate, any); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _({}).chain().omit('a'); + result = _({}).chain().omit(0, 'a'); + result = _({}).chain().omit(true, 0, 'a'); + result = _({}).chain().omit(['b', 1, false], true, 0, 'a'); + result = _({}).chain().omit(predicate); + result = _({}).chain().omit(predicate, any); + } } -result = _.omit({ 'name': 'moe', 'age': 40 }, 'age'); -result = _.omit({ 'name': 'moe', 'age': 40 }, ['age']); -result = _.omit({ 'name': 'moe', 'age': 40 }, function (value) { - return typeof value == 'number'; -}); -result = _({ 'name': 'moe', 'age': 40 }).omit('age').value(); -result = _({ 'name': 'moe', 'age': 40 }).omit(['age']).value(); -result = _({ 'name': 'moe', 'age': 40 }).omit(function (value) { - return typeof value == 'number'; -}).value(); // _.pairs module TestPairs { @@ -7047,18 +7767,41 @@ module TestPairs { } // _.pick -interface TestPickFn { - (element: any, key: string, collection: any): boolean; -} -{ - let testPickFn: TestPickFn; - let result: TResult; - result = _.pick({}, 0, '1', true, [2], ['3'], [true], [4, '5', true]); - result = _.pick({}, testPickFn); - result = _.pick({}, testPickFn, any); - result = _({}).pick(0, '1', true, [2], ['3'], [true], [4, '5', true]).value(); - result = _({}).pick(testPickFn).value(); - result = _({}).pick(testPickFn, any).value(); +module TestPick { + let predicate: (element: any, key: string, collection: any) => boolean; + + { + let result: TResult; + + result = _.pick({}, 'a'); + result = _.pick({}, 0, 'a'); + result = _.pick({}, true, 0, 'a'); + result = _.pick({}, ['b', 1, false], true, 0, 'a'); + result = _.pick({}, predicate); + result = _.pick({}, predicate, any); + } + + { + let result: _.LoDashImplicitObjectWrapper; + + result = _({}).pick('a'); + result = _({}).pick(0, 'a'); + result = _({}).pick(true, 0, 'a'); + result = _({}).pick(['b', 1, false], true, 0, 'a'); + result = _({}).pick(predicate); + result = _({}).pick(predicate, any); + } + + { + let result: _.LoDashExplicitObjectWrapper; + + result = _({}).chain().pick('a'); + result = _({}).chain().pick(0, 'a'); + result = _({}).chain().pick(true, 0, 'a'); + result = _({}).chain().pick(['b', 1, false], true, 0, 'a'); + result = _({}).chain().pick(predicate); + result = _({}).chain().pick(predicate, any); + } } // _.result diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ed8d72443a..c45ec90eea 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2156,71 +2156,222 @@ declare module _ { //_.sortedLastIndex interface LoDashStatic { /** - * Uses a binary search to determine the highest index at which a value should be inserted - * into a given sorted array in order to maintain the sort order of the array. If a callback - * is provided it will be executed for value and each element of array to compute their sort - * ranking. The callback is bound to thisArg and invoked with one argument; (value). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array The sorted list. - * @param value The value to determine its index within `list`. - * @param callback Iterator to compute the sort ranking of each value, optional. - * @return The index at which value should be inserted into array. - **/ - sortedLastIndex( - array: Array, - value: T, - callback?: (x: T) => TSort, - thisArg?: any): number; - - /** - * @see _.sortedLastIndex - **/ + * This method is like _.sortedIndex except that it returns the highest index at which value should be + * inserted into array in order to maintain its sort order. + * + * @param array The sorted array to inspect. + * @param value The value to evaluate. + * @param iteratee The function invoked per iteration. + * @param thisArg The this binding of iteratee. + * @return Returns the index at which value should be inserted into array. + */ sortedLastIndex( array: List, value: T, - callback?: (x: T) => TSort, - thisArg?: any): number; + iteratee?: (x: T) => TSort, + thisArg?: any + ): number; /** - * @see _.sortedLastIndex - * @param pluckValue the _.pluck style callback - **/ - sortedLastIndex( - array: Array, - value: T, - pluckValue: string): number; - - /** - * @see _.sortedLastIndex - * @param pluckValue the _.pluck style callback - **/ + * @see _.sortedLastIndex + */ sortedLastIndex( array: List, value: T, - pluckValue: string): number; + iteratee?: (x: T) => any, + thisArg?: any + ): number; /** - * @see _.sortedLastIndex - * @param pluckValue the _.where style callback - **/ - sortedLastIndex( - array: Array, + * @see _.sortedLastIndex + */ + sortedLastIndex( + array: List, value: T, - whereValue: W): number; + iteratee: string + ): number; /** - * @see _.sortedLastIndex - * @param pluckValue the _.where style callback - **/ + * @see _.sortedLastIndex + */ sortedLastIndex( array: List, value: T, - whereValue: W): number; + iteratee: W + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + array: List, + value: T, + iteratee: Object + ): number; + } + + interface LoDashImplicitWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: string, + iteratee?: (x: string) => TSort, + thisArg?: any + ): number; + } + + interface LoDashImplicitArrayWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => TSort, + thisArg?: any + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: string + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: W + ): number; + } + + interface LoDashImplicitObjectWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => TSort, + thisArg?: any + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => any, + thisArg?: any + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: string + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: W + ): number; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: Object + ): number; + } + + interface LoDashExplicitWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: string, + iteratee?: (x: string) => TSort, + thisArg?: any + ): LoDashExplicitWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => TSort, + thisArg?: any + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: W + ): LoDashExplicitWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => TSort, + thisArg?: any + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee?: (x: T) => any, + thisArg?: any + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: string + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: W + ): LoDashExplicitWrapper; + + /** + * @see _.sortedLastIndex + */ + sortedLastIndex( + value: T, + iteratee: Object + ): LoDashExplicitWrapper; } //_.tail @@ -2686,343 +2837,810 @@ declare module _ { //_.uniq interface LoDashStatic { /** - * Creates a duplicate-value-free version of an array using strict equality for comparisons, - * i.e. ===. If the array is sorted, providing true for isSorted will use a faster algorithm. - * If a callback is provided each element of array is passed through the callback before - * uniqueness is computed. The callback is bound to thisArg and invoked with three arguments; - * (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. - * @param array Array to remove duplicates from. - * @param isSorted True if `array` is already sorted, optiona, default = false. - * @param iterator Transform the elements of `array` before comparisons for uniqueness. - * @param context 'this' object in `iterator`, optional. - * @return Copy of `array` where all elements are unique. - **/ - uniq(array: Array, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - uniq(array: List, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: Array, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: List, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - uniq( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: Array, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ + * Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only + * the first occurrence of each element is kept. Providing true for isSorted performs a faster search + * algorithm for sorted arrays. If an iteratee function is provided it’s invoked for each element in the + * array to generate the criterion by which uniqueness is computed. The iteratee is bound to thisArg and + * invoked with three arguments: (value, index, array). + * + * If a property name is provided for iteratee the created _.property style callback returns the property + * value of the given element. + * + * If a value is also provided for thisArg the created _.matchesProperty style callback returns true for + * elements that have a matching property value, else false. + * + * If an object is provided for iteratee the created _.matches style callback returns true for elements that + * have the properties of the given object, else false. + * + * @alias _.unique + * + * @param array The array to inspect. + * @param isSorted Specify the array is sorted. + * @param iteratee The function invoked per iteration. + * @param thisArg iteratee + * @return Returns the new duplicate-value-free array. + */ uniq( array: List, - isSorted: boolean, - pluckValue: string): T[]; + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): T[]; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq( - array: Array, - pluckValue: string): T[]; + * @see _.uniq + */ + uniq( + array: List, + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): T[]; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ + * @see _.uniq + */ uniq( array: List, - pluckValue: string): T[]; + iteratee?: ListIterator, + thisArg?: any + ): T[]; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: Array, - isSorted: boolean, - whereValue: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( + * @see _.uniq + */ + uniq( array: List, - isSorted: boolean, - whereValue: W): T[]; + iteratee?: ListIterator, + thisArg?: any + ): T[]; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - array: Array, - whereValue: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( + * @see _.uniq + */ + uniq( array: List, - whereValue: W): T[]; + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): T[]; /** - * @see _.uniq - **/ - unique(array: Array, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - unique(array: List, isSorted?: boolean): T[]; - - /** - * @see _.uniq - **/ - unique( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - unique( + * @see _.uniq + */ + uniq( array: List, - callback: ListIterator, - thisArg?: any): T[]; + iteratee?: string, + thisArg?: any + ): T[]; /** - * @see _.uniq - **/ - unique( - array: Array, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.uniq - **/ - unique( + * @see _.uniq + */ + uniq( array: List, - isSorted: boolean, - callback: ListIterator, - thisArg?: any): T[]; + isSorted?: boolean, + iteratee?: Object + ): T[]; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: Array, - isSorted: boolean, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( + * @see _.uniq + */ + uniq( array: List, - isSorted: boolean, - pluckValue: string): T[]; + isSorted?: boolean, + iteratee?: TWhere + ): T[]; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique( + * @see _.uniq + */ + uniq( array: List, - pluckValue: string): T[]; + iteratee?: Object + ): T[]; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: Array, - whereValue?: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( + * @see _.uniq + */ + uniq( array: List, - whereValue?: W): T[]; + iteratee?: TWhere + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: Array, - isSorted: boolean, - whereValue?: W): T[]; - - /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - array: List, - isSorted: boolean, - whereValue?: W): T[]; + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; } interface LoDashImplicitArrayWrapper { /** - * @see _.uniq - **/ - uniq(isSorted?: boolean): LoDashImplicitArrayWrapper; - - /** - * @see _.uniq - **/ + * @see _.uniq + */ uniq( - isSorted: boolean, - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - **/ + * @see _.uniq + */ uniq( - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ + * @see _.uniq + */ uniq( - isSorted: boolean, - pluckValue: string): LoDashImplicitArrayWrapper; + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - uniq(pluckValue: string): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + uniq( + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - isSorted: boolean, - whereValue: W): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - uniq( - whereValue: W): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + uniq( + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + } + + interface LoDashImplicitObjectWrapper { + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - **/ - unique(isSorted?: boolean): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - **/ + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: Object + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: Object + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: Object + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: Object + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + uniq( + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + } + + //_.unique + interface LoDashStatic { + /** + * @see _.uniq + */ + unique( + array: List, + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + iteratee?: ListIterator, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + iteratee?: string, + thisArg?: any + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + isSorted?: boolean, + iteratee?: Object + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + isSorted?: boolean, + iteratee?: TWhere + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + iteratee?: Object + ): T[]; + + /** + * @see _.uniq + */ + unique( + array: List, + iteratee?: TWhere + ): T[]; + } + + interface LoDashImplicitWrapper { + /** + * @see _.uniq + */ unique( - isSorted: boolean, - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - **/ + * @see _.uniq + */ unique( - callback: ListIterator, - thisArg?: any): LoDashImplicitArrayWrapper; + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + } + + interface LoDashImplicitArrayWrapper { + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ unique( - isSorted: boolean, - pluckValue: string): LoDashImplicitArrayWrapper; + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param pluckValue _.pluck style callback - **/ - unique(pluckValue: string): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + unique( + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - isSorted: boolean, - whereValue: W): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; /** - * @see _.uniq - * @param whereValue _.where style callback - **/ - unique( - whereValue: W): LoDashImplicitArrayWrapper; + * @see _.uniq + */ + unique( + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + } + + interface LoDashImplicitObjectWrapper { + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: string, + thisArg?: any + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: Object + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: Object + ): LoDashImplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: TWhere + ): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitArrayWrapper { + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + } + + interface LoDashExplicitObjectWrapper { + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: ListIterator, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: string, + thisArg?: any + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: Object + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + isSorted?: boolean, + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: Object + ): LoDashExplicitArrayWrapper; + + /** + * @see _.uniq + */ + unique( + iteratee?: TWhere + ): LoDashExplicitArrayWrapper; } //_.unzip @@ -3911,7 +4529,16 @@ declare module _ { * @see _.some */ any( - collection: List|Dictionary, + collection: NumericDictionary, + predicate?: NumericDictionaryIterator, + thisArg?: any + ): boolean; + + /** + * @see _.some + */ + any( + collection: List|Dictionary|NumericDictionary, predicate?: string, thisArg?: any ): boolean; @@ -3920,7 +4547,7 @@ declare module _ { * @see _.some */ any( - collection: List|Dictionary, + collection: List|Dictionary|NumericDictionary, predicate?: TObject ): boolean; } @@ -3930,7 +4557,7 @@ declare module _ { * @see _.some */ any( - predicate?: ListIterator, + predicate?: ListIterator|NumericDictionaryIterator, thisArg?: any ): boolean; @@ -3955,7 +4582,7 @@ declare module _ { * @see _.some */ any( - predicate?: ListIterator|DictionaryIterator, + predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator, thisArg?: any ): boolean; @@ -3980,7 +4607,7 @@ declare module _ { * @see _.some */ any( - predicate?: ListIterator, + predicate?: ListIterator|NumericDictionaryIterator, thisArg?: any ): LoDashExplicitWrapper; @@ -4005,7 +4632,7 @@ declare module _ { * @see _.some */ any( - predicate?: ListIterator|DictionaryIterator, + predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator, thisArg?: any ): LoDashExplicitWrapper; @@ -7326,7 +7953,16 @@ declare module _ { * @see _.some */ some( - collection: List|Dictionary, + collection: NumericDictionary, + predicate?: NumericDictionaryIterator, + thisArg?: any + ): boolean; + + /** + * @see _.some + */ + some( + collection: List|Dictionary|NumericDictionary, predicate?: string, thisArg?: any ): boolean; @@ -7335,7 +7971,7 @@ declare module _ { * @see _.some */ some( - collection: List|Dictionary, + collection: List|Dictionary|NumericDictionary, predicate?: TObject ): boolean; } @@ -7345,7 +7981,7 @@ declare module _ { * @see _.some */ some( - predicate?: ListIterator, + predicate?: ListIterator|NumericDictionaryIterator, thisArg?: any ): boolean; @@ -7370,7 +8006,7 @@ declare module _ { * @see _.some */ some( - predicate?: ListIterator|DictionaryIterator, + predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator, thisArg?: any ): boolean; @@ -7395,7 +8031,7 @@ declare module _ { * @see _.some */ some( - predicate?: ListIterator, + predicate?: ListIterator|NumericDictionaryIterator, thisArg?: any ): LoDashExplicitWrapper; @@ -7420,7 +8056,7 @@ declare module _ { * @see _.some */ some( - predicate?: ListIterator|DictionaryIterator, + predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator, thisArg?: any ): LoDashExplicitWrapper; @@ -7897,20 +8533,31 @@ declare module _ { interface LoDashStatic { /** * Creates a function that invokes func, with the this binding and arguments of the created function, while - * it is called less than n times. Subsequent calls to the created function return the result of the last func + * it’s called less than n times. Subsequent calls to the created function return the result of the last func * invocation. + * * @param n The number of calls at which func is no longer invoked. * @param func The function to restrict. * @return Returns the new restricted function. */ - before(n: number, func: TFunc): TFunc; + before( + n: number, + func: TFunc + ): TFunc; } interface LoDashImplicitWrapper { /** - * @sed _.before - */ - before(func: TFunc): TFunc; + * @see _.before + **/ + before(func: TFunc): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.before + **/ + before(func: TFunc): LoDashExplicitObjectWrapper; } //_.bind @@ -7941,24 +8588,35 @@ declare module _ { //_.bindAll interface LoDashStatic { /** - * Binds methods of an object to the object itself, overwriting the existing method. Method - * names may be specified as individual arguments or as arrays of method names. If no method - * names are provided all the function properties of object will be bound. - * @param object The object to bind and assign the bound methods to. - * @param methodNames The object method names to bind, specified as individual method names - * or arrays of method names. - * @return object - **/ + * Binds methods of an object to the object itself, overwriting the existing method. Method names may be + * specified as individual arguments or as arrays of method names. If no method names are provided all + * enumerable function properties, own and inherited, of object are bound. + * + * Note: This method does not set the "length" property of bound functions. + * + * @param object The object to bind and assign the bound methods to. + * @param methodNames The object method names to bind, specified as individual method names or arrays of + * method names. + * @return Returns object. + */ bindAll( object: T, - ...methodNames: string[]): T; + ...methodNames: (string|string[])[] + ): T; } interface LoDashImplicitObjectWrapper { /** - * @see _.bindAll - **/ - bindAll(...methodNames: string[]): LoDashImplicitWrapper; + * @see _.bindAll + */ + bindAll(...methodNames: (string|string[])[]): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.bindAll + */ + bindAll(...methodNames: (string|string[])[]): LoDashExplicitObjectWrapper; } //_.bindKey @@ -8218,54 +8876,69 @@ declare module _ { } //_.debounce + interface DebounceSettings { + /** + * Specify invoking on the leading edge of the timeout. + */ + leading?: boolean; + + /** + * The maximum time func is allowed to be delayed before it’s invoked. + */ + maxWait?: number; + + /** + * Specify invoking on the trailing edge of the timeout. + */ + trailing?: boolean; + } + interface LoDashStatic { /** - * Creates a function that will delay the execution of func until after wait milliseconds have - * elapsed since the last time it was invoked. Provide an options object to indicate that func - * should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls - * to the debounced function will return the result of the last func call. - * - * Note: If leading and trailing options are true func will be called on the trailing edge of - * the timeout only if the the debounced function is invoked more than once during the wait - * timeout. - * @param func The function to debounce. - * @param wait The number of milliseconds to delay. - * @param options The options object. - * @param options.leading Specify execution on the leading edge of the timeout. - * @param options.maxWait The maximum time func is allowed to be delayed before it's called. - * @param options.trailing Specify execution on the trailing edge of the timeout. - * @return The new debounced function. - **/ + * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since + * the last time the debounced function was invoked. The debounced function comes with a cancel method to + * cancel delayed invocations. Provide an options object to indicate that func should be invoked on the + * leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the + * result of the last func invocation. + * + * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only + * if the the debounced function is invoked more than once during the wait timeout. + * + * See David Corbacho’s article for details over the differences between _.debounce and _.throttle. + * + * @param func The function to debounce. + * @param wait The number of milliseconds to delay. + * @param options The options object. + * @param options.leading Specify invoking on the leading edge of the timeout. + * @param options.maxWait The maximum time func is allowed to be delayed before it’s invoked. + * @param options.trailing Specify invoking on the trailing edge of the timeout. + * @return Returns the new debounced function. + */ debounce( func: T, - wait: number, - options?: DebounceSettings): T; + wait?: number, + options?: DebounceSettings + ): T & Cancelable; } interface LoDashImplicitObjectWrapper { /** - * @see _.debounce - **/ + * @see _.debounce + */ debounce( - wait: number, - options?: DebounceSettings): LoDashImplicitObjectWrapper; + wait?: number, + options?: DebounceSettings + ): LoDashImplicitObjectWrapper; } - interface DebounceSettings { + interface LoDashExplicitObjectWrapper { /** - * Specify execution on the leading edge of the timeout. - **/ - leading?: boolean; - - /** - * The maximum time func is allowed to be delayed before it's called. - **/ - maxWait?: number; - - /** - * Specify execution on the trailing edge of the timeout. - **/ - trailing?: boolean; + * @see _.debounce + */ + debounce( + wait?: number, + options?: DebounceSettings + ): LoDashExplicitObjectWrapper; } //_.defer @@ -8340,6 +9013,7 @@ declare module _ { /** * Creates a function that returns the result of invoking the provided functions with the this binding of the * created function, where each successive invocation is supplied the return value of the previous. + * * @param funcs Functions to invoke. * @return Returns the new function. */ @@ -8349,10 +9023,17 @@ declare module _ { interface LoDashImplicitObjectWrapper { /** * @see _.flow - **/ + */ flow(...funcs: Function[]): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.flow + */ + flow(...funcs: Function[]): LoDashExplicitObjectWrapper; + } + //_.flowRight interface LoDashStatic { /** @@ -8462,6 +9143,7 @@ declare module _ { /** * Creates a function that negates the result of the predicate func. The func predicate is invoked with * the this binding and arguments of the created function. + * * @param predicate The predicate to negate. * @return Returns the new function. */ @@ -8485,6 +9167,18 @@ declare module _ { negate(): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.negate + */ + negate(): LoDashExplicitObjectWrapper<(...args: any[]) => boolean>; + + /** + * @see _.negate + */ + negate(): LoDashExplicitObjectWrapper; + } + //_.once interface LoDashStatic { /** @@ -9045,9 +9739,10 @@ declare module _ { /** * Checks if value is classified as an Array object. * @param value The value to check. + * * @return Returns true if value is correctly classified, else false. - **/ - isArray(value?: any): value is any[]; + */ + isArray(value?: any): value is T[]; } interface LoDashImplicitWrapperBase { @@ -9057,13 +9752,21 @@ declare module _ { isArray(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isArray + */ + isArray(): LoDashExplicitWrapper; + } + //_.isBoolean interface LoDashStatic { /** * Checks if value is classified as a boolean primitive or object. + * * @param value The value to check. * @return Returns true if value is correctly classified, else false. - **/ + */ isBoolean(value?: any): value is boolean; } @@ -9074,13 +9777,21 @@ declare module _ { isBoolean(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isBoolean + */ + isBoolean(): LoDashExplicitWrapper; + } + //_.isDate interface LoDashStatic { /** * Checks if value is classified as a Date object. * @param value The value to check. + * * @return Returns true if value is correctly classified, else false. - **/ + */ isDate(value?: any): value is Date; } @@ -9091,6 +9802,13 @@ declare module _ { isDate(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isDate + */ + isDate(): LoDashExplicitWrapper; + } + //_.isElement interface LoDashStatic { /** @@ -9210,11 +9928,13 @@ declare module _ { interface LoDashStatic { /** * Checks if value is a finite primitive number. + * * Note: This method is based on Number.isFinite. + * * @param value The value to check. * @return Returns true if value is a finite number, else false. - **/ - isFinite(value?: any): value is number; + */ + isFinite(value?: any): boolean; } interface LoDashImplicitWrapperBase { @@ -9224,13 +9944,21 @@ declare module _ { isFinite(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isFinite + */ + isFinite(): LoDashExplicitWrapper; + } + //_.isFunction interface LoDashStatic { /** * Checks if value is classified as a Function object. + * * @param value The value to check. * @return Returns true if value is correctly classified, else false. - **/ + */ isFunction(value?: any): value is Function; } @@ -9241,6 +9969,13 @@ declare module _ { isFunction(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isFunction + */ + isFunction(): LoDashExplicitWrapper; + } + //_.isMatch interface isMatchCustomizer { (value: any, other: any, indexOrKey?: number|string): boolean; @@ -9272,7 +10007,9 @@ declare module _ { interface LoDashStatic { /** * Checks if value is NaN. + * * Note: This method is not the same as isNaN which returns true for undefined and other non-numeric values. + * * @param value The value to check. * @return Returns true if value is NaN, else false. */ @@ -9286,11 +10023,19 @@ declare module _ { isNaN(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * @see _.isNaN + */ + isNaN(): LoDashExplicitWrapper; + } + //_.isNative interface LoDashStatic { /** * Checks if value is a native function. * @param value The value to check. + * * @retrun Returns true if value is a native function, else false. */ isNative(value: any): value is Function; @@ -9303,6 +10048,13 @@ declare module _ { isNative(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isNative + */ + isNative(): LoDashExplicitWrapper; + } + //_.isNull interface LoDashStatic { /** @@ -9332,7 +10084,9 @@ declare module _ { interface LoDashStatic { /** * Checks if value is classified as a Number primitive or object. + * * Note: To exclude Infinity, -Infinity, and NaN, which are classified as numbers, use the _.isFinite method. + * * @param value The value to check. * @return Returns true if value is correctly classified, else false. */ @@ -9346,14 +10100,22 @@ declare module _ { isNumber(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isNumber + */ + isNumber(): LoDashExplicitWrapper; + } + //_.isObject interface LoDashStatic { /** * Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), * and new String('')) + * * @param value The value to check. * @return Returns true if value is an object, else false. - **/ + */ isObject(value?: any): boolean; } @@ -9364,6 +10126,13 @@ declare module _ { isObject(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isObject + */ + isObject(): LoDashExplicitWrapper; + } + //_.isPlainObject interface LoDashStatic { /** @@ -9390,6 +10159,7 @@ declare module _ { /** * Checks if value is classified as a RegExp object. * @param value The value to check. + * * @return Returns true if value is correctly classified, else false. */ isRegExp(value?: any): value is RegExp; @@ -9402,13 +10172,21 @@ declare module _ { isRegExp(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isRegExp + */ + isRegExp(): LoDashExplicitWrapper; + } + //_.isString interface LoDashStatic { /** * Checks if value is classified as a String primitive or object. + * * @param value The value to check. * @return Returns true if value is correctly classified, else false. - **/ + */ isString(value?: any): value is string; } @@ -9419,6 +10197,13 @@ declare module _ { isString(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isString + */ + isString(): LoDashExplicitWrapper; + } + //_.isTypedArray interface LoDashStatic { /** @@ -9448,9 +10233,10 @@ declare module _ { interface LoDashStatic { /** * Checks if value is undefined. + * * @param value The value to check. * @return Returns true if value is undefined, else false. - **/ + */ isUndefined(value: any): boolean; } @@ -9461,6 +10247,13 @@ declare module _ { isUndefined(): boolean; } + interface LoDashExplicitWrapperBase { + /** + * see _.isUndefined + */ + isUndefined(): LoDashExplicitWrapper; + } + //_.lt interface LoDashStatic { /** @@ -11682,54 +12475,62 @@ declare module _ { //_.omit interface LoDashStatic { /** - * Creates a shallow clone of object excluding the specified properties. Property names may be - * specified as individual arguments or as arrays of property names. If a callback is provided - * it will be executed for each property of object omitting the properties the callback returns - * truey for. The callback is bound to thisArg and invoked with three arguments; (value, key, - * object). - * @param object The source object. - * @param keys The properties to omit. - * @return An object without the omitted properties. - **/ - omit( + * The opposite of _.pick; this method creates an object composed of the own and inherited enumerable + * properties of object that are not omitted. + * + * @param object The source object. + * @param predicate The function invoked per iteration or property names to omit, specified as individual + * property names or arrays of property names. + * @param thisArg The this binding of predicate. + * @return Returns the new object. + */ + omit( object: T, - ...keys: string[]): Omitted; + predicate: ObjectIterator, + thisArg?: any + ): TResult; /** - * @see _.omit - **/ - omit( + * @see _.omit + */ + omit( object: T, - keys: string[]): Omitted; - - /** - * @see _.omit - **/ - omit( - object: T, - callback: ObjectIterator, - thisArg?: any): Omitted; + ...predicate: (StringRepresentable|StringRepresentable[])[] + ): TResult; } interface LoDashImplicitObjectWrapper { /** - * @see _.omit - **/ - omit( - ...keys: string[]): LoDashImplicitObjectWrapper; + * @see _.omit + */ + omit( + predicate: ObjectIterator, + thisArg?: any + ): LoDashImplicitObjectWrapper; /** - * @see _.omit - **/ - omit( - keys: string[]): LoDashImplicitObjectWrapper; + * @see _.omit + */ + omit( + ...predicate: (StringRepresentable|StringRepresentable[])[] + ): LoDashImplicitObjectWrapper; + } + + interface LoDashExplicitObjectWrapper { + /** + * @see _.omit + */ + omit( + predicate: ObjectIterator, + thisArg?: any + ): LoDashExplicitObjectWrapper; /** - * @see _.omit - **/ - omit( - callback: ObjectIterator, - thisArg?: any): LoDashImplicitObjectWrapper; + * @see _.omit + */ + omit( + ...predicate: (StringRepresentable|StringRepresentable[])[] + ): LoDashExplicitObjectWrapper; } //_.pairs @@ -11771,9 +12572,9 @@ declare module _ { * @param predicate The function invoked per iteration or property names to pick, specified as individual * property names or arrays of property names. * @param thisArg The this binding of predicate. - * @return An object composed of the picked properties. + * @return Returns the new object. */ - pick( + pick( object: T, predicate: ObjectIterator, thisArg?: any @@ -11782,9 +12583,9 @@ declare module _ { /** * @see _.pick */ - pick( + pick( object: T, - ...predicate: Array> + ...predicate: (StringRepresentable|StringRepresentable[])[] ): TResult; } @@ -11792,7 +12593,7 @@ declare module _ { /** * @see _.pick */ - pick( + pick( predicate: ObjectIterator, thisArg?: any ): LoDashImplicitObjectWrapper; @@ -11800,11 +12601,28 @@ declare module _ { /** * @see _.pick */ - pick( - ...predicate: Array> + pick( + ...predicate: (StringRepresentable|StringRepresentable[])[] ): LoDashImplicitObjectWrapper; } + interface LoDashExplicitObjectWrapper { + /** + * @see _.pick + */ + pick( + predicate: ObjectIterator, + thisArg?: any + ): LoDashExplicitObjectWrapper; + + /** + * @see _.pick + */ + pick( + ...predicate: (StringRepresentable|StringRepresentable[])[] + ): LoDashExplicitObjectWrapper; + } + //_.result interface LoDashStatic { /** @@ -13487,6 +14305,10 @@ declare module _ { (value: T, key?: string, collection?: Dictionary): TResult; } + interface NumericDictionaryIterator { + (value: T, key?: number, collection?: Dictionary): TResult; + } + interface ObjectIterator { (element: T, key?: string, collection?: any): TResult; } @@ -13521,6 +14343,10 @@ declare module _ { [index: string]: T; } + interface NumericDictionary { + [index: number]: T; + } + interface StringRepresentable { toString(): string; } diff --git a/lwip/lwip.d.ts b/lwip/lwip.d.ts index 63d2c701b8..0f40c63d25 100644 --- a/lwip/lwip.d.ts +++ b/lwip/lwip.d.ts @@ -12,6 +12,10 @@ declare module "lwip" { interface ImageCallback { (err: any, image: Image): void; } + + interface BufferCallback { + (err: any, buffer: Buffer): void; + } /** * Open an image @@ -386,7 +390,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "jpg", callback: ImageCallback): void; + toBuffer(format: "jpg", callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -396,7 +400,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "jpg", params: JpegBufferParams, callback: ImageCallback): void; + toBuffer(format: "jpg", params: JpegBufferParams, callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -405,7 +409,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "png", callback: ImageCallback): void; + toBuffer(format: "png", callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -415,7 +419,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "png", params: PngBufferParams, callback: ImageCallback): void; + toBuffer(format: "png", params: PngBufferParams, callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -424,7 +428,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "gif", callback: ImageCallback): void; + toBuffer(format: "gif", callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -434,7 +438,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "gif", params: GifBufferParams, callback: ImageCallback): void; + toBuffer(format: "gif", params: GifBufferParams, callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -443,7 +447,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: string, callback: ImageCallback): void; + toBuffer(format: string, callback: BufferCallback): void; /** * Get encoded binary image data as a NodeJS Buffer. @@ -453,7 +457,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: string, params: JpegBufferParams | PngBufferParams | GifBufferParams, callback: ImageCallback): void; + toBuffer(format: string, params: JpegBufferParams | PngBufferParams | GifBufferParams, callback: BufferCallback): void; /** * Write encoded binary image data directly to a file. @@ -848,7 +852,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "jpg", callback: ImageCallback): void; + toBuffer(format: "jpg", callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -858,7 +862,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "jpg", params: JpegBufferParams, callback: ImageCallback): void; + toBuffer(format: "jpg", params: JpegBufferParams, callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -867,7 +871,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "png", callback: ImageCallback): void; + toBuffer(format: "png", callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -877,7 +881,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "png", params: PngBufferParams, callback: ImageCallback): void; + toBuffer(format: "png", params: PngBufferParams, callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -886,7 +890,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: "gif", callback: ImageCallback): void; + toBuffer(format: "gif", callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -896,7 +900,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: "gif", params: GifBufferParams, callback: ImageCallback): void; + toBuffer(format: "gif", params: GifBufferParams, callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -905,7 +909,7 @@ declare module "lwip" { * * @param format Encoding format. */ - toBuffer(format: string, callback: ImageCallback): void; + toBuffer(format: string, callback: BufferCallback): void; /** * Execute batch and obtain a Buffer object @@ -915,7 +919,7 @@ declare module "lwip" { * @param format Encoding format. * @param params Format-specific parameters. */ - toBuffer(format: string, params: JpegBufferParams | PngBufferParams | GifBufferParams, callback: ImageCallback): void; + toBuffer(format: string, params: JpegBufferParams | PngBufferParams | GifBufferParams, callback: BufferCallback): void; /** * Execute batch and write to file diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts index 9e67cc78a9..b45ce05d97 100644 --- a/mailparser/mailparser.d.ts +++ b/mailparser/mailparser.d.ts @@ -78,9 +78,11 @@ declare module 'mailparser' { once(event: string, listener: Function): EventEmitter; removeListener(event: string, listener: Function): EventEmitter; removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; + setMaxListeners(n: number): EventEmitter; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; } } diff --git a/maker.js/makerjs-tests.ts b/maker.js/makerjs-tests.ts index 59a50e4fce..4b6b5f80e2 100644 --- a/maker.js/makerjs-tests.ts +++ b/maker.js/makerjs-tests.ts @@ -40,6 +40,8 @@ function test() { function testExporter() { new makerjs.exporter.Exporter({}); makerjs.exporter.toDXF(model); + makerjs.exporter.toOpenJsCad(model); + makerjs.exporter.toSTL(model); makerjs.exporter.toSVG(model); makerjs.exporter.tryGetModelUnits(model); } @@ -47,8 +49,8 @@ function test() { function testKit() { makerjs.kit.construct(null, null); makerjs.kit.getParameterValues(null); - ({}).max; - ({}).metaParameters; + ({}).max; + ({}).metaParameters; } function testMeasure() { @@ -64,14 +66,22 @@ function test() { } function testModel(){ - makerjs.model.combine(model, model, true, false, true, false); + makerjs.model.breakPathsAtIntersections(model, { paths:{ } }); + var opts: MakerJs.ICombineOptions = { trimDeadEnds: true, pointMatchingDistance: 2 }; + makerjs.model.combine(model, model, true, false, true, false, opts); makerjs.model.convertUnits(model, makerjs.unitType.Centimeter); + makerjs.model.countChildModels(model); + makerjs.model.detachLoop(model); + makerjs.model.findLoops(model); + makerjs.model.getSimilarModelId(model, 'foo'); makerjs.model.getSimilarPathId(model, 'foo'); + makerjs.model.isPathInsideModel(paths.line, model); makerjs.model.mirror(model, false, true); makerjs.model.move(makerjs.model.originate(model, [9,9]), [0,0]); makerjs.model.moveRelative(model, [1,1]); makerjs.model.originate(model); makerjs.model.rotate(makerjs.model.scale(model, 6), 45, [0,0]); + makerjs.model.scale(model, 7); makerjs.model.walkPaths(model, (modelContext: MakerJs.IModel, pathId: string, pathContext: MakerJs.IPath) => {}); } @@ -80,20 +90,22 @@ function test() { new makerjs.models.BoltCircle(7, 7, 7, 7), new makerjs.models.BoltRectangle(2, 2, 2), new makerjs.models.ConnectTheDots(true, [ [0,0], [1,1] ]), + new makerjs.models.Dome(5, 7), new makerjs.models.Oval(7, 7), - new makerjs.models.OvalArc(6, 4, 2, 12), + new makerjs.models.OvalArc(6, 4, 2, 12, true), new makerjs.models.Polygon(7, 5), new makerjs.models.Rectangle(8, 9), new makerjs.models.Ring(7, 7), new makerjs.models.RoundRectangle(2, 2, 0), new makerjs.models.SCurve(5, .9), + new makerjs.models.Slot([0, 0], [1, 1], 7), new makerjs.models.Square(8), new makerjs.models.Star(5, 10, 5) ]; } function testPath() { - makerjs.path.areEqual(paths.line, paths.circle); + 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); @@ -132,6 +144,7 @@ function test() { 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]); makerjs.point.fromAngleOnCircle(22, paths.circle); @@ -141,7 +154,9 @@ function test() { makerjs.point.middle(paths.line); makerjs.point.mirror(p1, true, false); 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 69cd3dbb7f..cb217adb49 100644 --- a/maker.js/makerjs.d.ts +++ b/maker.js/makerjs.d.ts @@ -247,6 +247,50 @@ declare module MakerJs { */ path2Angles?: number[]; } + /** + * Options when matching points + */ + interface IPointMatchOptions { + /** + * Max distance to consider two points as the same. + */ + pointMatchingDistance?: number; + } + /** + * Options to pass to model.combine. + */ + interface ICombineOptions extends IPointMatchOptions { + /** + * Flag to remove paths which are not part of a loop. + */ + trimDeadEnds?: boolean; + /** + * Point which is known to be outside of the model. + */ + farPoint?: IPoint; + } + /** + * Options to pass to model.findLoops. + */ + interface IFindLoopsOptions extends IPointMatchOptions { + /** + * Flag to remove looped paths from the original model. + */ + removeFromOriginal?: boolean; + } + /** + * A path that may be indicated to "flow" in either direction between its endpoints. + */ + interface IPathDirectional extends IPath { + /** + * The endpoints of the path. + */ + endPoints: IPoint[]; + /** + * Path flows forwards or reverse. + */ + reversed?: boolean; + } /** * Path objects by id. */ @@ -302,10 +346,73 @@ declare module MakerJs { */ layer?: string; } + /** + * Callback signature for model.walkPaths(). + */ + interface IModelPathCallback { + (modelContext: IModel, pathId: string, pathContext: IPath): void; + } /** * Test to see if an object implements the required properties of a model. */ function isModel(item: any): boolean; + /** + * Reference to a path id within a model. + */ + interface IRefPathIdInModel { + modelContext: IModel; + pathId: string; + } + /** + * Path and its reference id within a model + */ + interface IRefPathInModel extends IRefPathIdInModel { + pathContext: IPath; + } + /** + * Describes a parameter and its limits. + */ + interface IMetaParameter { + /** + * Display text of the parameter. + */ + title: string; + /** + * Type of the parameter. Currently supports "range". + */ + type: string; + /** + * Optional minimum value of the range. + */ + min?: number; + /** + * Optional maximum value of the range. + */ + max?: number; + /** + * Optional step value between min and max. + */ + step?: number; + /** + * Initial sample value for this parameter. + */ + value: any; + } + /** + * An IKit is a model-producing class with some sample parameters. Think of it as a packaged model with instructions on how to best use it. + */ + interface IKit { + /** + * The constructor. The kit must be "new-able" and it must produce an IModel. + * It can have any number of any type of parameters. + */ + new (...args: any[]): IModel; + /** + * Attached to the constructor is a property named metaParameters which is an array of IMetaParameter objects. + * Each element of the array corresponds to a parameter of the constructor, in order. + */ + metaParameters?: IMetaParameter[]; + } } declare module MakerJs.angle { /** @@ -315,7 +422,7 @@ declare module MakerJs.angle { * @param b Second angle. * @returns true if angles are the same, false if they are not */ - function areEqual(angle1: number, angle2: number): boolean; + function areEqual(angle1: number, angle2: number, accuracy?: number): boolean; /** * Ensures an angle is not greater than 360 * @@ -402,15 +509,24 @@ declare module MakerJs.point { * @param b Second point. * @returns true if points are the same, false if they are not */ - function areEqual(a: IPoint, b: IPoint): boolean; + 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. + * + * @param a First point. + * @param b Second point. + * @returns New point object which is the average of a and b. + */ + function average(a: IPoint, b: IPoint): IPoint; /** * Clone a point into a new point. * @@ -456,7 +572,7 @@ declare module MakerJs.point { */ function fromPathEnds(pathContext: IPath): IPoint[]; /** - * Get the middle point of a path. Currently only supports Arc and Line paths. + * Get the middle point of a path. * * @param pathContext The path object. * @param ratio Optional ratio (between 0 and 1) of point along the path. Default is .5 for middle. @@ -472,6 +588,14 @@ declare module MakerJs.point { * @returns Mirrored point. */ function mirror(pointToMirror: IPoint, mirrorX: boolean, mirrorY: boolean): IPoint; + /** + * Round the values of a point. + * + * @param pointContext The point to serialize. + * @param accuracy Optional exemplar number of decimal places. + * @returns A new point with the values rounded. + */ + function rounded(pointContext: IPoint, accuracy?: number): IPoint; /** * Rotate a point. * @@ -489,6 +613,14 @@ declare module 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). * @@ -513,7 +645,7 @@ declare module MakerJs.path { * @param b Second path. * @returns true if paths are the same, false if they are not */ - function areEqual(path1: IPath, path2: IPath): boolean; + function areEqual(path1: IPath, path2: IPath, withinPointDistance?: number): boolean; /** * Create a clone of a path, mirrored on either or both x and y axes. * @@ -637,11 +769,25 @@ declare module MakerJs.paths { } } declare module MakerJs.model { + /** + * Count the number of child models within a given model. + * + * @param modelContext The model containing other models. + * @returns Number of child models. + */ + function countChildModels(modelContext: IModel): number; + /** + * Get an unused id in the models map with the same prefix. + * + * @param modelContext The model containing the models map. + * @param modelId The id to use directly (if unused), or as a prefix. + */ + function getSimilarModelId(modelContext: IModel, modelId: string): string; /** * Get an unused id in the paths map with the same prefix. * * @param modelContext The model containing the paths map. - * @param pathId The pathId to use directly (if unused), or as a prefix. + * @param pathId The id to use directly (if unused), or as a prefix. */ function getSimilarPathId(modelContext: IModel, pathId: string): string; /** @@ -702,12 +848,6 @@ declare module MakerJs.model { * @returns The scaled model (for chaining). */ function convertUnits(modeltoConvert: IModel, destUnitType: string): IModel; - /** - * Callback signature for walkPaths. - */ - interface IModelPathCallback { - (modelContext: IModel, pathId: string, pathContext: IPath): void; - } /** * Recursively walk through all paths for a given model. * @@ -718,7 +858,23 @@ declare module MakerJs.model { } declare module MakerJs.model { /** - * Combine 2 models. The models should be originated. + * Check to see if a path is inside of a model. + * + * @param pathContext The path to check. + * @param modelContext The model to check against. + * @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; + /** + * Break a model's paths everywhere they intersect with another path. + * + * @param modelToBreak The model containing paths to be broken. + * @param modelToIntersect Optional model containing paths to look for intersection, or else the modelToBreak will be used. + */ + 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. * * @param modelA First model to combine. * @param modelB Second model to combine. @@ -726,9 +882,10 @@ declare module MakerJs.model { * @param includeAOutsideB Flag to include paths from modelA which are outside of modelB. * @param includeBInsideA Flag to include paths from modelB which are inside of modelA. * @param includeBOutsideA Flag to include paths from modelB which are outside of modelA. + * @param keepDuplicates Flag to include paths which are duplicate in both models. * @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, farPoint?: IPoint): void; + function combine(modelA: IModel, modelB: IModel, includeAInsideB?: boolean, includeAOutsideB?: boolean, includeBInsideA?: boolean, includeBOutsideA?: boolean, options?: ICombineOptions): void; } declare module MakerJs.units { /** @@ -927,7 +1084,7 @@ declare module MakerJs.path { * @param line2 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): IPathArc; + function dogbone(line1: IPathLine, line2: IPathLine, filletRadius: number, options?: IPointMatchOptions): IPathArc; /** * Adds a round corner to the inside angle between 2 paths. The paths must meet at one point. * @@ -935,53 +1092,9 @@ declare module MakerJs.path { * @param path2 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): IPathArc; + function fillet(path1: IPath, path2: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc; } declare module MakerJs.kit { - /** - * Describes a parameter and its limits. - */ - interface IMetaParameter { - /** - * Display text of the parameter. - */ - title: string; - /** - * Type of the parameter. Currently supports "range". - */ - type: string; - /** - * Optional minimum value of the range. - */ - min?: number; - /** - * Optional maximum value of the range. - */ - max?: number; - /** - * Optional step value between min and max. - */ - step?: number; - /** - * Initial sample value for this parameter. - */ - value: any; - } - /** - * An IKit is a model-producing class with some sample parameters. Think of it as a packaged model with instructions on how to best use it. - */ - interface IKit { - /** - * The constructor. The kit must be "new-able" and it must produce an IModel. - * It can have any number of any type of parameters. - */ - new (...args: any[]): IModel; - /** - * Attached to the constructor is a property named metaParameters which is an array of IMetaParameter objects. - * Each element of the array corresponds to a parameter of the constructor, in order. - */ - metaParameters?: IMetaParameter[]; - } /** * Helper function to use the JavaScript "apply" function in conjunction with the "new" keyword. * @@ -998,6 +1111,40 @@ declare module MakerJs.kit { */ function getParameterValues(ctor: IKit): any[]; } +declare module MakerJs.model { + /** + * @private + */ + 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; + } + /** + * Find paths that have common endpoints and form loops. + * + * @param modelContext The model to search for loops. + * @param options Optional options object. + * @returns A new model with child models ranked according to their containment within other found loops. The paths of models will be IPathDirectionalWithPrimeContext. + */ + function findLoops(modelContext: IModel, options?: IFindLoopsOptions): IModel; + /** + * Remove all paths in a loop model from the model(s) which contained them. + * + * @param loopToDetach The model to search for loops. + */ + function detachLoop(loopToDetach: IModel): void; + function removeDeadEnds(modelContext: IModel, pointMatchingDistance?: number): void; +} declare module MakerJs.exporter { /** * Attributes for an XML tag. @@ -1052,6 +1199,34 @@ declare module MakerJs.exporter { toString(): string; } } +declare module MakerJs.exporter { + function toOpenJsCad(modelToExport: IModel, options?: IOpenJsCadOptions): string; + function toOpenJsCad(pathsToExport: IPath[], options?: IOpenJsCadOptions): string; + function toOpenJsCad(pathToExport: IPath, options?: IOpenJsCadOptions): string; + /** + * Executes a JavaScript string with the OpenJsCad engine - converts 2D to 3D. + * + * @param modelToExport Model object to export. + * @param options Export options object. + * @param options.extrusion Height of 3D extrusion. + * @param options.resolution Size of facets. + * @returns String of STL format of 3D object. + */ + function toSTL(modelToExport: IModel, options?: IOpenJsCadOptions): string; + /** + * OpenJsCad export options. + */ + interface IOpenJsCadOptions extends IFindLoopsOptions { + /** + * Optional depth of 3D extrusion. + */ + extrusion?: number; + /** + * Optional size of curve facets. + */ + facetSize?: number; + } +} declare module MakerJs.exporter { function toSVG(modelToExport: IModel, options?: ISVGRenderOptions): string; function toSVG(pathsToExport: IPath[], options?: ISVGRenderOptions): string; @@ -1118,6 +1293,12 @@ declare module MakerJs.models { constructor(width: number, height: number, holeRadius: number); } } +declare module MakerJs.models { + class Dome implements IModel { + paths: IPathMap; + constructor(width: number, height: number, radius?: number); + } +} declare module MakerJs.models { class RoundRectangle implements IModel { paths: IPathMap; @@ -1132,7 +1313,7 @@ declare module MakerJs.models { declare module MakerJs.models { class OvalArc implements IModel { paths: IPathMap; - constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number); + constructor(startAngle: number, endAngle: number, sweepRadius: number, slotRadius: number, selfIntersect?: boolean); } } declare module MakerJs.models { @@ -1152,6 +1333,13 @@ declare module MakerJs.models { constructor(width: number, height: number); } } +declare module MakerJs.models { + class Slot implements IModel { + paths: IPathMap; + origin: IPoint; + constructor(origin: IPoint, endPoint: IPoint, radius: number); + } +} declare module MakerJs.models { class Square extends Rectangle { constructor(side: number); diff --git a/marked/marked-tests.ts b/marked/marked-tests.ts index 44be0f0e84..efb6715489 100644 --- a/marked/marked-tests.ts +++ b/marked/marked-tests.ts @@ -14,7 +14,8 @@ var options: MarkedOptions = { return ''; }, langPrefix: 'lang-', - smartypants: false + smartypants: false, + renderer: new marked.Renderer() }; function callback() { diff --git a/marked/marked.d.ts b/marked/marked.d.ts index 198cd26262..85103b0202 100644 --- a/marked/marked.d.ts +++ b/marked/marked.d.ts @@ -3,7 +3,6 @@ // Definitions by: William Orr // Definitions: https://github.com/borisyankov/DefinitelyTyped - interface MarkedStatic { /** * Compiles markdown to HTML. @@ -60,6 +59,43 @@ interface MarkedStatic { * @param options Hash of options */ setOptions(options: MarkedOptions): MarkedStatic; + + Renderer: { + new(): MarkedRenderer; + } + + Parser: { + new(options: MarkedOptions): MarkedParser; + } +} + +interface MarkedRenderer { + code(code: string, language: string): string; + blockquote(quote: string): string; + html(html: string): string; + heading(text: string, level: number): string; + hr(): string; + list(body: string, ordered: boolean): string; + listitem(text: string): string; + paragraph(text: string): string; + table(header: string, body: string): string; + tablerow(content: string): string; + tablecell(content: string, flags: { + header: boolean, + align: string + }): string; + strong(text: string): string; + em(text: string): string; + codespan(code: string): string; + br(): string; + del(text: string): string; + link(href: string, title: string, text: string): string; + image(href: string, title: string, text: string): string; + text(text: string): string; +} + +interface MarkedParser { + parse(source: any[]): string } interface MarkedOptions { @@ -68,7 +104,7 @@ interface MarkedOptions { * * An object containing functions to render tokens to HTML. */ - renderer?: Object; + renderer?: MarkedRenderer; /** * Enable GitHub flavored markdown. diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index 0165dee1f7..84fdad401b 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -6,6 +6,7 @@ import * as React from "react"; import * as LinkedStateMixin from "react-addons-linked-state-mixin"; import Checkbox = require("material-ui/lib/checkbox"); import Colors = require("material-ui/lib/styles/colors"); +import Spacing = require("material-ui/lib/styles/spacing"); import AppBar = require("material-ui/lib/app-bar"); import Badge = require("material-ui/lib/badge"); import IconButton = require("material-ui/lib/icon-button"); @@ -47,7 +48,13 @@ type CheckboxProps = __MaterialUI.CheckboxProps; type MuiTheme = __MaterialUI.Styles.MuiTheme; type TouchTapEvent = __MaterialUI.TouchTapEvent; -class MaterialUiTests extends React.Component<{}, {}> implements React.LinkedStateMixin { +interface MaterialUiTestsState { + showDialogStandardActions: boolean; + showDialogCustomActions: boolean; + showDialogScrollable: boolean; +} + +class MaterialUiTests extends React.Component<{}, MaterialUiTestsState> implements React.LinkedStateMixin { // injected with mixin linkState: (key: string) => React.ReactLink; @@ -60,6 +67,8 @@ class MaterialUiTests extends React.Component<{}, {}> implements React.LinkedSta } private selectFieldChangeHandler(e: TouchTapEvent, si: number, mi: any) { } + private handleRequestClose(buttonClicked: boolean) { + } render() { @@ -193,7 +202,8 @@ class MaterialUiTests extends React.Component<{}, {}> implements React.LinkedSta title="Dialog With Standard Actions" actions={standardActions} actionFocus="submit" - modal={true}> + open={this.state.showDialogStandardActions} + onRequestClose={this.handleRequestClose}> The actions in this window are created from the json that's passed in. ; @@ -212,12 +222,23 @@ class MaterialUiTests extends React.Component<{}, {}> implements React.LinkedSta element = + open={this.state.showDialogCustomActions} + onRequestClose={this.handleRequestClose}> The actions in this window were passed in as an array of react objects. ; + element = +
        + Really long content +
        +
        ; + // "http://material-ui.com/#/components/dropdown-menu" let menuItems = [ @@ -488,7 +509,8 @@ class MaterialUiTests extends React.Component<{}, {}> implements React.LinkedSta element = ; + cellHeight={200} + style={{ color: 'red' }} />; element = implements React.LinkedSta titlePosition="top" titleBackground="rgba(0, 0, 0, 0.4)" cols={2} - rows={1} > + rows={1} + style={{ color: 'red' }}>

        Children are Required!

        ; diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index df6a088a7a..afa268ba58 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -1,4 +1,4 @@ -// Type definitions for material-ui v0.13.1 +// Type definitions for material-ui v0.13.4 // Project: https://github.com/callemall/material-ui // Definitions by: Nathan Brown , Oliver Herrmann // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -123,6 +123,7 @@ declare namespace __MaterialUI { } interface AppCanvasProps extends React.Props { + style?: React.CSSProperties; } export class AppCanvas extends React.Component { } @@ -319,7 +320,7 @@ declare namespace __MaterialUI { interface DatePickerProps extends React.Props { autoOk?: boolean; defaultDate?: Date; - formatDate?: string; + formatDate?: (date:Date) => string; hintText?: string; floatingLabelText?: string; hideToolbarYearChange?: boolean; @@ -379,14 +380,18 @@ declare namespace __MaterialUI { openImmediately?: boolean; repositionOnUpdate?: boolean; title?: React.ReactNode; + defaultOpen?: boolean; + open?: boolean; onClickAway?: () => void; onDismiss?: () => void; onShow?: () => void; + onRequestClose?: (buttonClicked: boolean) => void; } export class Dialog extends React.Component { dismiss(): void; show(): void; + isOpen(): boolean; } interface DropDownIconProps extends React.Props { @@ -567,6 +572,7 @@ declare namespace __MaterialUI { nestedItems?: React.ReactElement[]; onKeyboardFocus?: React.FocusEventHandler; onNestedListToggle?: (item: ListItem) => void; + onClick?: React.MouseEventHandler; rightAvatar?: React.ReactElement; rightIcon?: React.ReactElement; rightIconButton?: React.ReactElement; @@ -782,6 +788,7 @@ declare namespace __MaterialUI { menuItemStyle?: React.CSSProperties; selectedIndex?: number; underlineStyle?: React.CSSProperties; + underlineFocusStyle?: React.CSSProperties; iconStyle?: React.CSSProperties; labelStyle?: React.CSSProperties; style?: React.CSSProperties; @@ -870,6 +877,8 @@ declare namespace __MaterialUI { desktopSubheaderHeight?: number; desktopToolbarHeight?: number; } + export var Spacing: Spacing; + interface ThemePalette { primary1Color?: string; primary2Color?: string; @@ -1133,7 +1142,7 @@ declare namespace __MaterialUI { namespace Tabs { interface TabProps extends React.Props { - label?: string; + label?: any; value?: string; selected?: boolean; width?: string; @@ -1250,7 +1259,9 @@ declare namespace __MaterialUI { interface TableRowColumnProps extends React.Props { columnNumber?: number; + colSpan?: number; hoverable?: boolean; + onClick?: React.MouseEventHandler; onHover?: (e: React.MouseEvent, column: number) => void; onHoverExit?: (e: React.MouseEvent, column: number) => void; style?: React.CSSProperties; @@ -1525,18 +1536,19 @@ declare namespace __MaterialUI { export class MenuDivider extends React.Component{ } } - + namespace GridList { - + interface GridListProps extends React.Props { cols?: number; padding?: number; cellHeight?: number; + style?: React.CSSProperties; } - + export class GridList extends React.Component{ } - + interface GridTileProps extends React.Props { title?: string; subtitle?: __React.ReactNode; @@ -1547,11 +1559,12 @@ declare namespace __MaterialUI { cols?: number; rows?: number; rootClass?: string | __React.Component; + style?: React.CSSProperties; } - + export class GridTile extends React.Component{ } - + } } // __MaterialUI diff --git a/mime/mime.d.ts b/mime/mime.d.ts index bfaa7a51f1..1009f006c0 100644 --- a/mime/mime.d.ts +++ b/mime/mime.d.ts @@ -16,4 +16,5 @@ declare module "mime" { } export var charsets: Charsets; + export var default_type: string; } diff --git a/mithril/mithril.d.ts b/mithril/mithril.d.ts index 3cd0e21e49..c2304e7ece 100644 --- a/mithril/mithril.d.ts +++ b/mithril/mithril.d.ts @@ -5,90 +5,174 @@ //Mithril type definitions for Typescript -interface MithrilStatic { - (selector: string, attributes: Object, children?: any): MithrilVirtualElement; - (selector: string, children?: any): MithrilVirtualElement; - prop(value?: T): (value?: T) => T; - prop(promise: MithrilPromise): MithrilPromiseProperty; - withAttr(property: string, callback: (value: any) => void): (e: Event) => any; - module(rootElement: Node, module: MithrilModule): void; - trust(html: string): String; - render(rootElement: Element, children?: any): void; - render(rootElement: HTMLDocument, children?: any): void; - redraw: MithrilRedraw; - route: MithrilRoute; - request(options: MithrilXHROptions): MithrilPromise; - deferred(): MithrilDeferred; - sync(promises: MithrilPromise[]): MithrilPromise; - startComputation(): void; - endComputation(): void; +declare module _mithril { + interface MithrilStatic { + + (selector: string, attributes: MithrilAttributes, ...children: Array>): MithrilVirtualElement; + (selector: string, ...children: Array>): MithrilVirtualElement; + + prop(promise: MithrilPromise) : MithrilPromiseProperty; + prop(value: T): MithrilProperty; + prop(): MithrilProperty; // might be that this should be Property + + withAttr(property: string, callback: (value: any) => void): (e: MithrilEvent) => any; + + module(rootElement: Node, component: MithrilComponent): T; + module(rootElement: Node): T; + mount(rootElement: Node, component: MithrilComponent): T; + mount(rootElement: Node): T; + + component(component: MithrilComponent, ...args: Array): MithrilComponent + + trust(html: string): string; + + render(rootElement: Element|HTMLDocument): void; + render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement, forceRecreation?: boolean): void; + render(rootElement: Element|HTMLDocument, children: MithrilVirtualElement[], forceRecreation?: boolean): void; + + redraw: { + (force?: boolean): void; + strategy: MithrilProperty; + } + + route: { + (rootElement: HTMLDocument, defaultRoute: string, routes: MithrilRoutes): void; + (rootElement: Element, defaultRoute: string, routes: MithrilRoutes): void; + + (element: Element, isInitialized: boolean, context: Object, vdom: Object): void; + (path: string, params?: any, shouldReplaceHistory?: boolean): void; + (): string; + + param(key: string): string; + mode: string; + buildQueryString(data: Object): String + parseQueryString(data: String): Object + } + + request(options: MithrilXHROptions): MithrilPromise; + + deferred: { + onerror(e: Error): void; + (): MithrilDeferred; + } + + sync(promises: MithrilPromise[]): MithrilPromise; + + startComputation(): void; + endComputation(): void; + + // For test suite + deps: { + (mockWindow: Window): Window; + factory: Object; + } + + } + + export interface MithrilVirtualElement { + key?: number; + tag?: string; + attrs?: MithrilAttributes; + children?: any[]; + } + + // Configuration function for an element + interface MithrilElementConfig { + (element: Element, isInitialized: boolean, context?: any, vdom?: MithrilVirtualElement): void; + } + + // Attributes on a virtual element + interface MithrilAttributes { + title?: string; + className?: string; + class?: string; + config?: MithrilElementConfig; + } + + // Defines the subset of Event that Mithril needs + interface MithrilEvent { + currentTarget: Element; + } + + interface MithrilController { + onunload?(evt: Event): any; + } + + interface MithrilControllerFunction extends MithrilController { + (): any; + } + + interface MithrilView { + (ctrl: T): string|MithrilVirtualElement; + } + + interface MithrilComponent { + controller: MithrilControllerFunction|{ new(): T }; + view: MithrilView; + } + + interface MithrilProperty { + (): T; + (value: T): T; + toJSON(): T; + } + + interface MithrilPromiseProperty extends MithrilPromise { + (): T; + (value: T): T; + toJSON(): T; + } + + interface MithrilRoutes { + [key: string]: MithrilComponent; + } + + + interface MithrilDeferred { + resolve(value?: T): void; + reject(value?: any): void; + promise: MithrilPromise; + } + + interface MithrilSuccessCallback { + (value: T): U; + (value: T): MithrilPromise; + } + + interface MithrilErrorCallback { + (value: Error): U; + (value: string): U; + } + + interface MithrilPromise { + (): T; + (value: T): T; + then(success: (value: T) => U): MithrilPromise; + then(success: (value: T) => MithrilPromise): MithrilPromise; + then(success: (value: T) => U, error: (value: Error) => V): MithrilPromise|MithrilPromise; + then(success: (value: T) => MithrilPromise, error: (value: Error) => V): MithrilPromise|MithrilPromise; + } + interface MithrilXHROptions { + method?: string; + url: string; + user?: string; + password?: string; + data?: any; + background?: boolean; + unwrapSuccess?(data: any): any; + unwrapError?(data: any): any; + serialize?(dataToSerialize: any): string; + deserialize?(dataToDeserialize: string): any; + extract?(xhr: XMLHttpRequest, options: MithrilXHROptions): string; + type?(data: Object): void; + config?(xhr: XMLHttpRequest, options: MithrilXHROptions): XMLHttpRequest; + dataType?: string; + } } -interface MithrilRoute { - (rootElement: Element, defaultRoute: string, routes: { [key: string]: MithrilModule }): void; - (rootElement: HTMLDocument, defaultRoute: string, routes: { [key: string]: MithrilModule }): void; - (path: string, params?: any, shouldReplaceHistory?: boolean): void; - (element: Element, isInitialized: boolean): void; - (): string; - mode: string; - param: MithrilParam; - buildQueryString(data: Object): string; - parseQueryString(queryString: string): Object; -} +declare var Mithril: _mithril.MithrilStatic; +declare var m: _mithril.MithrilStatic; -interface MithrilParam { - (param: string): string; +declare module "mithril" { + export = m; } - -interface MithrilRedraw { - (): void; - strategy: (value?: string) => string; -} - -interface MithrilVirtualElement { - tag: string; - attrs: Object; - children: any; -} - -interface MithrilModule { - controller: Function; - view: (controller?: any) => MithrilVirtualElement; -} - -interface MithrilDeferred { - resolve(value?: T): void; - reject(value?: any): void; - promise: MithrilPromise; -} - -interface MithrilPromise { - (value?: T): T; - then(successCallback?: (value: T) => R, errorCallback?: (value: any) => any): MithrilPromise; - then(successCallback?: (value: T) => MithrilPromise, errorCallback?: (value: any) => any): MithrilPromise; -} - -interface MithrilPromiseProperty extends MithrilPromise { - (): T; - (value: T): T; - toJSON(): T; -} - -interface MithrilXHROptions { - method: string; - url: string; - user?: string; - password?: string; - data?: any; - background?: boolean; - unwrapSuccess?(data: any): any; - unwrapError?(data: any): any; - serialize?(dataToSerialize: any): string; - deserialize?(dataToDeserialize: string): any; - extract?(xhr: XMLHttpRequest, options: MithrilXHROptions): string; - type?(data: Object): void; - config?(xhr: XMLHttpRequest, options: MithrilXHROptions): XMLHttpRequest; -} - -declare var Mithril: MithrilStatic; -declare var m: MithrilStatic; diff --git a/mmmagic/mmmagic-tests.ts b/mmmagic/mmmagic-tests.ts new file mode 100644 index 0000000000..afe93ff091 --- /dev/null +++ b/mmmagic/mmmagic-tests.ts @@ -0,0 +1,30 @@ +/// + +import Magic = require("mmmagic"); + +// get general description of a file +var magic: Magic.Magic; + +magic = new Magic.Magic(); +magic.detectFile('node_modules/mmmagic/build/Release/magic.node', function(err: Error, result: string) { + if (err) throw err; + console.log(result); + // output on Windows with 32-bit node: +}); + +// get mime type for a file +magic = new Magic.Magic(Magic.MAGIC_MIME_TYPE); +magic.detectFile('node_modules/mmmagic/build/Release/magic.node', function(err: Error, result: string) { + if (err) throw err; + console.log(result); +}); + +// get mime type and mime encoding for a file +magic = new Magic.Magic(); +var buf = new Buffer('import Options\nfrom os import unlink, symlink'); + +magic.detect(buf, function(err: Error, result: string) { + if (err) throw err; + console.log(result); + // output: Python script, ASCII text executable +}); \ No newline at end of file diff --git a/mmmagic/mmmagic.d.ts b/mmmagic/mmmagic.d.ts new file mode 100644 index 0000000000..b286c93319 --- /dev/null +++ b/mmmagic/mmmagic.d.ts @@ -0,0 +1,37 @@ +// Type definitions for mmmagic v0.4.1 +// Project: https://github.com/mscdex/mmmagic +// Definitions by: Andrei Sebastian Cîmpean +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "mmmagic" { + export type bitmask = number; + export class Magic { + constructor(magicPath?: string, mask?: bitmask); + constructor(mask?: bitmask); + detectFile(path: string, callback: (err: Error, result: string) => void): void; + detect(data: Buffer, callback: (err: Error, result: string) => void): void; + } + export var MAGIC_NONE: bitmask; // no flags set + export var MAGIC_DEBUG: bitmask; // turn on debugging + export var MAGIC_SYMLINK: bitmask; // follow symlinks (default for non-Windows) + export var MAGIC_DEVICES: bitmask; // look at the contents of devices + export var MAGIC_MIME_TYPE: bitmask; // return the MIME type + export var MAGIC_CONTINUE: bitmask; // return all matches (returned as an array of strings) + export var MAGIC_CHECK: bitmask; // print warnings to stderr + export var MAGIC_PRESERVE_ATIME: bitmask; // restore access time on exit + export var MAGIC_RAW: bitmask; // don't translate unprintable chars + export var MAGIC_MIME_ENCODING: bitmask; // return the MIME encoding + export var MAGIC_MIME: bitmask; // (export var MAGIC_MIME_TYPE | export var MAGIC_MIME_ENCODING) + export var MAGIC_APPLE: bitmask; // return the Apple creator and type + export var MAGIC_NO_CHECK_TAR: bitmask; // don't check for tar files + export var MAGIC_NO_CHECK_SOFT: bitmask; // don't check magic entries + export var MAGIC_NO_CHECK_APPTYPE: bitmask; // don't check application type + export var MAGIC_NO_CHECK_ELF: bitmask; // don't check for elf details + export var MAGIC_NO_CHECK_TEXT: bitmask; // don't check for text files + export var MAGIC_NO_CHECK_CDF: bitmask; // don't check for cdf files + export var MAGIC_NO_CHECK_TOKENS: bitmask; // don't check tokens + export var MAGIC_NO_CHECK_ENCODING: bitmask // don't check text encodings + +} \ No newline at end of file diff --git a/modernizr/modernizr-tests.ts b/modernizr/modernizr-tests.ts index 86355a3100..f5308dd9e7 100644 --- a/modernizr/modernizr-tests.ts +++ b/modernizr/modernizr-tests.ts @@ -19,9 +19,9 @@ $(function () { document.getElementById('#notice').innerHTML = msg; } - Modernizr.prefixed('boxSizing'); + Modernizr.prefixed('boxSizing'); Modernizr.prefixed('requestAnimationFrame', window); - var ms = Modernizr.prefixed("matchesSelector", HTMLElement.prototype, document.body); + var ms = Modernizr.prefixed("matchesSelector", HTMLElement.prototype, true); Modernizr.prefixed('requestAnimationFrame', window, false); Modernizr.mq('only all and (max-width: 400px)'); @@ -30,7 +30,7 @@ $(function () { Modernizr.addTest('track', () => { var video = document.createElement('video'); - // return typeof video.addTextTrack === 'function' + return typeof video.addTextTrack === 'function' }); Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', (elem, rule) => { @@ -45,10 +45,100 @@ $(function () { Modernizr.testAllProps('boxSizing'); - var elem; + var elem: Element; Modernizr.hasEvent('gesturestart', elem); - - if (!Modernizr.autofocus) { + + if (!Modernizr.input.autofocus) { $("[autofocus]").focus(); } }); + + +Modernizr.on('flash', function( result ) { + if (result) { + // the browser has flash + } else { + // the browser does not have flash + } +}); + +Modernizr.addTest('itsTuesday', function() { + var d = new Date(); + return d.getDay() === 2; +}); + +Modernizr.addTest('hasJquery', 'jQuery' in window); + +var detects = { + 'hasjquery': 'jQuery' in window, + 'itstuesday': function() { + var d = new Date(); + return d.getDay() === 2; + } +} +Modernizr.addTest(detects); + +var keyframes = Modernizr.atRule('@keyframes'); +if (keyframes) { + // keyframes are supported + // could be `@-webkit-keyframes` or `@keyframes` +} else { + // keyframes === `false` +} + +Modernizr._domPrefixes === [ "Moz", "O", "ms", "Webkit" ]; + +Modernizr.hasEvent('blur') // true; + +Modernizr.hasEvent('devicelight', window) // true; + +var query = Modernizr.mq('(min-width: 900px)'); +if (query) { + // the browser window is larger than 900px +} + +Modernizr.prefixed('boxSizing') + +var raf = Modernizr.prefixed('requestAnimationFrame', window); +raf(function() { +}); + +var rAFProp = Modernizr.prefixed('requestAnimationFrame', window, false); +rAFProp === 'WebkitRequestAnimationFrame' // in older webkit + +Modernizr.prefixedCSS('transition') // '-moz-transition' in old Firefox + +Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)') + +var rule = Modernizr._prefixes.join('transform: rotate(20deg); '); +rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);' + +rule = 'display:' + Modernizr._prefixes.join('flex; display:') + 'flex'; +rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex' + +Modernizr.testAllProps('boxSizing') // true +Modernizr.testAllProps('display', 'block') // true +Modernizr.testAllProps('display', 'penguin') // false +Modernizr.testAllProps('shapeOutside', 'content-box', true); + +Modernizr.testProp('pointerEvents') // true +Modernizr.testProp('pointerEvents', 'none') // true +Modernizr.testProp('pointerEvents', 'penguin') // false + +Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', function(elem, rule) { + // elem is the first DOM node in the page (by default #modernizr) + // rule is the first argument you supplied - the CSS rule in string form + Modernizr.addTest('widthworks', elem.style.width === '9px') +}); + +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { + document.getElementById('modernizr').style.width === '1px'; // true + document.getElementById('modernizr2').style.width === '2px'; // true + elem.firstChild === document.getElementById('modernizr2'); // true +}, 1); + +Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) { + document.getElementById('modernizr').style.width === '1px'; // true + document.getElementById('modernizr2').style.width === '2px'; // true + elem.firstChild === document.getElementById('modernizr2'); // true +}, 1); diff --git a/modernizr/modernizr-tests.ts.tscparams b/modernizr/modernizr-tests.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/modernizr/modernizr-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/modernizr/modernizr.d.ts b/modernizr/modernizr.d.ts index a9104fd226..fa976c217e 100644 --- a/modernizr/modernizr.d.ts +++ b/modernizr/modernizr.d.ts @@ -1,116 +1,379 @@ -// Type definitions for Modernizr 2.6.2 +// Type definitions for Modernizr 3.2.0 // Project: http://modernizr.com/ -// Definitions by: Boris Yankov , Theodore Brown -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions by: Boris Yankov , Theodore Brown , Leon Yu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare namespace __Modernizr { + interface AudioBoolean { + ogg: boolean; + mp3: boolean; + wav: boolean; + m4a: boolean; + } -interface Audioboolean { - ogg: boolean; - mp3: boolean; - wav: boolean; - m4a: boolean; + interface VideoBoolean { + ogg: boolean; + h264: boolean; + webm: boolean; + } + + interface InputBoolean { + autocomplete: boolean; + autofocus: boolean; + list: boolean; + placeholder: boolean; + max: boolean; + min: boolean; + multiple: boolean; + pattern: boolean; + required: boolean; + step: boolean; + } + + interface InputTypesBoolean { + color: boolean; + date: boolean; + datetime: boolean; + "datetime-local": boolean; + email: boolean; + month: boolean; + number: boolean; + range: boolean; + search: boolean; + tel: boolean; + time: boolean; + url: boolean; + week: boolean; + } + + interface FeatureDetects { + // Documented + + ambientlight: boolean; + applicationcache: boolean; + audio: AudioBoolean; + batteryapi: boolean; + blobconstructor: boolean; + canvas: boolean; + canvastext: boolean; + contenteditable: boolean; + contextmenu: boolean; + cookies: boolean; + cors: boolean; + cryptography: boolean; + customprotocolhandler: boolean; + customevent: boolean; + dart: boolean; + dataview: boolean; + emoji: boolean; + eventlistener: boolean; + exiforientation: boolean; + flash: boolean; + forcetouch: boolean; + fullscreen: boolean; + gamepads: boolean; + geolocation: boolean; + hashchange: boolean; + hiddenscroll: boolean; + history: boolean; + htmlimports: boolean; + ie8compat: boolean; + indexeddb: boolean; + indexeddbblob: boolean; + input: InputBoolean; + search: boolean; + inputtypes: InputTypesBoolean; + intl: boolean; + json: boolean; + ligatures: boolean; + olreversed: boolean; + mathml: boolean; + notification: boolean; + pagevisibility: boolean; + performance: boolean; + pointerevents: boolean; + pointerlock: boolean; + postmessage: boolean; + proximity: boolean; + queryselector: boolean; + quotamanagement: boolean; + requestanimationframe: boolean; + serviceworker: boolean; + svg: boolean; + templatestrings: boolean; + touchevents: boolean; + typedarrays: boolean; + unicoderange: boolean; + unicode: boolean; + userdata: boolean; + vibrate: boolean; + video: VideoBoolean; + vml: boolean; + webintents: boolean; + animation: boolean; + webgl: boolean; + websockets: boolean; + xdomainrequest: boolean; + adownload: boolean; + audioloop: boolean; + audiopreload: boolean; + webaudio: boolean; + lowbattery: boolean; + canvasblending: boolean; + todataurljpeg: boolean; + todataurlpng: boolean; + todataurlwebp: boolean; + canvaswinding: boolean; + getrandomvalues: boolean; + cssall: boolean; + cssanimations: boolean; + appearance: boolean; + backdropfilter: boolean; + backgroundblendmode: boolean; + backgroundcliptext: boolean; + bgpositionshorthand: boolean; + bgpositionxy: boolean; + bgrepeatspace: boolean; + bgrepeatround: boolean; + backgroundsize: boolean; + bgsizecover: boolean; + borderimage: boolean; + borderradius: boolean; + boxshadow: boolean; + boxsizing: boolean; + csscalc: boolean; + checked: boolean; + csschunit: boolean; + csscolumns: boolean; + cubicbezierrange: boolean; + "display-runin": boolean; + displaytable: boolean; + ellipsis: boolean; + cssescape: boolean; + cssexunit: boolean; + cssfilters: boolean; + flexbox: boolean; + flexboxlegacy: boolean; + flexboxtweener: boolean; + flexwrap: boolean; + fontface: boolean; + generatedcontent: boolean; + cssgradients: boolean; + csshairline: boolean; + hsla: boolean; + csshyphens: boolean; + softhyphens: boolean; + softhyphensfind: boolean; + cssinvalid: boolean; + lastchild: boolean; + cssmask: boolean; + mediaqueries: boolean; + multiplebgs: boolean; + nthchild: boolean; + objectfit: boolean; + opacity: boolean; + overflowscrolling: boolean; + csspointerevents: boolean; + csspositionsticky: boolean; + csspseudoanimations: boolean; + csspseudotransitions: boolean; + cssreflections: boolean; + regions: boolean; + cssremunit: boolean; + cssresize: boolean; + rgba: boolean; + cssscrollbar: boolean; + scrollsnappoints: boolean; + shapes: boolean; + siblinggeneral: boolean; + subpixelfont: boolean; + supports: boolean; + target: boolean; + textalignlast: boolean; + textshadow: boolean; + csstransforms: boolean; + csstransforms3d: boolean; + preserve3d: boolean; + csstransitions: boolean; + userselect: boolean; + cssvalid: boolean; + cssvhunit: boolean; + cssvmaxunit: boolean; + cssvminunit: boolean; + cssvwunit: boolean; + willchange: boolean; + wrapflow: boolean; + classlist: boolean; + createelementattrs: boolean; + "createelement-attrs": boolean; + dataset: boolean; + documentfragment: boolean; + hidden: boolean; + microdata: boolean; + mutationobserver: boolean; + bdi: boolean; + datalistelem: boolean; + details: boolean; + outputelem: boolean; + picture: boolean; + progressbar: boolean; + meter: boolean; + ruby: boolean; + template: boolean; + time: boolean; + texttrackapi: boolean; + track: boolean; + unknownelements: boolean; + es5array: boolean; + es5date: boolean; + es5function: boolean; + es5object: boolean; + es5: boolean; + strictmode: boolean; + es5string: boolean; + es5syntax: boolean; + es5undefined: boolean; + es6array: boolean; + es6collections: boolean; + contains: boolean; + generators: boolean; + es6math: boolean; + es6number: boolean; + es6object: boolean; + promises: boolean; + es6string: boolean; + devicemotion: boolean; + deviceorientation: boolean; + oninput: boolean; + filereader: boolean; + filesystem: boolean; + capture: boolean; + fileinput: boolean; + directory: boolean; + formattribute: boolean; + localizednumber: boolean; + placeholder: boolean; + requestautocomplete: boolean; + formvalidation: boolean; + sandbox: boolean; + seamless: boolean; + srcdoc: boolean; + apng: boolean; + imgcrossorigin: boolean; + jpeg2000: boolean; + jpegxr: boolean; + sizes: boolean; + srcset: boolean; + webpalpha: boolean; + webpanimation: boolean; + webplossless: boolean; + "webp-lossless": boolean; + webp: boolean; + inputformaction: boolean; + inputformenctype: boolean; + inputformmethod: boolean; + inputformtarget: boolean; + beacon: boolean; + lowbandwidth: boolean; + eventsource: boolean; + fetch: boolean; + xhrresponsetypearraybuffer: boolean; + xhrresponsetypeblob: boolean; + xhrresponsetypedocument: boolean; + xhrresponsetypejson: boolean; + xhrresponsetypetext: boolean; + xhrresponsetype: boolean; + xhr2: boolean; + scriptasync: boolean; + scriptdefer: boolean; + speechrecognition: boolean; + speechsynthesis: boolean; + localstorage: boolean; + sessionstorage: boolean; + websqldatabase: boolean; + stylescoped: boolean; + svgasimg: boolean; + svgclippaths: boolean; + svgfilters: boolean; + svgforeignobject: boolean; + inlinesvg: boolean; + smil: boolean; + textareamaxlength: boolean; + bloburls: boolean; + datauri: boolean; + urlparser: boolean; + videoautoplay: boolean; + videoloop: boolean; + videopreload: boolean; + webglextensions: boolean; + datachannel: boolean; + getusermedia: boolean; + peerconnection: boolean; + websocketsbinary: boolean; + atobbtoa: boolean; + framed: boolean; + matchmedia: boolean; + blobworkers: boolean; + dataworkers: boolean; + sharedworkers: boolean; + transferables: boolean; + webworkers: boolean; + + // Undocumented - usually aliases or new features + + "atob-btoa": boolean; + "battery-api": boolean; + "blob-constructor": boolean; + "display-table": boolean; + "input-formaction": boolean; + "input-formenctype": boolean; + "input-formtarget": boolean; + "object-fit": boolean; + crypto: boolean; + displayrunin: boolean; + fileinputdirectory: boolean; + hairline: boolean; + inputsearchevent: boolean; + raf: boolean; + webanimations: boolean; + } + + interface Dictionary { + [key: string]: T; + } + + interface ModernizrAPI { + on(feature: string, cb: (result: boolean) => any): void; + + addTest(feature: string, test: () => boolean): void; + addTest(feature: string, test: boolean): void; + addTest(feature: Dictionary): void; + + atRule(prop: string): boolean; + + _domPrefixes: string[]; + + hasEvent(eventName: string, element?: EventTarget): boolean; + + mq(mq: string): boolean; + + prefixed(prop: string): string; + prefixed(prop: string, obj: EventTarget, element?: boolean): any; + + prefixedCSS(prop: string): string; + + prefixedCSSValue(prop: string, value: string): string; + + _prefixes: string[]; + + testAllProps(prop: string, value?: string, skipValueTest?: boolean): boolean; + + testProp(prop: string, value?: string, useValue?: boolean): boolean; + + testStyles(rule: string, callback: (elem: HTMLDivElement, rule: string) => void, nodes?: number, testnames?: string[]): boolean; + } + + export interface ModernizrStatic extends ModernizrAPI, FeatureDetects { } } -interface Videoboolean { - ogg: boolean; - h264: boolean; - webm: boolean; -} - -interface Inputboolean { - autocomplete: boolean; - autofocus: boolean; - list: boolean; - placeholder: boolean; - max: boolean; - min: boolean; - multiple: boolean; - pattern: boolean; - required: boolean; - step: boolean; -} - -interface InputTypesboolean { - search: boolean; - tel: boolean; - url: boolean; - email: boolean; - datetime: boolean; - date: boolean; - month: boolean; - week: boolean; - time: boolean; - datetimelocal: boolean; - number: boolean; - range: boolean; - color: boolean; -} - -interface ModernizrStatic { - autofocus: boolean; - fontface: boolean; - backgroundsize: boolean; - borderimage: boolean; - borderradius: boolean; - boxshadow: boolean; - flexbox: boolean; - hsla: boolean; - multiplebgs: boolean; - opacity: boolean; - rgba: boolean; - textshadow: boolean; - cssanimations: boolean; - csscolumns: boolean; - generatedcontent: boolean; - cssgradients: boolean; - cssreflections: boolean; - csstransforms: boolean; - csstransforms3d: boolean; - csstransitions: boolean; - applicationcache: boolean; - canvas: boolean; - canvastext: boolean; - draganddrop: boolean; - hashchange: boolean; - history: boolean; - audio: Audioboolean; - video: Videoboolean; - indexeddb: boolean; - input: Inputboolean; - inputtypes: InputTypesboolean; - localstorage: boolean; - postmessage: boolean; - sessionstorage: boolean; - websockets: boolean; - websqldatabase: boolean; - webworkers: boolean; - geolocation: boolean; - inlinesvg: boolean; - smil: boolean; - svg: boolean; - svgclippaths: boolean; - touch: boolean; - webgl: boolean; - - load(resources: any[]): void; - load(resourceObject: any): void; - load(resourceString: string): void; - - prefixed(property: string): any; - prefixed(property: string, obj: any, element?: any): any; - - mq(mediaQuery: string): boolean; - - addTest(feature: string, test: () => any): void; - addTest(feature: string, test: boolean): void; - addTest(feature: any): void; - - testStyles(rule: string, callback: (element: HTMLDivElement, rule: string) => void, nodes?: number, testnames?: string[]): boolean; - testProp(property: string): boolean; - testAllProps(property: string, prefix?: string): boolean; - testAllProps(property: string, obj: any, element: any): boolean; - - hasEvent(eventName: string, element?: any): boolean; -} - -declare var Modernizr: ModernizrStatic; +declare var Modernizr: __Modernizr.ModernizrStatic; diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index babde41c92..3471a8fc30 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -1,10 +1,22 @@ -// Type definitions for Moment.js 2.8.0 +// Type definitions for Moment.js 2.10.5 // Project: https://github.com/timrwood/moment // Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya , Matt Brooks // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module moment { + interface MomentDateObject { + years?: number; + /* One digit */ + months?: number; + /* Day of the month */ + date?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + } + interface MomentInput { /** Year */ years?: number; @@ -247,8 +259,8 @@ declare module moment { dayOfYear(): number; dayOfYear(d: number): Moment; - from(f: Moment|string|number|Date|number[], suffix?: boolean): string; - to(f: Moment|string|number|Date|number[], suffix?: boolean): string; + from(f: Moment | string | number | Date | number[], suffix?: boolean): string; + to(f: Moment | string | number | Date | number[], suffix?: boolean): string; toNow(withoutPrefix?: boolean): string; diff(b: Moment): number; @@ -272,13 +284,13 @@ declare module moment { isDST(): boolean; isBefore(): boolean; - isBefore(b: Moment|string|number|Date|number[], granularity?: string): boolean; + isBefore(b: Moment | string | number | Date | number[], granularity?: string): boolean; isAfter(): boolean; - isAfter(b: Moment|string|number|Date|number[], granularity?: string): boolean; + isAfter(b: Moment | string | number | Date | number[], granularity?: string): boolean; - isSame(b: Moment|string|number|Date|number[], granularity?: string): boolean; - isBetween(a: Moment|string|number|Date|number[], b: Moment|string|number|Date|number[], granularity?: string): boolean; + isSame(b: Moment | string | number | Date | number[], granularity?: string): boolean; + isBetween(a: Moment | string | number | Date | number[], b: Moment | string | number | Date | number[], granularity?: string): boolean; // Deprecated as of 2.8.0. lang(language: string): Moment; @@ -294,43 +306,47 @@ declare module moment { localeData(): MomentLanguage; // Deprecated as of 2.7.0. - max(date: Moment|string|number|Date|any[]): Moment; + max(date: Moment | string | number | Date | any[]): Moment; max(date: string, format: string): Moment; // Deprecated as of 2.7.0. - min(date: Moment|string|number|Date|any[]): Moment; + min(date: Moment | string | number | Date | any[]): Moment; min(date: string, format: string): Moment; get(unit: string): number; set(unit: string, value: number): Moment; set(objectLiteral: MomentInput): Moment; + + /*This returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds.*/ + //Works with version 2.10.5+ + toObject(): MomentDateObject; } type formatFunction = () => string; interface MomentCalendar { - lastDay?: string | formatFunction; - sameDay?: string | formatFunction; - nextDay?: string | formatFunction; - lastWeek?: string | formatFunction; - nextWeek?: string | formatFunction; - sameElse?: string | formatFunction; + lastDay?: string | formatFunction; + sameDay?: string | formatFunction; + nextDay?: string | formatFunction; + lastWeek?: string | formatFunction; + nextWeek?: string | formatFunction; + sameElse?: string | formatFunction; } interface BaseMomentLanguage { - months ?: any; - monthsShort ?: any; - weekdays ?: any; - weekdaysShort ?: any; - weekdaysMin ?: any; - relativeTime ?: MomentRelativeTime; - meridiem ?: (hour: number, minute: number, isLowercase: boolean) => string; - calendar ?: MomentCalendar; - ordinal ?: (num: number) => string; + months?: any; + monthsShort?: any; + weekdays?: any; + weekdaysShort?: any; + weekdaysMin?: any; + relativeTime?: MomentRelativeTime; + meridiem?: (hour: number, minute: number, isLowercase: boolean) => string; + calendar?: MomentCalendar; + ordinal?: (num: number) => string; } interface MomentLanguage extends BaseMomentLanguage { - longDateFormat?: MomentLongDateFormat; + longDateFormat?: MomentLongDateFormat; } interface MomentLanguageData extends BaseMomentLanguage { @@ -341,34 +357,34 @@ declare module moment { } interface MomentLongDateFormat { - L: string; - LL: string; - LLL: string; - LLLL: string; - LT: string; - LTS: string; - l?: string; - ll?: string; - lll?: string; - llll?: string; - lt?: string; - lts?: string; + L: string; + LL: string; + LLL: string; + LLLL: string; + LT: string; + LTS: string; + l?: string; + ll?: string; + lll?: string; + llll?: string; + lt?: string; + lts?: string; } interface MomentRelativeTime { - future: any; - past: any; - s: any; - m: any; - mm: any; - h: any; - hh: any; - d: any; - dd: any; - M: any; - MM: any; - y: any; - yy: any; + future: any; + past: any; + s: any; + m: any; + mm: any; + h: any; + hh: any; + d: any; + dd: any; + M: any; + MM: any; + y: any; + yy: any; } interface MomentStatic { @@ -460,8 +476,8 @@ declare module moment { max(...moments: Moment[]): Moment; normalizeUnits(unit: string): string; - relativeTimeThreshold(threshold: string): number|boolean; - relativeTimeThreshold(threshold: string, limit:number): boolean; + relativeTimeThreshold(threshold: string): number | boolean; + relativeTimeThreshold(threshold: string, limit: number): boolean; /** * Constant used to enable explicit ISO_8601 format parsing. diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 4ccc9b72d1..3cb9c3575b 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -195,8 +195,8 @@ Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: I Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); -Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {}); -Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[]) => {}); +Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); +Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); var o = { diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index e840d8e050..b971622675 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -212,8 +212,8 @@ declare module "mongoose" { findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query; - geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query; + geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; + geoNear(point: number[], options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; increment(): T; mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; diff --git a/morgan/morgan-tests.ts b/morgan/morgan-tests.ts index 00e67f875d..4a0df99024 100644 --- a/morgan/morgan-tests.ts +++ b/morgan/morgan-tests.ts @@ -23,7 +23,9 @@ morgan('combined', { buffer: true, immediate: true, skip: function (req, res) { return res.statusCode < 400 }, - stream: (str: string) => { - console.log(str); + stream: { + write: (str: string) => { + console.log(str); + } } }); diff --git a/morgan/morgan.d.ts b/morgan/morgan.d.ts index b889bc7be4..048fce3d4e 100644 --- a/morgan/morgan.d.ts +++ b/morgan/morgan.d.ts @@ -12,6 +12,13 @@ declare module "morgan" { export function token(name: string, callback: (req: express.Request, res: express.Response) => T): express.RequestHandler; + export interface StreamOptions { + /** + * Output stream for writing log lines + */ + write: (str: string) => void; + } + /*** * Morgan accepts these properties in the options object. */ @@ -36,7 +43,7 @@ declare module "morgan" { * Output stream for writing log lines, defaults to process.stdout. * @param str */ - stream?: (str: string) => void; + stream?: StreamOptions; } } diff --git a/mssql/mssql-tests.ts b/mssql/mssql-tests.ts index e508ec3547..f1f1a20b2c 100644 --- a/mssql/mssql-tests.ts +++ b/mssql/mssql-tests.ts @@ -3,6 +3,10 @@ import sql = require('mssql'); +interface Entity{ + value: number; +} + var config: sql.config = { user: 'user', password: 'password', @@ -33,6 +37,18 @@ var connection: sql.Connection = new sql.Connection(config, function (err: any) } }); + getArticlesQuery = "SELECT 1 as value FROM TABLE"; + + requestQuery.query(getArticlesQuery, function (err, recordSet) { + if (err) { + console.error('Error happened calling Query: ' + err.name + " " + err.message); + + } + // checking to see if the articles returned as at least one. + else if (recordSet.length > 0 && recordSet[0].value) { + } + }); + var requestStoredProcedure = new sql.Request(connection); var testId: number = 0; var testString: string = 'test'; @@ -50,6 +66,15 @@ var connection: sql.Connection = new sql.Connection(config, function (err: any) } }); + requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { + if (err != null) { + console.error('Error happened calling Query: ' + err.name + " " + err.message); + } + else { + console.info(returnValue); + } + }); + var requestStoredProcedureWithOutput = new sql.Request(connection); var testId: number = 0; var testString: string = 'test'; @@ -74,6 +99,15 @@ var connection: sql.Connection = new sql.Connection(config, function (err: any) console.info(requestStoredProcedureWithOutput.parameters['output'].value); } }); + + requestStoredProcedure.execute('StoredProcedureName', function (err, recordsets, returnValue) { + if (err != null) { + console.error('Error happened calling Query: ' + err.name + " " + err.message); + } + else { + console.info(requestStoredProcedureWithOutput.parameters['output'].value); + } + }); } }); @@ -109,8 +143,10 @@ function test_promise_returns() { var request = new sql.Request(); request.batch('create procedure #temporary as select * from table').then((recordset) => { }); + request.batch('create procedure #temporary as select * from table;select 1 as value').then((recordset) => { }); request.bulk(new sql.Table("table_name")).then(() => { }); request.query('SELECT 1').then((recordset) => { }); + request.query('SELECT 1 as value').then(res => { }); request.execute('procedure_name').then((recordset) => { }); } @@ -120,7 +156,7 @@ function test_request_constructor() { var connection: sql.Connection = new sql.Connection(config); var preparedStatment = new sql.PreparedStatement(connection); var transaction = new sql.Transaction(connection); - + var request1 = new sql.Request(connection); var request2 = new sql.Request(preparedStatment); var request3 = new sql.Request(transaction); @@ -141,4 +177,4 @@ function test_classes_extend_eventemitter() { request.on('error', () => { }); preparedStatment.on('error', () => { }) -} \ No newline at end of file +} diff --git a/mssql/mssql.d.ts b/mssql/mssql.d.ts index c434444d3f..2b3db48075 100644 --- a/mssql/mssql.d.ts +++ b/mssql/mssql.d.ts @@ -7,7 +7,7 @@ /// declare module "mssql" { - import events = require('events'); + import events = require('events'); type sqlTypeWithNoParams = { type: sqlTypeFactoryWithNoParams } type sqlTypeWithLength = { type: sqlTypeFactoryWithLength, length: number } @@ -200,15 +200,19 @@ declare module "mssql" { public constructor(transaction: Transaction); public constructor(preparedStatement: PreparedStatement); public execute(procedure: string): Promise; - public execute(procedure: string, callback: (err?: any, recordsets?: any, returnValue?: any) => void): void; + public execute(procedure: string, callback: (err?: any, recordsets?: Entity[], returnValue?: any) => void): void; public input(name: string, value: any): void; public input(name: string, type: any, value: any): void; public output(name: string, type: any, value?: any): void; public pipe(stream: NodeJS.WritableStream): void; public query(command: string): Promise; + public query(command: string): Promise; public query(command: string, callback: (err?: any, recordset?: any) => void): void; + public query(command: string, callback: (err?: any, recordset?: Entity[]) => void): void; public batch(batch: string): Promise; + public batch(batch: string): Promise; public batch(batch: string, callback: (err?: any, recordset?: any) => void): void; + public batch(batch: string, callback: (err?: any, recordset?: Entity[]) => void): void; public bulk(table: Table): Promise; public bulk(table: Table, callback: (err: any, rowCount: any) => void): void; public cancel(): void; @@ -254,7 +258,9 @@ declare module "mssql" { public prepare(statement?: string): Promise; public prepare(statement?: string, callback?: (err?: any) => void): void; public execute(values: Object): Promise; + public execute(values: Object): Promise; public execute(values: Object, callback: (err: any, recordSet: recordSet) => void): void; + public execute(values: Object, callback: (err: any, recordSet: Entity[]) => void): void; public unprepare(): Promise; public unprepare(callback: (err?: any) => void): void; } diff --git a/multer/multer-tests.ts b/multer/multer-tests.ts index 8131293f5d..009ec4fbd0 100644 --- a/multer/multer-tests.ts +++ b/multer/multer-tests.ts @@ -4,5 +4,30 @@ import express = require('express'); import multer = require('multer'); -var app: express.Express = express(); -app.use(multer()); \ No newline at end of file +var upload = multer({ dest: 'uploads/' }); + +var app = express(); + +app.post('/profile', upload.single('avatar'), (req, res, next) => { +}); + +app.post('/photos/upload', upload.array('photos', 12), (req, res, next) => { +}); + +var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]) +app.post('/cool-profile', cpUpload, (req, res, next) => { +}); + +var diskStorage = multer.diskStorage({ + destination(req, file, cb) { + cb(null, '/tmp/my-uploads'); + }, + filename(req, file, cb) { + cb(null, file.fieldname + '-' + Date.now()); + } +}) + +var diskUpload = multer({ storage: diskStorage }); + +var memoryStorage = multer.memoryStorage(); +var memoryUpload = multer({ storage: memoryStorage }); diff --git a/multer/multer.d.ts b/multer/multer.d.ts index 06a9d4f7af..facd3da535 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -1,16 +1,16 @@ // Type definitions for multer // Project: https://github.com/expressjs/multer -// Definitions by: jt000 , vilicvane +// Definitions by: jt000 , vilicvane , David Broder-Rodgers // Definitions: https://github.com/borisyankov/DefinitelyTyped /// - declare module Express { export interface Request { + file: Multer.File; files: { [fieldname: string]: Multer.File - } + }; } module Multer { @@ -40,13 +40,19 @@ declare module Express { declare module "multer" { import express = require('express'); - function multer(options?: multer.Options): express.RequestHandler; - module multer { + interface Field { + /** The field name. */ + name: string; + /** Optional maximum number of files per field to accept. */ + maxCount?: number; + } - type Options = { + interface Options { /** The destination directory for the uploaded files. */ dest?: string; + /** The storage engine to use for uploaded files. */ + storage?: StorageEngine; /** An object specifying the size limits of the following optional properties. This object is passed to busboy directly, and the details of properties can be found on https://github.com/mscdex/busboy#busboy-methods */ limits?: { /** Max field name size (Default: 100 bytes) */ @@ -64,36 +70,45 @@ declare module "multer" { /** For multipart forms, the max number of header key=> value pairs to parse Default: 2000(same as node's http). */ headerPairs?: number; }; - /** A Boolean value to specify whether empty submitted values should be processed and applied to req.body; defaults to false; */ - includeEmptyFields?: boolean; - /** If this Boolean value is true, the file.buffer property holds the data in-memory that Multer would have written to disk. The dest option is still populated and the path property contains the proposed path to save the file. Defaults to false. */ - inMemory?: boolean; - /** Function to rename the uploaded files. Whatever the function returns will become the new name of the uploaded file (extension is not included). The fieldname and filename of the file will be available in this function, use them if you need to. */ - rename?: (fieldname: string, filename: string, req: Express.Request, res: Express.Response) => string; - /** Function to rename the directory in which to place uploaded files. The dest parameter is the default value originally assigned or passed into multer. The req and res parameters are also passed into the function because they may contain information (eg session data) needed to create the path (eg get userid from the session). */ - changeDest?: (dest: string, req: Express.Request, res: Express.Response) => string; - /** Event handler triggered when a file starts to be uploaded. A file object, with the following properties, is available to this function: fieldname, originalname, name, encoding, mimetype, path, and extension. */ - onFileUploadStart?: (file: Express.Multer.File, req: Express.Request, res: Express.Response) => void; - /** Event handler triggered when a chunk of buffer is received. A buffer object along with a file object is available to the function. */ - onFileUploadData?: (file: Express.Multer.File, data: Buffer, req: Express.Request, res: Express.Response) => void; - /** Event handler trigger when a file is completely uploaded. A file object is available to the function. */ - onFileUploadComplete?: (file: Express.Multer.File, req: Express.Request, res: Express.Response) => void; - /** Event handler triggered when the form parsing starts. */ - onParseStart?: () => void; - /** Event handler triggered when the form parsing completes. The request object and the next objects are are passed to the function. */ - onParseEnd?: (req: Express.Request, next: () => void) => void; - /** Event handler for any errors encountering while processing the form. The error object and the next object is available to the function. If you are handling errors yourself, make sure to terminate the request or call the next() function, else the request will be left hanging. */ - onError?: () => void; - /** Event handler triggered when a file size exceeds the specification in the limit object. No more files will be parsed after the limit is reached. */ - onFileSizeLimit?: (file: Express.Multer.File) => void; - /** Event handler triggered when the number of files exceed the specification in the limit object. No more files will be parsed after the limit is reached. */ - onFilesLimit?: () => void; - /** Event handler triggered when the number of fields exceed the specification in the limit object. No more fields will be parsed after the limit is reached. */ - onFieldsLimit?: () => void; - /** Event handler triggered when the number of parts exceed the specification in the limit object. No more files or fields will be parsed after the limit is reached. */ - onPartsLimit?: () => void; - }; + /** A function to control which files to upload and which to skip. */ + fileFilter?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, acceptFile: boolean) => void) => void; + } + + interface StorageEngine { + _handleFile(req: express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; + _removeFile(req: express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; + } + + interface DiskStorageOptions { + /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ + destination?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void; + /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ + filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; + } + + interface Instance { + /** Accept a single file with the name fieldname. The single file will be stored in req.file. */ + single(fieldame: string): express.RequestHandler; + /** Accept an array of files, all with the name fieldname. Optionally error out if more than maxCount files are uploaded. The array of files will be stored in req.files. */ + array(fieldame: string, maxCount?: number): express.RequestHandler; + /** Accept a mix of files, specified by fields. An object with arrays of files will be stored in req.files. */ + fields(fields: Field[]): express.RequestHandler; + /** Accepts all files that comes over the wire. An array of files will be stored in req.files. */ + any(): express.RequestHandler; + } } + interface Multer { + + (options?: multer.Options): multer.Instance; + + /* The disk storage engine gives you full control on storing files to disk. */ + diskStorage(options: multer.DiskStorageOptions): multer.StorageEngine; + /* The memory storage engine stores the files in memory as Buffer objects. */ + memoryStorage(): multer.StorageEngine; + } + + var multer: Multer; + export = multer; } diff --git a/natural/natural.d.ts b/natural/natural.d.ts index d559f38012..aaf3305a01 100644 --- a/natural/natural.d.ts +++ b/natural/natural.d.ts @@ -8,24 +8,27 @@ declare module "natural" { import events = require("events"); - class WordTokenizer { + interface Tokenizer { tokenize(text: string): string[]; } - class AggressiveTokenizer { + class WordTokenizer implements Tokenizer { tokenize(text: string): string[]; } - class TreebankWordTokenizer { + class AggressiveTokenizer implements Tokenizer { + tokenize(text: string): string[]; + } + class TreebankWordTokenizer implements Tokenizer { tokenize(text: string): string[]; } interface RegexTokenizerOptions { pattern: RegExp; discardEmpty?: boolean; } - class RegexpTokenizer { + class RegexpTokenizer implements Tokenizer { constructor(options: RegexTokenizerOptions); tokenize(text: string): string[]; } - class WordPunctTokenizer { + class WordPunctTokenizer implements Tokenizer { tokenize(text: string): string[]; } @@ -60,6 +63,9 @@ declare module "natural" { var PorterStemmerPt: { stem(token: string): string; } + var LancasterStemmer: { + stem(token: string): string; + } interface BayesClassifierCallback { (err: any, classifier: any): void } class BayesClassifier { @@ -74,6 +80,10 @@ declare module "natural" { static restore(classifier: any, stemmer?: Stemmer): BayesClassifier; } + interface Phonetic { + compare(stringA: string, stringB: string): boolean; + process(token: string, maxLength?: number): string; + } var Metaphone: { compare(stringA: string, stringB: string): boolean; process(token: string, maxLength?: number): string; diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index 758e0e53f5..0d663483a4 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -38,8 +38,8 @@ module NavigationTests { // Configuration Navigation.StateInfoConfig.build([ - { key: 'home', initial: 'page', states: [ - { key: 'page', route: '' } + { key: 'home', initial: 'page', help: 'home.htm', states: [ + { key: 'page', route: '', help: 'page.htm' } ]}, { key: 'person', initial: 'list', states: [ { key: 'list', route: ['people/{page}', 'people/{page}/sort/{sort}'], transitions: [ @@ -78,10 +78,20 @@ module NavigationTests { // State Handler class LogStateHandler extends Navigation.StateHandler { + getNavigationLink(state: Navigation.State, data: any): string { + console.log('get navigation link'); + return super.getNavigationLink(state, data, { ids: [] }); + } getNavigationData(state: Navigation.State, url: string): any { console.log('get navigation data'); - super.getNavigationData(state, url); + super.getNavigationData(state, url, {}); } + urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string { + return queryString ? val.replace(/\s/g, '+') : super.urlEncode(state, key, val, queryString); + } + urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string { + return queryString ? val.replace(/\+/g, ' ') : super.urlDecode(state, key, val, queryString); + } } homePage.stateHandler = new LogStateHandler(); personList.stateHandler = new LogStateHandler(); @@ -97,24 +107,28 @@ module NavigationTests { // Navigation Navigation.start('home'); Navigation.StateController.navigate('person'); + Navigation.StateController.navigate('person', null, Navigation.HistoryAction.Add); Navigation.StateController.refresh(); - Navigation.StateController.refresh({ page: 2 }); + Navigation.StateController.refresh({ page: 3 }); + Navigation.StateController.refresh({ page: 2 }, Navigation.HistoryAction.Replace); Navigation.StateController.navigate('select', { id: 10 }); var canGoBack: boolean = Navigation.StateController.canNavigateBack(1); Navigation.StateController.navigateBack(1); + Navigation.StateController.clearStateContext(); // Navigation Link var link = Navigation.StateController.getNavigationLink('person'); link = Navigation.StateController.getRefreshLink(); link = Navigation.StateController.getRefreshLink({ page: 2 }); + Navigation.StateController.navigateLink(link); link = Navigation.StateController.getNavigationLink('select', { id: 10 }); var nextDialog = Navigation.StateController.getNextState('select').parent; person = nextDialog; - Navigation.StateController.navigateLink(link); + Navigation.StateController.navigateLink(link, false); link = Navigation.StateController.getNavigationBackLink(1); var crumb = Navigation.StateController.crumbs[0]; link = crumb.navigationLink; - Navigation.StateController.navigateLink(link, true); + Navigation.StateController.navigateLink(link, true, Navigation.HistoryAction.None); // StateContext Navigation.StateController.navigate('home'); @@ -124,10 +138,15 @@ module NavigationTests { person === Navigation.StateContext.dialog; personList === Navigation.StateContext.state; var url: string = Navigation.StateContext.url; + var title: string = Navigation.StateContext.title; var page: number = Navigation.StateContext.data.page; + Navigation.StateController.refresh({ page: 2 }); + person = Navigation.StateContext.oldDialog; + personList = Navigation.StateContext.oldState; + page = Navigation.StateContext.oldData.page; + page = Navigation.StateContext.previousData.page; // Navigation Data - Navigation.StateController.refresh({ page: 2 }); var data = Navigation.StateContext.includeCurrentData({ sort: 'name' }, ['page']); Navigation.StateController.refresh(data); Navigation.StateContext.clear('sort'); diff --git a/navigation/navigation.d.ts b/navigation/navigation.d.ts index 59af79ca29..a9f2e1e0ea 100644 --- a/navigation/navigation.d.ts +++ b/navigation/navigation.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Navigation 1.1.0 +// Type definitions for Navigation 1.3.0 // Project: http://grahammendick.github.io/navigation/ // Definitions by: Graham Mendick // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -31,6 +31,10 @@ declare module Navigation { * Gets the textual description of the dialog */ title?: string; + /** + * Gets the additional dialog attributes + */ + [extras: string]: any; } /** @@ -75,6 +79,10 @@ declare module Navigation { * preserved when navigating */ trackTypes?: boolean; + /** + * Gets the additional state attributes + */ + [extras: string]: any; } /** @@ -278,6 +286,24 @@ declare module Navigation { */ static build(dialogs: IDialog[]>[]>[]): void; } + + /** + * Determines the effect on browser history after a successful navigation + */ + enum HistoryAction { + /** + * Creates a new browser history entry + */ + Add = 0, + /** + * Changes the current browser history entry + */ + Replace = 1, + /** + * Leaves browser history unchanged + */ + None = 2, + } /** * Defines a contract a class must implement in order to manage the browser @@ -295,9 +321,17 @@ declare module Navigation { /** * Adds browser history * @param state The State navigated to - * @param url The current url + * @param url The current url */ addHistory(state: State, url: string): void; + /** + * Adds browser history + * @param state The State navigated to + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(state: State, url: string, replace: boolean): void; /** * Gets the current location */ @@ -339,6 +373,14 @@ declare module Navigation { * @param url The current url */ addHistory(state: State, url: string): void; + /** + * Sets the browser Url's hash to the url + * @param state The State navigated to + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(state: State, url: string, replace: boolean): void; /** * Gets the current location */ @@ -375,6 +417,14 @@ declare module Navigation { * @param url The current url */ addHistory(state: State, url: string): void; + /** + * Sets the browser Url to the url using pushState + * @param state The State navigated to + * @param url The current url + * @param replace A value indicating whether to replace the current + * browser history entry + */ + addHistory(state: State, url: string, replace: boolean): void; /** * Gets the current location */ @@ -479,6 +529,14 @@ declare module Navigation { * @returns The navigation link */ getNavigationLink(state: State, data: any): string; + /** + * Gets a link that navigates to the state passing the data + * @param state The State to navigate to + * @param data The data to pass when navigating + * @param queryStringData The query string array data + * @returns The navigation link + */ + getNavigationLink(state: State, data: any, queryStringData: { [index: string]: string[]; }): string; /** * Navigates to the url * @param oldState The current State @@ -493,6 +551,30 @@ declare module Navigation { * @returns The navigation data */ getNavigationData(state: State, url: string): any; + /** + * Gets the data parsed from the url + * @param state The State navigated to + * @param url The current url + * @param queryStringData Stores query string keys + * @returns The navigation data + */ + getNavigationData(state: State, url: string, queryStringData: any): any; + /** + * Encodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlEncode?(state: State, key: string, val: string, queryString: boolean): string; + /** + * Decodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlDecode?(state: State, key: string, val: string, queryString: boolean): string; /** * Truncates the crumb trail * @param The State navigated to @@ -587,6 +669,16 @@ declare module Navigation { * ReturnData should be part of the CrumbTrail */ combineCrumbTrail: boolean; + /** + * Gets or sets a value indicating whether to track PreviousData when + * navigating back or refreshing and combineCrumbTrail is false + */ + trackAllPreviousData: boolean; + /** + * Gets or sets a value indicating whether arrays should be stored in + * a single query string parameter + */ + combineArray: boolean; } /** @@ -595,6 +687,18 @@ declare module Navigation { * previous State (this is not the same as the previous Crumb) */ class StateContext { + /** + * Gets the last State displayed before the current State + */ + static oldState: State; + /** + * Gets the parent of the OldState property + */ + static oldDialog: Dialog; + /** + * Gets the NavigationData for the last displayed State + */ + static oldData: any; /** * Gets the State navigated away from to reach the current State */ @@ -603,6 +707,10 @@ declare module Navigation { * Gets the parent of the PreviousState property */ static previousDialog: Dialog; + /** + * Gets the NavigationData for the navigated away from State + */ + static previousData: any; /** * Gets the current State */ @@ -612,14 +720,17 @@ declare module Navigation { */ static dialog: Dialog; /** - * Gets the NavigationData for the current State. It can be accessed. - * Will become the data stored in a Crumb when part of a crumb trail + * Gets the NavigationData for the current State */ static data: any; /** * Gets the current Url */ static url: string; + /** + * Gets or sets the current title + */ + static title: string; /** * Combines the data with all the current NavigationData * @param The data to add to the current NavigationData @@ -660,6 +771,10 @@ declare module Navigation { * @param url The current Url */ static setStateContext(state: State, url: string): void; + /** + * Clears the Context Data + */ + static clearStateContext(): void; /** * Registers a navigate event listener * @param handler The navigate event listener @@ -694,6 +809,20 @@ declare module Navigation { * @throws A mandatory route parameter has not been supplied a value */ static navigate(action: string, toData: any): void; + /** + * Navigates to a State. Depending on the action will either navigate + * to the 'to' State of a Transition or the 'initial' State of a + * Dialog + * @param action The key of a child Transition or the key of a Dialog + * @param toData The NavigationData to be passed to the next State and + * stored in the StateContext + * @param A value determining the effect on browser history + * @throws action does not match the key of a child Transition or the + * key of a Dialog; or there is NavigationData that cannot be converted + * to a String + * @throws A mandatory route parameter has not been supplied a value + */ + static navigate(action: string, toData: any, historyAction: HistoryAction): void; /** * Gets a Url to navigate to a State. Depending on the action will * either navigate to the 'to' State of a Transition or the 'initial' @@ -733,6 +862,17 @@ declare module Navigation { * @throws A mandatory route parameter has not been supplied a value */ static navigateBack(distance: number): void; + /** + * Navigates back to the Crumb contained in the crumb trail, + * represented by the Crumbs collection, as specified by the distance. + * In the crumb trail no two crumbs can have the same State but all + * must have the same Dialog + * @param distance Starting at 1, the number of Crumb steps to go back + * @param A value determining the effect on browser history + * @throws canNavigateBack returns false for this distance + * @throws A mandatory route parameter has not been supplied a value + */ + static navigateBack(distance: number, historyAction: HistoryAction): void; /** * Gets a Url to navigate to a Crumb contained in the crumb trail, * represented by the Crumbs collection, as specified by the distance. @@ -755,6 +895,15 @@ declare module Navigation { * @throws A mandatory route parameter has not been supplied a value */ static refresh(toData: any): void; + /** + * Navigates to the current State + * @param toData The NavigationData to be passed to the current State + * and stored in the StateContext + * @param A value determining the effect on browser history + * @throws There is NavigationData that cannot be converted to a String + * @throws A mandatory route parameter has not been supplied a value + */ + static refresh(toData: any, historyAction: HistoryAction): void; /** * Gets a Url to navigate to the current State passing no * NavigationData @@ -779,6 +928,13 @@ declare module Navigation { * @param history A value indicating whether browser history was used */ static navigateLink(url: string, history: boolean): void; + /** + * Navigates to the url + * @param url The target location + * @param history A value indicating whether browser history was used + * @param A value determining the effect on browser history + */ + static navigateLink(url: string, history: boolean, historyAction: HistoryAction): void; /** * Gets the next State. Depending on the action will either return the * 'to' State of a Transition or the 'initial' State of a Dialog @@ -800,6 +956,14 @@ declare module Navigation { * @returns The navigation link */ getNavigationLink(state: State, data: any): string; + /** + * Gets a link that navigates to the state passing the data + * @param state The State to navigate to + * @param data The data to pass when navigating + * @param queryStringData The query string array data + * @returns The navigation link + */ + getNavigationLink(state: State, data: any, queryStringData: { [index: string]: string[]; }): string; /** * Navigates to the url * @param oldState The current State @@ -814,6 +978,30 @@ declare module Navigation { * @returns The navigation data */ getNavigationData(state: State, url: string): any; + /** + * Gets the data parsed from the url + * @param state The State navigated to + * @param url The current url + * @param queryStringData Stores query string keys + * @returns The navigation data + */ + getNavigationData(state: State, url: string, queryStringData: any): any; + /** + * Encodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlEncode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Decodes the Url value + * @param state The State navigated to + * @param key The key of the navigation data item + * @param val The Url value of the navigation data item + * @param queryString A value indicating the Url value's location + */ + urlDecode(state: State, key: string, val: string, queryString: boolean): string; /** * Truncates the crumb trail whenever a repeated or initial State is * encountered @@ -924,6 +1112,13 @@ declare module Navigation { * @returns The matched data or null if there's no match */ match(path: string): any; + /** + * Gets the matching data for the path + * @param path The path to match + * @param urlDecode The function that decodes the Url value + * @returns The matched data or null if there's no match + */ + match(path: string, urlDecode: (route: Route, name: string, val: string) => string): any; /** * Gets the route populated with default values * @returns The built route @@ -931,10 +1126,17 @@ declare module Navigation { build(): string; /** * Gets the route populated with data and default values - * @param The data for the route parameters + * @param data The data for the route parameters * @returns The built route */ build(data: any): string; + /** + * Gets the route populated with data and default values + * @param data The data for the route parameters + * @param urlEncode The function that encodes the Url value + * @returns The built route + */ + build(data: any, urlEncode: (route: Route, name: string, val: string) => string): string; } /** @@ -956,10 +1158,17 @@ declare module Navigation { addRoute(path: string, defaults: any): Route; /** * Gets the matching route and data for the path - * @param route The path to match + * @param path The path to match * @returns The matched route and data */ match(path: string): { route: Route; data: any; }; + /** + * Gets the matching route and data for the path + * @param path The path to match + * @param urlDecode The function that decodes the Url value + * @returns The matched route and data + */ + match(path: string, urlDecode: (route: Route, name: string, val: string) => string): { route: Route; data: any; }; /** * Sorts the routes by the comparer * @param compare The route comparer function diff --git a/nconf/nconf-tests.ts b/nconf/nconf-tests.ts index 7037abfb60..673c05dca1 100644 --- a/nconf/nconf-tests.ts +++ b/nconf/nconf-tests.ts @@ -48,6 +48,8 @@ p = nconf.use(str, opts); p = nconf.defaults(); p = nconf.defaults(opts); +p = nconf.defaults({foo: 'bar'}); + nconf.init(); nconf.init(opts); diff --git a/nconf/nconf.d.ts b/nconf/nconf.d.ts index ee59591fd8..8453bfca80 100644 --- a/nconf/nconf.d.ts +++ b/nconf/nconf.d.ts @@ -48,11 +48,12 @@ declare module "nconf" { parse: (str: string) => any; } - export interface IOptions { - type?: string; + export interface IOptions { + [index: string]: any; } - export interface IFileOptions extends IOptions { + export interface IFileOptions { + type?: string; file?: string; dir?: string; search?: boolean; diff --git a/ng-cordova/actionSheet-tests.ts b/ng-cordova/actionSheet-tests.ts new file mode 100644 index 0000000000..07d105b549 --- /dev/null +++ b/ng-cordova/actionSheet-tests.ts @@ -0,0 +1,27 @@ +/// +/// + +module ngCordova { + 'use strict'; + + angular.module('test') + // Adapted from http://ngcordova.com/docs/plugins/actionSheet/ + .controller('ThisCtrl', function($cordovaActionSheet: ngCordova.IActionSheetService) { + + var options = { + title: 'What do you want with this image?', + buttonLabels: ['Share via Facebook', 'Share via Twitter'], + addCancelButtonWithLabel: 'Cancel', + androidEnableCancelButton: true, + winphoneEnableCancelButton: true, + addDestructiveButtonWithLabel: 'Delete it' + }; + + document.addEventListener("deviceready", function() { + $cordovaActionSheet.show(options) + .then(function(btnIndex) { + var index: number = btnIndex; + }); + }, false); + }); +} diff --git a/ng-cordova/actionSheet.d.ts b/ng-cordova/actionSheet.d.ts new file mode 100644 index 0000000000..1809d7fb0e --- /dev/null +++ b/ng-cordova/actionSheet.d.ts @@ -0,0 +1,22 @@ +// Type definitions for ngCordova Action Sheet plugin +// Project: https://github.com/driftyco/ng-cordova +// Definitions by: Phil McCloghry-Laing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module ngCordova { + export interface IActionSheetService { + show(options: ShowOptions): ng.IPromise; + hide(): ng.IPromise; + } + + export interface ShowOptions { + title?: string; + buttonLabels?: string[]; + addCancelButtonWithLabel?: string; + addDestructiveButtonWithLabel?: string; + androidEnableCancelButton?: boolean; + winphoneEnableCancelButton?: boolean; + } +} diff --git a/ng-cordova/badge-tests.ts b/ng-cordova/badge-tests.ts new file mode 100644 index 0000000000..854f66b39d --- /dev/null +++ b/ng-cordova/badge-tests.ts @@ -0,0 +1,59 @@ +/// +/// + +module ngCordova { + 'use strict'; + + angular.module('test') + // Adapted from http://ngcordova.com/docs/plugins/badge/ + .controller('ThisCtrl', function($cordovaBadge: ngCordova.IBadgeService) { + + $cordovaBadge.hasPermission().then(function(yes) { + // You have permission + }, function(no) { + // You do not have permission + }); + + $cordovaBadge.set(3).then(function() { + // You have permission, badge set. + }, function(err) { + // You do not have permission. + }); + + $cordovaBadge.get().then(function(badge) { + // You have permission, badge returned. + var badgeNo: number = badge; + }, function(err) { + // You do not have permission. + }); + + $cordovaBadge.clear().then(function() { + // You have permission, badge cleared. + }, function(err) { + // You do not have permission. + }); + + $cordovaBadge.increase().then(function() { + // You have permission, badge increased. + }, function(err) { + // You do not have permission. + }); + $cordovaBadge.increase(3).then(function() { + // You have permission, badge increased. + }, function(err) { + // You do not have permission. + }); + + $cordovaBadge.decrease().then(function() { + // You have permission, badge increased. + }, function(err) { + // You do not have permission. + }); + $cordovaBadge.decrease(2).then(function() { + // You have permission, badge increased. + }, function(err) { + // You do not have permission. + }); + + }); +} diff --git a/ng-cordova/badge.d.ts b/ng-cordova/badge.d.ts new file mode 100644 index 0000000000..b73b3182c4 --- /dev/null +++ b/ng-cordova/badge.d.ts @@ -0,0 +1,18 @@ +// Type definitions for ngCordova badge plugin +// Project: https://github.com/driftyco/ng-cordova +// Definitions by: Phil McCloghry-Laing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module ngCordova { + export interface IBadgeService { + hasPermission(): ng.IPromise; + promptForPermission(): ng.IPromise; + set(badge: number, callback?: Function, scope?: {}): ng.IPromise; + get(): ng.IPromise; + clear(callback?: Function, scope?: {}): ng.IPromise; + increase(count?: number, callback?: Function, scope?: {}): ng.IPromise; + decrease(count?: number, callback?: Function, scope?: {}): ng.IPromise; + } +} diff --git a/ng-cordova/file-tests.ts b/ng-cordova/file-tests.ts new file mode 100644 index 0000000000..6a4297394d --- /dev/null +++ b/ng-cordova/file-tests.ts @@ -0,0 +1,184 @@ +/// +/// +/// + +module ngCordova { + 'use strict'; + + + angular.module('test') + // Adapted from http://ngcordova.com/docs/plugins/file/ + .controller('MyCtrl', function($scope: ng.IScope, $cordovaFile: ngCordova.IFileService) { + + document.addEventListener('deviceready', function() { + + $cordovaFile.getFreeDiskSpace() + .then(function(success) { + // success in kilobytes + var freeSpace: number = success; + }, function(error) { + // error + }); + + + // CHECK + $cordovaFile.checkDir(cordova.file.dataDirectory, "dir/other_dir") + .then(function(success) { + // success + var dir: DirectoryEntry = success; + }, function(error) { + // error + }); + + + $cordovaFile.checkFile(cordova.file.dataDirectory, "some_file.txt") + .then(function(success) { + // success + var fileResult: FileEntry = success; + }, function(error) { + // error + }); + + + // CREATE + $cordovaFile.createDir(cordova.file.dataDirectory, "new_dir", false) + .then(function(success) { + // success + var dir: DirectoryEntry = success; + }, function(error) { + // error + }); + + $cordovaFile.createFile(cordova.file.dataDirectory, "new_file.txt", true) + .then(function(success) { + // success + var fileResult: FileEntry = success; + }, function(error) { + // error + }); + + + // REMOVE + $cordovaFile.removeDir(cordova.file.dataDirectory, "some_dir") + .then(function(success) { + // success + if (success.success) { + var dirResult: DirectoryEntry = success.fileRemoved; + } + }, function(error) { + // error + }); + + $cordovaFile.removeFile(cordova.file.dataDirectory, "some_file.txt") + .then(function(success) { + // success + if (success.success) { + var fileResult: FileEntry = success.fileRemoved; + } + }, function(error) { + // error + }); + + $cordovaFile.removeRecursively(cordova.file.dataDirectory, "") + .then(function(success) { + // success + if (success.success) { + var dirResult: DirectoryEntry = success.fileRemoved; + } + }, function(error) { + // error + }); + + + // WRITE + $cordovaFile.writeFile(cordova.file.dataDirectory, "file.txt", "text", true) + .then(function(success) { + // success + var endEvent: ProgressEvent = success; + }, function(error) { + // error + }); + + $cordovaFile.writeExistingFile(cordova.file.dataDirectory, "file.txt", "text") + .then(function(success) { + // success + var endEvent: ProgressEvent = success; + }, function(error) { + // error + }); + + + // READ + $cordovaFile.readAsText(cordova.file.dataDirectory, "file.txt") + .then(function(success) { + // success + var text: string = success; + }, function(error) { + // error + }); + + $cordovaFile.readAsDataURL(cordova.file.dataDirectory, "file.txt") + .then(function(success) { + // success + var text: string = success; + }, function(error) { + // error + }); + + $cordovaFile.readAsBinaryString(cordova.file.dataDirectory, "file.txt") + .then(function(success) { + // success + var text: string = success; + }, function(error) { + // error + }); + + $cordovaFile.readAsArrayBuffer(cordova.file.dataDirectory, "file.txt") + .then(function(success) { + // success + var buffer: ArrayBuffer = success; + }, function(error) { + // error + }); + + + // MOVE + $cordovaFile.moveDir(cordova.file.dataDirectory, "dir", cordova.file.tempDirectory, "new_dir") + .then(function(success) { + // success + var dirResult: DirectoryEntry = success; + }, function(error) { + // error + }); + + $cordovaFile.moveFile(cordova.file.dataDirectory, "file.txt", cordova.file.tempDirectory) + .then(function(success) { + // success + var fileResult: FileEntry = success; + }, function(error) { + // error + }); + + + // COPY + $cordovaFile.copyDir(cordova.file.dataDirectory, "dir", cordova.file.tempDirectory, "new_dir") + .then(function(success) { + // success + var dirResult: DirectoryEntry = success; + }, function(error) { + // error + }); + + $cordovaFile.copyFile(cordova.file.dataDirectory, "file.txt", cordova.file.tempDirectory, "new_file.txt") + .then(function(success) { + // success + var fileResult: FileEntry = success; + }, function(error) { + // error + }); + + + }); + + }); +} diff --git a/ng-cordova/file.d.ts b/ng-cordova/file.d.ts new file mode 100644 index 0000000000..04f19080a1 --- /dev/null +++ b/ng-cordova/file.d.ts @@ -0,0 +1,51 @@ +// Type definitions for ngCordova file plugin +// Project: https://github.com/driftyco/ng-cordova +// Definitions by: Phil McCloghry-Laing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module ngCordova { + export interface IFileService { + getFreeDiskSpace(): IFilePromise; + + checkDir(path: string, directory: string): IFilePromise; + checkFile(path: string, file: string): IFilePromise; + + createDir(path: string, directory: string, replace?: boolean): IFilePromise; + createFile(path: string, file: string, replace?: boolean): IFilePromise; + + removeDir(path: string, directory: string): IFilePromise>; + removeFile(path: string, file: string): IFilePromise>; + removeRecursively(path: string, directory: string): IFilePromise>; + + writeFile(path: string, file: string, text: string | Blob, replace?: boolean): IFilePromise; + writeExistingFile(path: string, file: string, text: string | Blob): IFilePromise; + + readAsText(path: string, file: string): ng.IPromise; + readAsDataURL(path: string, file: string): ng.IPromise; + readAsBinaryString(path: string, file: string): ng.IPromise; + readAsArrayBuffer(path: string, file: string): ng.IPromise; + + moveDir(path: string, directory: string, newPath: string, newDirectory?: string): IFilePromise; + moveFile(path: string, file: string, newPath: string, newFile?: string): IFilePromise; + + copyDir(path: string, directory: string, newPath: string, newDirectory?: string): IFilePromise; + copyFile(path: string, file: string, newPath: string, newFile?: string): IFilePromise; + } + + export interface IFilePromise extends ng.IPromise { + then(successCallback: (promiseValue: T) => ng.IPromise | TResult, errorCallback?: (error: IFileError) => ng.IPromise | TResult): ng.IPromise; + catch(onRejected: (error: IFileError) => ng.IPromise | TResult): ng.IPromise; + } + + export interface IFileRemoveResult { + success: boolean; + fileRemoved: TEntry; + } + + export interface IFileError extends FileError { + message: string; + } +} diff --git a/ng-cordova/fileTransfer-tests.ts b/ng-cordova/fileTransfer-tests.ts new file mode 100644 index 0000000000..0c188f239f --- /dev/null +++ b/ng-cordova/fileTransfer-tests.ts @@ -0,0 +1,53 @@ +/// +/// +/// + +module ngCordova { + 'use strict'; + + angular.module('test') + // Adapted from http://ngcordova.com/docs/plugins/fileTransfer/ + .controller('MyCtrl', function($scope: ng.IScope & { downloadProgress: number; }, $timeout: ng.ITimeoutService, $cordovaFileTransfer: ngCordova.IFileTransferService) { + + document.addEventListener('deviceready', function() { + + var url = "http://cdn.wall-pix.net/albums/art-space/00030109.jpg"; + var targetPath = cordova.file.documentsDirectory + "testImage.png"; + var trustHosts = true + var options = {}; + + $cordovaFileTransfer.download(url, targetPath, options, trustHosts) + .then(function(result) { + // Success! + var file: FileEntry = result; + }, function(err) { + // Error + }, function(progress) { + $timeout(function() { + $scope.downloadProgress = (progress.loaded / progress.total) * 100; + }) + }); + + }, false); + + + document.addEventListener('deviceready', function() { + + var url = "http://cdn.wall-pix.net/uploads"; + var filePath = cordova.file.documentsDirectory + "testImage.png"; + var trustHosts = true + var options = {}; + + $cordovaFileTransfer.upload(url, filePath, options, trustHosts) + .then(function(result) { + // Success! + var file: FileUploadResult = result; + }, function(err) { + // Error + }, function(progress) { + // constant progress updates + }); + + }, false); + }); +} diff --git a/ng-cordova/fileTransfer.d.ts b/ng-cordova/fileTransfer.d.ts new file mode 100644 index 0000000000..838302e10c --- /dev/null +++ b/ng-cordova/fileTransfer.d.ts @@ -0,0 +1,30 @@ +// Type definitions for ngCordova file-transfer plugin +// Project: https://github.com/driftyco/ng-cordova +// Definitions by: Phil McCloghry-Laing +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare module ngCordova { + export interface IFileTransferService { + download(url: string, filePath: string, options?: IFileDownloadOptions, trustAllHosts?: boolean): IFileTransferPromise; + upload(url: string, filePath: string, options?: IFileUploadOptions, trustAllHosts?: boolean): IFileTransferPromise; + } + + export interface IFileTransferPromise extends ng.IPromise { + then(successCallback: (promiseValue: T) => ng.IPromise | TResult, errorCallback?: (error: FileTransferError) => ng.IPromise | TResult, notifyCallback?: (state: any) => any): ng.IPromise; + catch(onRejected: (error: FileTransferError) => ng.IPromise | TResult): ng.IPromise; + } + + export interface IFileDownloadOptions extends FileDownloadOptions { + encodeURI?: boolean; + timeout?: number; + } + + export interface IFileUploadOptions extends FileUploadOptions { + encodeURI?: boolean; + timeout?: number; + } +} diff --git a/ng-cordova/tsd.d.ts b/ng-cordova/tsd.d.ts index 5f17dd7065..791b61144b 100644 --- a/ng-cordova/tsd.d.ts +++ b/ng-cordova/tsd.d.ts @@ -15,3 +15,7 @@ /// /// /// +/// +/// +/// +/// diff --git a/ng-dialog/ng-dialog-tests.ts b/ng-dialog/ng-dialog-tests.ts index 6d68111a6d..27f50f89c9 100644 --- a/ng-dialog/ng-dialog-tests.ts +++ b/ng-dialog/ng-dialog-tests.ts @@ -20,6 +20,8 @@ class DialogTestController { template: "login.html", className: "default flat-ui", closeByEscape: false, + data: "string", + disableAnimation: false, name: "login-popup" }); diff --git a/ng-dialog/ng-dialog.d.ts b/ng-dialog/ng-dialog.d.ts index 3ad5c4d09a..95f02af632 100644 --- a/ng-dialog/ng-dialog.d.ts +++ b/ng-dialog/ng-dialog.d.ts @@ -61,6 +61,12 @@ declare module angular.dialog { * It will be appended with the "ngdialog" class e.g. className is "default-theme flat-ui" it will be class="ngdialog default-theme flat-ui". */ className?: string; + + /** + * If true then animation for the dialog will be disabled, default false. + */ + disableAnimation?: boolean; + /** * If false it allows to hide overlay div behind the modals, default true. */ @@ -106,5 +112,9 @@ declare module angular.dialog { * Scope object that will be passed to dialog. If you use controller with separate $scope service this object will be passed to $scope.$parent param. */ scope?: ng.IScope; + /** + * Any serializable data that you want to be stored in the controller's dialog scope. + */ + data?: string|Object|any[]; } } diff --git a/ng-notify/ng-notify-tests.ts b/ng-notify/ng-notify-tests.ts new file mode 100644 index 0000000000..4a03d62cec --- /dev/null +++ b/ng-notify/ng-notify-tests.ts @@ -0,0 +1,11 @@ +/// +/// + +class NgNotifyTestController { + + static $inject = ['$scope', 'ngNotify']; + + constructor($scope:ng.IScope, ngNotify:ngNotify.INotifyService) { + ngNotify.set('Your error message goes here!', 'error'); + } +}; \ No newline at end of file diff --git a/ng-notify/ng-notify.d.ts b/ng-notify/ng-notify.d.ts new file mode 100644 index 0000000000..f1092df625 --- /dev/null +++ b/ng-notify/ng-notify.d.ts @@ -0,0 +1,72 @@ +// Type definitions for ng-notify 0.7.1 +// Project: https://github.com/matowens/ng-notify +// Definitions by: Nick Zamosenchuk +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +declare module ngNotify { + + /** + * Contains the options used to configure notification. + */ + interface IUserOptions{ + type?: string; + theme?: string; + position?: string; + duration?: number; + sticky?: boolean; + button?: boolean; + html?: boolean; + } + + /** + * Simply and lightweight notification service for AngularJS + */ + interface INotifyService { + + /** + * Allows to create a whole new set of styles for each notification type. + * @param themeName The name used when setting the theme in the config object. + * @param className The class used to target this theme in the stylesheet. + */ + addTheme(themeName:string, className:string):void; + + /** + * Allows to create a new type of notification to use in their app. + * @param typeName The name used to trigger this notification type in the set method. + * @param className The class used to target this type in the stylesheet. + */ + addType(typeName:string, className:string):void; + + /** + * Sets default settings for all notifications to take into account when displaying. + * @param userOptions Notification configuration object + */ + config(userOptions: IUserOptions):void; + + /** + * Manually dismisses any sticky notifications that may still be set. + */ + dismiss():void; + + /** + * Displays a notification message. + * @param message A message text to display. + */ + set(message: string):void; + + /** + * Displays a notification message and sets the type for this one notification. + * @param message A message text to display. + * @param type The type of the notification. + */ + set(message: string, type: string):void; + + /** + * displays a notification message and sets the formatting/behavioral options for this one notification. + * @param message A message text to display. + * @param userOptions Notification configuration object. + */ + set(message: string, userOptions: IUserOptions):void; + } +} diff --git a/ngwysiwyg/ngwysiwyg-tests.ts b/ngwysiwyg/ngwysiwyg-tests.ts new file mode 100644 index 0000000000..c779e918ea --- /dev/null +++ b/ngwysiwyg/ngwysiwyg-tests.ts @@ -0,0 +1,20 @@ +/// + +//import ngWYSIWYG = require("ngWYSIWYG"); + +var complete: ngWYSIWYG.Config = { + sanitize: false, + toolbar: [ + { name: "basicStyling", items: ["bold", "italic", "underline", "strikethrough", "subscript", "superscript", "-", "leftAlign", "centerAlign", "rightAlign", "blockJustify", "-"] }, + { name: "paragraph", items: ["orderedList", "unorderedList", "outdent", "indent", "-"] }, + { name: "doers", items: ["removeFormatting", "undo", "redo", "-"] }, + { name: "colors", items: ["fontColor", "backgroundColor", "-"] }, + { name: "links", items: ["image", "hr", "symbols", "link", "unlink", "-"] }, + { name: "tools", items: ["print", "-"] }, + { name: "styling", items: ["font", "size", "format"] }, + ] +}; + +var partial: ngWYSIWYG.Config = { + sanitize: false +}; diff --git a/ngwysiwyg/ngwysiwyg.d.ts b/ngwysiwyg/ngwysiwyg.d.ts new file mode 100644 index 0000000000..9f5ba18ca8 --- /dev/null +++ b/ngwysiwyg/ngwysiwyg.d.ts @@ -0,0 +1,16 @@ +// Type definitions for Marked +// Project: https://github.com/psergus/ngWYSIWYG +// Definitions by: Patrick Mac Kay +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ngWYSIWYG { + export interface Toolbar { + name: string; + items: string[]; + } + + export interface Config { + sanitize: boolean; + toolbar?: Toolbar[]; + } +} \ No newline at end of file diff --git a/node-dir/node-dir-tests.ts b/node-dir/node-dir-tests.ts new file mode 100644 index 0000000000..6cc03ec538 --- /dev/null +++ b/node-dir/node-dir-tests.ts @@ -0,0 +1,90 @@ +/// + +import * as dir from "node-dir"; + +// display contents of files in this script's directory +dir.readFiles("./", + function(err, content, next) { + console.log('content:', content); + next(); + }, + function(err, files) { + console.log('finished reading files:', files); + }); + +// display contents of huge files in this script's directory +dir.readFilesStream("./", + function(err: any, stream: any, next: any) { + var content = ''; + stream.on('data', function(buffer: any) { + content += buffer.toString(); + }); + stream.on('end',function() { + console.log('content:', content); + next(); + }); + }, + function(err, files) { + console.log('finished reading files:', files); + }); + +// match only filenames with a .txt extension and that don't start with a `.´ +dir.readFiles("./", { + match: /.txt$/, + exclude: /^\./ + }, function(err, content, next) { + console.log('content:', content); + next(); + }, + function(err, files){ + console.log('finished reading files:',files); + }); + +// exclude an array of subdirectory names +dir.readFiles("./", { + exclude: ['node_modules', 'test'] + }, function(err, content, next) { + console.log('content:', content); + next(); + }, + function(err, files){ + console.log('finished reading files:',files); + }); + + +// the callback for each file can optionally have a filename argument as its 3rd parameter +// and the finishedCallback argument is optional, e.g. +dir.readFiles("./", function(err: any, content: any, filename: string, next: any) { + console.log('processing content of file', filename); + next(); +}); + +dir.files("./", function(err, files) { + console.log(files); +}); + +dir.files("./", function(err, files) { + // sort descending + files.reverse(); + // include only certain filenames + files = files.filter(function(file: any) { + return ['allowed', 'file', 'names'].indexOf(file) > -1; + }); + // exclude some filenames + files = files.filter(function(file: any) { + return ['exclude', 'these', 'files'].indexOf(file) === -1; + }); +}); + +dir.subdirs("./", function(err, subdirs) { + console.log(subdirs); +}); + +dir.paths("./", function(err, paths) { + console.log('files:\n', paths.files); + console.log('subdirs:\n', paths.dirs); +}); + +dir.paths("./", true, function(err, paths) { + console.log('paths:\n', paths); +}); diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts new file mode 100644 index 0000000000..d131f6b9a1 --- /dev/null +++ b/node-dir/node-dir.d.ts @@ -0,0 +1,65 @@ +// Type definitions for node-dir +// Project: https://github.com/fshost/node-dir +// Definitions by: Panu Horsmalahti +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "node-dir" { + export interface Options { + // file encoding (defaults to 'utf8') + encoding?: string; + + // a regex pattern or array to specify filenames to ignore + exclude?: RegExp | string[]; + + // a regex pattern or array to specify directories to ignore + excludeDir?: RegExp | string[]; + + // a regex pattern or array to specify filenames to operate on + match?: RegExp | string[]; + + // a regex pattern or array to specify directories to recurse + matchDir?: RegExp | string[]; + + // whether to recurse subdirectories when reading files (defaults to true) + recursive?: boolean; + + // sort files in each directory in descending order + reverse?: boolean; + + // whether to aggregate only the base filename rather than the full filepath + shortName?: boolean; + + // sort files in each directory in ascending order (defaults to true) + sort?: boolean; + + // control if done function called on error (defaults to true) + doneOnErr?: boolean; + } + + export interface FileCallback { + (error: any, content: any, next: () => void): void; + } + + export interface FileNamedCallback { + (error: any, content: any, filename: string, next: () => void): void; + } + + export interface StreamCallback { + (error: any, stream: any, next: () => void): void; + } + + export interface FinishedCallback { + (error: any, files: any): void; + } + + export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, + finishedCallback?: FinishedCallback): void; + export function files(dir: string, callback: (error: any, files: any) => void): void; + export function subdirs(dir: string, callback: (error: any, subdirs: any) => void): void; + export function paths(dir: string, callback: (error: any, paths: any) => void): void; + export function paths(dir: string, combine: boolean, callback: (error: any, paths: any) => void): void; +} diff --git a/node/node-0.10.d.ts b/node/node-0.10.d.ts index a4cd5b1a6b..c77c724a6b 100644 --- a/node/node-0.10.d.ts +++ b/node/node-0.10.d.ts @@ -176,7 +176,7 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; @@ -1191,8 +1191,8 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; export function randomBytes(size: number): Buffer; export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export function pseudoRandomBytes(size: number): Buffer; diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index 05aee911de..e6943e2540 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -176,7 +176,7 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; @@ -1099,8 +1099,8 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; export function randomBytes(size: number): Buffer; export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export function pseudoRandomBytes(size: number): Buffer; diff --git a/node/node-0.12.d.ts b/node/node-0.12.d.ts index 11fd92d245..08564c2247 100644 --- a/node/node-0.12.d.ts +++ b/node/node-0.12.d.ts @@ -256,7 +256,7 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; @@ -1654,8 +1654,8 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number, digest: string) : Buffer; export function randomBytes(size: number): Buffer; diff --git a/node/node-0.8.8.d.ts b/node/node-0.8.8.d.ts index 1972e0cdcf..592760360a 100644 --- a/node/node-0.8.8.d.ts +++ b/node/node-0.8.8.d.ts @@ -150,7 +150,7 @@ interface NodeProcess extends EventEmitter { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; @@ -326,7 +326,7 @@ declare module "cluster" { export function disconnect(callback?: Function): void; export var workers: any; - // Event emitter + // Event emitter export function addListener(event: string, listener: Function): void; export function on(event: string, listener: Function): any; export function once(event: string, listener: Function): void; @@ -970,7 +970,7 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: string) => any): void; export function randomBytes(size: number, callback?: (err: Error, buf: Buffer) =>void ); } diff --git a/node/node-tests.ts b/node/node-tests.ts index 930bd1a71e..eaab3c2c8d 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -14,6 +14,7 @@ import * as querystring from "querystring"; import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; +import * as os from "os"; assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -31,6 +32,54 @@ assert.doesNotThrow(() => { if (false) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); +//////////////////////////////////////////////////// +/// Events tests : http://nodejs.org/api/events.html +//////////////////////////////////////////////////// + +module events_tests { + let emitter: events.EventEmitter; + let event: string; + let listener: Function; + let any: any; + + { + let result: events.EventEmitter; + + result = emitter.addListener(event, listener); + result = emitter.on(event, listener); + result = emitter.once(event, listener); + result = emitter.removeListener(event, listener); + result = emitter.removeAllListeners(); + result = emitter.removeAllListeners(event); + result = emitter.setMaxListeners(42); + } + + { + let result: number; + + result = events.EventEmitter.defaultMaxListeners; + result = events.EventEmitter.listenerCount(emitter, event); // deprecated + + result = emitter.getMaxListeners(); + result = emitter.listenerCount(event); + } + + { + let result: Function[]; + + result = emitter.listeners(event); + } + + { + let result: boolean; + + result = emitter.emit(event); + result = emitter.emit(event, any); + result = emitter.emit(event, any, any); + result = emitter.emit(event, any, any, any); + } +} + //////////////////////////////////////////////////// /// File system tests : http://nodejs.org/api/fs.html //////////////////////////////////////////////////// @@ -197,6 +246,13 @@ var ctx: tls.SecureContext = tls.createSecureContext({ }); var blah = ctx.context; +var tlsOpts: tls.TlsOptions = { + host: "127.0.0.1", + port: 55 +}; +var tlsSocket = tls.connect(tlsOpts); + + //////////////////////////////////////////////////// // Make sure .listen() and .close() retuern a Server instance @@ -225,6 +281,16 @@ module http_tests { }); var agent: http.Agent = http.globalAgent; + + http.request({ + agent: false + }); + http.request({ + agent: agent + }); + http.request({ + agent: undefined + }); } //////////////////////////////////////////////////// @@ -238,16 +304,47 @@ ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: numb }); //////////////////////////////////////////////////// -///Querystring tests : https://gist.github.com/musubu/2202583 +///Querystring tests : https://nodejs.org/api/querystring.html //////////////////////////////////////////////////// -var original: string = 'http://example.com/product/abcde.html'; -var escaped: string = querystring.escape(original); -console.log(escaped); -// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html -var unescaped: string = querystring.unescape(escaped); -console.log(unescaped); -// http://example.com/product/abcde.html +module querystring_tests { + type SampleObject = {a: string; b: number;} + + { + let obj: SampleObject; + let sep: string; + let eq: string; + let options: querystring.StringifyOptions; + let result: string; + + result = querystring.stringify(obj); + result = querystring.stringify(obj, sep); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq); + result = querystring.stringify(obj, sep, eq, options); + } + + { + let str: string; + let sep: string; + let eq: string; + let options: querystring.ParseOptions; + let result: SampleObject; + + result = querystring.parse(str); + result = querystring.parse(str, sep); + result = querystring.parse(str, sep, eq); + result = querystring.parse(str, sep, eq, options); + } + + { + let str: string; + let result: string; + + result = querystring.escape(str); + result = querystring.unescape(str); + } +} //////////////////////////////////////////////////// /// path tests : http://nodejs.org/api/path.html @@ -389,21 +486,101 @@ module path_tests { } //////////////////////////////////////////////////// -///ReadLine tests : https://nodejs.org/api/readline.html +/// readline tests : https://nodejs.org/api/readline.html //////////////////////////////////////////////////// -var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout, -}); +module readline_tests { + let rl: readline.ReadLine; -rl.setPrompt("$>"); -rl.prompt(); -rl.prompt(true); + { + let options: readline.ReadLineOptions; + let input: NodeJS.ReadableStream; + let output: NodeJS.WritableStream; + let completer: readline.Completer; + let terminal: boolean; -rl.question("do you like typescript?", function(answer: string) { - rl.close(); -}); + let result: readline.ReadLine; + + result = readline.createInterface(options); + result = readline.createInterface(input); + result = readline.createInterface(input, output); + result = readline.createInterface(input, output, completer); + result = readline.createInterface(input, output, completer, terminal); + } + + { + let prompt: string; + + rl.setPrompt(prompt); + } + + { + let preserveCursor: boolean; + + rl.prompt(); + rl.prompt(preserveCursor); + } + + { + let query: string; + let callback: (answer: string) => void; + + rl.question(query, callback); + } + + { + let result: readline.ReadLine; + + result = rl.pause(); + } + + { + let result: readline.ReadLine; + + result = rl.resume(); + } + + { + rl.close(); + } + + { + let data: string|Buffer; + let key: readline.Key; + + rl.write(data); + rl.write(null, key); + } + + { + let stream: NodeJS.WritableStream; + let x: number; + let y: number; + + readline.cursorTo(stream, x, y); + } + + { + let stream: NodeJS.WritableStream; + let dx: number|string; + let dy: number|string; + + readline.moveCursor(stream, dx, dy); + } + + { + let stream: NodeJS.WritableStream; + let dir: number; + + readline.clearLine(stream, dir); + } + + { + let stream: NodeJS.WritableStream; + + readline.clearScreenDown(stream); + } +} ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// @@ -411,3 +588,49 @@ rl.question("do you like typescript?", function(answer: string) { childProcess.exec("echo test"); childProcess.spawnSync("echo test"); + +//////////////////////////////////////////////////// +/// os tests : https://nodejs.org/api/os.html +//////////////////////////////////////////////////// + +module os_tests { + { + let result: string; + + result = os.tmpdir(); + result = os.homedir(); + result = os.endianness(); + result = os.hostname(); + result = os.type(); + result = os.platform(); + result = os.arch(); + result = os.release(); + result = os.EOL; + } + + { + let result: number; + + result = os.uptime(); + result = os.totalmem(); + result = os.freemem(); + } + + { + let result: number[]; + + result = os.loadavg(); + } + + { + let result: os.CpuInfo[]; + + result = os.cpus(); + } + + { + let result: {[index: string]: os.NetworkInterfaceInfo[]}; + + result = os.networkInterfaces(); + } +} diff --git a/node/node.d.ts b/node/node.d.ts index 017ca8e6b9..450facb4a5 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -173,9 +173,11 @@ declare module NodeJS { once(event: string, listener: Function): EventEmitter; removeListener(event: string, listener: Function): EventEmitter; removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; + setMaxListeners(n: number): EventEmitter; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; } export interface ReadableStream extends EventEmitter { @@ -256,7 +258,7 @@ declare module NodeJS { visibility: string; }; }; - kill(pid: number, signal?: string): void; + kill(pid:number, signal?: string|number): void; pid: number; title: string; arch: string; @@ -405,25 +407,39 @@ declare module "buffer" { } declare module "querystring" { - export function stringify(obj: any, sep?: string, eq?: string): string; - export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any; + export interface StringifyOptions { + encodeURIComponent?: Function; + } + + export interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: Function; + } + + export function stringify(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any; + export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): T; export function escape(str: string): string; export function unescape(str: string): string; } declare module "events" { export class EventEmitter implements NodeJS.EventEmitter { - static listenerCount(emitter: EventEmitter, event: string): number; + static EventEmitter: EventEmitter; + static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static defaultMaxListeners: number; addListener(event: string, listener: Function): EventEmitter; on(event: string, listener: Function): EventEmitter; once(event: string, listener: Function): EventEmitter; removeListener(event: string, listener: Function): EventEmitter; removeAllListeners(event?: string): EventEmitter; - setMaxListeners(n: number): void; + setMaxListeners(n: number): EventEmitter; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; - } + listenerCount(type: string): number; + } } declare module "http" { @@ -443,7 +459,7 @@ declare module "http" { path?: string; headers?: { [key: string]: any }; auth?: string; - agent?: Agent; + agent?: Agent|boolean; } export interface Server extends events.EventEmitter { @@ -474,6 +490,7 @@ declare module "http" { writeHead(statusCode: number, headers?: any): void; statusCode: number; statusMessage: string; + headersSent: boolean; setHeader(name: string, value: string): void; sendDate: boolean; getHeader(name: string): string; @@ -698,7 +715,29 @@ declare module "zlib" { } declare module "os" { + export interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + } + } + + export interface NetworkInterfaceInfo { + address: string; + netmask: string; + family: string; + mac: string; + internal: boolean; + } + export function tmpdir(): string; + export function homedir(): string; + export function endianness(): string; export function hostname(): string; export function type(): string; export function platform(): string; @@ -708,8 +747,8 @@ declare module "os" { export function loadavg(): number[]; export function totalmem(): number; export function freemem(): number; - export function cpus(): { model: string; speed: number; times: { user: number; nice: number; sys: number; idle: number; irq: number; }; }[]; - export function networkInterfaces(): any; + export function cpus(): CpuInfo[]; + export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; export var EOL: string; } @@ -794,22 +833,49 @@ declare module "readline" { import * as events from "events"; import * as stream from "stream"; + export interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + export interface ReadLine extends events.EventEmitter { setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; - question(query: string, callback: Function): void; - pause(): void; - resume(): void; + question(query: string, callback: (answer: string) => void): void; + pause(): ReadLine; + resume(): ReadLine; close(): void; - write(data: any, key?: any): void; + write(data: string|Buffer, key?: Key): void; } + + export interface Completer { + (line: string): CompleterResult; + (line: string, callback: (err: any, result: CompleterResult) => void): any; + } + + export interface CompleterResult { + completions: string[]; + line: string; + } + export interface ReadLineOptions { input: NodeJS.ReadableStream; - output: NodeJS.WritableStream; - completer?: Function; + output?: NodeJS.WritableStream; + completer?: Completer; terminal?: boolean; + historySize?: number; } + + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine; export function createInterface(options: ReadLineOptions): ReadLine; + + export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; + export function clearLine(stream: NodeJS.WritableStream, dir: number): void; + export function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { @@ -875,7 +941,11 @@ declare module "child_process" { export function fork(modulePath: string, args?: string[], options?: { cwd?: string; env?: any; - encoding?: string; + execPath?: string; + execArgv?: string[]; + silent?: boolean; + uid?: number; + gid?: number; }): ChildProcess; export function spawnSync(command: string, args?: string[], options?: { cwd?: string; @@ -1503,6 +1573,8 @@ declare module "tls" { var CLIENT_RENEG_WINDOW: number; export interface TlsOptions { + host?: string; + port?: number; pfx?: any; //string or buffer key?: any; //string or buffer passphrase?: string; @@ -1662,10 +1734,10 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string, salt: string, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number) : Buffer; - export function pbkdf2Sync(password: string, salt: string, iterations: number, keylen: number, digest: string) : Buffer; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; + export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; export function randomBytes(size: number): Buffer; export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; export function pseudoRandomBytes(size: number): Buffer; @@ -1675,7 +1747,7 @@ declare module "crypto" { declare module "stream" { import * as events from "events"; - export interface Stream extends events.EventEmitter { + export class Stream extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; } diff --git a/nodemailer/nodemailer-tests.ts b/nodemailer/nodemailer-tests.ts index 1d99046c0a..a991096d5b 100644 --- a/nodemailer/nodemailer-tests.ts +++ b/nodemailer/nodemailer-tests.ts @@ -11,6 +11,20 @@ var transporter: nodemailer.Transporter = nodemailer.createTransport({ } }); +// create reusable transporter object using SMTP transport and set default values for mail options. +transporter = nodemailer.createTransport({ + service: 'Gmail', + auth: { + user: 'gmail.user@gmail.com', + pass: 'userpass' + } +}, { + from: 'sender@address', + headers: { + 'My-Awesome-Header': '123' + } +}); + // setup e-mail data with unicode symbols var mailOptions: nodemailer.SendMailOptions = { from: 'Fred Foo ✔ ', // sender address @@ -24,5 +38,3 @@ var mailOptions: nodemailer.SendMailOptions = { transporter.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => { // nothing }); - - diff --git a/nodemailer/nodemailer.d.ts b/nodemailer/nodemailer.d.ts index e0d1300b0a..e7d09f54f2 100644 --- a/nodemailer/nodemailer.d.ts +++ b/nodemailer/nodemailer.d.ts @@ -51,13 +51,13 @@ declare module "nodemailer" { /** * Create a direct transporter */ - export function createTransport(options?: directTransport.DirectOptions): Transporter; + export function createTransport(options?: directTransport.DirectOptions, defaults?: Object): Transporter; /** * Create an SMTP transporter */ - export function createTransport(options?: smtpTransport.SmtpOptions): Transporter; + export function createTransport(options?: smtpTransport.SmtpOptions, defaults?: Object): Transporter; /** * Create a transporter from a given implementation */ - export function createTransport(transport: Transport): Transporter; + export function createTransport(transport: Transport, defaults?: Object): Transporter; } diff --git a/onsenui/onsenui-tests.ts b/onsenui/onsenui-tests.ts index 58b72da6ea..f0918dc624 100644 --- a/onsenui/onsenui-tests.ts +++ b/onsenui/onsenui-tests.ts @@ -191,7 +191,7 @@ function onsTabbar(tabBar: TabbarView): void { keepPage: true }; tabBar.setActiveTab(2, options); - var activeTab: number = tabBar.getActiveTab(); + var activeTab: number = tabBar.getActiveTabIndex(); tabBar.loadPage('myPage.html'); tabBar.on('eventName', null); tabBar.once('eventName', null); diff --git a/onsenui/onsenui.d.ts b/onsenui/onsenui.d.ts index 287c8e2f51..9eed8c020e 100644 --- a/onsenui/onsenui.d.ts +++ b/onsenui/onsenui.d.ts @@ -634,7 +634,7 @@ interface TabbarView { * @return {Number} The index of the currently active tab * @description Returns tab index on current active tab. If active tab is not found, returns -1 */ - getActiveTab(): number; + getActiveTabIndex(): number; /** * @param {String} url Page URL. Can be either an HTML document or an <ons-template> * @description Displays a new page without changing the active index diff --git a/opn/opn-tests.ts b/opn/opn-tests.ts index 361725970d..2b39f1950c 100644 --- a/opn/opn-tests.ts +++ b/opn/opn-tests.ts @@ -1,10 +1,18 @@ /// -import opn = require('opn'); +import * as opn from "opn"; var errorCallback: (err: Error) => void; -opn('foo'); -opn('foo', 'bar'); -opn('foo', errorCallback); -opn('foo', 'bar', errorCallback); +opn("foo"); +opn("foo", errorCallback); + +opn("foo", { app: "bar" }); +opn("foo", { app: ["bar", "--arg"] }); +opn("foo", { app: "bar", wait: false }); +opn("foo", { app: ["bar", "--arg"] , wait: false}); + +opn("foo", { app: "bar" }, errorCallback); +opn("foo", { app: ["bar", "--arg"] }, errorCallback); +opn("foo", { app: "bar", wait: false }, errorCallback); +opn("foo", { app: ["bar", "--arg"], wait: false }, errorCallback); diff --git a/opn/opn.d.ts b/opn/opn.d.ts index 10a34ce60c..6e6a5a1788 100644 --- a/opn/opn.d.ts +++ b/opn/opn.d.ts @@ -1,10 +1,82 @@ -// Type definitions for opn 1.0.0 +// Type definitions for opn 3.0.2 // Project: https://github.com/sindresorhus/opn -// Definitions by: Shinnosuke Watanabe +// Definitions by: Shinnosuke Watanabe , +// Maxime LUCE // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module 'opn' { - function opn(target: string, callback?: (err: Error) => void): void; - function opn(target: string, app: string, callback?: (err: Error) => void): void; - export = opn; +/// + +declare namespace Opn { + export interface Options { + /** + * Wait for the opened app to exit before calling the `callback`. + * If `false` it's called immediately when opening the app. + * On Windows you have to explicitly specify an app for it to be able to wait. + */ + wait?: boolean; + + /** + * Specify the app to open the target with, or an array with the app and app arguments. + * The app name is platform dependent. Don't hard code it in reusable modules. + * Eg. Chrome is `google chrome` on OS X, `google-chrome` on Linux and `chrome` on Windows. + */ + app?: string | string[]; + } +} + +declare module "opn" { + import * as cp from "child_process"; + + interface DefaultFunction { + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + */ + (target: string): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. + */ + (target: string, callback: (err: Error) => void): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param options - Options to be passed to opn. + */ + (target: string, options: Opn.Options): cp.ChildProcess; + + /** + * Uses the command open on OS X, start on Windows and xdg-open on other platforms. + * + * Returns the spawned child process. + * You'd normally not need to use this for anything, but it can be useful if you'd like + * to attach custom event listeners or perform other operations directly on the spawned process. + * + * @param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. Eg. URLs opens in your default browser. + * @param options - Options to be passed to opn. + * @param callback- Called when the opened app exits, or if `wait: false`, immediately when opening. + */ + (target: string, options: Opn.Options, callback: (err: Error) => void): cp.ChildProcess; + } + + const opn: DefaultFunction; + export = opn; } diff --git a/parsimmon/parsimmon-tests.ts b/parsimmon/parsimmon-tests.ts index 3f80198917..569328296f 100644 --- a/parsimmon/parsimmon-tests.ts +++ b/parsimmon/parsimmon-tests.ts @@ -110,6 +110,9 @@ fooPar = P.succeed(foo); fooArrPar = P.seq(fooPar, fooPar); anyArrPar = P.seq(barPar, fooPar, numPar); +fooPar = P.custom((success, failure) => (stream, i) => { str = stream; num = i; return success(num, foo); }); +fooPar = P.custom((success, failure) => (stream, i) => failure(num, str)); + fooPar = P.alt(fooPar, fooPar); anyPar = P.alt(barPar, fooPar, numPar); diff --git a/parsimmon/parsimmon.d.ts b/parsimmon/parsimmon.d.ts index 719e9c937d..94b1b3be12 100644 --- a/parsimmon/parsimmon.d.ts +++ b/parsimmon/parsimmon.d.ts @@ -1,12 +1,14 @@ // Type definitions for Parsimmon 0.5.0 // Project: https://github.com/jneen/parsimmon -// Definitions by: Bart van der Schoor +// Definitions by: Bart van der Schoor , Mizunashi Mana // Definitions: https://github.com/borisyankov/DefinitelyTyped // TODO convert to generics declare module 'parsimmon' { module Parsimmon { + + export type StreamType = string; export interface Mark { start: number; @@ -103,6 +105,14 @@ declare module 'parsimmon' { export function seq(...parsers: Parser[]): Parser; export function seq(...parsers: Parser[]): Parser; + export type SuccessFunctionType = (index: number, result: U) => Result; + export type FailureFunctionType = (index: number, msg: string) => Result; + export type ParseFunctionType = (stream: StreamType, index: number) => Result; + /* + allows to add custom primitive parsers. + */ + export function custom(parsingFunction: (success: SuccessFunctionType, failure: FailureFunctionType) => ParseFunctionType): Parser; + /* accepts a variable number of parsers, and yields the value of the first one that succeeds, backtracking in between. */ diff --git a/pdf/pdf-tests.ts.tscparams b/pdf/pdf-tests.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/pdf/pdf-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pdf/pdf.d.ts b/pdf/pdf.d.ts index 8cac3a81c1..107031cade 100644 --- a/pdf/pdf.d.ts +++ b/pdf/pdf.d.ts @@ -221,22 +221,22 @@ interface PDFPageProxy { /** * Page number of the page. First page is 1. **/ - pageNumber(): number; + pageNumber: number; /** * The number of degrees the page is rotated clockwise. **/ - rotate(): number; + rotate: number; /** * The reference that points to this page. **/ - ref(): PDFRef; + ref: PDFRef; /** * @return An array of the visible portion of the PDF page in the user space units - [x1, y1, x2, y2]. **/ - view(): number[]; + view: number[]; /** * @param scale The desired scale of the viewport. diff --git a/pdf/pdf.d.ts.tscparams b/pdf/pdf.d.ts.tscparams deleted file mode 100644 index d3f5a12faa..0000000000 --- a/pdf/pdf.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/polymer-ts/polymer-ts-tests.ts b/polymer-ts/polymer-ts-tests.ts new file mode 100644 index 0000000000..1347b3bb71 --- /dev/null +++ b/polymer-ts/polymer-ts-tests.ts @@ -0,0 +1,24 @@ +/// + +namespace Components { + + export class TestComponent extends polymer.Base { + + public field: string = 'foo'; + public is: string; + + constructor() { + super(); + this.is = 'test-test'; + } + + public ready(): void { + console.log('ready'); + this.async(() => { + console.log('delayed'); + }, 500); + } + } + + polymer.createElement(TestComponent); +} diff --git a/polymer-ts/polymer-ts.d.ts b/polymer-ts/polymer-ts.d.ts new file mode 100644 index 0000000000..921b256656 --- /dev/null +++ b/polymer-ts/polymer-ts.d.ts @@ -0,0 +1,132 @@ +// Type definitions for PolymerTS 0.1.19 +// Project: https://github.com/nippur72/PolymerTS +// Definitions by: Louis Grignon +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module polymer { + class PolymerBase extends HTMLElement { + $: any; + $$: any; + root: HTMLElement; + shadyRoot: HTMLElement; + style: CSSStyleDeclaration; + customStyle: { + [property: string]: string; + }; + arrayDelete(path: string, item: string | any): any; + async(callback: Function, waitTime?: number): any; + attachedCallback(): void; + attributeFollows(name: string, toElement: HTMLElement, fromElement: HTMLElement): void; + cancelAsync(handle: number): void; + cancelDebouncer(jobName: string): void; + classFollows(name: string, toElement: HTMLElement, fromElement: HTMLElement): void; + create(tag: string, props: Object): any; + debounce(jobName: string, callback: Function, wait?: number): void; + deserialize(value: string, type: any): any; + distributeContent(): void; + domHost(): void; + elementMatches(selector: string, node: Element): any; + fire(type: string, detail?: Object, options?: FireOptions): any; + flushDebouncer(jobName: string): void; + get(path: string | Array): any; + getContentChildNodes(slctr: string): any; + getContentChildren(slctr: string): any; + getNativePrototype(tag: string): any; + getPropertyInfo(property: string): any; + importHref(href: string, onload?: Function, onerror?: Function): any; + instanceTemplate(template: any): any; + isDebouncerActive(jobName: string): any; + linkPaths(to: string, from: string): void; + listen(node: Element, eventName: string, methodName: string): void; + mixin(target: Object, source: Object): void; + notifyPath(path: string, value: any, fromAbove?: any): void; + pop(path: string): any; + push(path: string, value: any): any; + reflectPropertyToAttribute(name: string): void; + resolveUrl(url: string): any; + scopeSubtree(container: Element, shouldObserve: boolean): void; + serialize(value: string): any; + serializeValueToAttribute(value: any, attribute: string, node: Element): void; + set(path: string, value: any, root?: Object): any; + setScrollDirection(direction: string, node: HTMLElement): void; + shift(path: string, value: any): any; + splice(path: string, start: number, deleteCount: number): any; + toggleAttribute(name: string, bool: boolean, node?: HTMLElement): void; + toggleClass(name: string, bool: boolean, node?: HTMLElement): void; + transform(transform: string, node?: HTMLElement): void; + translate3d(x: any, y: any, z: any, node?: HTMLElement): void; + unlinkPaths(path: string): void; + unshift(path: string, value: any): any; + updateStyles(): void; + } + interface dom { + (node: HTMLElement): HTMLElement; + (node: polymer.Base): HTMLElement; + flush(): any; + } + interface FireOptions { + node?: HTMLElement | polymer.Base; + bubbles?: boolean; + cancelable?: boolean; + } + interface Element { + properties?: Object; + listeners?: Object; + behaviors?: Object[]; + observers?: String[]; + factoryImpl?(...args: any[]): void; + ready?(): void; + created?(): void; + attached?(): void; + detached?(): void; + attributeChanged?(attrName: string, oldVal: any, newVal: any): void; + prototype?: Object; + } + interface PolymerTSElement { + $custom_cons?: FunctionConstructor; + $custom_cons_args?: any[]; + template?: string; + style?: string; + } + interface Property { + name?: string; + type?: any; + value?: any; + reflectToAttribute?: boolean; + readOnly?: boolean; + notify?: boolean; + computed?: string; + observer?: string; + } + class Base extends polymer.PolymerBase implements polymer.Element { + static create(...args: any[]): T; + static register(): void; + is: string; + } + function createEs6PolymerBase(): void; + function prepareForRegistration(elementClass: Function): polymer.Element; + function createDomModule(definition: polymer.Element): void; + function createElement(element: new (...args: any[]) => T): new (...args: any[]) => T; + function createClass(element: new (...args: any[]) => T): new (...args: any[]) => T; + function isRegistered(element: polymer.Element): boolean; +} +declare var Polymer: { + (prototype: polymer.Element): FunctionConstructor; + Class(prototype: polymer.Element): Function; + dom: polymer.dom; + appendChild(node: HTMLElement): HTMLElement; + insertBefore(node: HTMLElement, beforeNode: HTMLElement): HTMLElement; + removeChild(node: HTMLElement): HTMLElement; + updateStyles(): void; + Base: any; +}; +declare function component(tagname: string, extendsTag?: string): (target: Function) => void; +declare function extend(tagname: string): (target: Function) => void; +declare function template(templateString: string): (target: Function) => void; +declare function style(styleString: string): (target: Function) => void; +declare function hostAttributes(attributes: Object): (target: Function) => void; +declare function property(ob?: polymer.Property): (target: polymer.Element, propertyKey: string) => void; +declare function computed(ob?: polymer.Property): (target: polymer.Element, computedFuncName: string) => void; +declare function listen(eventName: string): (target: polymer.Element, propertyKey: string) => void; +declare function behavior(behaviorObject: any): any; +declare function observe(observedProps: string): (target: polymer.Element, observerFuncName: string) => void; diff --git a/progress/progress.d.ts b/progress/progress.d.ts index 2c7e683ec4..afb8ccf732 100644 --- a/progress/progress.d.ts +++ b/progress/progress.d.ts @@ -115,7 +115,7 @@ declare module "progress" */ terminate():void; } - + module ProgressBar { } export = ProgressBar; } diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts new file mode 100644 index 0000000000..6c39f1401a --- /dev/null +++ b/protractor-http-mock/protractor-http-mock-tests.ts @@ -0,0 +1,212 @@ +/// + +function TestConfig() { + mock.config = { + rootDirectory: 'root', + protractorConfig: 'protractor.conf.js' + }; +} + +function TestCtorOverloads() { + let noParam: mock.ProtractorHttpMock = mock(); + let emptyArray: mock.ProtractorHttpMock = mock([]); + let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); + let skipDefaults: mock.ProtractorHttpMock = mock([], true); + + let del: mock.requests.Delete = { + request: { + path: 'path', + method: 'DELETE' + }, + response: { + status: 400, + data: 1 + } + }; + let put: mock.requests.Put = { + request: { + path: 'path', + method: 'PUT' + }, + response: { + status: 400, + data: 1 + } + }; + let mocks: mock.ProtractorHttpMock = mock([del, put]); +} + +function TestTeardown() { + mock.teardown(); +} + +function TestRequestsMade() { + let values: Array; + mock.requestsMade().then(v => values = v); +} + +function TestClearRequests() { + let promiseValue: boolean; + mock.clearRequests().then(value => { + promiseValue = value; + }); +} + +function TestGetRequestDefinitions() { + let getMinium: mock.requests.Get = { + request: { + path: 'path', + method: 'GET' + }, + response: { + data: 1, + status: 500 + } + }; + + let getParams: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + params: { + param1: 'param1', + param2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; + + let post: mock.requests.Post = { + request: { + path: 'path', + method: 'POST' + }, + response: { + data: 1, + status: 500 + } + }; + + let getQueryString: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + queryString: { + query1: 'query1', + query2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; + + let getHeaders: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + headers: { + head1: 'head1', + head2: 'head2' + } + }, + response: { + data: 1, + status: 500 + } + }; +} + +function TestPostRequestDefinitions() { + let post: mock.requests.Post = { + request: { + path: 'path', + method: 'POST' + }, + response: { + data: 1, + status: 500 + } + }; + + let postData: mock.requests.PostData = { + request: { + path: 'path', + method: 'POST', + data: 'data' + }, + response: { + data: 1, + status: 500 + } + }; +} + +function TestHeadRequestDefinitions() { + let head: mock.requests.Head = { + request: { + path: 'path', + method: 'HEAD' + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestDeleteRequestDefinitions() { + let del: mock.requests.Delete = { + request: { + path: 'path', + method: 'DELETE' + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestPutRequestDefinitions() { + let put: mock.requests.Put = { + request: { + path: 'path', + method: 'PUT' + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestPatchRequestDefinitions() { + let patch: mock.requests.Patch = { + request: { + path: 'path', + method: 'PATCH' + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestJsonpRequestDefinitions() { + let jsonp: mock.requests.Jsonp = { + request: { + path: 'path', + method: 'JSONP' + }, + response: { + status: 500, + data: 1 + } + }; +} diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts new file mode 100644 index 0000000000..41c4ef41f8 --- /dev/null +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -0,0 +1,209 @@ +// Type definitions for protractor-http-mock +// Project: https://github.com/atecarlos/protractor-http-mock +// Definitions by: Crevil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module mock { + interface ProtractorHttpMock { + /** + * Instantiate mock module. This must be done before the browser connects. + * + * @param mocks An array of mock modules to load into the application. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks?: Array>, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock modules from files. This must be done before the browser connects. + * + * @param mocks An array of mock module names relative to the rootDirectory configuration. + */ + (mocks: Array): ProtractorHttpMock; + + /** + * Clean up. + * Typically done in the afterEach call to ensure the teardown + * is executed regardless of what happens in the test execution. + */ + teardown(): void; + + /** + * Returns a promise that will be resolved with an array of + * all matched HTTP requests. + */ + requestsMade(): webdriver.promise.Promise>; + + /** + * Returns a promise that will be resolved with a true boolean + * when all matched HTTP requests are cleared. + */ + clearRequests(): webdriver.promise.Promise; + + /** + * Module configuration to setup + */ + config: { + /** + * Mocks directory where mock files are located. + * Default: process.cwd() + */ + rootDirectory?: string; + + /** + * Path to protractor configuration file. + * Default: protractor.conf + */ + protractorConfig?: string; + }; + } + + /** + * Matched request. + */ + interface ReceivedRequest { + url: string; + method: string; + } + + module requests { + /** + * Base request mock used for all mocks. + */ + interface BaseRequest { + request: { + method: string; + path: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * GET request mock. + */ + interface Get extends BaseRequest { + request: { + method: string; + path: string; + params?: Object; + queryString?: Object; + headers?: Object; + interceptedRequest?: boolean; + interceptedAnonymousRequest?: boolean; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * POST request mock with payload. + */ + interface PostData extends BaseRequest { + request: { + path: string; + method: string; + data: TPayload; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * POST request mock. + */ + interface Post extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * HEAD request mock. + */ + interface Head extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * HTTP Delete request mock. + */ + interface Delete extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * PUT request mock. + */ + interface Put extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * PATCH request mock. + */ + interface Patch extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + + /** + * JSONP request mock. + */ + interface Jsonp extends BaseRequest { + request: { + path: string; + method: string; + }; + response: { + status: number; + data: TResponse; + }; + } + } +} + +declare var mock: mock.ProtractorHttpMock; + +declare module 'protractor-http-mock' { + export = mock; +} diff --git a/pty.js/pty.js.d.ts b/pty.js/pty.js.d.ts index 937dff0c05..ab874a574c 100644 --- a/pty.js/pty.js.d.ts +++ b/pty.js/pty.js.d.ts @@ -85,9 +85,11 @@ declare module 'pty.js' { removeListener(event: string, listener: Function): NodeJS.EventEmitter; removeAllListeners(event?: string): NodeJS.EventEmitter; // NOTE: this method is not actually defined in pty.js - setMaxListeners(n: number): void; + setMaxListeners(n: number): NodeJS.EventEmitter; + getMaxListeners(): number; listeners(event: string): Function[]; emit(event: string, ...args: any[]): boolean; + listenerCount(type: string): number; } /** diff --git a/q/Q.d.ts b/q/Q.d.ts index ba30b2745a..2594df7f7c 100644 --- a/q/Q.d.ts +++ b/q/Q.d.ts @@ -20,7 +20,7 @@ declare module Q { interface Deferred { promise: Promise; - resolve(value: T): void; + resolve(value?: T): void; reject(reason: any): void; notify(value: any): void; makeNodeResolver(): (reason: any, value: T) => void; diff --git a/raty/raty-tests.ts b/raty/raty-tests.ts new file mode 100644 index 0000000000..89efb79c3d --- /dev/null +++ b/raty/raty-tests.ts @@ -0,0 +1,54 @@ +/// +/// + + +var $element: JQuery = $('
        '); + +$element.raty(); + +$element.raty({ + cancel: false, + cancelClass: 'raty-cancel', + cancelHint: 'Cancel this rating!', + cancelOff: 'cancel-off.png', + cancelOn: 'cancel-on.png', + cancelPlace: 'left', + click: undefined, + half: false, + halfShow: true, + hints: ['bad', 'poor', 'regular', 'good', 'gorgeous'], + iconRange: undefined, + mouseout: undefined, + mouseover: undefined, + noRatedMsg: 'Not rated yet!', + number: 5, + numberMax: 20, + path: undefined, + precision: false, + readOnly: false, + round: { down: .25, full: .6, up: .76 }, + score: undefined, + scoreName: 'score', + single: false, + space: true, + starHalf: 'star-half.png', + starOff: 'star-off.png', + starOn: 'star-on.png', + target: undefined, + targetFormat: '{score}', + targetKeep: false, + targetScore: undefined, + targetText: '', + targetType: 'hint', + starType: 'img', +}); + +var score: number = $element.raty('score'); +$element.raty('score', 4); +$element.raty('click', 2); +$element.raty('readOnly', true); +$element.raty('cancel', true); +$element.raty('reload'); +$element.raty('set', { space: false }); +$element.raty('destroy'); +$element.raty('move', 3); diff --git a/raty/raty.d.ts b/raty/raty.d.ts new file mode 100644 index 0000000000..bb02d94752 --- /dev/null +++ b/raty/raty.d.ts @@ -0,0 +1,64 @@ +// Type definitions for jQuery.raty 2.7.0 +// Project: https://github.com/wbotelhos/raty +// Definitions by: Matt Wheatley +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface JQuery { + raty(): JQuery; + raty(options: JQueryRatyOptions): JQuery; + raty(method: string, parameter: any): any; + raty(method: 'score'): number; + raty(method: 'score', score: number): void; + raty(method: 'click', star: number): void; + raty(method: 'readonly', on: boolean): void; + raty(method: 'cancel', on: boolean): void; + raty(method: 'reload'): void; + raty(method: 'set', options: JQueryRatyOptions): void; + raty(method: 'destroy'): JQuery; + raty(method: 'move', number: number): void; +} + +interface JQueryRatyOptions { + cancel?: boolean, + cancelClass?: string, + cancelHint?: string, + cancelOff?: string, + cancelOn?: string, + cancelPlace?: string, + click?: (score: number, event: JQueryEventObject) => void, + half?: boolean, + halfShow?: boolean, + hints?: string[], + iconRange?: any[][], + mouseout?: (score: number, event: JQueryEventObject) => void, + mouseover?: (score: number, event: JQueryEventObject) => void, + noRatedMsg?: string, + number?: number, + numberMax?: number, + path?: string, + precision?: boolean, + readOnly?: boolean, + round?: JQueryRatyRoundingOptions, + score?: number, + scoreName?: string, + single?: boolean, + space?: boolean, + starHalf?: string, + starOff?: string, + starOn?: string, + target?: string, + targetFormat?: string, + targetKeep?: boolean, + targetScore?: string, + targetText?: string, + targetType?: string, + starType?: string, +} + +interface JQueryRatyRoundingOptions { + down: number, + full: number, + up: number, +} diff --git a/rcloader/rcloader-tests.ts b/rcloader/rcloader-tests.ts new file mode 100644 index 0000000000..16ade8c555 --- /dev/null +++ b/rcloader/rcloader-tests.ts @@ -0,0 +1,11 @@ +/// + +import RcLoader = require("rcloader"); + +const rcLoader = new RcLoader(".configfilename", { + lookup: true +}); + +rcLoader.for("foo.json", (err, fileOpts) => { + // send the file along +}); diff --git a/rcloader/rcloader.d.ts b/rcloader/rcloader.d.ts new file mode 100644 index 0000000000..e06ac5905d --- /dev/null +++ b/rcloader/rcloader.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rcloader +// Project: https://github.com/spalger/rcloader +// Definitions by: Panu Horsmalahti +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "rcloader" { + interface Options { + [property: string]: any; + lookup?: boolean; + } + + class RcLoader { + constructor(configfilename: string, options: string | Options); + for(path: string, callback?: (error: any, fileOpts: any) => void): void; + } + + export = RcLoader; +} diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx new file mode 100644 index 0000000000..a18e430130 --- /dev/null +++ b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker-tests.tsx @@ -0,0 +1,7 @@ +/// +/// + +import * as DateRangePicker from "react-bootstrap-daterangepicker"; +import * as React from "react"; + +let pickerCoponent = true} />; diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx new file mode 100644 index 0000000000..e80a258a46 --- /dev/null +++ b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.d.tsx @@ -0,0 +1,29 @@ +// Type definitions for react-bootstrap-daterangepicker +// Project: https://github.com/skratchdot/react-bootstrap-daterangepicker +// Definitions by: Ian Ker-Seymer https://github.com/ianks +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module ReactBootstrapDaterangepicker { + export interface EventHandler { (event?: any, picker?: any): any; } + + export interface Props extends DatepickerOptions { + onShow?: EventHandler; + onHide?: EventHandler; + onShowCalendar?: EventHandler; + onHideCalendar?: EventHandler; + onApply?: EventHandler; + onCancel?: EventHandler; + onEvent?: EventHandler; + } + + export class DateRangePicker extends __React.Component {} +} + +declare var DateRangePicker: typeof ReactBootstrapDaterangepicker.DateRangePicker; + +declare module "react-bootstrap-daterangepicker" { + export = DateRangePicker; +} diff --git a/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams new file mode 100644 index 0000000000..36c3b9323c --- /dev/null +++ b/react-bootstrap-daterangepicker/react-bootstrap-daterangepicker.tsx.tscparams @@ -0,0 +1 @@ +--noImplicitAny --module commonjs --jsx react diff --git a/react-datagrid/react-datagrid-tests.tsx b/react-datagrid/react-datagrid-tests.tsx new file mode 100644 index 0000000000..c0ca90a1a9 --- /dev/null +++ b/react-datagrid/react-datagrid-tests.tsx @@ -0,0 +1,82 @@ +/// +/// +/// + +import * as React from "react"; +import ReactDataGrid = require("react-datagrid"); + +var data: any[] = []; + +var columns: ReactDataGrid.Column[] = [ + { name: 'index', title: '#', width: 50 }, + { name: 'firstName', style: { color: 'red' }, visible: true}, + { name: 'lastName', render: (v) => {return v + " Phd"}}, + { name: 'city', textAlign: 'right', defaultVisible: true}, + { name: 'email', defaultHidden: true } +]; +var selected = {}; +var sortInfo: ReactDataGrid.SortInfo[] = [ { name: 'country', dir: 'asc'}] + +export module X { +export class ExampleBasic extends React.Component<{},{}> { + render(): React.ReactElement { + return ( + + ); + } +} +} + +class ExampleFull extends React.Component<{},{}> { + + render(): React.ReactElement { + return ( + {}} + onPageSizeChange={(pageSize: number, props: ReactDataGrid.DataGridProps) => {}} + onColumnOrderChange={(index: number, dropIndex: number) => {}} + onColumnResize={(firstCol: ReactDataGrid.Column, firstSize: number, secondCol: ReactDataGrid.Column, secondSize: number) => {}} + onSelectionChange={(newSelectedId: string, data: any) => {}} + onSortChange={(sortInfo: ReactDataGrid.SortInfo[]) => {}} + onFilter={(column: ReactDataGrid.Column, value: any, allFilterValues: any[]) => {} } + /> + ); + } +} diff --git a/react-datagrid/react-datagrid.d.ts b/react-datagrid/react-datagrid.d.ts new file mode 100644 index 0000000000..1dc5d83616 --- /dev/null +++ b/react-datagrid/react-datagrid.d.ts @@ -0,0 +1,311 @@ +// Type definitions for react-datagrid 1.2.15 +// Project: https://github.com/zippyui/react-datagrid.git +// Definitions by: Stephen Jelfs +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "react-datagrid" { + import DataGrid = ReactDataGrid.DataGrid; + export = DataGrid; +} + +declare namespace ReactDataGrid { + import React = __React; + + interface DataGridProps extends React.Props { + /** + * Array/String/Function/Promise - for local data, an array of object + * to render in the grid. For remote data, a string url, or a function + * that returns a promise. + */ + dataSource: any[] | string | ((query: {pageSize: number, skip: number}) => Promise); + + dataSourceCount?: number; + + /** + * String - the name of the property where the id is found for each + * object in the data array. + */ + idProperty: string; + + /** + * Array - an array of columns that are going to be rendered in the + * grid. + */ + columns: Column[]; + + /** + * Sorting the data array is not done by the grid. You can however + * pass in sort info so the grid renders with sorting icons as needed. + */ + onSortChange?: (sortInfo: SortInfo[]) => void; + + /** + * Array - an array with sorting information. + */ + sortInfo?: SortInfo[]; + + style?: __React.CSSProperties; + + /** + * Object/Function - you can specify either a style object to be + * applied to all rows, or a function. The function is called with + * (data, props) (so you have access to props.index for example) and + * is expected to return a style object. + */ + rowStyle?: __React.CSSProperties | ((data: any, props: RowProps) => React.CSSProperties); + + /** + * Boolean - show a column menu to show/hide columns. + */ + withColumnMenu?: boolean; + + /** + * If you want to enable column reordering, just specify the + * onColumnOrderChange prop on the grid: + */ + onColumnOrderChange?: (index: number, dropIndex: number) => void; + + /** + * If you want to enable column resized, just specify the + * onColumnResize prop on the grid: + */ + onColumnResize?: (firstCol: Column, firstSize: number, + secondCol: Column, secondSize: number) => void; + + /** + * If you want to enable selection, just specify the + * onSelectionChange prop on the grid: + */ + onSelectionChange?: (newSelected: {}, data: any) => void; + + /** + * When a column is shown/hidden, you can be notified using the + * onColumnVisibilityChange callback prop. + */ + onColumnVisibilityChange?: (column: Column, visibility: boolean) => void; + + /** + * The current selection. + */ + selected?: {}; + + /** + * Group rows by matching values. + */ + groupBy?: any[]; + + /** + * If you want to enable filter, just specify the + * onFilter prop on the grid: + */ + onFilter?: (column: Column, value: any, allFilterValues: any[]) => void; + + /** + * To apply the filter while typing. + */ + liveFilter?: boolean; + + /** + * Empty text for no records. + */ + emptyText?: string; + + /** + * Loading grid. + */ + loading?: boolean; + + /** + * If you dont want loadMask over header, specify + */ + loadMaskOverHeader?: boolean; + + /** + * Show cell borders. Other valid values: 'horizontal', 'vertical'. + */ + showCellBorders?: boolean | string; + + /** + * Custom row height. + */ + rowHeight?: number; + + /** + * When you have remote data, pagination is setup by default. If you + * want to disable pagination, specify the pagination prop with a false + * value. + */ + pagination?: boolean; + defaultPageSize?: number; + defaultPage?: number; + + /** + * Number - controlled alternative for defaultPageSize. When pageSize + * changes, onPageSizeChange(pageSize) is called. + */ + pageSize?: number; + + /** + * Number - controlled alternative for defaultPage. When page changes, + * onPageChange(page) is called. + */ + page?: number; + + /** + * Customize the pagination toolbar. + */ + paginationToolbarProps?: PaginationToolbarProps; + + /** + * handle page changes. + */ + onPageChange?: (page: number) => void; + + /** + * handle page size changes. + */ + onPageSizeChange?: (pageSize: number, props: DataGridProps) => void; + } + + interface SortInfo { + name: string; + dir: string; + } + + interface Column { + /** + * String - each column should have a name property. + */ + name: string; + + /** + * String/ReactElement - a title to show in the header. If not + * specified, a humanized version of name will be used. Can be a string + * or anything that React can render, so you can customize it as you + * please. + */ + title?: string | React.ReactElement; + + /** + * Function - if you want custom rendering, specify this property. + * + * The column.render function is called with 3 args: + * value - the default value to be rendered (equals to data[column.name]) + * data - the corresponding data object for the current row + cellProps - an object with props for the current cell + */ + render?: (value: any, data: any, cellProps: CellProps) => any; + + /** + * Object - if you want cells in this column to be have a custom + * style. + */ + style?: __React.CSSProperties; + + /** + * String - one of 'left', 'right', 'center'. + */ + textAlign?: string; + + /** + * String - a className to be applied to all cells in this column + */ + className?: string; + + width?: number; + + minWidth?: number; + + /** + * Columns are flexible via flexbox. Specify a flex property for this. + * Unless a column specifies a flex or a width property, it is assumed + * to have flex: 1. + */ + flex?: number; + + /** + * Specify a column as visible/hidden. + */ + defaultVisible?: boolean; + defaultHidden?: boolean; + + /** + * Boolean - controlled (which means you have to manually set column + * visibility when it changes, by using onColumnVisibilityChange). + */ + visible?: boolean; + } + + interface CellProps { + /** + * the index of the row + */ + rowIndex: number; + + /** + * the index of the column + */ + index: number; + + /** + * a style for the cell + */ + style: React.CSSProperties; + + /** + * a class name for the cell + */ + className: string; + } + + interface RowProps { + /** + * the index of the row + */ + index: number; + + /** + * a class name for the row when the mouse is over it + */ + overClassName: string; + + /** + * a class name for the row when selected + */ + selectedClassName: string; + + /** + * a class name for the row + */ + className: string; + } + + interface PaginationToolbarProps { + /** + * Available page sizes. + */ + pageSizes: number[]; + + /** + * Hide/show page sizes. + */ + showPageSize: boolean; + + /** + * Customize icons. + */ + showRefreshIcon: boolean; + iconSize: number; + iconProps: { + style: React.SVGAttributes, + overStyle: React.SVGAttributes, + disabledStyle: React.SVGAttributes + } + } + + export class DataGrid extends __React.Component { + } +} diff --git a/react-day-picker/react-day-picker-tests.tsx.tscparams b/react-day-picker/react-day-picker-tests.tsx.tscparams deleted file mode 100644 index 0fa3ed7176..0000000000 --- a/react-day-picker/react-day-picker-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny --jsx react diff --git a/react-dropzone/react-dropzone-tests.tsx.tscparams b/react-dropzone/react-dropzone-tests.tsx.tscparams deleted file mode 100644 index c90abf04fc..0000000000 --- a/react-dropzone/react-dropzone-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny --experimentalDecorators --jsx react diff --git a/react-infinite/react-infinite-tests.tsx b/react-infinite/react-infinite-tests.tsx new file mode 100644 index 0000000000..91a86abce2 --- /dev/null +++ b/react-infinite/react-infinite-tests.tsx @@ -0,0 +1,113 @@ +/// +/// + +import * as React from 'react'; +import Infinite = require('react-infinite'); + +class Test1 extends React.Component<{}, {}> { + render() { + return ( + +
        +
        +
        + + ); + } +} + +class Test2 extends React.Component<{}, {}> { + render() { + return ( + +
        +
        +
        + + ); + } +} + +class Test3 extends React.Component<{}, {}> { + render() { + return ( + +
        +
        +
        + + ); + } +} + +class Test4 extends React.Component<{}, {}> { + render() { + return ( + +
        +
        +
        + + ); + } +} + +var ListItem = React.createClass<{key: number; num: number;}, {}>({ + render: function() { + return
        + List Item {this.props.num} +
        ; + } +}); + +var InfiniteList = React.createClass({ + getInitialState: function() { + return { + elements: this.buildElements(0, 20), + isInfiniteLoading: false + } + }, + + buildElements: function(start: number, end: number) { + var elements = [] as React.ReactElement[]; + for (var i = start; i < end; i++) { + elements.push() + } + return elements; + }, + + handleInfiniteLoad: function() { + var that = this; + this.setState({ + isInfiniteLoading: true + }); + setTimeout(function() { + var elemLength = that.state.elements.length, + newElements = that.buildElements(elemLength, elemLength + 1000); + that.setState({ + isInfiniteLoading: false, + elements: that.state.elements.concat(newElements) + }); + }, 2500); + }, + + elementInfiniteLoad: function() { + return
        + Loading... +
        ; + }, + + render: function() { + return + {this.state.elements} + ; + } +}); diff --git a/react-infinite/react-infinite.d.ts b/react-infinite/react-infinite.d.ts new file mode 100644 index 0000000000..123883a0e0 --- /dev/null +++ b/react-infinite/react-infinite.d.ts @@ -0,0 +1,36 @@ +// Type definitions for react-infinite +// Project: https://github.com/seatgeek/react-infinite +// Definitions by: rhysd +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-infinite" { + import Infinite = ReactInfinite.Infinite; + export = Infinite; +} + +declare namespace ReactInfinite { + import React = __React; + + interface InfiniteProps extends React.Props { + elementHeight: number | number[]; + containerHeight?: number; + preloadBatchSize?: number | Object; + preloadAdditionalHeight?: number | Object; + handleScroll?: (node: React.ReactElement) => void; + infiniteLoadBeginBottomOffset?: number; + infiniteLoadBeginEdgeOffset?: number; + onInfiniteLoad?: () => void; + loadingSpinnerDelegate?: React.ReactElement; + isInfiniteLoading?: boolean; + timeScrollStateLastsForAfterUserScrolls?: number; + className?: string; + useWindowAsScrollContainer?: boolean; + displayBottomUpwards?: boolean; + } + + export class Infinite extends React.Component { + static containerHeightScaleFactor(n: number): any; + } +} diff --git a/react-intl/react-intl-tests.tsx.tscparams b/react-intl/react-intl-tests.tsx.tscparams deleted file mode 100644 index 7cf88bb1b2..0000000000 --- a/react-intl/react-intl-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny --experimentalDecorators --jsx react --module commonjs diff --git a/react-native/react-native-tests.tsx.tscparams b/react-native/react-native-tests.tsx.tscparams deleted file mode 100644 index 7cf88bb1b2..0000000000 --- a/react-native/react-native-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---target es5 --noImplicitAny --experimentalDecorators --jsx react --module commonjs diff --git a/react-router/react-router-tests.tsx.tscparams b/react-router/react-router-tests.tsx.tscparams deleted file mode 100644 index f479837784..0000000000 --- a/react-router/react-router-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny -jsx react --target es5 \ No newline at end of file diff --git a/react-select/react-select-tests.ts b/react-select/react-select-tests.ts new file mode 100644 index 0000000000..e69de29bb2 diff --git a/react-select/react-select.d.ts b/react-select/react-select.d.ts new file mode 100644 index 0000000000..ee365fe9ba --- /dev/null +++ b/react-select/react-select.d.ts @@ -0,0 +1,67 @@ +// Type definitions for react-select v0.9.10 +// Project: https://github.com/JedWatson/react-select +// Definitions by: ESQUIBET Hugo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// Typings for https://github.com/JedWatson/react-select +//***Usage*** +// import ReactSelect = require('react-select'); +// + +declare module "react-select" { + // Import React + import React = require("react"); + + interface Option{ + label : string; + value : string; + } + + interface ReactSelectProps extends React.Props{ + addLabelText? : string; + allowCreate? : boolean; + autoload? : boolean; + backspaceRemoves? : boolean; + cacheAsyncResults? : boolean; + className? : string; + clearable? : boolean; + clearAllText? : string; + clearValueText? : string; + delimiter? : string; + disabled? : boolean; + filterOption? : (option : Option,filterString : string)=>Option; + filterOptions? : (options:Array