From ee872c633411d2524cafc68d339f016acbfa1fd6 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Sun, 14 Sep 2014 00:08:00 +0300 Subject: [PATCH 001/881] Added definitions for "cors" and "tea-merge" --- cors/cors-tests.ts | 11 +++++++++++ cors/cors.d.ts | 24 ++++++++++++++++++++++++ tea-merge/tea-merge-tests.ts | 6 ++++++ tea-merge/tea-merge.d.ts | 9 +++++++++ 4 files changed, 50 insertions(+) create mode 100644 cors/cors-tests.ts create mode 100644 cors/cors.d.ts create mode 100644 tea-merge/tea-merge-tests.ts create mode 100644 tea-merge/tea-merge.d.ts diff --git a/cors/cors-tests.ts b/cors/cors-tests.ts new file mode 100644 index 000000000..a3f5ea10e --- /dev/null +++ b/cors/cors-tests.ts @@ -0,0 +1,11 @@ +/// + +import express = require('express'); +import cors = require('cors'); + +var app = express(); +app.use(cors()); +app.use(cors({ + maxAge: 100, + credentials: true +})); diff --git a/cors/cors.d.ts b/cors/cors.d.ts new file mode 100644 index 000000000..92fdd9634 --- /dev/null +++ b/cors/cors.d.ts @@ -0,0 +1,24 @@ +// Type definitions for cors +// Project: https://github.com/troygoode/node-cors/ +// Definitions by: Mihhail Lapushkin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cors" { + import express = require('express'); + + module e { + interface CorsOptions { + origin?: any; + methods?: any; + allowedHeaders?: any; + exposedHeaders?: any; + credentials?: boolean; + maxAge?: number; + } + } + + function e(options?: e.CorsOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/tea-merge/tea-merge-tests.ts b/tea-merge/tea-merge-tests.ts new file mode 100644 index 000000000..9d59bd65e --- /dev/null +++ b/tea-merge/tea-merge-tests.ts @@ -0,0 +1,6 @@ +/// + +import merge = require('tea-merge'); + +merge({ a: 1 }, { b: 2 }, { c: 'hello' }); +merge({ a1: true, a2: { b: 'hello' } }, { bca: [], a2: { c: 'world' } }); diff --git a/tea-merge/tea-merge.d.ts b/tea-merge/tea-merge.d.ts new file mode 100644 index 000000000..2000e9bcd --- /dev/null +++ b/tea-merge/tea-merge.d.ts @@ -0,0 +1,9 @@ +// Type definitions for tea-merge +// Project: https://github.com/qualiancy/tea-merge +// Definitions by: Mihhail Lapushkin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "tea-merge" { + function e(destination: Object, ...sources: Object[]): Object; + export = e; +} \ No newline at end of file From a63e25478678d2cf4e6f646717b06ac30392ace7 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Wed, 17 Sep 2014 20:34:25 +0300 Subject: [PATCH 002/881] Cordova Contacts plugin fix In find() method the onError callback should be optional. https://cordova.apache.org/docs/en/3.3.0/cordova_contacts_contacts.md.ht ml#contacts.find --- cordova/plugins/Contacts.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index f054c12d0..afc3aa903 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -32,7 +32,7 @@ interface Contacts { */ find(fields: string[], onSuccess: (contacts: Contact[]) => void, - onError: (error: ContactError) => void, + onError?: (error: ContactError) => void, options?: ContactFindOptions): void; } From a4b7732937f1eebd5902a7d6fc2fd164d8574d67 Mon Sep 17 00:00:00 2001 From: flashandy Date: Sat, 17 Jan 2015 12:10:10 +0100 Subject: [PATCH 003/881] Update underscore.d.ts missing declaration for wrapped.pick --- underscore/underscore.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 8cf92df12..2b3818c3e 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -3020,6 +3020,7 @@ interface _Chain { * @see _.pick **/ pick(...keys: string[]): _Chain; + pick(keys: string[]): _Chain; pick(fn: (value: any, key: any, object: any) => any): _Chain; /** From 52444b5afa70f89d846fa4e0d8671bc90fc169b7 Mon Sep 17 00:00:00 2001 From: Ralf Kruse Date: Sun, 10 May 2015 02:23:43 +0200 Subject: [PATCH 004/881] getElementByPoint returns Snap.Element --- snapsvg/snapsvg.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapsvg/snapsvg.d.ts b/snapsvg/snapsvg.d.ts index a900680bc..cce6e6750 100644 --- a/snapsvg/snapsvg.d.ts +++ b/snapsvg/snapsvg.d.ts @@ -43,7 +43,7 @@ declare module Snap { export function ajax(url:string,callback:Function,scope?:Object):XMLHttpRequest; export function format(token:string,json:Object):string; export function fragment(varargs:any):Fragment; - export function getElementByPoint(x:number,y:number):Object; + export function getElementByPoint(x:number,y:number):Snap.Element; export function is(o:any,type:string):boolean; export function load(url:string,callback:Function,scope?:Object):void; export function plugin(f:Function):void; From bfcc6ddbc0c3d3761d7935f60cf46bf99a24ff1f Mon Sep 17 00:00:00 2001 From: Ralf Kruse Date: Sun, 10 May 2015 02:24:05 +0200 Subject: [PATCH 005/881] Snap.Element has an id property --- snapsvg/snapsvg.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/snapsvg/snapsvg.d.ts b/snapsvg/snapsvg.d.ts index cce6e6750..c7add1165 100644 --- a/snapsvg/snapsvg.d.ts +++ b/snapsvg/snapsvg.d.ts @@ -131,6 +131,7 @@ declare module Snap { getSubpath(from:number,to:number):string; getTotalLength():number; hasClass(value:string):boolean; + id:string; inAnim():Object; innerSVG():string; insertAfter(el:Snap.Element):Snap.Element; From b29697846d7c2469b63a5ae4e2ba5cb968aa8d4c Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Mon, 11 May 2015 09:19:22 -0400 Subject: [PATCH 006/881] Adding missing property & other minor changes * the `permissionLevel` property was missing * `needsPermission` and `isSupported` are properties, not functions * Spelling fixes in comments --- notifyjs/notifyjs.d.ts | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index 0cff4e0c5..5fe321efa 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -10,20 +10,25 @@ declare var Notify: { * Check is permission is needed for the user to receive notifications. * @return true : needs permission, false : does not need */ - needsPermission() : boolean; + needsPermission : boolean; /** * Asks the user for permission to display notifications - * @param onPermissionGrantedCallback A callback for permmision is granted. - * @param onPermissionDeniedCallback A callback for permmision is denied. + * @param onPermissionGrantedCallback A callback for permission is granted. + * @param onPermissionDeniedCallback A callback for permission is denied. */ requestPermission(onPermissionGrantedCallback?: ()=> any, onPermissionDeniedCallback? : ()=> any) : void; /** * return true if the browser supports HTML5 Notification - * @param true : the browser supports HTML5 Notification, false ; the browswer does not supports HTML5 Notification. + * @param true : the browser supports HTML5 Notification, false ; the browser does not supports HTML5 Notification. */ - isSupported() : boolean; + isSupported: boolean; + + /** + * shows the user's current permission level (granted, denied or default), returns null if notifications are not supported. + */ + permissionLevel: string; } declare module notifyjs { From 75f03d73ce8a8a10f4594bd6500d6f207b2e8191 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Tue, 12 May 2015 08:13:37 -0400 Subject: [PATCH 007/881] Adding missing `timeout` property, changing others to be properties instead of functions, spelling fixes --- notifyjs/notifyjs-tests.ts | 6 ++++-- notifyjs/notifyjs.d.ts | 25 ++++++++++++++++++------- 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/notifyjs/notifyjs-tests.ts b/notifyjs/notifyjs-tests.ts index 8771224c8..3289791de 100644 --- a/notifyjs/notifyjs-tests.ts +++ b/notifyjs/notifyjs-tests.ts @@ -14,6 +14,7 @@ function test_Notify_constructor() { body : "fuga", icon : "./logo.png", tag : "user", + timeout: 2, notifyShow : (e:Event)=> console.log("notifyShow", e), notifyClose : ()=> console.log("notifyClose"), notifyClick : ()=> console.log("notifyClick"), @@ -26,9 +27,10 @@ function test_Notify_constructor() { } function test_Notify_static_methods() { - Notify.needsPermission(); + Notify.needsPermission; Notify.requestPermission(); Notify.requestPermission(()=> console.log("onPermissionGrantedCallback")); Notify.requestPermission(()=> console.log("onPermissionGrantedCallback"), ()=> console.log("onPermissionDeniedCallback")); - Notify.isSupported(); + Notify.isSupported; + Notify.permissionLevel; } diff --git a/notifyjs/notifyjs.d.ts b/notifyjs/notifyjs.d.ts index f36b8fbcd..dc7bc57fe 100644 --- a/notifyjs/notifyjs.d.ts +++ b/notifyjs/notifyjs.d.ts @@ -1,4 +1,4 @@ -// Type definitions for notify.js 1.2.0 +// Type definitions for notify.js 1.2.3 // Project: https://github.com/alexgibson/notify.js // Definitions by: soundTricker // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -10,20 +10,26 @@ declare var Notify: { * Check is permission is needed for the user to receive notifications. * @return true : needs permission, false : does not need */ - needsPermission() : boolean; + needsPermission : boolean; /** * Asks the user for permission to display notifications - * @param onPermissionGrantedCallback A callback for permmision is granted. - * @param onPermissionDeniedCallback A callback for permmision is denied. + * @param onPermissionGrantedCallback A callback for permission is granted. + * @param onPermissionDeniedCallback A callback for permission is denied. */ requestPermission(onPermissionGrantedCallback?: ()=> any, onPermissionDeniedCallback? : ()=> any) : void; /** * return true if the browser supports HTML5 Notification - * @param true : the browser supports HTML5 Notification, false ; the browswer does not supports HTML5 Notification. + * @param true : the browser supports HTML5 Notification, false ; the browser does not supports HTML5 Notification. */ - isSupported() : boolean; + isSupported: boolean; + + /** + * shows the user's current permission level (granted, denied or default), returns null if notifications are not supported. + * @return 'granted' : permission has been given, 'denied' : permission has been denied, 'default' : permission has not yet been set, null : notifications are not supported + */ + permissionLevel: string; } declare module notifyjs { @@ -72,6 +78,11 @@ declare module notifyjs { * unique identifier to stop duplicate notifications */ tag? : string; + + /** + * number of seconds to close the notification automatically + */ + timeout? : number; /** * callback when notification is shown @@ -98,4 +109,4 @@ declare module notifyjs { */ permissionDenied? : Function; } -} +} \ No newline at end of file From 5bf40c59d1cc2c29a79dbfa9e09892d43d2f21d7 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Sat, 16 May 2015 15:25:33 -0400 Subject: [PATCH 008/881] Added an interface for the object returned during synchronous validations. --- joi/joi.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 951fc4045..ad9eb174d 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -61,6 +61,11 @@ declare module 'joi' { options?: ValidationOptions; } + export interface ValidationResult { + error: ValidationError; + value: T; + } + export interface SchemaMap { [key: string]: Schema; } @@ -461,8 +466,7 @@ declare module 'joi' { */ export function validate(value: T, schema: Schema, callback: (err: ValidationError, value: T) => void): void; export function validate(value: T, schema: Object, callback: (err: ValidationError, value: T) => void): void; - export function validate(value: T, schema: Schema, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void; - export function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): void; + export function validate(value: T, schema: Object, options?: ValidationOptions, callback?: (err: ValidationError, value: T) => void): ValidationResult; /** * Converts literal schema definition to joi schema object (or returns the same back if already a joi schema object). From c068c64bce9a2cfe7826e46dfe69a922978f9952 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 17 May 2015 00:47:08 +0300 Subject: [PATCH 009/881] Refactored sharepoint.d.ts to use microsoft.ajax.d.ts, added\fixed some definitions --- README.md | 0 angularjs/angular.d.ts | 0 chrome/chrome.d.ts | 0 microsoft-ajax/microsoft.ajax.d.ts | 992 ++++++----------- sharepoint/SharePoint.d.ts | 1642 ++++++++++++++++++++++++---- 5 files changed, 1768 insertions(+), 866 deletions(-) mode change 100644 => 100755 README.md mode change 100755 => 100644 angularjs/angular.d.ts mode change 100755 => 100644 chrome/chrome.d.ts diff --git a/README.md b/README.md old mode 100644 new mode 100755 diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100755 new mode 100644 diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts old mode 100755 new mode 100644 diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 1c8968f44..7100b8c51 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -18,7 +18,7 @@ * Object Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb397554(v=vs.100).aspx} */ -interface Object { +interface ObjectConstructor { /** * Formats a number by using the invariant culture. */ @@ -34,173 +34,9 @@ interface Object { * Array Type Extensions * @see {@link http://msdn.microsoft.com/en-us/library/bb383786(v=vs.100).aspx} */ -interface Array { - - //#region lib.d.ts - - new (arrayLength?: number): any[]; - new (arrayLength: number): T[]; - new (...items: T[]): T[]; - (arrayLength?: number): any[]; - (arrayLength: number): T[]; - (...items: T[]): T[]; - isArray(arg: any): boolean; - prototype: Array; - - ///** - // * Returns a string representation of an array. - // */ - //toString(): string; - //toLocaleString(): string; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: U[]): T[]; - ///** - // * Combines two or more arrays. - // * @param items Additional items to add to the end of array1. - // */ - //concat(...items: T[]): T[]; - ///** - // * Adds all the elements of an array separated by the specified separator string. - // * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. - // */ - //join(separator?: string): string; - ///** - // * Removes the last element from an array and returns it. - // */ - //pop(): T; - ///** - // * Appends new elements to an array, and returns the new length of the array. - // * @param items New elements of the Array. - // */ - //push(...items: T[]): number; - ///** - // * Reverses the elements in an Array. - // */ - //reverse(): T[]; - ///** - // * Removes the first element from an array and returns it. - // */ - //shift(): T; - ///** - // * Returns a section of an array. - // * @param start The beginning of the specified portion of the array. - // * @param end The end of the specified portion of the array. - // */ - //slice(start?: number, end?: number): T[]; - - ///** - // * Sorts an array. - // * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order. - // */ - //sort(compareFn?: (a: T, b: T) => number): T[]; - - ///** - // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - // * @param start The zero-based location in the array from which to start removing elements. - // */ - //splice(start: number): T[]; - - ///** - // * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. - // * @param start The zero-based location in the array from which to start removing elements. - // * @param deleteCount The number of elements to remove. - // * @param items Elements to insert into the array in place of the deleted elements. - // */ - //splice(start: number, deleteCount: number, ...items: T[]): T[]; - - ///** - // * Inserts new elements at the start of an array. - // * @param items Elements to insert at the start of the Array. - // */ - //unshift(...items: T[]): number; - - ///** - // * Returns the index of the first occurrence of a value in an array. - // * @param searchElement The value to locate in the array. - // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. - // */ - //indexOf(searchElement: T, fromIndex?: number): number; - - ///** - // * Returns the index of the last occurrence of a specified value in an array. - // * @param searchElement The value to locate in the array. - // * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. - // */ - //lastIndexOf(searchElement: T, fromIndex?: number): number; - - ///** - // * Determines whether all the members of an array satisfy the specified test. - // * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //every(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - ///** - // * Determines whether the specified callback function returns true for any element of an array. - // * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //some(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): boolean; - - ///** - // * Performs the specified action for each element in an array. - // * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; - - ///** - // * Calls a defined callback function on each element of an array, and returns an array that contains the results. - // * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //map(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[]; - - ///** - // * Returns the elements of an array that meet the condition specified in a callback function. - // * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. - // * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. - // */ - //filter(callbackfn: (value: T, index: number, array: T[]) => boolean, thisArg?: any): T[]; - - ///** - // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - ///** - // * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduce(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - ///** - // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduceRight(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue?: T): T; - ///** - // * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. - // * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. - // * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. - // */ - //reduceRight(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U; - - ///** - // * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. - // */ - //length: number; - - //[n: number]: T; - - //#endregion +interface ArrayConstructor { + //#region Extensions /** @@ -210,55 +46,55 @@ interface Array { * @param item * */ - add(array: any[], element: any): void; + add(array: T[], element: T): void; /** * Copies all the elements of the specified array to the end of an Array object. */ - addRange(array: any, items: any): void; + addRange(array: T[], items: T[]): void; /** * Removes all elements from an Array object. */ - clear(): void; + clear(array: T[]): void; /** * Creates a shallow copy of an Array object. */ - clone(): any[]; + clone(array: T[]): T[]; /** * Determines whether an element is in an Array object. */ - contains(element: any): boolean; + contains(array: T[], element: T): boolean; /** * Removes the first element from an Array object. */ - dequeue(): any; + dequeue(array: T[]): T; /** * Adds an element to the end of an Array object. Use the add function instead of the Array.enqueue function. */ - enqueue(element: any): void; + enqueue(array: T[], element: T): void; /** * Performs a specified action on each element of an Array object. */ - forEach(array: any[], method: Function, instance: any[]): void; + forEach(array: T[], method: (element: T, index: number, array: T[]) => void, instance: any): void; /** * Searches for the specified element of an Array object and returns its index. */ - indexOf(array: any[], item: any, startIndex?: number): number; + indexOf(array: T[], item: T, startIndex?: number): number; /** * Inserts a value at the specified location in an Array object. */ - insert(array: any[], index: number, item: any); + insert(array: T[], index: number, item: T): void; /** * Creates an Array object from a string representation. */ - parse(value: string): any[]; + parse(value: string): T[]; /** * Removes the first occurrence of an element in an Array object. */ - remove(array: any[], item: any): boolean; + remove(array: T[], item: T): boolean; /** * Removes an element at the specified location in an Array object. */ - removeAt(array: any[], index: number): void; + removeAt(array: T[], index: number): void; //#endregion } @@ -277,6 +113,10 @@ interface Number { * Formats a number by using the current culture. */ localeFormat(format: string): string; +} + +interface NumberConstructor { + /** * Returns a numeric value from a string representation of a number. This function is static and can be called without creating an instance of the object. */ @@ -297,11 +137,14 @@ interface Date { /** * Formats a date by using the invariant (culture-independent) culture. */ - format(value: string): string; + format(format: string): string; /** * Formats a date by using the current culture. This function is static and can be invoked without creating an instance of the object. */ - localeFormat(value: string): string; + localeFormat(format: string): string; +} + +interface DateConstructor { /** * Creates a date from a locale-specific string by using the current culture. This function is static and can be invoked without creating an instance of the object. * @exception (Debug) formats contains an invalid format. @@ -310,9 +153,8 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseLocale(value: string): string; - parseLocale(value: string, formats?: string[]): string; - parseLocale(value: string, ...formats: string[]): string; + parseLocale(value: string, formats?: string[]): Date; + parseLocale(value: string, ...formats: string[]): Date; /** * Creates a date from a string by using the invariant culture. This function is static and can be invoked without creating an instance of the object. * @return If value is a valid string representation of a date in the invariant format, an object of type Date; otherwise, null. @@ -321,352 +163,172 @@ interface Date { * @param formats * (Optional) An array of custom formats. */ - parseInvariant(value: string): string; parseInvariant(value: string, formats?: string[]): string; parseInvariant(value: string, ...formats: string[]): string; } -declare module MicrosoftAjaxBaseTypeExtensions { + +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception +* details and support for application-compilation modes (debug or release). +* @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} +*/ +interface FunctionConstructor { + + //#region Extensions /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Function type by including exception - * details and support for application-compilation modes (debug or release). - * @see {@link http://msdn.microsoft.com/en-us/library/dd409270(v=vs.100).aspx} - */ - interface Function { - - //#region lib.d.ts - - /** - * Creates a new function. - * @param args A list of arguments the function accepts. - */ - new (...args: string[]): Function; - (...args: string[]): Function; - prototype: Function; - - //#endregion - - //#region Extensions - - /** - * Creates a delegate function that retains the context first used during an objects creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } - */ - createCallback(method: Function, ...context: any[]): Function; - /** - * Creates a callback function that retains the parameter initially used during an object's creation. - * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } - */ - createDelegate(instance: any, method: Function): Function; - - /** - * A function that does nothing. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } - */ - emptyMethod(): Function; - - /** - * Validates the parameters to a method are as expected. - * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } - */ - validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - - //#endregion - } + * Creates a delegate function that retains the context first used during an objects creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx } + */ + createCallback(method: Function, ...context: any[]): Function; + /** + * Creates a callback function that retains the parameter initially used during an object's creation. + * @see {@link http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx } + */ + createDelegate(instance: any, method: Function): Function; /** - * Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). - * Error Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} - */ - interface Error { - - //#region lib.d.ts - - name: string; - message: string; - - new (message?: string): Error; - (message?: string): Error; - prototype: Error; - - //#endregion - - //#region Extensions - - /** - * Creates an Error object that represents the Sys.ParameterCountException exception. - */ - parameterCount(message?: string): Error; - /** - * Creates an Error object that represents the Sys.NotImplementedException exception. - */ - notImplemented(message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentException exception. - */ - argument(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentNullException exception. - */ - argumentNull(paramName?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. - */ - argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentTypeException exception. - */ - argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; - /** - * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. - */ - argumentUndefined(paramName?: string, message?: string): Error; - /** - * Creates an Error object that can contain additional error information. - */ - create(message?: string, errorInfo?: Object): Error; - /** - * Creates an Error object that represents the Sys.FormatException exception. - */ - format(message?: string): Error; - /** - * Creates an Error object that represents the Sys.InvalidOperationException exception. - */ - invalidOperation(message?: string): Error; - /** - * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. - */ - popStackFrame(): void; - - //#endregion - } + * A function that does nothing. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393667(v=vs.100).aspx } + */ + emptyMethod(): Function; /** - * Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. - * String Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} - */ - interface String { + * Validates the parameters to a method are as expected. + * @see {@link http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx } + */ + validateParameters(parameters: any, expectedParameters: Object[], validateParameterCount?: boolean): any; - //#region lib.d.ts + //#endregion +} - new (value?: any): String; - (value?: any): string; - prototype: String; - fromCharCode(...codes: number[]): string; +/** +* Provides static functions that extend the built-in ECMAScript (JavaScript) Error type by including exception details and support for application-compilation modes (debug or release). +* Error Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb310947(v=vs.100).aspx} +*/ +interface ErrorConstructor { - /** Returns a string representation of a string. */ - toString(): string; - - /** - * Returns the character at the specified index. - * @param pos The zero-based index of the desired character. - */ - charAt(pos: number): string; - - /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. - */ - charCodeAt(index: number): number; - - /** - * Returns a string that contains the concatenation of two or more strings. - * @param strings The strings to append to the end of the string. - */ - concat(...strings: string[]): string; - - /** - * Returns the position of the first occurrence of a substring. - * @param searchString The substring to search for in the string - * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. - */ - indexOf(searchString: string, position?: number): number; - - /** - * Returns the last occurrence of a substring in the string. - * @param searchString The substring to search for. - * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. - */ - lastIndexOf(searchString: string, position?: number): number; - - /** - * Determines whether two strings are equivalent in the current locale. - * @param that String to compare to target string - */ - localeCompare(that: string): number; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A variable name or string literal containing the regular expression pattern and flags. - */ - match(regexp: string): string[]; - - /** - * Matches a string with a regular expression, and returns an array containing the results of that search. - * @param regexp A regular expression object that contains the regular expression pattern and applicable flags. - */ - match(regexp: RegExp): string[]; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: string, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A String object or string literal that represents the regular expression - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: string, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A String object or string literal containing the text to replace for every successful match of rgExp in stringObj. - */ - replace(searchValue: RegExp, replaceValue: string): string; - - /** - * Replaces text in a string, using a regular expression or search string. - * @param searchValue A Regular Expression object containing the regular expression pattern and applicable flags - * @param replaceValue A function that returns the replacement text. - */ - replace(searchValue: RegExp, replaceValue: (substring: string, ...args: any[]) => string): string; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: string): number; - - /** - * Finds the first substring match in a regular expression search. - * @param regexp The regular expression pattern and applicable flags. - */ - search(regexp: RegExp): number; - - /** - * Returns a section of a string. - * @param start The index to the beginning of the specified portion of stringObj. - * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. - * If this value is not specified, the substring continues to the end of stringObj. - */ - slice(start?: number, end?: number): string; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: string, limit?: number): string[]; - - /** - * Split a string into substrings using the specified separator and return them as an array. - * @param separator A Regular Express that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. - * @param limit A value used to limit the number of elements returned in the array. - */ - split(separator: RegExp, limit?: number): string[]; - - /** - * Returns the substring at the specified location within a String object. - * @param start The zero-based index number indicating the beginning of the substring. - * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. - * If end is omitted, the characters from start through the end of the original string are returned. - */ - substring(start: number, end?: number): string; - - /** Converts all the alphabetic characters in a string to lowercase. */ - toLowerCase(): string; - - /** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */ - toLocaleLowerCase(): string; - - /** Converts all the alphabetic characters in a string to uppercase. */ - toUpperCase(): string; - - /** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */ - toLocaleUpperCase(): string; - - /** Returns the length of a String object. */ - length: number; - - // IE extensions - /** - * Gets a substring beginning at the specified location and having the specified length. - * @param from The starting position of the desired substring. The index of the first character in the string is zero. - * @param length The number of characters to include in the returned substring. - */ - substr(from: number, length?: number): string; - - [index: number]: string; - - //#endregion - - //#region Extensions - - /** - * Formats a number by using the invariant culture. - * @returns true if the end of the String object matches suffix; otherwise, false. - */ - endsWith(suffix: string): boolean; - /** - * Replaces each format item in a String object with the text equivalent of a corresponding object's value. - * @returns A copy of the string with the formatting applied. - */ - format(format: string, ...args: any[]): string; - /** - * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. - * @returns A copy of the string with the formatting applied. - */ - localeFormat(format: string, ...args: any[]): string; - /** - * Removes leading and trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start and end of the string. - */ - trim(): string; - /** - * Removes trailing white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the end of the string. - */ - trimEnd(): string; - /** - * Removes leading white-space characters from a String object. - * @returns A copy of the string with all white-space characters removed from the start of the string. - */ - trimStart(): string; - - //#endregion - } + //#region Extensions /** - * Provides extensions to the base ECMAScript (JavaScript) Boolean object. - * Boolean Type Extensions - * @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} + * Creates an Error object that represents the Sys.ParameterCountException exception. */ - interface Boolean { + parameterCount(message?: string): Error; + /** + * Creates an Error object that represents the Sys.NotImplementedException exception. + */ + notImplemented(message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentException exception. + */ + argument(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentNullException exception. + */ + argumentNull(paramName?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentOutOfRangeException exception. + */ + argumentOutOfRange(paramName?: string, actualValue?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentTypeException exception. + */ + argumentType(paramName?: string, actualType?: any, expectedType?: any, message?: string): Error; + /** + * Creates an Error object that represents the Sys.ArgumentUndefinedException exception. + */ + argumentUndefined(paramName?: string, message?: string): Error; + /** + * Creates an Error object that can contain additional error information. + */ + create(message?: string, errorInfo?: Object): Error; + /** + * Creates an Error object that represents the Sys.FormatException exception. + */ + format(message?: string): Error; + /** + * Creates an Error object that represents the Sys.InvalidOperationException exception. + */ + invalidOperation(message?: string): Error; - //#region lib.d.ts - new (value?: any): Boolean; - (value?: any): boolean; - prototype: Boolean; + //#endregion +} - //#endregion +interface Error { + /** + * Updates the fileName and lineNumber properties of an Error instance to indicate where the error was thrown instead of where the error was created. Use this function if you are creating custom error types. + */ + popStackFrame(): void; +} - //#region Extensions - /** - * Converts a string representation of a logical value to its Boolean object equivalent. - */ - parse(value: string): Boolean; - //#endregion - } +interface String { + + //#region Extensions + + /** + * Formats a number by using the invariant culture. + * @returns true if the end of the String object matches suffix; otherwise, false. + */ + endsWith(suffix: string): boolean; + + /** + * Removes leading and trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start and end of the string. + */ + trim(): string; + /** + * Removes trailing white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the end of the string. + */ + trimEnd(): string; + /** + * Removes leading white-space characters from a String object. + * @returns A copy of the string with all white-space characters removed from the start of the string. + */ + trimStart(): string; + + //#endregion +} + +/** +* Provides extensions to the base ECMAScript (JavaScript) String object by including static and instance methods. +* String Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397472(v=vs.100).aspx} +*/ +interface StringConstructor { + /** +* Replaces each format item in a String object with the text equivalent of a corresponding object's value. +* @returns A copy of the string with the formatting applied. +*/ + format(format: string, ...args: any[]): string; + /** + * Replaces the format items in a String object with the text equivalent of a corresponding object's value. The current culture is used to format dates and numbers. + * @returns A copy of the string with the formatting applied. + */ + localeFormat(format: string, ...args: any[]): string; +} + + +/** +* Provides extensions to the base ECMAScript (JavaScript) Boolean object. +* Boolean Type Extensions +* @see {@link http://msdn.microsoft.com/en-us/library/bb397557(v=vs.100).aspx} +*/ +interface BooleanConstructor { + + //#region Extensions + + /** + * Converts a string representation of a logical value to its Boolean object equivalent. + */ + parse(value: string): Boolean; + + //#endregion } //#endregion @@ -908,7 +570,7 @@ declare function $find(id: string, parent?: HTMLElement): Sys.Component; * @param handler The event handler to add. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandler(element: Sys.UI.DomElement, eventName: string, handler: Function, autoRemove?: boolean): void; +declare function $addHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void, autoRemove?: boolean): void; /** * Provides a shortcut to the addHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -918,7 +580,7 @@ declare function $addHandler(element: Sys.UI.DomElement, eventName: string, hand * @param handlerOwner (Optional) The object instance that is the context for the delegates that should be created from the handlers. * @param autoRemove (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ -declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOwner?: any, autoRemove?: boolean): void; +declare function $addHandlers(element: HTMLElement, events: { [event: string]: (e: Sys.UI.DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Provides a shortcut to the clearHandlers method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -926,21 +588,19 @@ declare function $addHandlers(element: Sys.UI.DomElement, events: any, handlerOw * @see {@link http://msdn.microsoft.com/en-us/library/bb310959(v=vs.100).aspx} * @param The DOM element that exposes the events. */ -declare function $clearHandlers(element: Sys.UI.DomElement): void; +declare function $clearHandlers(element: HTMLElement): void; /** -* Provides a shortcut to the getElementById method of the Sys.UI.DomElement class. This member is static and can be invoked without creating an instance of the class. +* Provides a shortcut to the getElementById method of the HTMLElement class. This member is static and can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb397717(v=vs.100).aspx} * @param id * The ID of the DOM element to find. * @param element * The parent element to search. The default is the document element. * @return -* The Sys.UI.DomElement +* The HTMLElement */ -declare function $get(id: string): any; // Examples use HTMLElement and DomElement declare function $get(id: string, element?: HTMLElement): HTMLElement; -declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; /** * Provides a shortcut to the removeHandler method of the Sys.UI.DomEvent class. This member is static and can be invoked without creating an instance of the class. @@ -949,9 +609,7 @@ declare function $get(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElemen * @param eventName The name of the DOM event. * @param handler The event handler to remove. */ -declare function $removeHandler(element: any, eventName: string, handler: Function): void; -declare function $removeHandler(element: HTMLElement, eventName: string, handler: Function): void; -declare function $removeHandler(element: Sys.UI.DomElement, eventName: string, handler: Function): void; +declare function $removeHandler(element: HTMLElement, eventName: string, handler: (e: Sys.UI.DomEvent) => void): void; //#endregion @@ -973,7 +631,7 @@ declare module Sys { * The members can be invoked without creating an instance of the class. * @see {@link http://msdn.microsoft.com/en-us/library/bb384161(v=vs.100).aspx} */ - interface Application { + interface Application extends Component, IContainer { //#region Constructors @@ -986,27 +644,27 @@ declare module Sys { /** * Raised after all scripts have been loaded but before objects are created. */ - add_init(handler: Function): void; + add_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded but before objects are created. */ - remove_init(handler: Function): void; + remove_init(handler: (sender: Application, eventArgs: EventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - add_load(handler: Function): void; + add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Raised after all scripts have been loaded and after the objects in the application have been created and initialized. */ - remove_load(handler: Function): void; + remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - add_navigate(handler: Function): void; + add_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Occurs when the user clicks the browser's Back or Forward button. */ - remove_navigate(handler: Function): void; + remove_navigate(handler: (sender: Application, eventArgs: HistoryEventArgs) => void): void; /** * Raised before all objects in the client application are disposed, typically when the DOM window.unload event is raised. @@ -2175,67 +1833,67 @@ declare module Sys { //#endregion //#region Exception Types + // Really not a types + ///** + //* Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. + //*/ + //class ArgumentException { - /** - * Raised when a function or method is invoked and at least one of the passed arguments does not meet the parameter specification of the called function or method. - */ - class ArgumentException { + //} + ///** + //* Raised when an argument has an invalid value of null. + //*/ + //class ArgumentNullException { - } - /** - * Raised when an argument has an invalid value of null. - */ - class ArgumentNullException { + //} + ///** + //* Raised when an argument value is outside an acceptable range. + //*/ + //class ArgumentOutOfRangeException { - } - /** - * Raised when an argument value is outside an acceptable range. - */ - class ArgumentOutOfRangeException { + //} + ///** + //* Raised when a parameter is not an allowed type. + //*/ + //class ArgumentTypeException { - } - /** - * Raised when a parameter is not an allowed type. - */ - class ArgumentTypeException { + //} + ///** + //* Raised when an argument for a required method parameter is undefined. + //*/ + //class ArgumentUndefinedException { - } - /** - * Raised when an argument for a required method parameter is undefined. - */ - class ArgumentUndefinedException { + //} + ///** + //* + //*/ + //class FormatException { - } - /** - * - */ - class FormatException { + //} + ///** + //* Raised when a call to a method has failed, but the reason was not invalid arguments. + //*/ + //class InvalidOperationException { - } - /** - * Raised when a call to a method has failed, but the reason was not invalid arguments. - */ - class InvalidOperationException { + //} + ///** + //* Raised when a requested method is not supported by an object. + //*/ + //class NotImplementedException { - } - /** - * Raised when a requested method is not supported by an object. - */ - class NotImplementedException { + //} + ///** + //* Raised when an invalid number of arguments have been passed to a function. + //*/ + //class ParameterCountException { - } - /** - * Raised when an invalid number of arguments have been passed to a function. - */ - class ParameterCountException { + //} + ///** + //* Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. + //*/ + //class ScriptLoadFailedException { - } - /** - * Raised by the Microsoft Ajax Library framework when a script does not load successfully. This exception should not be thrown by the developer. - */ - class ScriptLoadFailedException { - - } + //} //#endregion @@ -2252,7 +1910,28 @@ declare module Sys { * Enables your application to call Web services asynchronously by using ECMAScript (JavaScript). * @see {@link http://msdn.microsoft.com/en-us/library/bb310823(v=vs.100).aspx} */ - // Cannot create definitions for generated proxy classes. + class WebServiceProxy { + static invoke( + servicePath: string, + methodName: string, + useGet?: boolean, + params?: any, + onSuccess?: (result: string, eventArgs: EventArgs) => void, + onFailure?: (error: WebServiceError) => void, + userContext?: any, + timeout?: number, + enableJsonp?: boolean, + jsonpCallbackParameter?: string): WebRequest; + } + + class WebServiceError { + get_errorObject(): any; + get_exceptionType(): any; + get_message(): string; + get_stackTrace(): string; + get_statusCode(): number; + get_timedOut(): boolean; + } /** * Contains information about a Web request that is ready to be sent to the current Sys.Net.WebRequestExecutor instance. @@ -2261,7 +1940,7 @@ declare module Sys { * * @see {@link http://msdn.microsoft.com/en-us/library/bb397488(v=vs.100).aspx} */ - class NetWorkRequestEventArgs { + class NetworkRequestEventArgs { //#region Constructors @@ -2310,6 +1989,19 @@ declare module Sys { //#endregion //#region Members + get_url(): string; + set_url(value: string): void; + get_httpVerb(): string; + set_httpVerb(value: string): void; + get_timeout(): number; + set_timeout(value: number): void; + get_body(): string; + set_body(value: string): void; + get_headers(): { [key: string]: string; }; + get_userContext(): any; + set_userContext(value: any): void; + get_executor(): WebRequestExecutor; + set_executor(value: WebRequestExecutor): void; /** * Registers a handler for the completed request event of the Web request. @@ -2387,7 +2079,7 @@ declare module Sys { * Gets the value of the specified response header. * @return The specified response header. */ - getResponseHeader(): string; + getResponseHeader(key: string): string; //#endregion @@ -2478,13 +2170,13 @@ declare module Sys { * @param handler * The function registered to handle the completed request event. */ - add_completedRequest(handler: (sender: any, eventArgs: any) => void): void; + add_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Registers a handler for processing the invoking request event of the WebRequestManager. * @param handler * The function registered to handle the invoking request event. */ - add_invokingRequest(handler: (sender: any, networkRequestEventArgs: any) => void): void; + add_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; /** * Sends Web requests to the default network executor. * This member supports the client-script infrastructure and is not intended to be used directly from your code. @@ -2498,14 +2190,14 @@ declare module Sys { * @param handler * The function that handles the completed request event. */ - remove_completedRequest(handler: Function): void; + remove_completedRequest(handler: (sender: WebRequestExecutor, eventArgs: EventArgs) => void): void; /** * Removes the event handler set by the add_invokingRequest method. * Use the remove_invokingRequest method to remove the event handler you set using the add_invokingRequest method. * @param handler * The function that handles the invoking request event. */ - remove_invokingRequest(handler: Function): void; + remove_invokingRequest(handler: (sender: WebRequestExecutor, networkRequestEventArgs: NetworkRequestEventArgs) => void): void; //#endregion @@ -2943,16 +2635,16 @@ declare module Sys { * Gets a Sys.UI.Behavior instance with the specified name property from the specified HTML Document Object Model (DOM) element. This member a static member and can be invoked without creating an instance of the class. * @return The specified Behavior object, if found; otherwise, null. */ - static getBehaviorByName(element: Sys.UI.DomElement, name: string): Behavior; + static getBehaviorByName(element: HTMLElement, name: string): Behavior; /** * Gets an array of Sys.UI.Behavior objects that are of the specified type from the specified HTML Document Object Model (DOM) element. This method is static and can be invoked without creating an instance of the class. * @return An array of all Behavior objects of the specified type that are associated with the specified DOM element, if found; otherwise, an empty array. */ - static getBehaviorsByType(element: Sys.UI.DomElement, type: Sys.UI.Behavior): Behavior[]; + static getBehaviorsByType(element: HTMLElement, type: Sys.UI.Behavior): Behavior[]; /** * Gets the Sys.UI.Behavior objects that are associated with the specified HTML Document Object Model (DOM) element. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to search. + * The HTMLElement object to search. * @return An array of references to Behavior objects, or null if no references exist. */ static getBehaviors(element: DomElement): Behavior[]; @@ -2971,10 +2663,10 @@ declare module Sys { * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Behavior object is associated with. * @return The DOM element that the current Behavior object is associated with. */ - get_element(): Sys.UI.DomElement; + get_element(): HTMLElement; /** * Gets or sets the identifier for the Sys.UI.Behavior object. - * A generated identifier that consists of the ID of the associated Sys.UI.DomElement, the "$" character, and the name value of the Behavior object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Behavior object. */ get_id(): string; /** @@ -3050,11 +2742,11 @@ declare module Sys { * When called from a derived class, initializes a new instance of that class. * The Control constructor is a complete constructor function. However, because the Control class is an abstract base class, the constructor should be called only from derived classes. * @param element - * The Sys.UI.DomElement object that the control will be associated with. + * The HTMLElement object that the control will be associated with. * * @throws Error.invalidOperation Function */ - constructor(element: Sys.UI.DomElement); + constructor(element: HTMLElement); //#endregion @@ -3122,6 +2814,33 @@ declare module Sys { toggleCssClass(className: string): void; //#endregion + + //#region Properties + + /** + * Gets the HTML Document Object Model (DOM) element that the current Sys.UI.Control object is associated with. + * @return The DOM element that the current Control object is associated with. + */ + get_element(): HTMLElement; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * A generated identifier that consists of the ID of the associated HTMLElement, the "$" character, and the name value of the Control object. + */ + get_id(): string; + /** + * Gets or sets the identifier for the Sys.UI.Control object. + * @param value + * The string value to use as the identifier. + */ + set_id(value: string): void; + /* + * Gets or sets the name of the Sys.UI.Control object. + * If you do not explicitly set the name property, getting the property value sets it to its default value, which is equal to the type of the Control object. The name property remains null until it is accessed. + * @param value + * A string value to use as the name. + */ + + //#endregion } /** * Defines static methods and properties that provide helper APIs for manipulating and inspecting DOM elements. @@ -3131,11 +2850,7 @@ declare module Sys { //#region Constructors - /** - * Initializes a new instance of the Sys.UI.DomElement class. - */ - constructor(): void; - + //#endregion //#region Methods @@ -3144,38 +2859,38 @@ declare module Sys { * Adds a CSS class to a DOM element if the class is not already part of the DOM element. This member is static and can be invoked without creating an instance of the class. * If the element does not support a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to add the CSS class to. + * The HTMLElement object to add the CSS class to. * @param className * The name of the CSS class to add. */ - addCssClass(element: Sys.UI.DomElement, className: string): void; + addCssClass(element: HTMLElement, className: string): void; /** * Gets a value that indicates whether the DOM element contains the specified CSS class. This member is static and can be invoked without creating an instance of the class. * @param element - * The Sys.UI.DomElement object to test for the CSS class. + * The HTMLElement object to test for the CSS class. * @param className * The name of the CSS class to test for. * @return * true if the element contains the specified CSS class; otherwise, false. */ - containsCssClass(element: Sys.UI.DomElement, className: string): boolean; + containsCssClass(element: HTMLElement, className: string): boolean; /** * Gets a set of integer coordinates that represent the position, width, and height of a DOM element. This member is static and can be invoked without creating an instance of the class. * * @param element - * The Sys.UI.DomElement instance to get the coordinates of. + * The HTMLElement instance to get the coordinates of. * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the upper-left corner, the width, and the height of the element in pixels. */ - getBounds(element: Sys.UI.DomElement): Object; + getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; /** * @param id * The ID of the element to find. * @param element * (optional) The parent element to search in. The default is the document element. */ - getElementById(id: string): Sys.UI.DomElement; - getElementById(id: string, element?: Sys.UI.DomElement): Sys.UI.DomElement; + getElementById(id: string): HTMLElement; + getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element?: HTMLElement): HTMLElement; getElementById(id: string, element: any): any; /** @@ -3185,17 +2900,15 @@ declare module Sys { * @return * An object of the JavaScript type Object that contains the x-coordinate and y-coordinate of the element in pixels. */ - getLocation(element: Sys.UI.DomElement): Sys.UI.Point; - getLocation(element: any): Object; + getLocation(element: HTMLElement): Sys.UI.Point; /* - * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. This member is static and can be invoked without creating an instance of the class. + * Returns a value that represents the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. This member is static and can be invoked without creating an instance of the class. * @param element * The target DOM element. * @return * A Sys.UI.VisibilityMode enumeration value that indicates the layout characteristics of element when it is hidden by invoking the setVisible method. */ - getVisibilityMode(element: Sys.UI.DomElement): Sys.UI.VisibilityMode; - getVisibilityMode(element: any): Sys.UI.VisibilityMode; + getVisibilityMode(element: HTMLElement): Sys.UI.VisibilityMode; /** * Gets a value that indicates whether a DOM element is currently visible on the Web page. This member is static and can be invoked without creating an instance of the class. * @param element @@ -3219,16 +2932,15 @@ declare module Sys { * @param args * The event arguments */ - raiseBubbleEvent(source: Sys.UI.DomElement, args: EventArgs): void; - raiseBubbleEvent(source: any, args: any): void; + raiseBubbleEvent(source: HTMLElement, args: EventArgs): void; /** * Removes a CSS class from a DOM element. This member is static and can be invoked without creating an instance of the class. If the element does not include a CSS class, no change is made to the element. * @param element - * The Sys.UI.DomElement object to remove the CSS class from. + * The HTMLElement object to remove the CSS class from. * @param className * The name of the CSS class to remove. */ - removeCssClass(element: Sys.UI.DomElement, className: string): void; + removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: HTMLElement, className: string): void; removeCssClass(element: any, className: string): void; /** @@ -3241,9 +2953,7 @@ declare module Sys { * @return * A DOM element. */ - resolveElement(elementOrElementId: Sys.UI.DomElement, containerElement?: Sys.UI.DomElement): Sys.UI.DomElement; - resolveElement(elementOrElementId: HTMLElement, containerElement?: HTMLElement): HTMLElement; - resolveElement(elementOrElementId: string): any; + resolveElement(elementOrElementId: string|HTMLElement, containerElement?: HTMLElement): HTMLElement; /** * Sets the position of a DOM element. This member is static and can be invoked without creating an instance of the class. * he left and top style attributes (upper-left corner) of an element specify the relative position of an element. @@ -3252,14 +2962,12 @@ declare module Sys { * @param x The x-coordinate in pixels. * @param y The y-coordinate in pixels. */ - setLocation(element: Sys.UI.DomElement, x: number, y: number): void; setLocation(element: HTMLElement, x: number, y: number): void; - setLocation(element: any, x: number, y: number): void; /** - * Sets the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Sets the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * This member is static and can be invoked without creating an instance of the class. * - * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the Sys.UI.DomElement.setVisible method. + * Use the setVisibilityMode method to set the layout characteristics of a DOM element when it is hidden by invoking the HTMLElement.setVisible method. * For example, if value is set to Sys.UI.VisibilityMode.collapse, the element uses no space on the page when the setVisible method is called to hide the element. * * @param element @@ -3267,41 +2975,37 @@ declare module Sys { * @param value * A Sys.UI.VisibilityMode enumeration value. */ - setVisibilityMode(element: Sys.UI.DomElement, value: Sys.UI.VisibilityMode): void; + setVisibilityMode(element: HTMLElement, value: Sys.UI.VisibilityMode): void; /** * Sets a DOM element to be visible or hidden. This member is static and can be invoked without creating an instance of the class. * * Use the setVisible method to set a DOM element as visible or hidden on the Web page. * If you invoke this method with value set to false for an element whose visibility mode is set to "hide," the element will not be visible. * However, it will occupy space on the page. If the element's visibility mode is set to "collapse," the element will occupy no space in the page. - * For more information about how to set the layout characteristics of hidden DOM elements, see Sys.UI.DomElement setVisibilityMode Method. + * For more information about how to set the layout characteristics of hidden DOM elements, see HTMLElement setVisibilityMode Method. * * @param element * The target DOM element. * @param value * true to make element visible on the Web page; false to hide element. */ - setVisible(element: Sys.UI.DomElement, value: boolean): void; setVisible(element: HTMLElement, value: boolean): void; - setVisible(element: any, value: boolean): void; /** * Toggles a CSS class in a DOM element. This member is static and can be invoked without creating an instance of the class. * Use the toggleCssClass method to hide a CSS class of an element if it is shown, or to show a CSS class of an element if it is hidden. * * @param element - * The Sys.UI.DomElement object to toggle. + * The HTMLElement object to toggle. * @param className * The name of the CSS class to toggle. */ - toggleCssClass(element: Sys.UI.DomElement, className: string): void; toggleCssClass(element: HTMLElement, className: string): void; - toggleCssClass(element: any, className: string): void; //#endregion } - var DomElement: Sys.UI.DomElement; + var DomElement: DomElement; /** * Provides cross-browser access to DOM event properties and helper APIs that are used to attach handlers to DOM element events. @@ -3312,12 +3016,11 @@ declare module Sys { //#region Constructors /** - * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified DomElement object. + * Initializes a new instance of the Sys.UI.DomEvent class and associates it with the specified HTMLElement object. * @param domElement - * The DomElement object to associate with the event. + * The HTMLElement object to associate with the event. */ - constructor(domElement: DomElement); - constructor(domElement: any); + constructor(domElement: HTMLElement); //#endregion @@ -3337,7 +3040,7 @@ declare module Sys { * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ - static addHandler(element: any, eventName: string, handler: Function, autoRemove?: boolean): void; + static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean); /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. @@ -3359,7 +3062,7 @@ declare module Sys { * @throws Error.invalidOperation - (Debug) One of the handlers specified in events is not a function. * */ - static addHandlers(element: any, events: any, handlerOwner?: any, autoRemove?: boolean): void; + static addHandlers(element: HTMLElement, events: { [event: string]: (e: DomEvent) => void }, handlerOwner?: any, autoRemove?: boolean): void; /** * Removes all DOM event handlers from a DOM element that were added through the Sys.UI.DomEvent addHandler or the Sys.UI.DomEvent addHandlers methods. * This member is static and can be invoked without creating an instance of the class. @@ -3368,7 +3071,7 @@ declare module Sys { * @param element * The element that exposes the events. */ - static clearHandlers(element: any): void; + static clearHandlers(element: HTMLElement): void; /** * Removes a DOM event handler from the DOM element that exposes the event. This member is static and can be invoked without creating an instance of the class. * @@ -3379,7 +3082,7 @@ declare module Sys { * @param handler * The event handler to remove. */ - static removeHandler(element: any, eventName: string, handler: Function): void; + static removeHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void): void; /** * Prevents the default DOM event action from happening. * Use the preventDefault method to prevent the default event action for the browser from occurring. @@ -3544,10 +3247,21 @@ declare module Sys { * Describes mouse button locations. */ enum MouseButton { - // todo + /** + * Represents the left mouse button. + */ + leftButton, + /** + * Represents the middle mouse button. + */ + middleButton, + /** + * Represents the right mouse button. + */ + rightButton } /** - * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the Sys.UI.DomElement class returns a Point object. + * Creates an object that contains a set of integer coordinates that represent a position. The getLocation method of the HTMLElement class returns a Point object. * @see {@link http://msdn.microsoft.com/en-us/library/bb383992(v=vs.100).aspx} * */ class Point { @@ -3829,7 +3543,7 @@ declare module Sys { * The pageLoading event of the Sys.WebForms.PageRequestManager class uses a PageLoadingEventArgs object to return its event data. * @return An array of
elements that will be deleted from the DOM. If no elements will be deleted, the property returns null. */ - get_panelsDeleted(): HTMLDivElement[]; + get_panelsDeleting(): HTMLDivElement[]; /** * Gets an array of HTML
elements that represent UpdatePanel controls that will be updated in the DOM as a result of the current asynchronous postback. * If the contents of any UpdatePanel controls will be updated as the result of a partial-page update, the panelsUpdating property contains an array that references the corresponding
elements. diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 1f7a2feaf..026658ef8 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,157 +1,13 @@ -// Type definitions for sptypescript +// Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan , Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module Sys { - export class EventArgs { - static Empty: Sys.EventArgs; - } - export class StringBuilder { - /** Appends a string to the string builder */ - append(s: string): void; - /** Appends a line to the string builder */ - appendLine(s: string): void; - /** Clears the contents of the string builder */ - clear(): void; - /** Indicates wherever the string builder is empty */ - isEmpty(): boolean; - /** Gets the contents of the string builder as a string */ - toString(): string; - } - export class Component { - get_id(): string; - static create(type: Component, properties?: any, events?: any, references?: any, element?: Node); - initialize(): void; - updated(): void; - } - - export interface IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - } - - export class Application extends Component implements IContainer { - addComponent(component: Component): void; - findComponent(id: string): Component; - getComponents(): Component[]; - removeComponent(component: Component); - - static add_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - static remove_load(handler: (sender: Application, eventArgs: ApplicationLoadEventArgs) => void); - } - - export class ApplicationLoadEventArgs { - constructor(components: Component[], isPartialLoad: boolean); - public components: Component[]; - public isPartialLoad: boolean; - } - - module UI { - export class Control extends Component { } - export class DomEvent { - static addHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - static removeHandler(element: HTMLElement, eventName: string, handler: (e: Event) => void); - } - - export class DomElement { - static getBounds(element: HTMLElement): { x: number; y: number; width: number; height: number; }; - } - } - module Net { - export class WebRequest { - get_url(): string; - set_url(value: string): void; - get_httpVerb(): string; - set_httpVerb(value: string): void; - get_timeout(): number; - set_timeout(value: number): void; - get_body(): string; - set_body(value: string): void; - get_headers(): { [key: string]: string; }; - get_userContext(): any; - set_userContext(value: any): void; - get_executor(): WebRequestExecutor; - set_executor(value: WebRequestExecutor): void; - - getResolvedUrl(); string; - invoke(): void; - completed(args: Sys.EventArgs): void; - - add_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - remove_completed(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - } - - export class WebRequestExecutor { - get_aborted(): boolean; - get_responseAvailable(): boolean; - get_responseData(): string; - get_object(): any; - get_started(): boolean; - get_statusCode(): number; - get_statusText(): string; - get_timedOut(): boolean; - get_xml(): Document; - get_webRequest(): WebRequest; - abort(): void; - executeRequest(): void; - getAllResponseHeaders(): string; - getResponseHeader(key: string): string; - } - - export class NetworkRequestEventArgs extends EventArgs { - get_webRequest(): WebRequest; - } - - - export class WebRequestManager { - static get_defaultExecutorType(): string; - static set_defaultExecutorType(value: string): void; - static get_defaultTimeout(): number; - static set_defaultTimeout(value: number): void; - - static executeRequest(request: WebRequest): void; - static add_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static remove_completedRequest(handler: (executor: WebRequestExecutor, args: Sys.EventArgs) => void): void; - static add_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - static remove_invokingRequest(handler: (executor: WebRequestExecutor, args: NetworkRequestEventArgs) => void): void; - } - - export class WebServiceProxy { - static invoke( - servicePath: string, - methodName: string, - useGet?: boolean, - params?: any, - onSuccess?: (result: string, eventArgs: EventArgs) => void, - onFailure?: (error: WebServiceError) => void, - userContext?: any, - timeout?: number, - enableJsonp?: boolean, - jsonpCallbackParameter?: string): WebRequest; - } - - export class WebServiceError { - get_errorObject(): any; - get_exceptionType(): any; - get_message(): string; - get_stackTrace(): string; - get_statusCode(): number; - get_timedOut(): boolean; - } - } - interface IDisposable { - dispose(): void; - } - -} - -declare var $get: { (id: string): HTMLElement; }; -declare var $addHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; -declare var $removeHandler: { (element: HTMLElement, eventName: string, handler: (e: Event) => void): void; }; +/// +declare var _spBodyOnLoadFunctions: Function[]; +declare var _spBodyOnLoadFunctionNames: string[]; +declare var _spBodyOnLoadCalled: boolean; declare module SP { export class SOD { @@ -463,7 +319,8 @@ interface ContextInfo extends SPClientTemplates.RenderContext { } -declare function GetCurrentCtx():ContextInfo; +declare function GetCurrentCtx(): ContextInfo; +declare function SetFullScreenMode(fullscreen: boolean); declare module SP { export enum RequestExecutorErrors { requestAbortedOrTimedout, @@ -490,7 +347,7 @@ declare module SP { method?: string; headers?: { [key: string]: string; }; /** Can be string or bytearray depending on binaryStringRequestBody field */ - body?: any; + body?: string|Uint8Array; binaryStringRequestBody?: boolean; /** Currently need fix to get ginary response. Details: http://techmikael.blogspot.ru/2013/07/how-to-copy-files-between-sites-using.html */ @@ -509,7 +366,7 @@ declare module SP { headers?: { [key: string]: string; }; contentType?: string; /** Can be string or bytearray depending on request.binaryStringResponseBody field */ - body?: any; + body?: string|Uint8Array; state?: any; } @@ -1116,8 +973,8 @@ declare module SPClientTemplates { Type: string; } -/** Represents field schema in Grid mode and on list forms. - Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ + /** Represents field schema in Grid mode and on list forms. + Consider casting objects of this type to more specific field types, e.g. FieldSchemaInForm_Lookup */ export interface FieldSchema_InForm extends FieldSchema { /** Description for this field. */ Description: string; @@ -1166,6 +1023,7 @@ declare module SPClientTemplates { FormUniqueId: string; ListData: ListData_InForm; ListSchema: ListSchema_InForm; + CSRCustomLayout?: boolean; } @@ -1389,7 +1247,7 @@ declare module SPClientTemplates { StateInitDone: boolean; TableCbxFocusHandler: any; TableMouseOverHandler: any; - TotalListItems: any; + TotalListItems: number; verEnabled: number; /** Guid of the view. */ view: string; @@ -1404,10 +1262,10 @@ declare module SPClientTemplates { } export interface RenderContext_FieldInView extends RenderContext_ItemInView { /** If in grid mode (context.inGridMode == true), cast to FieldSchema_InForm, otherwise cast to FieldSchema_InView */ - CurrentFieldSchema: any; + CurrentFieldSchema: FieldSchema_InForm | FieldSchema_InView; CurrentFieldValue: any; FieldControlsModes: { [fieldInternalName: string]: ClientControlMode; }; - FormContext: any; + FormContext: ClientFormContext; FormUniqueId: string; } @@ -1417,6 +1275,7 @@ declare module SPClientTemplates { export interface Group { Items: Item[]; } + type RenderCallback = (ctx: RenderContext) => void; export interface RenderContext { BaseViewID?: number; @@ -1426,8 +1285,8 @@ declare module SPClientTemplates { CurrentSelectedItems?: any; CurrentUICultureName?: string; ListTemplateType?: number; - OnPostRender?: any; - OnPreRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; + OnPreRender?: RenderCallback | RenderCallback[]; onRefreshFailed?: any; RenderBody?: (renderContext: RenderContext) => string; RenderFieldByName?: (renderContext: RenderContext, fieldName: string) => string; @@ -1484,18 +1343,18 @@ declare module SPClientTemplates { } export interface Templates { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplates; } @@ -1505,18 +1364,18 @@ declare module SPClientTemplates { } export interface TemplateOverrides { - View?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template - Body?: (renderContext: any) => string; // TODO: determine appropriate context type and purpose of this template + View?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template + Body?: RenderCallback | string; // TODO: determine appropriate context type and purpose of this template /** Defines templates for rendering groups (aggregations). */ - Group?: GroupCallback; + Group?: GroupCallback| string; /** Defines templates for list items rendering. */ - Item?: ItemCallback; + Item?: ItemCallback| string; /** Defines template for rendering list view header. Can be either string or SingleTemplateCallback */ - Header?: SingleTemplateCallback; + Header?: SingleTemplateCallback| string; /** Defines template for rendering list view footer. Can be either string or SingleTemplateCallback */ - Footer?: SingleTemplateCallback; + Footer?: SingleTemplateCallback| string; /** Defines templates for fields rendering. The field is specified by it's internal name. */ Fields?: FieldTemplateMap; } @@ -1525,10 +1384,10 @@ declare module SPClientTemplates { Templates?: TemplateOverrides; /** �allbacks called before rendering starts. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPreRender?: any; + OnPreRender?: RenderCallback | RenderCallback[]; /** �allbacks called after rendered html inserted into DOM. Can be function (ctx: RenderContext) => void or array of functions.*/ - OnPostRender?: any; + OnPostRender?: RenderCallback | RenderCallback[]; /** View style (SPView.StyleID) for which the templates should be applied. If not defined, the templates will be applied only to default view style. */ @@ -1538,11 +1397,11 @@ declare module SPClientTemplates { ListTemplateType?: number; /** Base view ID (SPView.BaseViewID) for which the template should be applied. If not defined, the templates will be applied to all views. */ - BaseViewID?: any; + BaseViewID?: number|string; } export class TemplateManager { static RegisterTemplateOverrides(renderCtx: TemplateOverridesOptions): void; - static GetTemplates(renderCtx: any): Templates; + static GetTemplates(renderCtx: RenderContext): Templates; } export interface ClientUserValue { @@ -1616,13 +1475,13 @@ declare module SPClientTemplates { EnableVesioning: boolean; Id: string; }; - registerInitCallback(fieldname: string, callback: () => void ): void; - registerFocusCallback(fieldname: string, callback: () => void ): void; - registerValidationErrorCallback(fieldname: string, callback: (error: any) => void ): void; + registerInitCallback(fieldname: string, callback: () => void): void; + registerFocusCallback(fieldname: string, callback: () => void): void; + registerValidationErrorCallback(fieldname: string, callback: (error: any) => void): void; registerGetValueCallback(fieldname: string, callback: () => any): void; updateControlValue(fieldname: string, value: any): void; registerClientValidator(fieldname: string, validator: SPClientForms.ClientValidation.ValidatorSet): void; - registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void ); + registerHasValueChangedCallback(fieldname: string, callback: (eventArg?: any) => void); } } @@ -1653,6 +1512,14 @@ declare module SPClientForms { } } +declare class SPMgr { + NewGroup(listItem: Object, fieldName: string): boolean; + RenderHeader(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema): string; + RenderField(renderCtx: SPClientTemplates.RenderContext, field: SPClientTemplates.FieldSchema, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; + RenderFieldByName(renderCtx: SPClientTemplates.RenderContext, fieldName: string, listItem: Object, listSchema: SPClientTemplates.ListSchema): string; +} + +declare var spMgr: SPMgr; declare module SPAnimation { export enum Attribute { @@ -7241,7 +7108,7 @@ declare module SP { } export class Status { - static addStatus(strTitle: string, strHtml: string, atBegining: boolean): string; + static addStatus(strTitle: string, strHtml?: string, atBegining?: boolean): string; static appendStatus(sid: string, strTitle: string, strHtml: string): string; static updateStatus(sid: string, strHtml: string): void; static setStatusPriColor(sid: string, strColor: string): void; @@ -7378,19 +7245,19 @@ declare module SP { @param url overrides options.url @param callback overrides options.dialogResultValueCallback @param args overrides options.args */ - static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback: SP.UI.DialogReturnValueCallback, args: any): void; + static commonModalDialogOpen(url: string, options: SP.UI.IDialogOptions, callback?: SP.UI.DialogReturnValueCallback, args?: any): void; /** Refresh the page if specified dialogResult equals to SP.UI.DialogResult.OK */ static RefreshPage(dialogResult: SP.UI.DialogResult): void; /** Show page specified by the url in a modal dialog. If the dialog returns SP.UI.DialogResult.OK, the page is refreshed. */ static ShowPopupDialog(url: string): void; /** Show modal dialog specified by url, callback, height and width. */ - static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width: number, height: number): void; + static OpenPopUpPage(url: string, callback: SP.UI.DialogReturnValueCallback, width?: number, height?: number): void; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel/close button is not shown. */ - static showWaitScreenWithNoClose(title: string, message: string, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenWithNoClose(title: string, message?: string, height?: number, width?: number): SP.UI.ModalDialog; /** Displays a wait/loading modal dialog with the specified title, message, height and width. Height and width are defined in pixels. Cancel button is shown. If user clicks it, the callbackFunc is called. */ - static showWaitScreenSize(title: string, message: string, callbackFunc: SP.UI.DialogReturnValueCallback, height: number, width: number): SP.UI.ModalDialog; + static showWaitScreenSize(title: string, message?: string, callbackFunc?: SP.UI.DialogReturnValueCallback, height?: number, width?: number): SP.UI.ModalDialog; static showPlatformFirstRunDialog(url: string, callbackFunc: SP.UI.DialogReturnValueCallback): SP.UI.ModalDialog; - static get_childDialog: any; + static get_childDialog: ModalDialog; /** Closes the dialog using the specified dialog result. */ close(dialogResult: SP.UI.DialogResult): void; } @@ -7469,6 +7336,11 @@ declare module SP { } } + export module Workplace { + export function add_resized(handler: Function); + export function remove_resized(handler:Function); + } + export module UIUtility { export function generateRandomElementId(): string; export function cancelEvent(evt: Event): void; @@ -8410,11 +8282,11 @@ declare module SP.WorkflowServices { /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - get_restrictScope(): string; + get_restrictToScope(): string; /** RestrictToScope is a GUID value, used in conjunction with the RestrictToType property to further restrict the scope of the definition. For example, if the RestrictToType is "List", then setting the RestrictToScope to a particular list identifier limits the definition to be associable only to the specified list. If the RestrictToType is "List" but the RestrictToScope is null or the empty string, then the definition is associable to any list. */ - set_restrictScope(value: string): string; + set_restrictToScope(value: string): string; /** RestrictToType determines the possible event source type for a workflow subscription that uses this definition. Possible values include "List", "Site", the empty string, or null. */ get_restrictToType(): string; @@ -9441,6 +9313,7 @@ interface ISPClientAutoFillData { AutoFillMenuOptionType?: number; } + declare class SPClientPeoplePicker { static ValueName: string; // = 'Key'; static DisplayTextName: string; // = 'DisplayText'; @@ -9460,54 +9333,112 @@ declare class SPClientPeoplePicker { }; static InitializeStandalonePeoplePicker(clientId: string, value: ISPClientPeoplePickerEntity[], schema: ISPClientPeoplePickerSchema): void; + static ParseUserKeyPaste(userKey: string): string; + static GetTopLevelControl(elmChild: HTMLElement): HTMLElement; + static AugmentEntity(entity: ISPClientPeoplePickerEntity): ISPClientPeoplePickerEntity; + static AugmentEntitySuggestions(pickerObj: SPClientPeoplePicker, allEntities: ISPClientPeoplePickerEntity[], mergeLocal?: boolean): ISPClientPeoplePickerEntity[]; + static PickerObjectFromSubElement(elmSubElement: HTMLElement): SPClientPeoplePicker; + static TestLocalMatch(strSearchLower: string, dataEntity: ISPClientPeoplePickerEntity): boolean; + static BuildUnresolvedEntity(key: string, dispText: string): ISPClientPeoplePickerEntity; + static AddAutoFillMetaData(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[], numOpts: number): ISPClientPeoplePickerEntity[]; + static BuildAutoFillMenuItems(pickerObj: SPClientPeoplePicker, options: ISPClientPeoplePickerEntity[]): ISPClientPeoplePickerEntity[]; + static IsUserEntity(entity: ISPClientPeoplePickerEntity): boolean; + static CreateSPPrincipalType(acctStr: string): number; - public TopLevelElementId: string;// '', - public EditorElementId: string;//'', - public AutoFillElementId: string;//'', - public ResolvedListElementId: string;//'', - public InitialHelpTextElementId: string;//'', - public WaitImageId: string;//'', - public HiddenInputId: string;//'', - public AllowEmpty: boolean;//true, - public ForceClaims: boolean;//false, - public AutoFillEnabled: boolean;//true, - public AllowMultipleUsers: boolean;//false, + + public TopLevelElementId: string; // '', + public EditorElementId: string; //'', + public AutoFillElementId: string; //'', + public ResolvedListElementId: string; //'', + public InitialHelpTextElementId: string; //'', + public WaitImageId: string; //'', + public HiddenInputId: string; //'', + public AllowEmpty: boolean; //true, + public ForceClaims: boolean; //false, + public AutoFillEnabled: boolean; //true, + public AllowMultipleUsers: boolean; //false, public OnValueChangedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnUserResolvedClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; public OnControlValidateClientScript: (pickerElementId: string, users: ISPClientPeoplePickerEntity[]) => void; - public UrlZone: string;//null, - public AllUrlZones: boolean;//false, - public SharePointGroupID: number;//0, - public AllowEmailAddresses: boolean;//false, + public UrlZone: SP.UrlZone; //null, + public AllUrlZones: boolean; //false, + public SharePointGroupID: number; //0, + public AllowEmailAddresses: boolean; //false, public PPMRU: SPClientPeoplePickerMRU; - public UseLocalSuggestionCache: boolean;//true, - public CurrentQueryStr: string;//'', - public LatestSearchQueryStr: string;// '', + public UseLocalSuggestionCache: boolean; //true, + public CurrentQueryStr: string; //'', + public LatestSearchQueryStr: string; // '', public InitialSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestions: ISPClientPeoplePickerEntity[]; public CurrentLocalSuggestionsDict: ISPClientPeoplePickerEntity; - public VisibleSuggestions: number;//5, - public PrincipalAccountType: string;//'', + public VisibleSuggestions: number; //5, + public PrincipalAccountType: string; //'', public PrincipalAccountTypeEnum: SP.Utilities.PrincipalType; - public EnabledClaimProviders: string;//'', - public SearchPrincipalSource: SP.Utilities.PrincipalSource;//null, - public ResolvePrincipalSource: SP.Utilities.PrincipalSource;//null, - public MaximumEntitySuggestions: number;//30, - public EditorWidthSet: boolean;//false, - public QueryScriptInit: boolean;//false, - public AutoFillControl: string;//null, - public TotalUserCount: number;//0, - public UnresolvedUserCount: number;//0, - public UserQueryDict: ISPClientPeoplePickerEntity; - public ProcessedUserList: ISPClientPeoplePickerEntity; - public HasInputError: boolean;//false, - public HasServerError: boolean;//false, - public ShowUserPresence: boolean;//true, - public TerminatingCharacter: string;//';', - public UnresolvedUserElmIdToReplace: string;//'', - public WebApplicationID: SP.Guid;//'{00000000-0000-0000-0000-000000000000}', - + public EnabledClaimProviders: string; //'', + public SearchPrincipalSource: SP.Utilities.PrincipalSource; //null, + public ResolvePrincipalSource: SP.Utilities.PrincipalSource; //null, + public MaximumEntitySuggestions: number; //30, + public EditorWidthSet: boolean; //false, + public QueryScriptInit: boolean; //false, + public AutoFillControl: SPClientAutoFill; //null, + public TotalUserCount: number; //0, + public UnresolvedUserCount: number; //0, + public UserQueryDict: { [index: string]: SP.StringResult }; + public ProcessedUserList: { [index: string]: SPClientPeoplePickerProcessedUser }; + public HasInputError: boolean; //false, + public HasServerError: boolean; //false, + public ShowUserPresence: boolean; //true, + public TerminatingCharacter: string; //';', + public UnresolvedUserElmIdToReplace: string; //'', + public WebApplicationID: SP.Guid; //'{00000000-0000-0000-0000-000000000000}', public GetAllUserInfo(): ISPClientPeoplePickerEntity[]; + + public SetInitialValue(entities: ISPClientPeoplePickerEntity[], initialErrorMsg?: string): void + public AddUserKeys(userKeys: string, bSearch: boolean): void; + public BatchAddUserKeysOperation(allKeys: string[], numProcessed: number); + public ResolveAllUsers(fnContinuation: () => void): void; + public ExecutePickerQuery(queryIds: string, onSuccess: (queryId: string, result: SP.StringResult) => void, onFailure: (queryId: string, result: SP.StringResult) => void, fnContinuation: () => void): void; + public AddUnresolvedUserFromEditor(bRunQuery?: boolean): void; + public AddUnresolvedUser(unresolvedUserObj: ISPClientPeoplePickerEntity, bRunQuery?: boolean): void; + public UpdateUnresolvedUser(results: SP.StringResult, user: ISPClientPeoplePickerEntity): void; + public AddPickerSearchQuery(queryStr: string): string; + public AddPickerResolveQuery(queryStr: string): string; + public GetPeoplePickerQueryParameters(): SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters; + public AddProcessedUser(userObject: ISPClientPeoplePickerEntity, fResolved?: boolean): string; + public DeleteProcessedUser(elmToRemove: HTMLElement): void; + public OnControlValueChanged(): void; + public OnControlResolvedUserChanged(): void; + public EnsureAutoFillControl(): void; + public ShowAutoFill(resultsTable: ISPClientAutoFillData[]): void; + public FocusAutoFill(): void; + public BlurAutoFill(): void; + public IsAutoFillOpen(): boolean; + public EnsureEditorWidth(): void; + public SetFocusOnEditorEnd(): void; + public ToggleWaitImageDisplay(bShowImage?: boolean): void; + public SaveAllUserKeysToHiddenInput(): void; + public GetCurrentEditorValue(): string; + public GetControlValueAsJSObject(): ISPClientPeoplePickerEntity[]; + public GetAllUserKeys(): string; + public GetControlValueAsText(): string; + public IsEmpty(): boolean; + public IterateEachProcessedUser(fnCallback: (index: number, user: SPClientPeoplePickerProcessedUser) => void): void; + public HasResolvedUsers(): boolean; + public Validate(): void; + public ValidateCurrentState(): void + public GetUnresolvedEntityErrorMessage(): string; + public ShowErrorMessage(msg: string): void; + public ClearServerError(): void; + public SetServerError(): void; + public OnControlValidate(): void; + public SetEnabledState(bEnabled: boolean): void; + public DisplayLocalSuggestions(): void; + public CompileLocalSuggestions(input: string): void; + public PlanningGlobalSearch(): boolean; + public AddLoadingSuggestionMenuOption(): void; + public ShowingLocalSuggestions(): boolean; + public ShouldUsePPMRU(): boolean; + public AddResolvedUserToLocalCache(resolvedEntity: ISPClientPeoplePickerEntity, resolveText: string); } interface ISPClientPeoplePickerSchema { @@ -9583,11 +9514,38 @@ interface ISPClientPeoplePickerEntity { Department: string; Email: string; }; - MultipleMatches: Object[]; + MultipleMatches: ISPClientPeoplePickerEntity[]; DomainText?: string; [key: string]: any; } +declare class SPClientPeoplePickerProcessedUser { + UserContainerElementId: string;// '', + DisplayElementId: string;// '', + PresenceElementId: string;// '', + DeleteUserElementId: string;// '', + SID: string;// '', + DisplayName: string;// '', + SIPAddress: string;// '', + UserInfo: ISPClientPeoplePickerEntity;// null, + ResolvedUser: boolean;// true, + Suggestions: ISPClientAutoFillData[];// null, + ErrorDescription: string;// '', + ResolveText: string;// '', + public UpdateResolvedUser(newUserInfo: ISPClientPeoplePickerEntity, strNewElementId: string): void; + public UpdateSuggestions(entity: ISPClientPeoplePickerEntity); + public BuildUserHTML(): string; + public UpdateUserMaxWidth(): void; + public ResolvedAsUnverifiedEmail(): string; + + static BuildUserPresenceHtml(elmId: string, strSip: string, bResolved?: boolean): string; + static GetUserContainerElement(elmChild: HTMLElement): HTMLElement; + static HandleProcessedUserClick(ndClicked: HTMLElement): void; + static DeleteProcessedUser(elmToRemove: HTMLElement): void; + static HandleDeleteProcessedUserKey(e: Event): void; + static HandleResolveProcessedUserKey(e: Event): void; +} + declare module Microsoft { export module Office { export module Server { @@ -9757,4 +9715,1234 @@ declare module SPThemeUtils { export function Suspend(): void; } +declare module SP { + export module JsGrid { + export enum TextDirection { + Default, //0, + RightToLeft, //1, + LeftToRight //2 + } + + export enum PaneId { + MainGrid, //0, + PivotedGrid, //1, + Gantt //2 + } + + export enum PaneLayout { + GridOnly, //0, + GridAndGantt, //1, + GridAndPivotedGrid //2 + + } + export enum EditMode { + ReadOnly, //0, + ReadWrite, //1, + ReadOnlyDefer, //2, + ReadWriteDefer, //3, + Defer //4 + } + + export enum GanttDrawBarFlags { + LeftLink, //0x01, + RightLink //0x02 + + } + export enum GanttBarDateType { + Start, //0, + End //1 + } + + export enum ValidationState { + Valid, //0, + Pending, //1, + Invalid //2 + } + + export enum HierarchyMode { + None, //0, + Standard, //1, + Grouping //2 + } + + export enum EditActorWriteType { + Both, //1, + LocalizedOnly, //2, + DataOnly, //3, + Either //4 + } + + export enum EditActorReadType { + Both, //1, + LocalizedOnly, //2, + DataOnly //3 + } + + export enum EditActorUpdateType { + Committed, //0, + Uncommitted, //1 + } + + export enum SortMode { + Ascending, //1, + Descending, //-1, + None //0 + } + + export module RowHeaderStyleId { + export var Transfer: string; //'Transfer', + export var Conflict: string; //'Conflict' + + } + + export module RowHeaderAutoStyleId { + export var Dirty:string; //'Dirty', + export var Error: string; //'Error', + export var NewRow: string; //'NewRow' + } + + export enum RowHeaderStatePriorities { + Dirty, //10, + Transfer, //30, + CellError, //40, + Conflict, //50, + RowError, //60, + NewRow //90 + } + + export enum UpdateSerializeMode { + Cancel, //0, + Default, //1, + PropDataOnly, //2, + PropLocalizedOnly, //3, + PropBoth //4 + } + + export enum UpdateTrackingMode { + PropData, //2, + PropLocalized, //3, + PropBoth //4 + } + + export module UserAction { + export var UserEdit:string; //'User Edit':string; + export var DeleteRecord:string; //'Delete Record':string; + export var InsertRecord:string; //'Insert Record':string; + export var Indent:string; //'Indent':string; + export var Outdent:string; //'Outdent':string; + export var Fill:string; //'Fill':string; + export var Paste:string; //'Paste':string; + export var CutPaste: string; //'Cut/Paste' + } + + export enum ReadOnlyActiveState { + ReadOnlyActive, //0, + ReadOnlyDisabled, //1 + } + + export interface IValue { + data?: any; + localized?:string; + } + + + export class JsGridControl { + constructor(parentNode: HTMLElement, bShowLoadingBanner: boolean); + /** Returns true if Init method has been executed successfully */ + IsInitialized(): boolean; + /** Replaces the control TableCache object with the provided one */ + ResetData(cache: SP.JsGrid.TableCache): void; + /** Initialize the control */ + Init(parameters: SP.JsGrid.JsGridControl.Parameters): void; + Cleanup(): void; + /** Removes all event handlers and markup associated with the control */ + Dispose(): void; + + // todo + NotifyDataAvailable(): void; + NotifySave(): void; + NotifyHide(): void; + NotifyResize(): void; + ClearTableView(): void; + HideInitialLoadingBanner(): void; + ShowInitialGridErrorMsg(errorMsg: string): void; + ShowGridErrorMsg(errorMsg: string): void; + LaunchPrintView(additionalScriptFiles, beforeInitFnName, beforeInitFnArgsObj, title, bEnableGantt, optGanttDelegateNames, optInitTableViewParamsFnName, optInitTableViewParamsFnArgsObj, optInitGanttStylesFnName, optInitGanttStylesFnArgsObj): void; + GetAllDataJson(fnOnFinished, optFnGetCellStyleID?): void; + SetTableView(tableViewParams): void; + SetRowView(rowViewParams): void; + + /** Enable grid after Disable. */ + Enable(): void; + /** Covers the grid with the semi-transparent panel, preventing any operations with it. + Additionally, displays loading animated gif and optMsg as the message next to it. + If optMsg is not specified, displays "Loading..." text. */ + Disable(optMsg?: string): void; + /** Enables grid editing */ + EnableEditing(): void; + /** Disables grid editing: all the records become readonly */ + DisableEditing(): void; + /** Switches the currently selected cell into edit mode: displays edit control and sets focus into it. + Returns true if success. */ + TryBeginEdit(): boolean; + FinalizeEditing(fnContinue, fnError): void; + /** Get diff tracker object that tracks changes to the grid data. */ + GetDiffTracker(): SP.JsGrid.Internal.DiffTracker; + /** Moves focus to the JsGrid control */ + Focus(): void; + + /** Try saving the new record row (aka entry row) if it was edited. */ + TryCommitFirstEntryRecords(fnCommitComplete: { (): void }): void; + /** Removes all new record rows (aka entry rows), including unsaved and even empty ones. + The latter seems to be a bug, as I haven't found any easy way to restore the empty entry row. */ + ClearUncommitedEntryRecords(): void; + /** Returns true if there are any unsaved new record rows (aka entry rows). */ + AnyUncommitedEntryRecords(): boolean; + + + // todo + AnyUncomittedProvisionalRecords(): boolean; + + /** Gets record based on the recordKey + @recordKey internal unique id of a row. You can get recordKey from view index via GetRecordKeyByViewIndex method. */ + GetRecord(recordKey: number): IRecord; + /** Get entry record with the specified key. + Entry record is a special type of record because it represents a new record that doesn't exist yet. */ + GetEntryRecord(key): any; + /** Determine if the specified record key identifies valid entry row. */ + IsEntryRecord(recordKey: number): boolean; + /** Determine whether the specified cell is editable. */ + IsCellEditable(record: IRecord, fieldKey: string, optPaneId?): boolean; + /** Adds one of builtin row state indicator icons into the row header. + Please pass one of the values of SP.JsGrid.RowHeaderStyleId + Row header is the leftmost gray column of the table. */ + AddBuiltInRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + /** Adds the specified state into the row header. + There can be several row header states for one row. Only one is shown (according to the Priority). + Row header is the leftmost gray column of the table. */ + AddRowHeaderState(recordKey: number, rowHeaderState: SP.JsGrid.RowHeaderState): void; + /** Removes header state with specified id from the row. */ + RemoveRowHeaderState(recordKey: number, rowHeaderStateId: string): void; + + GetCheckSelectionManager(): any; + UpdateProperties(propertyUpdates, changeName, optChangeKey?): any; + GetLastRecordKey(): string; + InsertProvisionalRecordBefore(beforeRecordKey: number, newRecord, initialValues): any; + InsertProvisionalRecordAfter(afterRecordKey: number, newRecord, initialValues): any; + IsProvisionalRecordKey(recordKey: number): boolean; + InsertRecordBefore(beforeRecordKey: number, newRecord, optChangeKey?): any; + InsertRecordAfter(afterRecordKey: number, newRecord, optChangeKey?): any; + InsertHiddenRecord(recordKey: number, changeKey, optAfterRecordKey?): any; + DeleteRecords(recordKeys, optChangeKey?): any; + IndentRecords(recordKeys, optChangeKey?): any; + OutdentRecords(recordKeys, optChangeKey?): any; + ReorderRecords(beginRecordKey: number, endRecordKey: number, afterRecordKey: number, bSelectAfterwards: boolean): any; + GetContiguousRowSelectionWithoutEntryRecords(): { begin; end; keys }; + CanMoveRecordsUpByOne(recordKeys): boolean; + CanMoveRecordsDownByOne(recordKeys): boolean; + MoveRecordsUpByOne(recordKeys): any; + MoveRecordsDownByOne(recordKeys): any; + GetReorderRange(recordKeys): any; + GetNodeExpandCollapseState(recordKey): any; + ToggleExpandCollapse(recordKey: number): void; + + /** Attach event handler to a particular event type */ + AttachEvent(eventType: JsGrid.EventType, fnOnEvent: { (args: IEventArgs): void }): void; + /** Detach a previously set event handler */ + DetachEvent(eventType: JsGrid.EventType, fnOnEvent): void; + + /** Set a delegate. Delegates are way to replace default functionality with custom one. */ + SetDelegate(delegateKey: JsGrid.DelegateType, fn): void; + /** Get current delegate. */ + GetDelegate(delegateKey: JsGrid.DelegateType): any; + + /** Re-render the specified row in the view. */ + RefreshRow(recordKey: number): void; + /** Re-render all rows in the view. + It can be used e.g. if you have some custom display controls and they are rendered differently depending on some external settings. + In this case, if you update the external settings, obviously you have to then update the view for these settings to take effect. */ + RefreshAllRows(): void; + /** Clears undo queue, and also differencies tracker state and versions manager state. */ + ClearChanges(): void; + + GetGanttZoomLevel(): any; + SetGanttZoomLevel(level: any): void; + ScrollGanttToDate(date): void; + + /** Get top record view index. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRecordIndex(): number; + /** Get number of rows displayed in the current view. */ + GetViewRecordCount(): number; + /** Get record key for a row that is specified by the viewIdx. + viewIdx - index of the row in the view, use GetTopRecordIndex to get the first one. + Returns recordKey, which is a unique numeric identifier of a row within a dataset. + Main difference between viewIdx and recordKey is that viewIdx is only unique within a view, + e.g. if you do paging, it can be same for different records. + */ + GetRecordKeyByViewIndex(viewIdx: number): number; + /** Opposite to GetRecordKeyByViewIndex, resolves the view index of the record based on record key. + recordKey - unique numeric identifier of a row in the current dataset. + Returns viewIdx - index of the row in the current view */ + GetViewIndexOfRecord(recordKey: number): number; + /** Get top row index. Usually returns 0. + You can then use GetRecordKeyByViewIndex to convert this value into the recordKey. */ + GetTopRowIndex(): number; + + GetOutlineLevel(record): any; + GetSplitterPosition(): any; + SetSplitterPosition(pos): void; + GetLeftColumnIndex(optPaneId?): any; + EnsurePaneWidth(): void; + + /** Show a previously hidden column at a specified position. + If atIdx is not defined, column will be shown at it's previous position. */ + ShowColumn(columnKey: string, atIdx?: number): void; + /** Hide the specified column from grid */ + HideColumn(columnKey: string): void; + /** Update column descriptions */ + UpdateColumns(columnInfoCollection: ColumnInfoCollection): void; + GetColumns(optPaneId?): ColumnInfo[]; + /** Get ColumnInfo object by fieldKey + @fieldKey when working with SharePoint data sources, fieldKey corresponds to field internal name */ + GetColumnByFieldKey(fieldKey: string, optPaneId?): ColumnInfo; + /** Adds a column, based on the specified grid field */ + AddColumn(columnInfo: ColumnInfo, gridField: GridField): void; + + /** Switches column header in rename mode, showing textbox and thus giving the user possibility to rename this column. */ + RenameColumn(columnKey: string): void; + /** Shows a dialog where user can reorder columns and change their widths. */ + ShowColumnConfigurationDialog(): void; + + + /** Returns true, if there are any errors in the JsGrid */ + AnyErrors(): boolean; + /** Returns true, if there are any errors in a specified row */ + AnyErrorsInRecord(recordKey: number): boolean; + /** Set error for the specified by recordKey and fieldKey cell. + Returns id of the error, so that later you can clear the error using this id. */ + SetCellError(recordKey: number, fieldKey: string, errorMessage: string): number; + /** Set error for the specified by recordKey row. + In the leftmost column of this row, exclamation mark error indicator will appear. + Clicking on this indicator will cause the specified error message appear in form of a reddish tooltip. + Returns id of the error, so that later you can clear the error using this id. */ + SetRowError(recordKey: number, errorMessage: string): number; + /** Clear specified by id error that was previously set on the specified by recordKey and fieldKey cell. */ + ClearCellError(recordKey: number, fieldKey: string, id: number): void; + /** Clear all errors in the specified cell. */ + ClearAllErrorsOnCell(recordKey: number, fieldKey: string): void; + /** Clear specified by id error that was previously set on the specified by recordKey row. */ + ClearRowError(recordKey: number, id: number): void; + /** Clear all errors in the specified row. */ + ClearAllErrorsOnRow(recordKey: number): void; + /** Get error message for the specified cell. + If many errors are set on the cell, only first is returned. + If there are no errors in the cell, returns null. */ + GetCellErrorMessage(recordKey: number, fieldKey: string): string; + /** Get error message for the specified row. + If many errors are set on the row, only first is returned. + If there are no errors in the row, returns null. */ + GetRowErrorMessage(recordKey: number): string; + /** This method is used mostly when you have a rather tall JSGrid and you want to ensure that user sees + that some error has occured. + You can specify the minId or/and filter function. + If minId is specified, method searches for an error with first id which is greater than minId. + Scrolls to the Returns the id of the found record. + If there aren't any errors, that satisfy the conditions, method does nothing and returns null. */ + ScrollToAndExpandNextError(minId?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }): any; + /** Same as ScrollToAndExpandNextError, but searches within the specified record. + recordKey should be not null, otherwise you'll get an exception. + bDontExpand controls whether the error tooltip will be shown (if bDontExpand=true, tooltip will not be shown). */ + ScrollToAndExpandNextErrorOnRecord(minId?: number, recordKey?: number, fnFilter?: { (recordKey: number, fieldKey: string, id: number): boolean }, bDontExpand?: boolean): any; + + GetFocusedItem(): any; + SendKeyDownEvent(eventInfo:Sys.UI.DomEvent): any; + /** Moves cursor to entry record (the row that is used to add new records) */ + JumpToEntryRecord(): void; + + SelectRowRange(rowIdx1, rowIdx2, bAppend, optPaneId?): void; + SelectColumnRange(colIdx1, colIdx2, bAppend, optPaneId?): void; + SelectCellRange(rowIdx1, rowIdx2, colIdx1, colIdx2, bAppend, optPaneId): void; + SelectRowRangeByKey(rowKey1, rowKey2, bAppend, optPaneId?): void; + SelectColumnRangeByKey(colKey1, colKey2, bAppend, optPaneId?): void; + SelectCellRangeByKey(recordKey1: string, recordKey2: string, colKey1, colKey2, bAppend, optPaneId?): void; + + ChangeKeys(oldKey, newKey): void; + GetSelectedRowRanges(optPaneId?): any; + GetSelectedColumnRanges(optPaneId?): any; + GetSelectedRanges(optPaneId?): any; + MarkPropUpdateInvalid(recordKey: number, fieldKey, changeKey, optErrorMsg?): any; + GetCurrentChangeKey(): any; + CreateAndSynchronizeToNewChangeKey(): any; + CreateDataUpdateCmd(bUseCustomInitialUpdate: boolean): any; + IsChangeKeyApplied(changeKey): any; + GetChangeKeyForVersion(version): any; + TryReadPropForChangeKey(recordKey: number, fieldKey, changeKey): any; + GetUnfilteredHierarchyMap(): any; + GetHierarchyState(bDecompressGuidKeys: boolean): any; + IsGroupingRecordKey(recordKey: number): boolean; + IsGroupingColumnKey(recordKey: number): boolean; + GetSelectedRecordKeys(bDuplicatesAllowed: boolean): any; + /** Cut data from currently selected cells into the clipboard. + Will not work if current selection contains entry row or readonly cells. */ + CutToClipboard(): void; + /** Copy data from currently selected cells into the clipboard. */ + CopyToClipboard(): void; + /** Paste data from clipboard into currently selected cells. */ + PasteFromClipboard(): void; + TryRestoreFocusAfterInsertOrDeleteColumns(origFocus): void; + /** Get undo manager for performing undo/redo operations programmatically. */ + GetUndoManager(): SP.JsGrid.CommandManager; + /** Gets number of records visible in the current view, including the entry row. */ + GetVisibleRecordCount(): number; + /** Returns index of the system RecordIndicatorCheckBoxColumn. If not present in the view, returns null. */ + GetRecordIndicatorCheckBoxColumnIndex(): number; + /** Determines if the specified record is visible in the current view. */ + IsRecordVisibleInView(recordKey: number): boolean; + GetHierarchyQueryObject(): any; + GetSpCsrRenderCtx(): any; + } + + export interface IChangeKey { + Reserve(): void; + Release(): void; + GetVersionNumber(): number; + CompareTo(changeKey: IChangeKey): number; + } + + export enum EventType { + OnCellFocusChanged, + OnRowFocusChanged, + OnCellEditBegin, + OnCellEditCompleted, + OnRightClick, + OnPropertyChanged, + OnRecordInserted, + OnRecordDeleted, + OnRecordChecked, + OnCellErrorStateChanged, + OnEntryRecordAdded, + OnEntryRecordCommitted, + OnEntryRecordPropertyChanged, + OnRowErrorStateChanged, + OnDoubleClick, + OnBeforeGridDispose, + OnSingleCellClick, + OnInitialChangesForChangeKeyComplete, + OnVacateChange, + OnGridErrorStateChanged, + OnSingleCellKeyDown, + OnRecordsReordered, + OnBeforePropertyChanged, + OnRowEscape, + OnBeginRenameColumn, + OnEndRenameColumn, + OnPasteBegin, + OnPasteEnd, + OnBeginRedoDataUpdateChange, + OnBeginUndoDataUpdateChange + } + + export enum DelegateType { + ExpandColumnMenu, + AddColumnMenuItems, + Sort, + Filter, + InsertRecord, + DeleteRecords, + IndentRecords, + OutdentRecords, + IsRecordInsertInView, + ExpandDelayLoadedHierarchyNode, + AutoFilter, + ExpandConflictResolution, + GetAutoFilterEntries, + LaunchFilterDialog, + ShowColumnConfigurationDialog, + GetRecordEditMode, + GetGridRowStyleId, + CreateEntryRecord, + TryInsertEntryRecord, + WillAddColumnMenuItems, + NextPage, + AddNewColumn, + RemoveColumnFromView, + ReorderColumnPositionInView, + TryCreateProvisionalRecord, + CanReorderRecords, + AddNewColumnMenuItems, + TryBeginPaste, + AllowSelectionChange, + GetFieldEditMode, + GetFieldReadOnlyActiveState, + OnBeforeRecordReordered + } + + export enum ClickContext { + SelectAllSquare, + RowHeader, + ColumnHeader, + Cell, + Gantt, + Other + } + + export class RowHeaderState { + constructor(id: string, img: SP.JsGrid.Image, priority: SP.JsGrid.RowHeaderStatePriorities, tooltip: string, fnOnClick: { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }); + GetId(): string; + GetImg(): SP.JsGrid.Image; + GetPriority(): SP.JsGrid.RowHeaderStatePriorities; + GetOnClick(): { (eventInfo:Sys.UI.DomEvent, recordKey: number): void }; + GetTooltip(): string; + toString(): string; + } + + export class Image { + /** optOuterCssNames and optImgCssNames are strings that contain css class names separated by spaces. + optImgCssNames are applied to the img tag. + if bIsClustered, image is rendered inside div, and optOuterCssNames are applied to the div. */ + constructor(imgSrc: string, bIsClustered: boolean, optOuterCssNames: string, optImgCssNames: string, bIsAnimated: boolean); + imgSrc: string; + bIsClustered: boolean; + optOuterCssNames: string; + imgCssNames: string; + bIsAnimated: boolean; + /** Renders the image with specified alternative text and on-click handler. + If bHideTooltip == false, then alternative text is also shown as the tooltip (title attribute). */ + Render(altText: string, clickFn: { (eventInfo:Sys.UI.DomEvent): void }, bHideTooltip: boolean): HTMLElement; + } + + export interface IEventArgs { } + export module EventArgs { + export class OnEntryRecordAdded implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + + export class CellFocusChanged implements IEventArgs { + constructor(newRecordKey: number, newFieldKey: string, oldRecordKey: number, oldFieldKey: string); + newRecordKey: number; + newFieldKey: string; + oldRecordKey: number; + oldFieldKey: string; + } + export class RowFocusChanged implements IEventArgs { + constructor(newRecordKey: number, oldRecordKey: number); + newRecordKey: number; + oldRecordKey: number; + } + export class CellEditBegin implements IEventArgs { + constructor(recordKey: number, fieldKey: string); + recordKey: number; + fieldKey: string; + } + export class CellEditCompleted implements IEventArgs { + constructor(recordKey: number, fieldKey: string, changeKey: JsGrid.IChangeKey, bCancelled: boolean); + recordKey: number; + fieldKey: string; + changeKey: JsGrid.IChangeKey; + bCancelled: boolean; + } + export class Click implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, context: JsGrid.ClickContext, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + context: JsGrid.ClickContext; + recordKey: number; + fieldKey: string; + } + export class PropertyChanged implements IEventArgs { + constructor(recordKey: number, fieldKey: string, oldProp: SP.JsGrid.Internal.PropertyUpdate, newProp: SP.JsGrid.Internal.PropertyUpdate, propType: SP.JsGrid.IPropertyType, changeKey: SP.JsGrid.IChangeKey, validationState: SP.JsGrid.ValidationState); + recordKey: number; + fieldKey: string; + oldProp: SP.JsGrid.Internal.PropertyUpdate; + newProp: SP.JsGrid.Internal.PropertyUpdate; + propType: SP.JsGrid.IPropertyType; + changeKey: SP.JsGrid.IChangeKey; + validationState: SP.JsGrid.ValidationState; + } + export class RecordInserted implements IEventArgs { + constructor(recordKey, recordIdx, afterRecordKey, changeKey); + recordKey: number; + recordIdx: number; + afterRecordKey: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordDeleted implements IEventArgs { + constructor(recordKey, recordIdx, changeKey); + recordKey: number; + recordIdx: number; + changeKey: JsGrid.IChangeKey; + } + export class RecordChecked implements IEventArgs { + constructor(recordKeySet: SP.Utilities.Set, bChecked: boolean); + recordKeySet: SP.Utilities.Set; + bChecked: boolean; + } + export class OnCellErrorStateChanged implements IEventArgs { + constructor(recordKey, fieldKey, bAddingError, bCellCurrentlyHasError, bCellHadError, errorId); + recordKey: number; + fieldKey: string; + bAddingError: boolean; + bCellCurrentlyHasError: boolean; + bCellHadError: boolean; + errorId: number; + } + export class OnRowErrorStateChanged implements IEventArgs { + constructor(recordKey, bAddingError, bErrorCurrentlyInRow, bRowHadError, errorId, message); + recordKey: number; + bAddingError: boolean; + bErrorCurrentlyInRow: boolean; + bRowHadError: boolean; + errorId: number; + message: string; + } + export class OnEntryRecordCommitted implements IEventArgs { + constructor(origRecKey: string, recordKey: number, changeKey: JsGrid.IChangeKey); + originalRecordKey: number; + recordKey: number; + changeKey: JsGrid.IChangeKey + } + export class SingleCellClick implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class PendingChangeKeyInitiallyComplete implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class VacateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class GridErrorStateChanged implements IEventArgs { + constructor(bAnyErrors: boolean); + bAnyErrors: boolean; + } + export class SingleCellKeyDown implements IEventArgs { + constructor(eventInfo:Sys.UI.DomEvent, recordKey: number, fieldKey: string); + eventInfo:Sys.UI.DomEvent; + recordKey: number; + fieldKey: string; + } + export class OnRecordsReordered implements IEventArgs { + constructor(recordKeys: string[], changeKey: JsGrid.IChangeKey); + reorderedKeys: string[]; + changeKey: JsGrid.IChangeKey; + } + export class OnRowEscape implements IEventArgs { + constructor(recordKey: number); + recordKey: number; + } + export class OnEndRenameColumn implements IEventArgs { + constructor(columnKey: string, originalColumnTitle: string, newColumnTitle: string); + columnKey: string; + originalColumnTitle: string; + newColumnTitle: string; + } + export class OnBeginRedoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + export class OnBeginUndoDataUpdateChange implements IEventArgs { + constructor(changeKey: JsGrid.IChangeKey); + changeKey: JsGrid.IChangeKey + } + + } + + export module JsGridControl { + export class Parameters { + tableCache: SP.JsGrid.TableCache; + name: any; // TODO + bNotificationsEnabled: boolean; + styleManager: IStyleManager; + minHeaderHeight: number; + minRowHeight: number; + commandMgr: SP.JsGrid.CommandManager; + enabledRowHeaderAutoStates: SP.Utilities.Set; + } + } + + export class CommandManager { + // todo + } + + export class TableCache { + // todo + } + + export interface IStyleManager { + gridPaneStyle: IStyleType.GridPane; + columnHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + rowHeaderStyleCollection: { + normal: IStyleType.Header; + normalHover: IStyleType.Header; + partSelected: IStyleType.Header; + partSelectedHover: IStyleType.Header; + allSelected: IStyleType.Header; + allSelectedHover: IStyleType.Header; + }; + splitterStyleCollection: { + normal: IStyleType.Splitter; + normalHandle: IStyleType.SplitterHandle; + hover: IStyleType.Splitter; + hoverHandle: IStyleType.SplitterHandle; + dra: IStyleType.Splitter; + dragHandle: IStyleType.SplitterHandle; + }; + defaultCellStyle: IStyleType.Cell; + readOnlyCellStyle: IStyleType.Cell; + readOnlyFocusedCellStyle: IStyleType.Cell; + timescaleTierStyle: IStyleType.TimescaleTier; + groupingStyles: any[]; + widgetDockStyle: IStyleType.Widget; + widgetDockHoverStyle: IStyleType.Widget; + widgetDockPressedStyle: IStyleType.Widget; + RegisterCellStyle(styleId: string, cellStyle: IStyleType.Cell): void; + GetCellStyle(styleId: string): IStyleType.Cell; + UpdateSplitterStyleFromCss(styleObject: IStyleType.Splitter, splitterStyleNameCollection): void; + UpdateHeaderStyleFromCss(styleObject: IStyleType.Header, headerStyleNameCol): void; + UpdateGridPaneStyleFromCss(styleObject: IStyleType.GridPane, gridStyleNameCollection): void; + UpdateDefaultCellStyleFromCss(styleObject: IStyleType.Cell, cssClass): void; + UpdateGroupStylesFromCss(styleObject, prefix): void; + } + + export interface IStyleType { } + export module IStyleType { + export interface Splitter extends IStyleType { + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + } + export interface SplitterHandle extends IStyleType{ + outerBorderColor: any; + leftInnerBorderColor: any; + innerBorderColor: any; + backgroundColor: any; + gripUpperColor: any; + gripLowerColor: any; + } + export interface GridPane { + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + backgroundColor: any; + columnDropIndicatorColor: any; + rowDropIndicatorColor: any; + linkColor: any; + visitedLinkColor: any; + copyRectForeBorderColor: any; + copyRectBackBorderColor: any; + focusRectBorderColor: any; + selectionRectBorderColor: any; + selectedCellBgColor: any; + readonlySelectionRectBorderColor: any; + changeHighlightCellBgColor: any; + fillRectBorderColor: any; + errorRectBorderColor: any; + } + export interface Header { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + eyeBrowBorderColor: any; + eyeBrowColor: any; + menuColor: any; + menuBorderColor: any; + resizeColor: any; + resizeBorderColor: any; + menuHoverColor: any; + menuHoverBorderColor: any; + resizeHoverColor: any; + resizeHoverBorderColor: any; + eyeBrowHoverColor: any; + eyeBrowHoverBorderColor: any; + elementClickColor: any; + elementClickBorderColor: any; + } + export interface Cell extends IStyleType { + /** -> CSS font-family */ + font: any; + /** -> CSS font-size */ + fontSize: any; + /** -> CSS font-weight */ + fontWeight: any; + /** -> CSS font-style */ + fontStyle: any; + /** -> CSS color */ + textColor: any; + /** -> CSS background-color */ + backgroundColor: any; + /** -> CSS text-align */ + textAlign: any; + } + export interface Widget { + backgroundColor: any; + borderColor: any; + } + export interface RowHeaderStyle { + backgroundColor: any; + outerBorderColor: any; + innerBorderColor: any; + } + export interface TimescaleTier { + font: any; + fontSize: any; + fontWeight: any; + textColor: any; + backgroundColor: any; + verticalBorderColor: any; + verticalBorderStyle: any; + horizontalBorderColor: any; + horizontalBorderStyle: any; + outerBorderColor: any; + todayLineColor: any; + } + } + + export class Style { + + static Type: { + Splitter: IStyleType.Splitter; + SplitterHandle: IStyleType.SplitterHandle; + GridPane: IStyleType.GridPane; + Header: IStyleType.Header; + RowHeaderStyle: IStyleType.RowHeaderStyle; + TimescaleTier: IStyleType.TimescaleTier; + Cell: IStyleType.Cell; + Widget: IStyleType.Widget; + }; + + static SetRTL: { (rtlObject): void; }; + static MakeJsGridStyleManager: { (): IStyleManager }; + static CreateStyleFromCss: { (styleType: IStyleType, cssStyleName: string, optExistingStyle, optClassId): any; }; + static CreateStyle: { (styleType: IStyleType, styleProps: any): any; }; + static MergeCellStyles: { (majorStyle, minorStyle): any; }; + static ApplyCellStyle: { (td, style): void; }; + static ApplyRowHeaderStyle: { (domObj, style, fnGetHeaderSibling): void; }; + static ApplyCornerHeaderBorderStyle: { (domObj, colStyle, rowStyle): void; }; + static ApplyHeaderInnerBorderStyle: { (domObj, bIsRowHeader, headerObject): void }; + static ApplyColumnContextMenuStyle: { (domObj, style): void }; + static ApplySplitterStyle: { (domObj, style): void }; + static MakeBorderString: { (width: number, style: string, color: string): string }; + static GetCellStyleDefaultBackgroundColor: { (): string }; + + } + + export class ColumnInfoCollection { + constructor(colInfoArray: any[]); + GetColumnByKey(key: string): any; + GetColumnArray(bVisibleOnly?: boolean): any[]; + GetColumnMap(): { [key: string]: any; }; + AppendColumn(colInfo: any): void; + InsertColumnAt(idx: number, colInfo: any): void; + RemoveColumn(key: string): void; + /** Returns null if the specified column is not found or hidden. */ + GetColumnPosition(key: string): number; + } + + export class ColumnInfo { + constructor(name: string, imgSrc: string, key: string, width: number); + /** Column title */ + name: string; + /** Column image URL. + If not null, the column header cell will show the image instead of title text. + If the title is defined at the same time as the imgSrc, the title will be shown as a tooltip. */ + imgSrc: string; + /** Custom image HTML. + If you define this in addition to the imgSrc attribute, then instead of standard img tag + the custom HTML defined by this field will be used. */ + imgRawSrc: string; + /** Column identifier */ + columnKey: string; + /** Field keys of the fields, that are displayed in this column */ + fieldKeys: string[]; + /** Width of the column */ + width: number; + bOpenMenuOnContentClick: boolean; + /** always returns 'column' */ + ColumnType(): string; + /** true by default */ + isVisible: boolean; + /** true by default */ + isHidable: boolean; + /** true by default */ + isResizable: boolean; + /** true by default */ + isSortable: boolean; + /** true by default */ + isAutoFilterable: boolean; + /** false by default */ + isFooter: boolean; + /** determine whether the cells in this column should be clickable */ + fnShouldLinkSingleValue: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): boolean }; + /** if a particular cell is determined as clickable by fnShouldLinkSingleValue, this function will be called when the cell is clicked */ + fnSingleValueClicked: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): void }; + /** this is used when you need to make some of the cells in the column readonly, but at the same time keep others editable */ + fnGetCellEditMode: { (record: IRecord, fieldKey: string): JsGrid.EditMode }; + /** this function should return name of the display control for the given cell in the column + the name should be previously associated with the display control via SP.JsGrid.PropertyType.Utils.RegisterDisplayControl method */ + fnGetDisplayControlName: { (record: IRecord, fieldKey: string): string }; + /** this function should return name of the edit control for the given cell in the column + the name should be previously associated with the edit control via SP.JsGrid.PropertyType.Utils.RegisterEditControl method */ + fnGetEditControlName: { (record: IRecord, fieldKey: string): string }; + /** set widget control names for a particular cell + widgets are basically in-cell buttons with associated popup controls, e.g. date selector or address book button + standard widget ids are defined in the SP.JsGrid.WidgetControl.Type enumeration + it is also possible to create your own widgets + usually this function is not used, and instead, widget control names are determined via PropertyType + */ + fnGetWidgetControlNames: { (record: IRecord, fieldKey: string): string[] }; + /** this function should return id of the style for the given cell in the column + styles and their ids are registered for a JsGridControl via jsGridParams.styleManager.RegisterCellStyle method */ + fnGetCellStyleId: { (record: IRecord, fieldKey: string, dataValue: any): string }; + /** set custom tooltip for the given cell in the column. by default, localized value is displayed as the tooltip */ + fnGetSingleValueTooltip: { (record: IRecord, fieldKey: string, dataValue: any, localizedValue: any): string }; + } + + + export interface IRecord { + /** True if this is an entry row */ + bIsNewRow: boolean; + + /** Please use SetProp and GetProp */ + properties: { [fieldKey: string]: IPropertyBase }; + + /** returns recordKey */ + key(): number; + /** returns raw data value for the specified field */ + GetDataValue(fieldKey: string): any; + /** returns localized text value for the specified field */ + GetLocalizedValue(fieldKey: string): string; + /** returns true if data value for the specified field is available */ + HasDataValue(fieldKey: string): boolean; + /** returns true if localized text value for the specified field is available */ + HasLocalizedValue(fieldKey: string): boolean; + + GetProp(fieldKey: string): IPropertyBase; + SetProp(fieldKey: string, prop: IPropertyBase): void; + + /** Update the specified field with the specified value */ + AddFieldValue(fieldKey: string, value: any): void; + /** Removes value of the specified field. + Does not refresh the view. */ + RemoveFieldValue(fieldKey: string): void; + } + + + export class RecordFactory { + constructor(gridFieldMap: any, keyColumnName: string, fnGetPropType: any); + gridFieldMap: any; + /** Create a new record */ + MakeRecord(dataPropMap, localizedPropMap, bKeepRawData): IRecord; + } + + export interface IPropertyBase { + HasLocalizedValue(): boolean; + HasDataValue(): boolean; + Clone(): IPropertyBase; + /** dataValue actually is cloned */ + Update(dataValue: any, localizedValue: string): void; + GetLocalized(): string; + GetData(): any; + } + + export class Property { + static MakeProperty(dataValue: any, localizedValue: string, bHasDataValue: boolean, bHasLocalizedValue: boolean, propType): IPropertyBase; + static MakePropertyFromGridField(gridField: any, dataValue: any, localizedVal: string, optPropType?): IPropertyBase; + } + + export class GridField { + constructor(key: string, hasDataValue: boolean, hasLocalizedValue: boolean, textDirection, defaultCellStyleId, editMode, dateOnly, csrInfo); + key: string; + hasDataValue: boolean; + hasLocalizedValue: boolean; + textDirection: any; + dateOnly: boolean; + csrInfo: any; + GetEditMode(): any; + SetEditMode(mode: any): void; + GetDefaultCellStyleId(): any; + CompareSingleDataEqual(dataValue1, dataValue2): boolean; + GetPropType(): any; + GetSingleValuePropType(): any; + GetMultiValuePropType(): any; + SetSingleValuePropType(svPropType: any): void; + SetIsMultiValue(listSeparator: any): void; + GetIsMultiValue(): boolean; + } + + export interface IEditActorGridContext { + jsGridObj: JsGridControl; + parentNode: HTMLElement; + styleManager: IStyleManager; + RTL: any; + emptyValue: any; + bLightFocus: boolean; + OnKeyDown: { (domEvent: Sys.UI.DomEvent): void; }; + } + + export interface IEditControlGridContext extends IEditActorGridContext { + OnActivateActor(): void; + OnDeactivateActor():void; + } + + export interface IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + } + + export interface ILookupPropertyType extends IPropertyType { + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + } + + export interface IMultiValuePropertyType extends IPropertyType { + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + + export class PropertyType { + /** Lookup property type factory, based on SP.JsGrid.PropertyType.LookupTable class. + displayCtrlName should be one of the following: SP.JsGrid.DisplayControl.Type.Image, SP.JsGrid.DisplayControl.Type.ImageText or SP.JsGrid.DisplayControl.Type.Text + */ + static RegisterNewLookupPropType(id: string, items: any[], displayCtrlName: string, bLimitToList: boolean): void; + + /** Register a custom property type. */ + static RegisterNewCustomPropType(propType: IPropertyType, displayCtrlName: string, editControlName: string, widgetControlNames: string[]): void; + + /** Register a custom property type, where display and edit controls, and also widgets, are derived from the specified parent property type. */ + static RegisterNewDerivedCustomPropType(propType: IPropertyType, baseTypeName: string): void; + } + + export module PropertyType { + export class String implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + toString(): string; + } + export class LookupTable implements ILookupPropertyType { + constructor(items: any[], id: string, bLimitToList: boolean); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + GetItems(fnCallback: any): void; + DataToLocalized(dataValue: any): string; + LocalizedToData(localized: string): any; + GetImageSource(record: IRecord, dataValue: any): string; + GetStyleId(dataValue: any): string; + GetIsLimitedToList(): boolean; + GetSerializableLookupPropType(): { items: any[]; id: string; bLimitToList: boolean }; + + } + export class CheckBoxBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class DropDownBoolean implements IPropertyType { + constructor(); + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + DataToLocalized(dataValue: any): string; + GetBool(dataValue: any): boolean; + toString(): string; + } + export class MultiValuePropType implements IMultiValuePropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bMultiValue: boolean; + separator: string; + singleValuePropType: string; + GetSerializableMultiValuePropType(): { singleValuePropTypeID: string; separatorChar: string; bDelayInit: boolean; }; + InitSingleValuePropType(): void; + LocStrToLocStrArray(locStr: string): string[]; + LocStrArrayToLocStr(locStrArray: string[]): string; + } + export class HyperLink implements IPropertyType { + ID: string; + BeginValidateNormalizeConvert(recordKey: number, fieldKey: string, newValue: any, bIsLocalized: boolean, fnCallback: { (args: { isValid: boolean; dataValue: any; normalizedLocValue: string }): void; }, fnError: any): void; + bHyperlink: boolean; + DataToLocalized(dataValue: any): string; + GetAddress(dataValue: any): string; + /** Returns string like this: '"http://site.com, Site title"' */ + GetCopyValue(record: IRecord, dataValue: any, locValue: string): string; + toString(): string; + } + + + export class Utils { + static RegisterDisplayControl(name: string, singleton, requiredFunctionNames: string[]); + static RegisterEditControl(name: string, factory: (gridContext: IEditControlGridContext, gridTextInputElement:HTMLElement) => IEditControl, requiredFunctionNames: string[]); + static RegisterWidgetControl(name: string, factory: { (ddContext): IPropertyType; }, requiredFunctionNames: string[]); + + static UpdateDisplayControlForPropType(propTypeName: string, displayControlType: string); + } + } + + export module WidgetControl { + export class Type { + static Demo: string; + static Date: string; + static AddressBook: string; + static Hyperlink: string; + } + } + + export module Internal { + export class DiffTracker { + constructor(objBag, fnGetChange); + ExternalAPI: { + AnyChanges(): boolean; + ChangeKeySliceInfo(): any; + ChangeQuery(): any; + EventSliceInfo(): any; + GetChanges(optStartEvent, optEndEvent, optRecordKeys, bFirstStartEvent: boolean, bStartInclusive: boolean, bEndInclusive: boolean, bIncludeInvalidPropUpdates: boolean, bLastEndEvent: boolean): any; + GetChangesAsJson(changeQuery, optfnPreProcessUpdateForSerialize?): string; + GetUniquePropertyChanges(changeQuery, optfnFilter): any; + RegisterEvent(changeKey: IChangeKey, eventObject): void; + UnregisterEvent(changeKey: IChangeKey, eventObject): void; + }; + Clear(): void; + NotifySynchronizeToChange(changeKey: IChangeKey): void; + NotifyRollbackChange(changeKey: IChangeKey): void; + NotifyVacateChange(changeKey: IChangeKey): void; + } + + export class PropertyUpdate implements IValue { + constructor(data: any, localized: string); + data: any; + localized: string; + } + } + + export interface IEditActorCellContext { + propType:IPropertyType; + originalValue:IValue; + record:IRecord; + column:ColumnInfo; + field:GridField; + fieldKey:string; + cellExpandSpace:{ left:number; top:number; fight:number; bottom:number; }; + SetCurrentValue(value): void; + } + + export interface IEditControlCellContext extends IEditActorCellContext{ + cellWidth: number; + cellHeight: number; + cellStyle: any; //TODO: Determine correct type + cellRect:any; + NotifyExpandControl(): void; + NotifyEditComplete(): void; + Show(element: HTMLElement): void; + Hide(element: HTMLElement): void; + } + + + export module EditControl { + + } + + export interface IEditControl { + SupportedWriteMode?: SP.JsGrid.EditActorWriteType; + SupportedReadMode?: SP.JsGrid.EditActorReadType; + GetCellContext? (): IEditControlCellContext; + GetOriginalValue?():IValue; + SetValue?(value:IValue):void; + Dispose():void; + GetInputElement?():HTMLElement; + Focus?(eventInfo:Sys.UI.DomEvent):void; + BindToCell (cellContext: IEditControlCellContext):void; + OnBeginEdit (eventInfo: Sys.UI.DomEvent):void; + Unbind():void; + OnEndEdit():void; + OnCellMove?():void; + OnValueChanged?(newValue: IValue):void; + IsCurrentlyUsingGridTextInputElement?(): boolean; + SetSize?(width:number, height:number):void; + } + + } + + export module Utilities { + export class Set { + constructor(items?: { [item: string]: number }); + constructor(items?: { [item: number]: number }); + /** Returns true if the set is empty */ + IsEmpty(): boolean; + /** Returns first item in the set */ + First(): any; + /** Returns the underlying collection of items as dictionary. + Items are the keys, and values are always 1. + So the return value may be either { [item: string]: number } or { [item: number]: number } */ + GetCollection(): any; + /** Returns all items from the set as an array */ + ToArray(): any[]; + /** Adds all items from array to the set, and returns the set */ + AddArray(array: any[]): SP.Utilities.Set; + /** Adds an item to the set */ + Add(item: any): any; + /** Removes the specified item from the set and returns the removed item */ + Remove(item: any): any; + /** Clears all the items from set */ + Clear(): SP.Utilities.Set; + /** Returns true if item exists in this set */ + Contains(item: any): boolean; + /** Returns a copy of this set */ + Clone(): SP.Utilities.Set; + /** Returns a set that contains all the items that exist only in one of the sets (this and other), but not in both */ + SymmetricDifference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a set that contains all the items that are in this set but not in the otherSet */ + Difference(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains items from this set and otherSet */ + Union(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Adds all items from otherSet to this set, and returns this set */ + UnionWith(otherSet: SP.Utilities.Set): SP.Utilities.Set; + /** Returns a new set, that contains only items that exist both in this set and the otherSet */ + Intersection(otherSet: SP.Utilities.Set): SP.Utilities.Set; + } + } +} + + + + + +declare module SP { + export class GanttControl { + static WaitForGanttCreation(callack: (control: GanttControl) => void): void; + static Instances: GanttControl[]; + static FnGanttCreationCallback: { (control: GanttControl): void }[]; + + get_Columns():SP.JsGrid.ColumnInfo[]; + } +} From 1ec7dac4f93c825f3a90372de6abfe2198343358 Mon Sep 17 00:00:00 2001 From: Sam Albert Date: Tue, 26 May 2015 16:01:50 -0400 Subject: [PATCH 010/881] Updated callback buffer with rest parameters. --- node_zeromq/zmq-tests.ts | 2 +- node_zeromq/zmq.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node_zeromq/zmq-tests.ts b/node_zeromq/zmq-tests.ts index 696a98c13..a62d97a6c 100644 --- a/node_zeromq/zmq-tests.ts +++ b/node_zeromq/zmq-tests.ts @@ -19,7 +19,7 @@ function test3() { var sock = zmq.socket('push'); sock.bindSync('tcp://127.0.0.1:3000'); sock.send(['hello', 'world']); - sock.on('message', function (buffer: Buffer) { + sock.on('message', function (buffer1: Buffer, buffer2: Buffer) { // }); } diff --git a/node_zeromq/zmq.d.ts b/node_zeromq/zmq.d.ts index 8d29e0569..3ab2d1f25 100644 --- a/node_zeromq/zmq.d.ts +++ b/node_zeromq/zmq.d.ts @@ -182,7 +182,7 @@ declare module 'zmq' { * @param eventName {string} * @param callback {Function} */ - on(eventName: string, callback: (buffer: Buffer) => void): void; + on(eventName: string, callback: (...buffer: Buffer[]) => void): void; // Socket Options _fd: any; From 2f1df1f63590f9b97134414eab0ea53eea206c94 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Tue, 2 Jun 2015 12:21:16 -0400 Subject: [PATCH 011/881] Added IP and Hostname validators to Joi.d.ts --- joi/joi.d.ts | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 5e4bfc37b..3df8ada9e 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -47,11 +47,16 @@ declare module 'joi' { contextPrefix?: string; } + export interface IPOptions { + version?: Array; + cidr?: string + } + export interface ValidationError { message: string; details: ValidationErrorItem[]; - simple (): string; - annotated (): string; + simple(): string; + annotated(): string; } export interface ValidationErrorItem { @@ -82,19 +87,19 @@ declare module 'joi' { /** * Whitelists a value */ - allow(value: any, ...values : any[]): T; + allow(value: any, ...values: any[]): T; allow(values: any[]): T; /** * Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ - valid(value: any, ...values : any[]): T; + valid(value: any, ...values: any[]): T; valid(values: any[]): T; /** * Blacklists a value */ - invalid(value: any, ...values : any[]): T; + invalid(value: any, ...values: any[]): T; invalid(values: any[]): T; /** @@ -257,6 +262,16 @@ declare module 'joi' { * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. */ trim(): StringSchema; + + /** + * Requires the string value be a valid hostname. + */ + hostname(): StringSchema; + + /** + * Requires the string value to be a valid IP address. + */ + ip(options: IPOptions): StringSchema; /** * Requires the string value to be a valid uri with the passed scheme. @@ -364,7 +379,7 @@ declare module 'joi' { /** * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). */ - unknown(allow?:boolean): ObjectSchema; + unknown(allow?: boolean): ObjectSchema; } export interface BinarySchema extends AnySchema { @@ -486,5 +501,5 @@ declare module 'joi' { /** * Generates a reference to the value of the named key. */ - export function ref(key:string, options?: ReferenceOptions): Reference; + export function ref(key: string, options?: ReferenceOptions): Reference; } From cde81f5458364ef1dc43a85e1be6a9e132c94e11 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Wed, 3 Jun 2015 11:18:34 -0400 Subject: [PATCH 012/881] exported BoomError interface on Boom.d.ts --- boom/boom.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/boom/boom.d.ts b/boom/boom.d.ts index d0f05065c..e1539d21b 100644 --- a/boom/boom.d.ts +++ b/boom/boom.d.ts @@ -6,7 +6,8 @@ /// declare module Boom { - interface BoomError { + + export interface BoomError { data: any; reformat: () => void; isBoom: boolean; From 575d43c508d56b5d5fc0aa0ddc2aab93b3a3676e Mon Sep 17 00:00:00 2001 From: Gitgiddy Date: Fri, 26 Jun 2015 09:24:50 -0400 Subject: [PATCH 013/881] Extendable interfaces for require, module.require Node's `require` should implement a new interface `NodeRequire` (rather than direct signature) for specialized extension by other libraries #4740 --- node/node.d.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 0c6b42740..6d73172f8 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -27,23 +27,30 @@ declare function clearInterval(intervalId: NodeJS.Timer): void; declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; declare function clearImmediate(immediateId: any): void; -declare var require: { +interface NodeRequireFunction { (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { resolve(id:string): string; cache: any; extensions: any; main: any; -}; +} -declare var module: { +declare var require: NodeRequire; + +interface NodeModule { exports: any; - require(id: string): any; + require: NodeRequireFunction; id: string; filename: string; loaded: boolean; parent: any; children: any[]; -}; +} + +declare var module: NodeModule; // Same as module.exports declare var exports: any; From 8dd3b27579a67c878e5605b8819718a17c34cf0b Mon Sep 17 00:00:00 2001 From: Laurence Dougal Myers Date: Mon, 22 Jun 2015 17:29:18 +1000 Subject: [PATCH 014/881] Joi: update definitions to v6.5.0 --- joi/joi-tests.ts | 248 ++++++++++++++++++++++++++++++++++++---- joi/joi.d.ts | 292 ++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 491 insertions(+), 49 deletions(-) diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 26048a9dc..fc1f8ef25 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -56,6 +56,7 @@ validOpts = {allowUnknown: bool}; validOpts = {skipFunctions: bool}; validOpts = {stripUnknown: bool}; validOpts = {language: bool}; +validOpts = {presence: str}; validOpts = {context: obj}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -65,6 +66,34 @@ var renOpts: Joi.RenameOptions = null; renOpts = {alias: bool}; renOpts = {multiple: bool}; renOpts = {override: bool}; +renOpts = {ignoreUndefined: bool}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var emailOpts: Joi.EmailOptions = null; + +emailOpts = {errorLevel: num}; +emailOpts = {errorLevel: bool}; +emailOpts = {tldWhitelist: strArr}; +emailOpts = {tldWhitelist: obj}; +emailOpts = {minDomainAtoms: num}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var ipOpts: Joi.IpOptions = null; + +ipOpts = {version: str}; +ipOpts = {version: strArr}; +ipOpts = {cidr: str}; + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + +var uriOpts: Joi.UriOptions = null; + +uriOpts = {scheme: str}; +uriOpts = {scheme: exp}; +uriOpts = {scheme: strArr}; +uriOpts = {scheme: expArr}; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -144,15 +173,30 @@ module common { anySchema = anySchema.valid(x); anySchema = anySchema.valid(x, x); anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); anySchema = anySchema.invalid(x); anySchema = anySchema.invalid(x, x); anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); + anySchema = anySchema.default(); anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); anySchema = anySchema.required(); anySchema = anySchema.optional(); anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); anySchema = anySchema.description(str); anySchema = anySchema.notes(str); @@ -166,43 +210,65 @@ module common { anySchema = anySchema.options(validOpts); anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); anySchema = anySchema.concat(x); altSchema = anySchema.when(str, whenOpts); altSchema = anySchema.when(ref, whenOpts); + + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- arrSchema = Joi.array(); +arrSchema = arrSchema.sparse(); +arrSchema = arrSchema.sparse(bool); +arrSchema = arrSchema.single(); +arrSchema = arrSchema.single(bool); arrSchema = arrSchema.min(num); arrSchema = arrSchema.max(num); arrSchema = arrSchema.length(num); +arrSchema = arrSchema.unique(); -arrSchema = arrSchema.includes(numSchema); -arrSchema = arrSchema.includes(numSchema, strSchema); -arrSchema = arrSchema.includes([numSchema, strSchema]); +arrSchema = arrSchema.items(numSchema); +arrSchema = arrSchema.items(numSchema, strSchema); +arrSchema = arrSchema.items([numSchema, strSchema]); -arrSchema = arrSchema.excludes(numSchema); -arrSchema = arrSchema.excludes(numSchema, strSchema); -arrSchema = arrSchema.excludes([numSchema, strSchema]); // - - - - - - - - module common_copy_paste { // use search & replace from any - anySchema = anySchema.allow(x); - anySchema = anySchema.allow(x, x); - anySchema = anySchema.allow([x, x, x]); - anySchema = anySchema.valid(x); - anySchema = anySchema.valid(x, x); - anySchema = anySchema.valid([x, x, x]); - anySchema = anySchema.invalid(x); - anySchema = anySchema.invalid(x, x); - anySchema = anySchema.invalid([x, x, x]); - - anySchema = anySchema.default(x); + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); + + arrSchema = arrSchema.default(x); arrSchema = arrSchema.required(); arrSchema = arrSchema.optional(); @@ -238,10 +304,22 @@ module common_copy_paste { boolSchema = boolSchema.valid(x); boolSchema = boolSchema.valid(x, x); boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); boolSchema = boolSchema.invalid(x); boolSchema = boolSchema.invalid(x, x); boolSchema = boolSchema.invalid([x, x, x]); - + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); + boolSchema = boolSchema.default(x); boolSchema = boolSchema.required(); @@ -270,6 +348,7 @@ module common_copy_paste { binSchema = Joi.binary(); +binSchema = binSchema.encoding(str); binSchema = binSchema.min(num); binSchema = binSchema.max(num); binSchema = binSchema.length(num); @@ -281,10 +360,22 @@ module common { binSchema = binSchema.valid(x); binSchema = binSchema.valid(x, x); binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); binSchema = binSchema.invalid(x); binSchema = binSchema.invalid(x, x); binSchema = binSchema.invalid([x, x, x]); - + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); + binSchema = binSchema.default(x); binSchema = binSchema.required(); @@ -322,6 +413,14 @@ dateSchema = dateSchema.max(str); dateSchema = dateSchema.min(num); dateSchema = dateSchema.max(num); +dateSchema = dateSchema.min(ref); +dateSchema = dateSchema.max(ref); + +dateSchema = dateSchema.format(str); +dateSchema = dateSchema.format(strArr); + +dateSchema = dateSchema.iso(); + module common { dateSchema = dateSchema.allow(x); dateSchema = dateSchema.allow(x, x); @@ -329,10 +428,22 @@ module common { dateSchema = dateSchema.valid(x); dateSchema = dateSchema.valid(x, x); dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); dateSchema = dateSchema.invalid(x); dateSchema = dateSchema.invalid(x, x); dateSchema = dateSchema.invalid([x, x, x]); - + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); + dateSchema = dateSchema.default(x); dateSchema = dateSchema.required(); @@ -366,8 +477,18 @@ funcSchema = Joi.func(); numSchema = Joi.number(); numSchema = numSchema.min(num); +numSchema = numSchema.min(ref); numSchema = numSchema.max(num); +numSchema = numSchema.max(ref); +numSchema = numSchema.greater(num); +numSchema = numSchema.greater(ref); +numSchema = numSchema.less(num); +numSchema = numSchema.less(ref); numSchema = numSchema.integer(); +numSchema = numSchema.precision(num); +numSchema = numSchema.multiple(num); +numSchema = numSchema.positive(); +numSchema = numSchema.negative(); module common { numSchema = numSchema.allow(x); @@ -376,10 +497,22 @@ module common { numSchema = numSchema.valid(x); numSchema = numSchema.valid(x, x); numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); numSchema = numSchema.invalid(x); numSchema = numSchema.invalid(x, x); numSchema = numSchema.invalid([x, x, x]); - + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); + numSchema = numSchema.default(x); numSchema = numSchema.required(); @@ -418,12 +551,23 @@ objSchema = objSchema.length(num); objSchema = objSchema.pattern(exp, schema); +objSchema = objSchema.and(str); +objSchema = objSchema.and(str, str); objSchema = objSchema.and(str, str, str); objSchema = objSchema.and(strArr); +objSchema = objSchema.nand(str); +objSchema = objSchema.nand(str, str); +objSchema = objSchema.nand(str, str, str); +objSchema = objSchema.nand(strArr); + +objSchema = objSchema.or(str); +objSchema = objSchema.or(str, str); objSchema = objSchema.or(str, str, str); objSchema = objSchema.or(strArr); +objSchema = objSchema.xor(str); +objSchema = objSchema.xor(str, str); objSchema = objSchema.xor(str, str, str); objSchema = objSchema.xor(strArr); @@ -442,6 +586,17 @@ objSchema = objSchema.assert(ref, schema, str); objSchema = objSchema.unknown(); objSchema = objSchema.unknown(bool); +objSchema = objSchema.type(func); +objSchema = objSchema.type(func, str); + +objSchema = objSchema.requiredKeys(str); +objSchema = objSchema.requiredKeys(str, str); +objSchema = objSchema.requiredKeys(strArr); + +objSchema = objSchema.optionalKeys(str); +objSchema = objSchema.optionalKeys(str, str); +objSchema = objSchema.optionalKeys(strArr); + module common { objSchema = objSchema.allow(x); objSchema = objSchema.allow(x, x); @@ -449,10 +604,22 @@ module common { objSchema = objSchema.valid(x); objSchema = objSchema.valid(x, x); objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); objSchema = objSchema.invalid(x); objSchema = objSchema.invalid(x, x); objSchema = objSchema.invalid([x, x, x]); - + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); + objSchema = objSchema.default(x); objSchema = objSchema.required(); @@ -483,13 +650,33 @@ strSchema = Joi.string(); strSchema = strSchema.insensitive(); strSchema = strSchema.min(num); +strSchema = strSchema.min(num, str); +strSchema = strSchema.min(ref); +strSchema = strSchema.min(ref, str); strSchema = strSchema.max(num); +strSchema = strSchema.max(num, str); +strSchema = strSchema.max(ref); +strSchema = strSchema.max(ref, str); +strSchema = strSchema.creditCard(); strSchema = strSchema.length(num); +strSchema = strSchema.length(num, str); +strSchema = strSchema.length(ref); +strSchema = strSchema.length(ref, str); strSchema = strSchema.regex(exp); +strSchema = strSchema.regex(exp, str); +strSchema = strSchema.replace(exp, str); +strSchema = strSchema.replace(str, str); strSchema = strSchema.alphanum(); strSchema = strSchema.token(); strSchema = strSchema.email(); +strSchema = strSchema.email(emailOpts); +strSchema = strSchema.ip(); +strSchema = strSchema.ip(ipOpts); +strSchema = strSchema.uri(); +strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); +strSchema = strSchema.hex(); +strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); strSchema = strSchema.lowercase(); strSchema = strSchema.uppercase(); @@ -502,10 +689,22 @@ module common { strSchema = strSchema.valid(x); strSchema = strSchema.valid(x, x); strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); strSchema = strSchema.invalid(x); strSchema = strSchema.invalid(x, x); strSchema = strSchema.invalid([x, x, x]); - + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); + strSchema = strSchema.default(x); strSchema = strSchema.required(); @@ -537,6 +736,7 @@ schema = Joi.alternatives(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +Joi.validate(value, obj); Joi.validate(value, schema); Joi.validate(value, schema, validOpts); Joi.validate(value, schema, validOpts, (err, value) => { @@ -566,6 +766,8 @@ Joi.validate(value, {}); schema = Joi.compile(obj); Joi.assert(obj, schema); +Joi.assert(obj, schema, str); +Joi.assert(obj, schema, err); ref = Joi.ref(str, refOpts); ref = Joi.ref(str); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 5e4bfc37b..20ef52a66 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 +// Definitions by: Bart van der Schoor , Laurence Dougal Myers // Definitions: https://github.com/borisyankov/DefinitelyTyped // TODO express type of Schema in a type-parameter (.default, .valid, .example etc) @@ -19,7 +19,9 @@ declare module 'joi' { // when true, unknown keys are deleted (only when value is an object). Defaults to false. stripUnknown?: boolean; // overrides individual error messages. Defaults to no override ({}). - language?: Object + language?: Object; + // sets the default presence requirements. Supported modes: 'optional', 'required', and 'forbidden'. Defaults to 'optional'. + presence?: string; // provides an external data set to be used in references context?: Object; } @@ -33,6 +35,28 @@ declare module 'joi' { override?: boolean; } + export interface EmailOptions { + // Numerical threshold at which an email address is considered invalid + errorLevel?: number | boolean; + // Specifies a list of acceptable TLDs. + tldWhitelist?: string[] | Object; + // Number of atoms required for the domain. Be careful since some domains, such as io, directly allow email. + minDomainAtoms?: number; + } + + export interface IpOptions { + // One or more IP address versions to validate against. Valid values: ipv4, ipv6, ipvfuture + version ?: string | string[]; + // Used to determine if a CIDR is allowed or not. Valid values: optional, required, forbidden + cidr?: string; + } + + export interface UriOptions { + // Specifies one or more acceptable Schemes, should only include the scheme name. + // Can be an Array or String (strings are automatically escaped for use in a Regular Expression). + scheme ?: string | RegExp | Array; + } + export interface WhenOptions { // the required condition joi type. is: Schema; @@ -90,12 +114,20 @@ declare module 'joi' { */ valid(value: any, ...values : any[]): T; valid(values: any[]): T; + only(value: any, ...values : any[]): T; + only(values: any[]): T; + equal(value: any, ...values : any[]): T; + equal(values: any[]): T; /** * Blacklists a value */ invalid(value: any, ...values : any[]): T; invalid(values: any[]): T; + disallow(value: any, ...values : any[]): T; + disallow(values: any[]): T; + not(value: any, ...values : any[]): T; + not(values: any[]): T; /** * Marks a key as required which will not allow undefined as value. All keys are optional by default. @@ -112,6 +144,11 @@ declare module 'joi' { */ forbidden(): T; + /** + * Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. + */ + strip(): T; + /** * Annotates the key */ @@ -152,12 +189,28 @@ declare module 'joi' { /** * Sets the options.convert options to false which prevent type casting for the current key and any child keys. */ - strict(): T; + strict(isStrict?: boolean): T; /** * Sets a default value if the original value is undefined. + * @param value - the value. + * value supports references. + * value may also be a function which returns the default value. + * If value is specified as a function that accepts a single parameter, that parameter will be a context + * object that can be used to derive the resulting value. This clones the object however, which incurs some + * overhead so if you don't need access to the context define your method so that it does not accept any + * parameters. + * Without any value, default has no effect, except for object that will then create nested defaults + * (applying inner defaults of that object). + * + * Note that if value is an object, any changes to the object after default() is called will change the + * reference and any future assignment. + * + * Additionally, when specifying a method you must either have a description property on your method or the + * second parameter is required. */ - default(value: any): T; + default(value: any, description?: string): T; + default(): T; /** * Returns a new type that is the result of adding the rules of one type to another. @@ -169,6 +222,22 @@ declare module 'joi' { */ when(ref: string, options: WhenOptions): AlternativesSchema; when(ref: Reference, options: WhenOptions): AlternativesSchema; + + /** + * Overrides the key name in error messages. + */ + label(name: string): T; + + /** + * Outputs the original untouched value instead of the casted value. + */ + raw(isRaw?: boolean): T; + + /** + * Considers anything that matches the schema to be empty (undefined). + * @param schema - any object or joi schema to match. An undefined schema unsets that rule. + */ + empty(schema?: any) : T; } export interface BooleanSchema extends AnySchema { @@ -178,18 +247,57 @@ declare module 'joi' { export interface NumberSchema extends AnySchema { /** * Specifies the minimum value. + * It can also be a reference to another field. */ min(limit: number): NumberSchema; + min(limit: Reference): NumberSchema; /** * Specifies the maximum value. + * It can also be a reference to another field. */ max(limit: number): NumberSchema; + max(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be greater than limit. + * It can also be a reference to another field. + */ + greater(limit: number): NumberSchema; + greater(limit: Reference): NumberSchema; + + /** + * Specifies that the value must be less than limit. + * It can also be a reference to another field. + */ + less(limit: number): NumberSchema; + less(limit: Reference): NumberSchema; /** * Requires the number to be an integer (no floating point). */ integer(): NumberSchema; + + /** + * Specifies the maximum number of decimal places where: + * limit - the maximum number of decimal places allowed. + */ + precision(limit: number): NumberSchema; + + /** + * Specifies that the value must be a multiple of base. + */ + multiple(base: number): NumberSchema; + + /** + * Requires the number to be positive. + */ + positive(): NumberSchema; + + /** + * Requires the number to be negative. + */ + negative(): NumberSchema; } export interface StringSchema extends AnySchema { @@ -200,23 +308,47 @@ declare module 'joi' { /** * Specifies the minimum number string characters. + * @param limit - the minimum number of string characters required. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - min(limit: number): StringSchema; + min(limit: number, encoding?: string): StringSchema; + min(limit: Reference, encoding?: string): StringSchema; /** * Specifies the maximum number of string characters. + * @param limit - the maximum number of string characters allowed. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - max(limit: number): StringSchema; + max(limit: number, encoding?: string): StringSchema; + max(limit: Reference, encoding?: string): StringSchema; + + /** + * Requires the number to be a credit card number (Using Lunh Algorithm). + */ + creditCard(): StringSchema; /** * Specifies the exact string length required + * @param limit - the required string length. It can also be a reference to another field. + * @param encoding - if specified, the string length is calculated in bytes using the provided encoding. */ - length(limit: number): StringSchema; + length(limit: number, encoding?: string): StringSchema; + length(limit: Reference, encoding?: string): StringSchema; /** * Defines a regular expression rule. + * @param pattern - a regular expression object the string value must match against. + * @param name - optional name for patterns (useful with multiple patterns). Defaults to 'required'. */ - regex(pattern: RegExp): StringSchema; + regex(pattern: RegExp, name?: string): StringSchema; + + /** + * Replace characters matching the given pattern with the specified replacement string where: + * @param pattern - a regular expression object to match against, or a string of which all occurrences will be replaced. + * @param replacement - the string that will replace the pattern. + */ + replace(pattern: RegExp, replacement: string): StringSchema; + replace(pattern: string, replacement: string): StringSchema; /** * Requires the string value to only contain a-z, A-Z, and 0-9. @@ -231,13 +363,33 @@ declare module 'joi' { /** * Requires the string value to be a valid email address. */ - email(): StringSchema; + email(options?: EmailOptions): StringSchema; + + /** + * Requires the string value to be a valid ip address. + */ + ip(options?: IpOptions): StringSchema; + + /** + * Requires the string value to be a valid RFC 3986 URI. + */ + uri(options?: UriOptions): StringSchema; /** * Requires the string value to be a valid GUID. */ guid(): StringSchema; + /** + * Requires the string value to be a valid hexadecimal string. + */ + hex(): StringSchema; + + /** + * Requires the string value to be a valid hostname as per RFC1123. + */ + hostname(): StringSchema; + /** * Requires the string value to be in valid ISO 8601 date format. */ @@ -257,25 +409,35 @@ declare module 'joi' { * Requires the string value to contain no whitespace before or after. If the validation convert option is on (enabled by default), the string will be trimmed. */ trim(): StringSchema; - - /** - * Requires the string value to be a valid uri with the passed scheme. - */ - uri(options?: { scheme?: string }): StringSchema; } export interface ArraySchema extends AnySchema { - /** - * List the types allowed for the array value - */ - includes(type: Schema, ...types: Schema[]): ArraySchema; - includes(types: Schema[]): ArraySchema; /** - * List the types forbidden for the array values. + * Allow this array to be sparse. + * enabled can be used with a falsy value to go back to the default behavior. */ - excludes(type: Schema, ...types: Schema[]): ArraySchema; - excludes(types: Schema[]): ArraySchema; + sparse(enabled?: any): ArraySchema; + + /** + * Allow single values to be checked against rules as if it were provided as an array. + * enabled can be used with a falsy value to go back to the default behavior. + */ + single(enabled?: any): ArraySchema; + + /** + * List the types allowed for the array values. + * type can be an array of values, or multiple values can be passed as individual arguments. + * If a given type is .required() then there must be a matching item in the array. + * If a type is .forbidden() then it cannot appear in the array. + * Required items can be added multiple times to signify that multiple items must be found. + * Errors will contain the number of items that didn't match. + * Any unmatched item having a label will be mentioned explicitly. + * + * @param type - a joi schema object to validate each array item against. + */ + items(type: Schema, ...types: Schema[]): ArraySchema; + items(types: Schema[]): ArraySchema; /** * Specifies the minimum number of items in the array. @@ -292,6 +454,12 @@ declare module 'joi' { */ length(limit: number): ArraySchema; + /** + * Requires the array values to be unique. + * Be aware that a deep equality is performed on elements of the array having a type of object, + * a performance penalty is to be expected for this kind of operation. + */ + unique(): ArraySchema; } export interface ObjectSchema extends AnySchema { @@ -322,20 +490,30 @@ declare module 'joi' { /** * Defines an all-or-nothing relationship between keys where if one of the peers is present, all of them are required as well. + * @param peers - the key names of which if one present, all are required. peers can be a single string value, + * an array of string values, or each peer provided as an argument. */ - and(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + and(peer1: string, ...peers: string[]): ObjectSchema; and(peers: string[]): ObjectSchema; + /** + * Defines a relationship between keys where not all peers can be present at the same time. + * @param peers - the key names of which if one present, the others may not all be present. + * peers can be a single string value, an array of string values, or each peer provided as an argument. + */ + nand(peer1: string, ...peers: string[]): ObjectSchema; + nand(peers: string[]): ObjectSchema; + /** * Defines a relationship between keys where one of the peers is required (and more than one is allowed). */ - or(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + or(peer1: string, ...peers: string[]): ObjectSchema; or(peers: string[]): ObjectSchema; /** * Defines an exclusive relationship between a set of keys. one of them is required but not at the same time where: */ - xor(peer1: string, peer2: string, ...peers: string[]): ObjectSchema; + xor(peer1: string, ...peers: string[]): ObjectSchema; xor(peers: string[]): ObjectSchema; /** @@ -365,9 +543,47 @@ declare module 'joi' { * Overrides the handling of unknown keys for the scope of the current object only (does not apply to children). */ unknown(allow?:boolean): ObjectSchema; + + /** + * Requires the object to be an instance of a given constructor. + * + * @param constructor - the constructor function that the object must be an instance of. + * @param name - an alternate name to use in validation errors. This is useful when the constructor function does not have a name. + */ + type(constructor: Function, name?: string): ObjectSchema; + + /** + * Sets the specified children to required. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * var schema = Joi.object().keys({ a: { b: Joi.number() }, c: { d: Joi.string() } }); + * var requiredSchema = schema.requiredKeys('', 'a.b', 'c', 'c.d'); + * + * Note that in this example '' means the current object, a is not required but b is, as well as c and d. + */ + requiredKeys(children: string): ObjectSchema; + requiredKeys(children: string[]): ObjectSchema; + requiredKeys(child:string, ...children: string[]): ObjectSchema; + + /** + * Sets the specified children to optional. + * + * @param children - can be a single string value, an array of string values, or each child provided as an argument. + * + * The behavior is exactly the same as requiredKeys. + */ + optionalKeys(children: string): ObjectSchema; + optionalKeys(children: string[]): ObjectSchema; + optionalKeys(child:string, ...children: string[]): ObjectSchema; } export interface BinarySchema extends AnySchema { + /** + * Sets the string encoding format if a string input is converted to a buffer. + */ + encoding(encoding: string): BinarySchema; + /** * Specifies the minimum length of the buffer. */ @@ -388,17 +604,37 @@ declare module 'joi' { /** * Specifies the oldest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. */ min(date: Date): DateSchema; min(date: number): DateSchema; min(date: string): DateSchema; + min(date: Reference): DateSchema; /** * Specifies the latest date allowed. + * Notes: 'now' can be passed in lieu of date so as to always compare relatively to the current date, + * allowing to explicitly ensure a date is either in the past or in the future. + * It can also be a reference to another field. */ max(date: Date): DateSchema; max(date: number): DateSchema; max(date: string): DateSchema; + max(date: Reference): DateSchema; + + /** + * Specifies the allowed date format: + * @param format - string or array of strings that follow the moment.js format. + */ + format(format: string): DateSchema; + format(format: string[]): DateSchema; + + /** + * Requires the string value to be in valid ISO 8601 date format. + */ + iso(): DateSchema; } export interface FunctionSchema extends AnySchema { @@ -480,8 +716,12 @@ declare module 'joi' { /** * Validates a value against a schema and throws if validation fails. + * + * @param value - the value to validate. + * @param schema - the schema object. + * @param message - optional message string prefix added in front of the error message. may also be an Error object. */ - export function assert(value: any, schema: Schema): void; + export function assert(value: any, schema: Schema, message?: string | Error): void; /** * Generates a reference to the value of the named key. From 7a6400a7d4b18de10b1c501955ed665f7af5a989 Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Sat, 4 Jul 2015 17:18:50 +0200 Subject: [PATCH 015/881] Improve gulp.watch() --- gulp/gulp-tests.ts | 39 +++++++++++++++++++++++++++++++++++++++ gulp/gulp.d.ts | 42 +++++++++--------------------------------- 2 files changed, 48 insertions(+), 33 deletions(-) diff --git a/gulp/gulp-tests.ts b/gulp/gulp-tests.ts index 7e07f25f7..07a92fc91 100644 --- a/gulp/gulp-tests.ts +++ b/gulp/gulp-tests.ts @@ -1,6 +1,8 @@ /// +/// import gulp = require("gulp"); +import browserSync = require("browser-sync"); var typescript: IGulpPlugin = null; // this would be the TypeScript compiler var jasmine: IGulpPlugin = null; // this would be the jasmine test runner @@ -27,3 +29,40 @@ gulp.task('test', ['compile', 'compile2'], function() }); gulp.task('default', ['compile', 'test']); + + +var opts = {}; + +gulp.watch('*.html', 'compile'); +gulp.watch('*.html', ['compile', 'test']); +gulp.watch('*.html', () => {}); +gulp.watch('*.html', [() => {}, (event) => {}]); +gulp.watch('*.html', ['compile', () => {}]); + +gulp.watch('*.html', opts, 'compile'); +gulp.watch('*.html', opts, ['compile', 'test']); +gulp.watch('*.html', opts, () => {}); +gulp.watch('*.html', opts, [() => {}, (event) => {}]); +gulp.watch('*.html', opts, ['compile', () => {}]); + +gulp.watch(['*.html', '*.ts'], 'compile'); +gulp.watch(['*.html', '*.ts'], ['compile', 'test']); +gulp.watch(['*.html', '*.ts'], () => {}); +gulp.watch(['*.html', '*.ts'], [() => {}, (event) => {}]); +gulp.watch(['*.html', '*.ts'], ['compile', () => {}]); + +gulp.watch(['*.html', '*.ts'], opts, 'compile'); +gulp.watch(['*.html', '*.ts'], opts, ['compile', 'test']); +gulp.watch(['*.html', '*.ts'], opts, () => {}); +gulp.watch(['*.html', '*.ts'], opts, [() => {}, (event) => {}]); +gulp.watch(['*.html', '*.ts'], opts, ['compile', () => {}]); + +var watcher = gulp.watch('*.html', event => { + console.log('Event type: ' + event.type); + console.log('Event path: ' + event.path); +}); + +gulp.task('serve', ['compile'], () => { + var browser = browserSync.create(); + gulp.watch(['*.html', '*.ts'], ['compile', browser.reload]); +}); diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 7ec11def7..d7a0dba57 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -236,45 +236,21 @@ declare module gulp { dest(outFolder:(file:string)=>string, opt?:IDestOptions): NodeJS.ReadWriteStream; - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param tasks names of task(s) to run when a file changes, added with gulp.task() - */ - watch(glob:string, tasks:string[]): EventEmitter; - watch(glob:string[], tasks:string[]): EventEmitter; - /** * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. * * @param glob a single glob or array of globs that indicate which files to watch for changes. * @param opt options, that are passed to the gaze library. - * @param tasks names of task(s) to run when a file changes, added with gulp.task() + * @param fn a callback or array of callbacks to be called on each change, or names of task(s) to run when a file changes, added with gulp.task(). */ - watch(glob:string, opt:IWatchOptions, tasks:string[]): EventEmitter; - watch(glob:string[], opt:IWatchOptions, tasks:string[]): EventEmitter; - - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param fn a callback or array of callbacks to be called on each change. - */ - watch(glob:string, fn:IWatchCallback): EventEmitter; - watch(glob:string[], fn:IWatchCallback): EventEmitter; - watch(glob:string, fn:IWatchCallback[]): EventEmitter; - watch(glob:string[], fn:IWatchCallback[]): EventEmitter; - - /** - * Watch files and do something when a file changes. This always returns an EventEmitter that emits change events. - * - * @param glob a single glob or array of globs that indicate which files to watch for changes. - * @param opt options, that are passed to the gaze library. - * @param fn a callback or array of callbacks to be called on each change. - */ - watch(glob:string, opt:IWatchOptions, fn:IWatchCallback): EventEmitter; - watch(glob:string, opt:IWatchOptions, fn:IWatchCallback[]): EventEmitter; + watch(glob:string, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string, fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string, opt:IWatchOptions, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string, opt:IWatchOptions, fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string[], fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string[], fn:(IWatchCallback|string)[]): EventEmitter; + watch(glob:string[], opt:IWatchOptions, fn:(IWatchCallback|string)): EventEmitter; + watch(glob:string[], opt:IWatchOptions, fn:(IWatchCallback|string)[]): EventEmitter; } } From c6a507446a0fc58043d1bc12a609b0ac5f9a212e Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:29:19 +0300 Subject: [PATCH 016/881] Fixed couple bugs --- sharepoint/SharePoint.d.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index 026658ef8..65e1f63a4 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ // Type definitions for sptypescript // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan and Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -159,6 +159,7 @@ declare class _spPageContextInfo { static currentUICultureName: string; //"ru-RU" static layoutsUrl: string; //"_layouts/15" static pageListId: string; //"{06ee6d96-f27f-4160-b6bb-c18f187b18a7}" + static pageItemId: number; static pagePersonalizationScope: string; //1 static serverRequestPath: string; //"/SPTypeScript/Lists/ConditionalFormattingTasksList/AllItems.aspx" static siteAbsoluteUrl: string; // "https://gandjustas-7b20d3715e8ed4.sharepoint.com" @@ -2440,7 +2441,7 @@ declare module SP { get_webId(): SP.Guid; getErrorDetails(): SP.ClientObjectList; uninstall(): SP.GuidResult; - upgrade(appPackageStream: any[]): void; + upgrade(appPackageStream: SP.Base64EncodedByteArray): void; cancelAllJobs(): SP.BooleanResult; install(): SP.GuidResult; getPreviousAppVersion(): SP.App; @@ -2515,8 +2516,8 @@ declare module SP { getByFileName(fileName: string): SP.Attachment; } export class AttachmentCreationInformation extends SP.ClientValueObject { - get_contentStream(): any[]; - set_contentStream(value: any[]): void; + get_contentStream(): SP.Base64EncodedByteArray; + set_contentStream(value: SP.Base64EncodedByteArray): void; get_fileName(): string; set_fileName(value: string): void; get_typeId(): string; @@ -3243,7 +3244,7 @@ declare module SP { boolean, number, currency, - uRL, + URL, computed, threading, guid, @@ -4812,9 +4813,9 @@ declare module SP { getSubwebsForCurrentUser(query: SP.SubwebQuery): SP.WebCollection; getAppInstanceById(appInstanceId: SP.Guid): SP.AppInstance; getAppInstancesByProductId(productId: SP.Guid): SP.ClientObjectList; - loadAndInstallAppInSpecifiedLocale(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadApp(appPackageStream: any[], installationLocaleLCID: number): SP.AppInstance; - loadAndInstallApp(appPackageStream: any[]): SP.AppInstance; + loadAndInstallAppInSpecifiedLocale(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadApp(appPackageStream: SP.Base64EncodedByteArray, installationLocaleLCID: number): SP.AppInstance; + loadAndInstallApp(appPackageStream: SP.Base64EncodedByteArray): SP.AppInstance; ensureUser(logonName: string): SP.User; applyTheme(colorPaletteUrl: string, fontSchemeUrl: string, backgroundImageUrl: string, shareGenerated: boolean): void; } From e53377052eb6bbb0307404938e728dd91b804103 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:48:28 +0300 Subject: [PATCH 017/881] Refactored microsoft.ajax.d.ts to compile with SharePoint.d.ts From e0ca94ea1317c51994d7dc1320601f99c127032a Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:49:32 +0300 Subject: [PATCH 018/881] Added spgantt definitions (not finished yet) to SharePoint.d.ts From 14a3909c9171566e377a8cda78ee3f54711e8a5d Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:55:16 +0300 Subject: [PATCH 019/881] Refactored SharePoint.d.ts to TypeScript 1.4 (union types) From 160132fdad7baa693eaf3af1ea31334a462278c3 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 18:58:09 +0300 Subject: [PATCH 020/881] Added and fixed definitions for dialogs in SharePoint.d.ts From db8c5956c24ee413134e0ffdf9b097c8f799d8b7 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Sun, 5 Jul 2015 19:01:31 +0300 Subject: [PATCH 021/881] Backported SharePoint.d.ts changes fom master From 3ea7cf7889743b5633df96508fa38189361b466c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Wed, 8 Jul 2015 19:22:36 +0900 Subject: [PATCH 022/881] Add missing selmicolons --- selenium-webdriver/selenium-webdriver.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index c4af933c9..bb7fefb3d 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -608,7 +608,7 @@ declare module webdriver { UNKNOWN_COMMAND: string; UNKNOWN_ERROR: string; UNSUPPORTED_OPERATION: string; - } + }; //endregion @@ -1464,7 +1464,7 @@ declare module webdriver { PENDING: number; REJECTED: number; RESOLVED: number; - } + }; //region Properties @@ -2030,7 +2030,7 @@ declare module webdriver { RIGHT: number; } - var Button: IButton + var Button: IButton; /** * Representations of pressable keys that aren't text. These are stored in @@ -2418,7 +2418,7 @@ declare module webdriver { HTMLUNIT: string; } - var Browser: IBrowser + var Browser: IBrowser; interface ProxyConfig { proxyType: string; @@ -4170,7 +4170,7 @@ declare module webdriver { * WebDriver wire protocol. * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol */ - getId(): webdriver.promise.Promise + getId(): webdriver.promise.Promise; /** * Schedules a command to retrieve the inner HTML of this element. From 33ae3d2f7b0dbb48b0a6366a4a0cdb7904ad684f Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 19:08:44 +0900 Subject: [PATCH 023/881] Update WebDriver#isElementPresent, #findElement and #findElements Related: https://github.com/SeleniumHQ/selenium.git dc974c4a760176d015a96196072b6fb728100903 TODO: Add webdriver.By.Hash --- .../selenium-webdriver-tests.ts | 12 +++--- selenium-webdriver/selenium-webdriver.d.ts | 40 ++++++++----------- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 73ea8561e..62ef0812a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -676,14 +676,14 @@ function TestWebDriver() { var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); element = driver.findElement({id: 'ABC'}); - element = driver.findElement(webdriver.By.js('function(){}'), 1, 2, 3); - element = driver.findElement({js: 'function(){}'}, 1, 2, 3); + element = driver.findElement(webdriver.By.js('function(){}')); + element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements(webdriver.By.js('function(){}'), 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }, 1, 2, 3).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -696,8 +696,8 @@ function TestWebDriver() { booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); booleanPromise = driver.isElementPresent({className: 'ABC'}); - booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}'), 1, 2, 3); - booleanPromise = driver.isElementPresent({js: 'function(){}'}, 1, 2, 3); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + booleanPromise = driver.isElementPresent({js: 'function(){}'}); var options: webdriver.WebDriverOptions = driver.manage(); var navigation: webdriver.WebDriverNavigation = driver.navigate(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index bb7fefb3d..84bbdf507 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3867,6 +3867,7 @@ declare module webdriver { * {@code webdriver.Locator} object, or a simple JSON object whose sole key * is one of the accepted locator strategies, as defined by * {@code webdriver.Locator.Strategy}. For example, the following two statements + * The search criteria for an element may be defined using one of the * are equivalent: *
          * var e1 = driver.findElement(By.id('foo'));
@@ -3882,48 +3883,41 @@ declare module webdriver {
          * one this instance is currently focused on), a
          * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned.
          *
-         * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The
-         *     locator strategy to use when searching for the element, or the actual
-         *     DOM element to be located by the server.
-         * @param {...} var_args Arguments to pass to {@code #executeScript} if using a
-         *     JavaScript locator.  Otherwise ignored.
+         * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The
+         *     locator to use.
          * @return {!webdriver.WebElement} A WebElement that can be used to issue
          *     commands against the located element. If the element is not found, the
          *     element will be invalidated and all scheduled commands aborted.
          */
-        findElement(locatorOrElement: Locator, ...var_args: any[]): WebElementPromise;
-        findElement(locatorOrElement: any, ...var_args: any[]): WebElementPromise;
+        findElement(locatorOrElement: Locator): WebElementPromise;
+        findElement(locatorOrElement: any): WebElementPromise;
 
         /**
          * Schedules a command to test if an element is present on the page.
          *
-         * 

If given a DOM element, this function will check if it belongs to the + * If given a DOM element, this function will check if it belongs to the * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|Object.|Element)} locatorOrElement The - * locator strategy to use when searching for the element, or the actual + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual * DOM element to be located by the server. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will resolve to whether - * the element is present on the page. + * @return {!webdriver.promise.Promise.} A promise that will resolve + * with whether the element is present on the page. */ - isElementPresent(locatorOrElement: Locator, ...var_args: any[]): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any, ...var_args: any[]): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator): webdriver.promise.Promise; + isElementPresent(locatorOrElement: any): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {webdriver.Locator|Object.} locator The locator + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator * strategy to use when searching for the element. - * @param {...} var_args Arguments to pass to {@code #executeScript} if using a - * JavaScript locator. Otherwise ignored. - * @return {!webdriver.promise.Promise} A promise that will be resolved to an - * array of the located {@link webdriver.WebElement}s. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator, ...var_args: any[]): webdriver.promise.Promise; - findElements(locator: any, ...var_args: any[]): webdriver.promise.Promise; + findElements(locator: Locator): webdriver.promise.Promise; + findElements(locator: any): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to From fa27980695ec1c948cc5fb3a79bbc98800a5f73c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 19:15:16 +0900 Subject: [PATCH 024/881] Add docs to webdriver.By.* (without Hash) --- selenium-webdriver/selenium-webdriver.d.ts | 87 +++++++++++++++++++++- 1 file changed, 86 insertions(+), 1 deletion(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 84bbdf507..47c27f8bd 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4685,14 +4685,99 @@ declare module webdriver { } interface ILocatorStrategy { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ className(value: string): Locator; + + /** + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. + * + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ id(value: string): Locator; - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ linkText(value: string): Locator; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ name(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} contains the given substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + */ partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ tagName(value: string): Locator; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector {@code "//div"}, WebDriver will search from the + * document root regardless of whether the locator was used with a + * WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ xpath(value: string): Locator; } From ecd7cc44b78eababef1efb7978c1d92be974310d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:00:28 +0900 Subject: [PATCH 025/881] Update webdriver.Locator --- .../selenium-webdriver-tests.ts | 20 +++++++-- selenium-webdriver/selenium-webdriver.d.ts | 43 +++++++++++++++---- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 62ef0812a..81c9875de 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -497,15 +497,29 @@ function TestLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = webdriver.By.className('class'); + var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); - var locatorStr: string = locator.toString(); + var locatorOrFn: webdriver.Locator|Function; + + locatorOrFn = webdriver.Locator.Strategy.className; + locatorOrFn = webdriver.Locator.Strategy.css; + locatorOrFn = webdriver.Locator.Strategy.id; + locatorOrFn = webdriver.Locator.Strategy.js; + locatorOrFn = webdriver.Locator.Strategy.linkText; + locatorOrFn = webdriver.Locator.Strategy.name; + locatorOrFn = webdriver.Locator.Strategy.partialLinkText; + locatorOrFn = webdriver.Locator.Strategy.tagName; + locatorOrFn = webdriver.Locator.Strategy.xpath; + + locatorOrFn = webdriver.Locator.checkLocator(locator); + locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); + locatorOrFn = webdriver.Locator.checkLocator(Error); var using: string = locator.using; var value: string = locator.value; - var str: string = locator.toString(); + locator = webdriver.By.className('class'); locator = webdriver.By.css('css'); locator = webdriver.By.id('id'); locator = webdriver.By.linkText('link'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 47c27f8bd..e9a854ac6 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4786,9 +4786,42 @@ declare module webdriver { /** * An element locator. */ - interface Locator { + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); - //region Properties + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof By.className; + css: typeof By.css; + id: typeof By.id; + js: typeof By.js; + linkText: typeof By.linkText; + name: typeof By.name; + partialLinkText: typeof By.partialLinkText; + tagName: typeof By.tagName; + xpath: typeof By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; /** * The search strategy to use when searching for an element. @@ -4802,14 +4835,8 @@ declare module webdriver { */ value: string; - //endregion - - //region Methods - /** @return {string} String representation of this locator. */ toString(): string; - - //endregion } /** From 03d49ee1b990f4321b904845208342794a22a7ca Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:39:37 +0900 Subject: [PATCH 026/881] WIP: Add webdriver.By.Hash `webdriver.By.Hash` is a Closure Llibrary style type alias. If we assign `webdriver.By.Hash`, we get an `undefined`. I think the assignment should have an error, because it have no meanings. --- .../selenium-webdriver-tests.ts | 10 ++++++ selenium-webdriver/selenium-webdriver.d.ts | 34 +++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 81c9875de..b296b62ee 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -528,6 +528,16 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); + var locatorHash: webdriver.By.Hash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e9a854ac6..b170d24c5 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4783,6 +4783,40 @@ declare module webdriver { var By: ILocatorStrategy; + module By { + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + /** * An element locator. */ From 08b91e601cfe273f8e81d387321a94ce4b8d2452 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 20:57:53 +0900 Subject: [PATCH 027/881] Comment out definitnions and tests for webdriver.By.Hash --- .../selenium-webdriver-tests.ts | 18 ++--- selenium-webdriver/selenium-webdriver.d.ts | 66 +++++++++---------- 2 files changed, 42 insertions(+), 42 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index b296b62ee..4b1449bce 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -528,15 +528,15 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); - var locatorHash: webdriver.By.Hash; - locatorHash = { className: 'class' }; - locatorHash = { css: 'css' }; - locatorHash = { id: 'id' }; - locatorHash = { linkText: 'link' }; - locatorHash = { name: 'name' }; - locatorHash = { partialLinkText: 'text' }; - locatorHash = { tagName: 'tag' }; - locatorHash = { xpath: 'xpath' }; + // var locatorHash: webdriver.By.Hash; + // locatorHash = { className: 'class' }; + // locatorHash = { css: 'css' }; + // locatorHash = { id: 'id' }; + // locatorHash = { linkText: 'link' }; + // locatorHash = { name: 'name' }; + // locatorHash = { partialLinkText: 'text' }; + // locatorHash = { tagName: 'tag' }; + // locatorHash = { xpath: 'xpath' }; webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b170d24c5..da1c2ab40 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4783,39 +4783,39 @@ declare module webdriver { var By: ILocatorStrategy; - module By { - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } + // module By { + // /** + // * Short-hand expressions for the primary element locator strategies. + // * For example the following two statements are equivalent: + // * + // * var e1 = driver.findElement(webdriver.By.id('foo')); + // * var e2 = driver.findElement({id: 'foo'}); + // * + // * Care should be taken when using JavaScript minifiers (such as the + // * Closure compiler), as locator hashes will always be parsed using + // * the un-obfuscated properties listed. + // * + // * @typedef {( + // * {className: string}| + // * {css: string}| + // * {id: string}| + // * {js: string}| + // * {linkText: string}| + // * {name: string}| + // * {partialLinkText: string}| + // * {tagName: string}| + // * {xpath: string})} + // */ + // type Hash = {className: string}| + // {css: string}| + // {id: string}| + // {js: string}| + // {linkText: string}| + // {name: string}| + // {partialLinkText: string}| + // {tagName: string}| + // {xpath: string}; + // } /** * An element locator. From 7c881f2e1a89adf44076b12b2aa630f94163eff9 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:00:26 +0900 Subject: [PATCH 028/881] Add webdriver.TestTouchSequence --- .../selenium-webdriver-tests.ts | 22 +++ selenium-webdriver/selenium-webdriver.d.ts | 137 ++++++++++++++++++ 2 files changed, 159 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4b1449bce..b805a8b5a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -182,6 +182,28 @@ function TestActionSequence() { sequence.perform().then(function () { }); } +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(function () { }); +} + function TestAlert() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index da1c2ab40..49555eb2a 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -2307,6 +2307,143 @@ declare module webdriver { //endregion } + + /** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new webdriver.TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ + class TouchSequence { + /* + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + + /** + * Taps an element. + * + * @param {!webdriver.WebElement} elem The element to tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + tap(elem: IWebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!webdriver.WebElement} elem The element to double tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + doubleTap(elem: IWebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!webdriver.WebElement} elem The element to long press. + * @return {!webdriver.TouchSequence} A self reference. + */ + longPress(elem: IWebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!webdriver.TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!webdriver.TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!webdriver.TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!webdriver.WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scrollFromElement(elem: IWebElement, offset: IOffset): TouchSequence; + + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!webdriver.WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flickElement(elem: IWebElement, offset: IOffset, speed: number): TouchSequence; + } + + + interface IOffset { + x: number; + y: number; + } + + + interface ISpeed { + xspeed: number; + yspeed: number; + } + + /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with From 1bbf7338c1ad40b04f7e38724bc5542bfc9613c8 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:17:14 +0900 Subject: [PATCH 029/881] Add webdriver.WebDriver#touchActions --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 16 ++++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index b805a8b5a..c93b96c00 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -697,6 +697,7 @@ function TestWebDriver() { var booleanPromise: webdriver.promise.Promise; var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); // call stringPromise = driver.call(function(){}); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 49555eb2a..b7afaa081 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3775,6 +3775,22 @@ declare module webdriver { */ actions(): ActionSequence; + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + /** * Schedules a command to execute JavaScript in the context of the currently * selected frame or window. The script fragment will be executed as the body From f2efb822f5756b4b8f07e83650bc1d6e54b2b19c Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:18:05 +0900 Subject: [PATCH 030/881] Add webdriver.FileDetector --- .../selenium-webdriver-tests.ts | 10 ++++++ selenium-webdriver/selenium-webdriver.d.ts | 35 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c93b96c00..4e5e9766b 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -586,6 +586,16 @@ function TestUnhandledAlertError() { } } +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then(function(path: string) {}); +} + function TestWebDriverLogs() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b7afaa081..4d4829342 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3645,6 +3645,41 @@ declare module webdriver { //endregion } + /** + * Used with {@link webdriver.WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain webdriver.WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ + class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; + } + /** * Creates a new WebDriver client, which provides control over a browser. * From d278c4283d910f6a4492ca7413dc025b40586d9b Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:24:30 +0900 Subject: [PATCH 031/881] Add webdriver.WabDriver#setFileDetector --- selenium-webdriver/selenium-webdriver-tests.ts | 3 +++ selenium-webdriver/selenium-webdriver.d.ts | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 4e5e9766b..3c663531e 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -760,6 +760,9 @@ function TestWebDriver() { var navigation: webdriver.WebDriverNavigation = driver.navigate(); var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + voidPromise = driver.quit(); voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); voidPromise = driver.sleep(123); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 4d4829342..e99c8d8f6 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3775,6 +3775,15 @@ declare module webdriver { */ schedule(command: Command, description: string): webdriver.promise.Promise; + + /** + * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * used with this instance. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + /** * @return {!webdriver.promise.Promise} A promise for this client's session. */ From 453d394a7bb1e7abe4dfeadb522a9ece359a6c83 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 21:25:11 +0900 Subject: [PATCH 032/881] Update webdriver.WebDriver annotations --- selenium-webdriver/selenium-webdriver.d.ts | 281 ++++++++++++--------- 1 file changed, 161 insertions(+), 120 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e99c8d8f6..8814e194e 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3251,6 +3251,7 @@ declare module webdriver { //endregion } + /** * Interface for navigating back and forth in the browser history. */ @@ -3270,29 +3271,29 @@ declare module webdriver { /** * Schedules a command to navigate to a new URL. * @param {string} url The URL to navigate to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * URL has been loaded. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the URL has been loaded. */ to(url: string): webdriver.promise.Promise; /** * Schedules a command to move backwards in the browser history. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ back(): webdriver.promise.Promise; /** * Schedules a command to move forwards in the browser history. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ forward(): webdriver.promise.Promise; /** * Schedules a command to refresh the current page. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * navigation event has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. */ refresh(): webdriver.promise.Promise; @@ -3785,22 +3786,25 @@ declare module webdriver { /** - * @return {!webdriver.promise.Promise} A promise for this client's session. + * @return {!webdriver.promise.Promise.} A promise for this + * client's session. */ getSession(): webdriver.promise.Promise; + /** - * @return {!webdriver.promise.Promise} A promise that will resolve with the - * this instance's capabilities. + * @return {!webdriver.promise.Promise.} A promise + * that will resolve with the this instance's capabilities. */ getCapabilities(): webdriver.promise.Promise; + /** * Schedules a command to quit the current session. After calling quit, this * instance will be invalidated and may no longer be used to issue commands * against the browser. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the command has completed. */ quit(): webdriver.promise.Promise; @@ -3857,20 +3861,20 @@ declare module webdriver { * If the script has a return value (i.e. if the script contains a return * statement), then the following steps will be taken for resolving this * functions return value: - *

    - *
  • For a HTML element, the value will resolve to a - * {@code webdriver.WebElement}
  • - *
  • Null and undefined return values will resolve to null
  • - *
  • Booleans, numbers, and strings will resolve as is
  • - *
  • Functions will resolve to their string representation
  • - *
  • For arrays and objects, each member item will be converted according to - * the rules above
  • - *
+ * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above * * @param {!(string|Function)} script The script to execute. * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * scripts return value. + * @template T */ executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; @@ -3888,102 +3892,126 @@ declare module webdriver { * Arrays and objects may also be used as script arguments as long as each item * adheres to the types previously mentioned. * - * Unlike executing synchronous JavaScript with - * {@code webdriver.WebDriver.prototype.executeScript}, scripts executed with - * this function must explicitly signal they are finished by invoking the - * provided callback. This callback will always be injected into the - * executed function as the last argument, and thus may be referenced with - * {@code arguments[arguments.length - 1]}. The following steps will be taken - * for resolving this functions return value against the first argument to the - * script's callback function: - *
    - *
  • For a HTML element, the value will resolve to a - * {@code webdriver.WebElement}
  • - *
  • Null and undefined return values will resolve to null
  • - *
  • Booleans, numbers, and strings will resolve as is
  • - *
  • Functions will resolve to their string representation
  • - *
  • For arrays and objects, each member item will be converted according to - * the rules above
  • - *
+ * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: * - * Example #1: Performing a sleep that is synchronized with the currently + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently * selected window: - *
-         * var start = new Date().getTime();
-         * driver.executeAsyncScript(
-         *     'window.setTimeout(arguments[arguments.length - 1], 500);').
-         *     then(function() {
-         *       console.log('Elapsed time: ' + (new Date().getTime() - start) + ' ms');
-         *     });
-         * 
* - * Example #2: Synchronizing a test with an AJAX application: - *
-         * var button = driver.findElement(By.id('compose-button'));
-         * button.click();
-         * driver.executeAsyncScript(
-         *     'var callback = arguments[arguments.length - 1];' +
-         *     'mailClient.getComposeWindowWidget().onload(callback);');
-         * driver.switchTo().frame('composeWidget');
-         * driver.findElement(By.id('to')).sendKEys('dog@example.com');
-         * 
+ * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); * - * Example #3: Injecting a XMLHttpRequest and waiting for the result. In this - * example, the inject script is specified with a function literal. When using - * this format, the function is converted to a string for injection, so it + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it * should not reference any symbols not defined in the scope of the page under * test. - *
-         * driver.executeAsyncScript(function() {
-         *   var callback = arguments[arguments.length - 1];
-         *   var xhr = new XMLHttpRequest();
-         *   xhr.open("GET", "/resource/data.json", true);
-         *   xhr.onreadystatechange = function() {
-         *     if (xhr.readyState == 4) {
-         *       callback(xhr.resposneText);
-         *     }
-         *   }
-         *   xhr.send('');
-         * }).then(function(str) {
-         *   console.log(JSON.parse(str)['food']);
-         * });
-         * 
+ * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open("GET", "/resource/data.json", true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); * * @param {!(string|Function)} script The script to execute. * @param {...*} var_args The arguments to pass to the script. - * @return {!webdriver.promise.Promise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * scripts return value. + * @template T */ executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute a custom function. - * @param {!Function} fn The function to execute. + * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to + * execute. * @param {Object=} opt_scope The object in whose scope to execute the function. * @param {...*} var_args Any arguments to pass to the function. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * function's result. + * @return {!webdriver.promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T */ call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; /** - * Schedules a command to wait for a condition to hold, as defined by some - * user supplied function. If any errors occur while evaluating the wait, they - * will be allowed to propagate. + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.until.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. * - *

In the event a condition returns a {@link webdriver.promise.Promise}, the + * For a {@link webdriver.until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the * polling loop will wait for it to be resolved and use the resolved value for - * evaluating whether the condition has been satisfied. The resolution time for + * whether the condition has been satisified. Note the resolution time for * a promise is factored into whether a wait has timed out. * - * @param {!(webdriver.until.Condition.| - * function(!webdriver.WebDriver): T)} condition Either a condition - * object, or a function to evaluate as a condition. - * @param {number} timeout How long to wait for the condition to be true. + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(webdriver.promise.Promise| + * webdriver.until.Condition| + * function(!webdriver.WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. * @param {string=} opt_message An optional message to use if the wait times * out. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @return {!webdriver.promise.Promise} A promise that will be fulfilled * with the first truthy value returned by the condition function, or * rejected if the condition times out. * @template T @@ -3994,22 +4022,22 @@ declare module webdriver { /** * Schedules a command to make the driver sleep for the given amount of time. * @param {number} ms The amount of time, in milliseconds, to sleep. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * sleep has finished. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the sleep has finished. */ sleep(ms: number): webdriver.promise.Promise; /** * Schedules a command to retrieve they current window handle. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current window handle. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current window handle. */ getWindowHandle(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current list of available window handles. - * @return {!webdriver.promise.Promise} A promise that will be resolved with an - * array of window handles. + * @return {!webdriver.promise.Promise.>} A promise that will + * be resolved with an array of window handles. */ getAllWindowHandles(): webdriver.promise.Promise; @@ -4018,60 +4046,73 @@ declare module webdriver { * returned is a representation of the underlying DOM: do not expect it to be * formatted or escaped in the same way as the response sent from the web * server. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current page source. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page source. */ getPageSource(): webdriver.promise.Promise; /** * Schedules a command to close the current window. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * this command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when this command has completed. */ close(): webdriver.promise.Promise; /** * Schedules a command to navigate to the given URL. * @param {string} url The fully qualified URL to open. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * document has finished loading. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the document has finished loading. */ get(url: string): webdriver.promise.Promise; /** * Schedules a command to retrieve the URL of the current page. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current URL. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current URL. */ getCurrentUrl(): webdriver.promise.Promise; /** * Schedules a command to retrieve the current page's title. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * current page's title. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page's title. */ getTitle(): webdriver.promise.Promise; /** * Schedule a command to find an element on the page. If the element cannot be - * found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned * by the driver. Unlike other commands, this error cannot be suppressed. In * other words, scheduling a command to find an element doubles as an assert * that the element is present on the page. To test whether an element is - * present on the page, use {@code #isElementPresent} instead. + * present on the page, use {@link #isElementPresent} instead. * - *

The search criteria for find an element may either be a - * {@code webdriver.Locator} object, or a simple JSON object whose sole key - * is one of the accepted locator strategies, as defined by - * {@code webdriver.Locator.Strategy}. For example, the following two statements * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements * are equivalent: - *

-         * var e1 = driver.findElement(By.id('foo'));
-         * var e2 = driver.findElement({id:'foo'});
-         * 
* - *

When running in the browser, a WebDriver cannot manipulate DOM elements + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * When running in the browser, a WebDriver cannot manipulate DOM elements * directly; it may do so only through a {@link webdriver.WebElement} reference. * This function may be used to generate a WebElement from a DOM element. A * reference to the DOM element will be stored in a known location and this @@ -4126,8 +4167,8 @@ declare module webdriver { *

  • The screenshot of the entire display containing the browser * * - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * screenshot as a base-64 encoded PNG. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; From 22c0bb370f3aa34209a9760cee79ec6e9a89bfd8 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:14:12 +0900 Subject: [PATCH 033/881] Remove deprecated methods Link: https://github.com/SeleniumHQ/selenium/commit/e7b442e01370178ca9fd64ed73cf39e2dc76b519#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 8 ------ selenium-webdriver/selenium-webdriver.d.ts | 28 ------------------- 2 files changed, 36 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 3c663531e..55890964f 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1035,19 +1035,11 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; - var e: any = flow.annotateError(new Error('Error')); - var stringPromise: webdriver.promise.Promise; - stringPromise = flow.await(stringPromise); - - flow.clearHistory(); - stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); - var history: string[] = flow.getHistory(); - var schedule: string = flow.getSchedule(); flow.reset(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 8814e194e..6ce13dfa9 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1611,26 +1611,7 @@ declare module webdriver { reset(): void; /** - * Returns a summary of the recent task activity for this instance. This - * includes the most recently completed task, as well as any parent tasks. In - * the returned summary, the task at index N is considered a sub-task of the - * task at index N+1. - * @return {!Array.} A summary of this instance's recent task - * activity. */ - getHistory(): string[]; - - /** Clears this instance's task history. */ - clearHistory(): void; - - /** - * Appends a summary of this instance's recent task history to the given - * error's stack trace. This function will also ensure the error's stack trace - * is in canonical form. - * @param {!(Error|goog.testing.JsUnitException)} e The error to annotate. - * @return {!(Error|goog.testing.JsUnitException)} The annotated error. - */ - annotateError(e: any): any; /** * @return {string} The scheduled tasks still pending with this instance. @@ -1687,15 +1668,6 @@ declare module webdriver { */ wait(condition: Function, timeout: number, opt_message?: string): Promise; - /** - * Schedules a task that will wait for another promise to resolve. The resolved - * promise's value will be returned as the task result. - * @param {!webdriver.promise.Promise} promise The promise to wait on. - * @return {!webdriver.promise.Promise} A promise that will resolve when the - * task has completed. - */ - await(promise: Promise): Promise; - //endregion } } From 69164fec6e1f2b7efcd8a0d7138d34dc9f5c9edf Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:19:36 +0900 Subject: [PATCH 034/881] Remove timers Link: https://github.com/SeleniumHQ/selenium/commit/43c1701222bf0314567e554c7a1dd1ad903bfa4f#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 13 +--- selenium-webdriver/selenium-webdriver.d.ts | 76 +++++++------------ 2 files changed, 30 insertions(+), 59 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 55890964f..07eb632c5 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1021,10 +1021,6 @@ function TestUntilModule() { function TestControlFlow() { var flow: webdriver.promise.ControlFlow; flow = new webdriver.promise.ControlFlow(); - flow = new webdriver.promise.ControlFlow({clearInterval: function(a: number) {}, - clearTimeout: function(a: number) {}, - setInterval: function(a: () => void, b: number) { return 2; }, - setTimeout: function(a: () => void, b: number) { return 2; }}); var emitter: webdriver.EventEmitter = flow; @@ -1036,11 +1032,13 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var stringPromise: webdriver.promise.Promise; - stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); - var schedule: string = flow.getSchedule(); + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); flow.reset(); @@ -1051,10 +1049,7 @@ function TestControlFlow() { voidPromise = flow.wait(function() { return true; }, 123, 'Timeout Message'); voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); - var timer: webdriver.promise.IControlFlowTimer = flow.timer; - timer = webdriver.promise.ControlFlow.defaultTimer; - var loopFrequency: number = webdriver.promise.ControlFlow.EVENT_LOOP_FREQUENCY; } function TestDeferred() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 6ce13dfa9..9b371b4d0 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1518,58 +1518,34 @@ declare module webdriver { * the ordered scheduled, starting each task only once those before it have * completed. * - *

    Each task scheduled within this flow may return a + * Each task scheduled within this flow may return a * {@link webdriver.promise.Promise} to indicate it is an asynchronous * operation. The ControlFlow will wait for such promises to be resolved before * marking the task as completed. * - *

    Tasks and each callback registered on a {@link webdriver.promise.Deferred} + * Tasks and each callback registered on a {@link webdriver.promise.Promise} * will be run in their own ControlFlow frame. Any tasks scheduled within a - * frame will have priority over previously scheduled tasks. Furthermore, if - * any of the tasks in the frame fails, the remainder of the tasks in that frame - * will be discarded and the failure will be propagated to the user through the + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the * callback/task's promised result. * - *

    Each time a ControlFlow empties its task queue, it will fire an - * {@link webdriver.promise.ControlFlow.EventType.IDLE} event. Conversely, + * Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, * whenever the flow terminates due to an unhandled error, it will remove all * remaining tasks in its queue and fire an - * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION} event. If - * there are no listeners registered with the flow, the error will be - * rethrown to the global error handler. + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. * - * @extends {webdriver.EventEmitter} + * @extends {EventEmitter} + * @final */ class ControlFlow extends EventEmitter { - - //region Constructors - /** - * @param {webdriver.promise.ControlFlow.Timer=} opt_timer The timer object - * to use. Should only be set for testing. * @constructor */ - constructor(opt_timer?: IControlFlowTimer); - - //endregion - - //region Properties - - /** - * The timer used by this instance. - * @type {webdriver.promise.ControlFlow.Timer} - */ - timer: IControlFlowTimer; - - //endregion - - //region Static Properties - - /** - * The default timer object, which uses the global timer functions. - * @type {webdriver.promise.ControlFlow.Timer} - */ - static defaultTimer: IControlFlowTimer; + constructor(); /** * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. @@ -1595,15 +1571,12 @@ declare module webdriver { }; /** - * How often, in milliseconds, the event loop should run. - * @type {number} - * @const + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override */ - static EVENT_LOOP_FREQUENCY: number; - - //endregion - - //region Methods + toString(): string; /** * Resets this instance, clearing its queue and removing all event listeners. @@ -1611,12 +1584,15 @@ declare module webdriver { reset(): void; /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. */ - - /** - * @return {string} The scheduled tasks still pending with this instance. - */ - getSchedule(): string; + getSchedule(opt_includeStackTraces?: boolean): string; /** * Schedules a task for execution. If there is nothing currently in the From 65ced8681c78c395802a199379fd9f5ac29934f7 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:21:13 +0900 Subject: [PATCH 035/881] Update webdriver.promise.ControlFlow#wait Link: https://github.com/SeleniumHQ/selenium/commit/f473be4a45751948e8e36344f83d6ffccc5574ef#diff-b1976f46bdbb6d0d51ba6baa46156d61 --- .../selenium-webdriver-tests.ts | 8 ++--- selenium-webdriver/selenium-webdriver.d.ts | 34 ++++++++++++------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 07eb632c5..ca729eba5 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1045,11 +1045,11 @@ function TestControlFlow() { var voidPromise: webdriver.promise.Promise = flow.timeout(123); voidPromise = flow.timeout(123, 'Description'); - voidPromise = flow.wait(function() { return true; }, 123); - voidPromise = flow.wait(function() { return true; }, 123, 'Timeout Message'); - voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); - + stringPromise = flow.wait(stringPromise); + voidPromise = flow.wait(function() { return true; }); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); } function TestDeferred() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9b371b4d0..9b065ff80 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1622,29 +1622,39 @@ declare module webdriver { * Schedules a task that shall wait for a condition to hold. Each condition * function may return any value, but it will always be evaluated as a boolean. * - *

    Condition functions may schedule sub-tasks with this instance, however, + * Condition functions may schedule sub-tasks with this instance, however, * their execution time will be factored into whether a wait has timed out. * - *

    In the event a condition returns a Promise, the polling loop will wait for + * In the event a condition returns a Promise, the polling loop will wait for * it to be resolved before evaluating whether the condition has been satisfied. * The resolution time for a promise is factored into whether a wait has timed * out. * - *

    If the condition function throws, or returns a rejected promise, the + * If the condition function throws, or returns a rejected promise, the * wait task will fail. * - * @param {!Function} condition The condition function to poll. - * @param {number} timeout How long to wait, in milliseconds, for the condition - * to hold before timing out. + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. * @param {string=} opt_message An optional error message to include if the * wait times out; defaults to the empty string. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * condition has been satisified. The promise shall be rejected if the wait - * times out waiting for the condition. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T */ - wait(condition: Function, timeout: number, opt_message?: string): Promise; - - //endregion + wait(condition: Promise|Function, opt_timeout?: number, opt_message?: string): Promise; } } From e9ca2ce12a18b1aaa6ed494a9939323b2227a160 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:23:05 +0900 Subject: [PATCH 036/881] Update webdriver.promise.ControlFlow#execute Link: https://github.com/SeleniumHQ/selenium/commit/7268c783d3c42abac34f6006f2f3ef9cd3daf58b --- selenium-webdriver/selenium-webdriver-tests.ts | 1 + selenium-webdriver/selenium-webdriver.d.ts | 18 +++++++++++------- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index ca729eba5..c887cb2ed 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1032,6 +1032,7 @@ function TestControlFlow() { eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(function() { return 'value'; }); stringPromise = flow.execute(function() { return stringPromise; }); stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 9b065ff80..d9fe8cc4b 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1596,16 +1596,20 @@ declare module webdriver { /** * Schedules a task for execution. If there is nothing currently in the - * queue, the task will be executed in the next turn of the event loop. + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link webdriver.promise.consume}. * - * @param {!Function} fn The function to call to start the task. If the - * function returns a {@link webdriver.promise.Promise}, this instance - * will wait for it to be resolved before starting the next task. + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link webdriver.promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. * @param {string=} opt_description A description of the task. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the result of the action. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T */ - execute(fn: Function, opt_description?: string): Promise; + execute(fn: ()=>(T|Promise), opt_description?: string): Promise; /** * Inserts a {@code setTimeout} into the command queue. This is equivalent to From 47f874f4ff35d5c8456c35474285a9c8e54cdb91 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Thu, 9 Jul 2015 23:55:51 +0900 Subject: [PATCH 037/881] Update webdriver.promise.Promise Link: https://github.com/SeleniumHQ/selenium/commit/762a18540c7a78ca15599dedf4af3145ed7dd3fb --- .../selenium-webdriver-tests.ts | 24 +++++++++--- selenium-webdriver/selenium-webdriver.d.ts | 39 ++++++++++++------- 2 files changed, 43 insertions(+), 20 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index c887cb2ed..adf42a2cc 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -100,7 +100,8 @@ function TestFirefoxProfile() { function TestExecutors() { var exec: webdriver.CommandExecutor = executors.createExecutor("url"); - exec = executors.createExecutor(new webdriver.promise.Promise()); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); } function TestBuilder() { @@ -694,7 +695,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); - var sessionPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var sessionPromise: webdriver.promise.Promise; var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); @@ -780,10 +781,11 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); - element = new webdriver.WebElement(driver, new webdriver.promise.Promise()); + element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; var stringPromise: webdriver.promise.Promise; @@ -896,12 +898,12 @@ function TestPromiseModule() { var str: string = cancellationError.message; str = cancellationError.name; - var stringPromise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var stringPromise: webdriver.promise.Promise; var numberPromise: webdriver.promise.Promise; var booleanPromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; - webdriver.promise.all([new webdriver.promise.Promise()]).then(function (values: string[]) { }); + webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); webdriver.promise.asap('abc', function(value: any){ return true; }); webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); @@ -1070,7 +1072,17 @@ function TestDeferred() { } function TestPromiseClass() { - var promise: webdriver.promise.Promise = new webdriver.promise.Promise(); + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: webdriver.promise.Promise)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }, controlFlow); promise.cancel('Abort'); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index d9fe8cc4b..871c39d8a 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1289,28 +1289,39 @@ declare module webdriver { static isImplementation(object: any): boolean; } + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + /** * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, resolved, or rejected. Each promise starts + * in one of three states: pending, fulfilled, or rejected. Each promise starts * in the pending state and may make a single transition to either a - * fulfilled or failed state. + * fulfilled or rejected state, at which point the promise is considered + * resolved. * - *

    This class is based on the Promise/A proposal from CommonJS. Additional - * functions are provided for API compatibility with Dojo Deferred objects. - * - * @see http://wiki.commonjs.org/wiki/Promises/A + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ */ class Promise implements IThenable { - - //region Constructors - /** - * @constructor - * @see http://wiki.commonjs.org/wiki/Promises/A + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback functions, + * one for fulfilling the promise and another for rejecting it. + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor */ - constructor(); - - //endregion + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts //region Methods From 4aaf75d9f2f61d96153499b4c67c85cef8483f62 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 12:20:56 +0900 Subject: [PATCH 038/881] Add webdriver.By.Hash as a type alias Limitation: We can not assign webdriver.By to any variables --- .../selenium-webdriver-tests.ts | 18 +-- selenium-webdriver/selenium-webdriver.d.ts | 116 ++++++++++-------- 2 files changed, 72 insertions(+), 62 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index adf42a2cc..5deb02f35 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -551,15 +551,15 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); - // var locatorHash: webdriver.By.Hash; - // locatorHash = { className: 'class' }; - // locatorHash = { css: 'css' }; - // locatorHash = { id: 'id' }; - // locatorHash = { linkText: 'link' }; - // locatorHash = { name: 'name' }; - // locatorHash = { partialLinkText: 'text' }; - // locatorHash = { tagName: 'tag' }; - // locatorHash = { xpath: 'xpath' }; + var locatorHash: webdriver.By.Hash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 871c39d8a..a5f6d87d2 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4895,7 +4895,7 @@ declare module webdriver { thenFinally(callback: () => any): webdriver.promise.Promise; } - interface ILocatorStrategy { + module By { /** * Locates elements that have a specific class name. The returned locator * is equivalent to searching for elements with the CSS selector ".clazz". @@ -4905,7 +4905,7 @@ declare module webdriver { * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes * @see http://www.w3.org/TR/CSS2/selector.html#class-html */ - className(value: string): Locator; + function className(value: string): Locator; /** * Locates elements using a CSS selector. For browsers that do not support @@ -4917,7 +4917,7 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/CSS2/selector.html */ - css(value: string): Locator; + function css(value: string): Locator; /** * Locates an element by its ID. @@ -4925,7 +4925,7 @@ declare module webdriver { * @param {string} id The ID to search for. * @return {!webdriver.Locator} The new locator. */ - id(value: string): Locator; + function id(value: string): Locator; /** * Locates link elements whose {@linkplain webdriver.WebElement#getText visible @@ -4934,7 +4934,7 @@ declare module webdriver { * @param {string} text The link text to search for. * @return {!webdriver.Locator} The new locator. */ - linkText(value: string): Locator; + function linkText(value: string): Locator; /** * Locates an elements by evaluating a @@ -4946,7 +4946,7 @@ declare module webdriver { * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, * JavaScript-based locator function. */ - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; /** * Locates elements whose {@code name} attribute has the given value. @@ -4954,7 +4954,7 @@ declare module webdriver { * @param {string} name The name attribute to search for. * @return {!webdriver.Locator} The new locator. */ - name(value: string): Locator; + function name(value: string): Locator; /** * Locates link elements whose {@linkplain webdriver.WebElement#getText visible @@ -4963,7 +4963,7 @@ declare module webdriver { * @param {string} text The substring to check for in a link's visible text. * @return {!webdriver.Locator} The new locator. */ - partialLinkText(value: string): Locator; + function partialLinkText(value: string): Locator; /** * Locates elements with a given tag name. The returned locator is @@ -4975,7 +4975,7 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html */ - tagName(value: string): Locator; + function tagName(value: string): Locator; /** * Locates elements matching a XPath selector. Care should be taken when @@ -4989,44 +4989,54 @@ declare module webdriver { * @return {!webdriver.Locator} The new locator. * @see http://www.w3.org/TR/xpath/ */ + function xpath(value: string): Locator; + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + // For angular-protractor/angular-protractor-tests.ts + interface ILocatorStrategy { + className(value: string): Locator; + css(value: string): Locator; + id(value: string): Locator; + linkText(value: string): Locator; + js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + name(value: string): Locator; + partialLinkText(value: string): Locator; + tagName(value: string): Locator; xpath(value: string): Locator; } - var By: ILocatorStrategy; - - // module By { - // /** - // * Short-hand expressions for the primary element locator strategies. - // * For example the following two statements are equivalent: - // * - // * var e1 = driver.findElement(webdriver.By.id('foo')); - // * var e2 = driver.findElement({id: 'foo'}); - // * - // * Care should be taken when using JavaScript minifiers (such as the - // * Closure compiler), as locator hashes will always be parsed using - // * the un-obfuscated properties listed. - // * - // * @typedef {( - // * {className: string}| - // * {css: string}| - // * {id: string}| - // * {js: string}| - // * {linkText: string}| - // * {name: string}| - // * {partialLinkText: string}| - // * {tagName: string}| - // * {xpath: string})} - // */ - // type Hash = {className: string}| - // {css: string}| - // {id: string}| - // {js: string}| - // {linkText: string}| - // {name: string}| - // {partialLinkText: string}| - // {tagName: string}| - // {xpath: string}; - // } /** * An element locator. @@ -5047,15 +5057,15 @@ declare module webdriver { * @const */ static Strategy: { - className: typeof By.className; - css: typeof By.css; - id: typeof By.id; - js: typeof By.js; - linkText: typeof By.linkText; - name: typeof By.name; - partialLinkText: typeof By.partialLinkText; - tagName: typeof By.tagName; - xpath: typeof By.xpath; + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; }; /** From 04fd7c612df1b9faf9d4af229edffffffd537a91 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 14:59:55 +0900 Subject: [PATCH 039/881] Remove ILocatorStrategy --- angular-protractor/angular-protractor.d.ts | 16 +++++++++++++++- selenium-webdriver/selenium-webdriver-tests.ts | 3 +++ selenium-webdriver/selenium-webdriver.d.ts | 14 -------------- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 76f0b5f10..39cb7a81a 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -1228,7 +1228,21 @@ declare module protractor { row(index: number): LocatorWithColumn; } - interface IProtractorLocatorStrategy extends webdriver.ILocatorStrategy { + interface IProtractorLocatorStrategy { + /** + * webdriver's By is an enum of locator functions, so we must set it to + * a prototype before inheriting from it. + */ + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + linkText: typeof webdriver.By.linkText; + js: typeof webdriver.By.js; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + /** * Add a locator to this instance of ProtractorBy. This locator can then be * used with element(by.locatorName(args)). diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 5deb02f35..e69f8e64d 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -551,6 +551,9 @@ function TestLocator() { locator = webdriver.By.tagName('tag'); locator = webdriver.By.xpath('xpath'); + // Can import "By" without import declarations + var By = webdriver.By; + var locatorHash: webdriver.By.Hash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index a5f6d87d2..dbe4e1325 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -5024,20 +5024,6 @@ declare module webdriver { {xpath: string}; } - // For angular-protractor/angular-protractor-tests.ts - interface ILocatorStrategy { - className(value: string): Locator; - css(value: string): Locator; - id(value: string): Locator; - linkText(value: string): Locator; - js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - name(value: string): Locator; - partialLinkText(value: string): Locator; - tagName(value: string): Locator; - xpath(value: string): Locator; - } - - /** * An element locator. */ From 2fbe16791b86c48dce2a08b333180ccd212e9696 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 15:02:51 +0900 Subject: [PATCH 040/881] Switch to use "webdriver.By.Hash" instead of "any" --- selenium-webdriver/selenium-webdriver.d.ts | 40 +++++++--------------- 1 file changed, 12 insertions(+), 28 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index dbe4e1325..e1954ca35 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1816,11 +1816,7 @@ declare module webdriver { * The frame identifier. * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number): Condition; - function ableToSwitchToFrame(frame: IWebElement): Condition; - function ableToSwitchToFrame(frame: Locator): Condition; - function ableToSwitchToFrame(frame: (webdriver: WebDriver) => IWebElement): Condition; - function ableToSwitchToFrame(frame: any): Condition; + function ableToSwitchToFrame(frame: number|IWebElement|Locator|By.Hash|((webdriver: WebDriver)=>IWebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1892,8 +1888,7 @@ declare module webdriver { * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator): Condition; - function elementLocated(locator: any): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -1940,8 +1935,7 @@ declare module webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator): Condition; - function elementsLocated(locator: any): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -4100,8 +4094,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator): WebElementPromise; - findElement(locatorOrElement: any): WebElementPromise; + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4116,8 +4109,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will resolve * with whether the element is present on the page. */ - isElementPresent(locatorOrElement: Locator): webdriver.promise.Promise; - isElementPresent(locatorOrElement: any): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. @@ -4127,8 +4119,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to @@ -4193,7 +4184,6 @@ declare module webdriver { * }); *

  • */ - interface IWebElement { //region Methods @@ -4428,8 +4418,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator): WebElementPromise; - findElement(locator: any): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4440,8 +4429,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator): webdriver.promise.Promise; - isElementPresent(locator: any): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4452,8 +4440,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } class WebElement implements IWebElement, IWebElementFinders { @@ -4531,8 +4518,7 @@ declare module webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator): WebElementPromise; - findElement(locator: any): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4543,8 +4529,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator): webdriver.promise.Promise; - isElementPresent(locator: any): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4555,8 +4540,7 @@ declare module webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator): webdriver.promise.Promise; - findElements(locator: any): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. From d019180cb868988184b782ad44bfbabfe1ad6814 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 15:06:28 +0900 Subject: [PATCH 041/881] Follow signatures to the recent doc --- selenium-webdriver/selenium-webdriver-tests.ts | 15 ++++++++++----- selenium-webdriver/selenium-webdriver.d.ts | 8 +++----- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index e69f8e64d..5d102b01a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -714,9 +714,10 @@ function TestWebDriver() { var touchActions: webdriver.TouchSequence = driver.touchActions(); // call - stringPromise = driver.call(function(){}); - stringPromise = driver.call(function(){ var d: any = this;}, driver); - stringPromise = driver.call(function(a: number){}, driver, 1); + stringPromise = driver.call(function(){ return 'value'; }); + stringPromise = driver.call(function(){ return stringPromise; }); + stringPromise = driver.call(function(){ var d: any = this; return 'value'; }, driver); + stringPromise = driver.call(function(a: number){ return 'value'; }, driver, 1); voidPromise = driver.close(); flow = driver.controlFlow(); @@ -772,8 +773,12 @@ function TestWebDriver() { voidPromise = driver.sleep(123); stringPromise = driver.takeScreenshot(); - booleanPromise = driver.wait(function() { return true; }, 123); - booleanPromise = driver.wait(function() { return true; }, 123, 'Message'); + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait(function(driver: webdriver.WebDriver) { return true; }); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index e1954ca35..17a2c1020 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -3922,8 +3922,7 @@ declare module webdriver { * scripts return value. * @template T */ - executeAsyncScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeAsyncScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeAsyncScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute a custom function. @@ -3935,7 +3934,7 @@ declare module webdriver { * with the function's result. * @template T */ - call(fn: Function, opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + call(fn: (...var_args: any[])=>(T|webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to wait for a condition to hold. The condition may be @@ -3983,8 +3982,7 @@ declare module webdriver { * rejected if the condition times out. * @template T */ - wait(condition: webdriver.until.Condition, timeout: number, opt_message?: string): webdriver.promise.Promise; - wait(condition: (webdriver: WebDriver) => any, timeout: number, opt_message?: string): webdriver.promise.Promise; + wait(condition: webdriver.promise.Promise|webdriver.until.Condition|((driver: WebDriver)=>T), timeout?: number, opt_message?: string): webdriver.promise.Promise; /** * Schedules a command to make the driver sleep for the given amount of time. From 37a07946a59dd0627fc811f93d4d353d218f9826 Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 17:33:47 +0900 Subject: [PATCH 042/881] Add webdriver.Serializable Link: https://github.com/SeleniumHQ/selenium/commit/36ae4e02490ea71ab22c4094b46aadd7a5eb42f1#diff-9fd8281e531ca110881ce204a571c9e5 --- selenium-webdriver/selenium-webdriver.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 17a2c1020..205812695 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4159,6 +4159,26 @@ declare module webdriver { ELEMENT: string; } + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@code webdriver.WebDriver} instance, or by searching From 2381796282a42320ca73bb34082a6e006ebe6a4d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 18:11:20 +0900 Subject: [PATCH 043/881] Update webdriver.WebElement --- .../selenium-webdriver-tests.ts | 11 +- selenium-webdriver/selenium-webdriver.d.ts | 272 +++++++++++------- 2 files changed, 177 insertions(+), 106 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 5d102b01a..664401628 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -784,6 +784,11 @@ function TestWebDriver() { driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); } +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string|webdriver.promise.Promise = serializable.serialize(); +} + function TestWebElement() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -824,11 +829,15 @@ function TestWebElement() { booleanPromise = element.isEnabled(); booleanPromise = element.isSelected(); voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: webdriver.IWebElementId) { }); + element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getRawId().then(function (id: string) { }); + element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); + var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; var key: string = webdriver.WebElement.ELEMENT_KEY; } diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 205812695..6406d16cf 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -4461,9 +4461,52 @@ declare module webdriver { findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } - class WebElement implements IWebElement, IWebElementFinders { - //region Constructors + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link webdriver.WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.Serializable.} + */ + class WebElement implements Serializable { /** * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this * element. @@ -4472,12 +4515,14 @@ declare module webdriver { * underlying DOM element. * @constructor */ - constructor(driver: WebDriver, id: webdriver.promise.Promise); - constructor(driver: WebDriver, id: IWebElementId); + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); - //endregion - - //region Static Properties + /** + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + */ + static Id: IWebElementId; /** * The property key used in the wire protocol to indicate that a JSON object @@ -4487,9 +4532,6 @@ declare module webdriver { */ static ELEMENT_KEY: string; - //endregion - - //region Methods /** * @return {!webdriver.WebDriver} The parent driver for this instance. @@ -4498,37 +4540,35 @@ declare module webdriver { /** * Schedule a command to find a descendant of this element. If the element - * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will * be returned by the driver. Unlike other commands, this error cannot be * suppressed. In other words, scheduling a command to find an element doubles * as an assert that the element is present on the page. To test whether an - * element is present on the page, use {@code #isElementPresent} instead. + * element is present on the page, use {@link #isElementPresent} instead. * - *

    The search criteria for an element may be defined using one of the + * The search criteria for an element may be defined using one of the * factories in the {@link webdriver.By} namespace, or as a short-hand * {@link webdriver.By.Hash} object. For example, the following two statements * are equivalent: - *

    -         * var e1 = element.findElement(By.id('foo'));
    -         * var e2 = element.findElement({id:'foo'});
    -         * 
    * - *

    You may also provide a custom locator function, which takes as input + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input * this WebDriver instance and returns a {@link webdriver.WebElement}, or a * promise that will resolve to a WebElement. For example, to find the first * visible link on a page, you could write: - *

    -         * var link = element.findElement(firstVisibleLink);
              *
    -         * function firstVisibleLink(element) {
    -         *   var links = element.findElements(By.tagName('a'));
    -         *   return webdriver.promise.filter(links, function(link) {
    -         *     return links.isDisplayed();
    -         *   }).then(function(visibleLinks) {
    -         *     return visibleLinks[0];
    -         *   });
    -         * }
    -         * 
    + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } * * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The * locator strategy to use when searching for the element. @@ -4562,57 +4602,70 @@ declare module webdriver { /** * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the click command has completed. */ click(): webdriver.promise.Promise; /** * Schedules a command to type a sequence on the DOM element represented by this * instance. - *

    + * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the * following occurs: - *

      - *
    • The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - *
    • - *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys("text was", - * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, - * "now text is"); - * // Alternatively: - * element.sendKeys("text was", - * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), - * "now text is"); - *
    • - *
    • The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - *
    • - *
    - * Note: On browsers where native keyboard events are not yet - * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking "Browse..." and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link webdriver.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special * punctionation keys will be synthesized according to a standard QWERTY en-us * keyboard layout. * - * @param {...string} var_args The sequence of keys to - * type. All arguments will be joined into a single sequence (var_args is - * permitted for convenience). - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * keys have been typed. + * @param {...(string|!webdriver.promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when all keys have been typed. */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; + sendKeys(...var_args: Array>): webdriver.promise.Promise; /** * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's tag name. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's tag name. */ getTagName(): webdriver.promise.Promise; @@ -4622,81 +4675,85 @@ declare module webdriver { * its parent, the parent will be queried for its value. Where possible, color * values will be converted to their hex representation (e.g. #00ff00 instead of * rgb(0, 255, 0)). - *

    - * Warning: the value returned will be as the browser interprets it, so + * + * _Warning:_ the value returned will be as the browser interprets it, so * it may be tricky to form a proper assertion. * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * requested CSS value. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; /** * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value even if it has been modified after the - * page has been loaded. More exactly, this method will return the value of the - * given attribute, unless that attribute is not present, in which case the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the * value of the property with the same name is returned. If neither value is - * set, null is returned. The "style" attribute is converted as best can be to a + * set, null is returned (for example, the "value" property of a textarea + * element). The "style" attribute is converted as best can be to a * text representation with a trailing semi-colon. The following are deemed to - * be "boolean" attributes and will be returned as thus: + * be "boolean" attributes and will return either "true" or null: * - *

    async, autofocus, autoplay, checked, compact, complete, controls, declare, + * async, autofocus, autoplay, checked, compact, complete, controls, declare, * defaultchecked, defaultselected, defer, disabled, draggable, ended, * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, * selected, spellcheck, truespeed, willvalidate * - *

    Finally, the following commonly mis-capitalized attribute/property names + * Finally, the following commonly mis-capitalized attribute/property names * are evaluated as expected: - *

      - *
    • "class" - *
    • "readonly" - *
    + * + * - "class" + * - "readonly" + * * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * attribute's value. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. */ getAttribute(attributeName: string): webdriver.promise.Promise; /** * Get the visible (i.e. not hidden by CSS) innerText of this element, including * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's visible text. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's visible text. */ getText(): webdriver.promise.Promise; /** * Schedules a command to compute the size of this element's bounding box, in * pixels. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's size as a {@code {width:number, height:number}} object. + * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. */ getSize(): webdriver.promise.Promise; /** * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * element's location as a {@code {x:number, y:number}} object. + * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. */ getLocation(): webdriver.promise.Promise; /** * Schedules a command to query whether the DOM element represented by this * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently enabled. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. */ isEnabled(): webdriver.promise.Promise; /** * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently selected. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. */ isSelected(): webdriver.promise.Promise; @@ -4704,8 +4761,8 @@ declare module webdriver { * Schedules a command to submit the form containing this element (or this * element if it is a FORM element). This command is a no-op if the element is * not contained in a form. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the form has been submitted. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the form has been submitted. */ submit(): webdriver.promise.Promise; @@ -4713,22 +4770,22 @@ declare module webdriver { * Schedules a command to clear the {@code value} of this element. This command * has no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the element has been cleared. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the element has been cleared. */ clear(): webdriver.promise.Promise; /** * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently visible on the page. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. */ isDisplayed(): webdriver.promise.Promise; /** * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the element's outer HTML. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's outer HTML. */ getOuterHtml(): webdriver.promise.Promise; @@ -4740,6 +4797,17 @@ declare module webdriver { */ getId(): webdriver.promise.Promise; + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4747,10 +4815,6 @@ declare module webdriver { */ getInnerHtml(): webdriver.promise.Promise; - //endregion - - //region Static Methods - /** * Compares to WebElements for equality. * @param {!webdriver.WebElement} a A WebElement. @@ -4759,8 +4823,6 @@ declare module webdriver { * whether the two WebElements are equal. */ static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; - - //endregion } /** From 7997188acd0dfc6b953bef6fa30d60989e1e2e5d Mon Sep 17 00:00:00 2001 From: Kuniwak Date: Fri, 10 Jul 2015 18:40:06 +0900 Subject: [PATCH 044/881] Remove references for IWebElement --- .../selenium-webdriver-tests.ts | 4 +- selenium-webdriver/selenium-webdriver.d.ts | 50 +++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 664401628..d8546c6df 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -1013,8 +1013,8 @@ function TestUntilModule() { var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: webdriver.until.Condition; - var conditionWebElements: webdriver.until.Condition; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; conditionB = webdriver.until.ableToSwitchToFrame(5); var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 6406d16cf..d54ea62fa 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1816,7 +1816,7 @@ declare module webdriver { * The frame identifier. * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number|IWebElement|Locator|By.Hash|((webdriver: WebDriver)=>IWebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the @@ -1833,7 +1833,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isEnabled */ - function elementIsDisabled(element: IWebElement): Condition; + function elementIsDisabled(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be enabled. @@ -1842,7 +1842,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isEnabled */ - function elementIsEnabled(element: IWebElement): Condition; + function elementIsEnabled(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be deselected. @@ -1851,7 +1851,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isSelected */ - function elementIsNotSelected(element: IWebElement): Condition; + function elementIsNotSelected(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be in the DOM, @@ -1861,7 +1861,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isDisplayed */ - function elementIsNotVisible(element: IWebElement): Condition; + function elementIsNotVisible(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to be selected. @@ -1869,7 +1869,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isSelected */ - function elementIsSelected(element: IWebElement): Condition; + function elementIsSelected(element: WebElement): Condition; /** * Creates a condition that will wait for the given element to become visible. @@ -1878,7 +1878,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#isDisplayed */ - function elementIsVisible(element: IWebElement): Condition; + function elementIsVisible(element: WebElement): Condition; /** * Creates a condition that will loop until an element is @@ -1888,7 +1888,7 @@ declare module webdriver { * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -1900,7 +1900,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextContains(element: IWebElement, substr: string): Condition; + function elementTextContains(element: WebElement, substr: string): Condition; /** * Creates a condition that will wait for the given element's @@ -1912,7 +1912,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextIs(element: IWebElement, text: string): Condition; + function elementTextIs(element: WebElement, text: string): Condition; /** * Creates a condition that will wait for the given element's @@ -1924,7 +1924,7 @@ declare module webdriver { * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ - function elementTextMatches(element: IWebElement, regex: RegExp): Condition; + function elementTextMatches(element: WebElement, regex: RegExp): Condition; /** * Creates a condition that will loop until at least one element is @@ -1935,7 +1935,7 @@ declare module webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -1945,7 +1945,7 @@ declare module webdriver { * @param {!webdriver.WebElement} element The element that should become stale. * @return {!until.Condition.} The new condition. */ - function stalenessOf(element: IWebElement): Condition; + function stalenessOf(element: WebElement): Condition; /** * Creates a condition that will wait for the current page's title to contain @@ -2135,7 +2135,7 @@ declare module webdriver { * Defaults to (0, 0). * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: IWebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; mouseMove(location: ILocation): ActionSequence; /** @@ -2160,7 +2160,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; mouseDown(opt_elementOrButton?: number): ActionSequence; /** @@ -2183,7 +2183,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; mouseUp(opt_elementOrButton?: number): ActionSequence; /** @@ -2195,8 +2195,8 @@ declare module webdriver { * location to drag to, either as another WebElement or an offset in pixels. * @return {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: IWebElement, location: IWebElement): ActionSequence; - dragAndDrop(element: IWebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. @@ -2214,7 +2214,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; click(opt_elementOrButton?: number): ActionSequence; /** @@ -2236,7 +2236,7 @@ declare module webdriver { * first argument. * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: IWebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; doubleClick(opt_elementOrButton?: number): ActionSequence; /** @@ -2309,7 +2309,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to tap. * @return {!webdriver.TouchSequence} A self reference. */ - tap(elem: IWebElement): TouchSequence; + tap(elem: WebElement): TouchSequence; /** @@ -2318,7 +2318,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to double tap. * @return {!webdriver.TouchSequence} A self reference. */ - doubleTap(elem: IWebElement): TouchSequence; + doubleTap(elem: WebElement): TouchSequence; /** @@ -2327,7 +2327,7 @@ declare module webdriver { * @param {!webdriver.WebElement} elem The element to long press. * @return {!webdriver.TouchSequence} A self reference. */ - longPress(elem: IWebElement): TouchSequence; + longPress(elem: WebElement): TouchSequence; /** @@ -2374,7 +2374,7 @@ declare module webdriver { * @param {{x: number, y: number}} offset The offset to scroll to. * @return {!webdriver.TouchSequence} A self reference. */ - scrollFromElement(elem: IWebElement, offset: IOffset): TouchSequence; + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; /** @@ -2395,7 +2395,7 @@ declare module webdriver { * @param {number} speed The speed to flick at in pixels per second. * @return {!webdriver.TouchSequence} A self reference. */ - flickElement(elem: IWebElement, offset: IOffset, speed: number): TouchSequence; + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } From ad21a10ba76af3ecca3cf733bafef8605eabb471 Mon Sep 17 00:00:00 2001 From: Anthony Guo Date: Tue, 7 Jul 2015 14:14:34 -0700 Subject: [PATCH 045/881] codemirror.d.ts: Changed the Doc class type to an interface, and exposed the CodeMirror.Pos constructor This allows the user to extend the definition for the CodeMirror.Doc interface over multiple files. It also allows for instantiating new CodeMirror.Position type objects using "new CodeMirror.Pos(...)" --- codemirror/codemirror.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 65692cf1c..8584b6a2b 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -7,6 +7,8 @@ declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfig declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare module CodeMirror { + export var Doc : CodeMirror.Doc; + export var Pos: CodeMirror.Position; export var Pass: any; function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; @@ -387,8 +389,8 @@ declare module CodeMirror { getTextArea(): HTMLTextAreaElement; } - class Doc { - constructor (text: string, mode?: any, firstLineNumber?: number); + interface Doc { + new (text: string, mode?: any, firstLineNumber?: number): Doc; /** Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n"). */ getValue(seperator?: string): string; @@ -616,6 +618,7 @@ declare module CodeMirror { } interface Position { + new (line: number, ch: number): Position; ch: number; line: number; } From cd5de37f831e63982d0b47d3684f37bbb3410b31 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:17:37 +0200 Subject: [PATCH 046/881] Added definitions for v1.3.5 of the socket.io lib --- .../legacy/socket.io-client-1.2.0.d.ts | 45 + socket.io-client/socket.io-client.d.ts | 665 ++++++++++++- socket.io/legacy/socket.io-1.2.0.d.ts | 96 ++ socket.io/socket.io.d.ts | 877 ++++++++++++++++-- 4 files changed, 1578 insertions(+), 105 deletions(-) create mode 100644 socket.io-client/legacy/socket.io-client-1.2.0.d.ts create mode 100644 socket.io/legacy/socket.io-1.2.0.d.ts diff --git a/socket.io-client/legacy/socket.io-client-1.2.0.d.ts b/socket.io-client/legacy/socket.io-client-1.2.0.d.ts new file mode 100644 index 000000000..c5d783764 --- /dev/null +++ b/socket.io-client/legacy/socket.io-client-1.2.0.d.ts @@ -0,0 +1,45 @@ +// Type definitions for socket.io-client 1.2.0 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare var io: SocketIOClientStatic; + +declare module 'socket.io-client' { + export = io; +} + +interface SocketIOClientStatic { + (host: string, details?: any): SocketIOClient.Socket; + (details?: any): SocketIOClient.Socket; + connect(host: string, details?: any): SocketIOClient.Socket; + connect(details?: any): SocketIOClient.Socket; + protocol: number; + Socket: { new (...args: any[]): SocketIOClient.Socket }; + Manager: SocketIOClient.ManagerStatic; +} + +declare module SocketIOClient { + interface Socket { + on(event: string, fn: Function): Socket; + once(event: string, fn: Function): Socket; + off(event?: string, fn?: Function): Socket; + emit(event: string, ...args: any[]): Socket; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + connected: boolean; + } + + interface ManagerStatic { + (url: string, opts: any): SocketIOClient.Manager; + new (url: string, opts: any): SocketIOClient.Manager; + } + + interface Manager { + reconnection(v: boolean): Manager; + reconnectionAttempts(v: boolean): Manager; + reconnectionDelay(v: boolean): Manager; + reconnectionDelayMax(v: boolean): Manager; + timeout(v: boolean): Manager; + } +} diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index c5d783764..7e15773e6 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -1,45 +1,650 @@ -// Type definitions for socket.io-client 1.2.0 +// Type definitions for socket.io-client 1.3.5 // Project: http://socket.io/ -// Definitions by: PROGRE +// Definitions by: divillysausages // Definitions: https://github.com/borisyankov/DefinitelyTyped declare var io: SocketIOClientStatic; declare module 'socket.io-client' { - export = io; + export = io; } interface SocketIOClientStatic { - (host: string, details?: any): SocketIOClient.Socket; - (details?: any): SocketIOClient.Socket; - connect(host: string, details?: any): SocketIOClient.Socket; - connect(details?: any): SocketIOClient.Socket; - protocol: number; - Socket: { new (...args: any[]): SocketIOClient.Socket }; - Manager: SocketIOClient.ManagerStatic; + + /** + * Looks up an existing 'Manager' for multiplexing. If the user summons: + * 'io( 'http://localhost/a' );' + * 'io( 'http://localhost/b' );' + * + * We reuse the existing instance based on the same scheme/port/host, and + * we initialize sockets for each namespace. If autoConnect isn't set to + * false in the options, then we'll automatically connect + * @param uri The uri that we'll connect to, including the namespace, where '/' is the default one (e.g. http://localhost:4000/somenamespace) + * @opts Any connect options that we want to pass along + * @return A Socket object + */ + ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * Auto-connects to the window location and defalt namespace. + * E.g. window.protocol + '//' + window.host + ':80/' + * @opts Any connect options that we want to pass along + * @return A Socket object + */ + ( opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * @see the default constructor (io(uri, opts)) + */ + connect( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * @see the default constructor (io(opts)) + */ + connect( opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Socket; + + /** + * The socket.io protocol revision number this client works with + * @default 4 + */ + protocol: number; + + /** + * Socket constructor - exposed for the standalone build + */ + Socket: SocketIOClient.Socket; + + /** + * Manager constructor - exposed for the standalone build + */ + Manager: SocketIOClient.ManagerStatic; } declare module SocketIOClient { - interface Socket { - on(event: string, fn: Function): Socket; - once(event: string, fn: Function): Socket; - off(event?: string, fn?: Function): Socket; - emit(event: string, ...args: any[]): Socket; - listeners(event: string): Function[]; - hasListeners(event: string): boolean; - connected: boolean; - } + + /** + * The base emiter class, used by Socket and Manager + */ + interface Emitter { + /** + * Adds a listener for a particular event. Calling multiple times will add + * multiple listeners + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on the + * event in question + * @return This Emitter + */ + on( event: string, fn: Function ):Emitter; + + /** + * @see on( event, fn ) + */ + addEventListener( event: string, fn: Function ):Emitter; + + /** + * Adds a listener for a particular event that will be invoked + * a single time before being automatically removed + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on + * the event in question + * @return This Emitter + */ + once( event: string, fn: Function ):Emitter; + + /** + * Removes a listener for a particular type of event. This will either + * remove a specific listener, or all listeners for this type of event + * @param event The event that we want to remove the listener of + * @param fn The function to remove, or null if we want to remove all functions + * @return This Emitter + */ + off( event: string, fn?: Function ):Emitter; + + /** + * @see off( event, fn ) + */ + removeListener( event: string, fn?: Function ):Emitter; + + /** + * @see off( event, fn ) + */ + removeEventListener( event: string, fn?: Function ):Emitter; + + /** + * Removes all event listeners on this object + * @return This Emitter + */ + removeAllListeners():Emitter; + + /** + * Emits 'event' with the given args + * @param event The event that we want to emit + * @param args Optional arguments to emit with the event + * @return Emitter + */ + emit( event: string, ...args: any[] ):Emitter; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + + /** + * Returns if we have listeners for a particular event + * @param event The event that we want to check if we've listeners for + * @return True if we have listeners for this event, false otherwise + */ + hasListeners( event: string ):boolean; + } + + /** + * The Socket static interface + */ + interface SocketStatic { + + /** + * Creates a new Socket, used for communicating with a specific namespace + * @param io The Manager that's controlling this socket + * @param nsp The namespace that this socket is for (@default '/') + * @return A new Socket + */ + ( io: SocketIOClient.Manager, nsp: string ): Socket; + + /** + * Creates a new Socket, used for communicating with a specific namespace + * @param io The Manager that's controlling this socket + * @param nsp The namespace that this socket is for (@default '/') + * @return A new Socket + */ + new ( url: string, opts: any ): SocketIOClient.Manager; + } + + /** + * The Socket that we use to connect to a Namespace on the server + */ + interface Socket extends Emitter { + + /** + * The Manager that's controller this socket + */ + io: SocketIOClient.Manager; + + /** + * The namespace that this socket is for + * @default '/' + */ + nsp: string; + + /** + * Are we currently connected? + * @default false + */ + connected: boolean; + + /** + * Are we currently disconnected? + * @default true + */ + disconnected: boolean; + + /** + * Opens our socket so that it connects. If the 'autoConnect' option for io is + * true (default), then this is called automatically when the Socket is created + */ + open(): Socket; + + /** + * @see open(); + */ + connect(): Socket; + + /** + * Sends a 'message' event + * @param args Any optional arguments that we want to send + * @see emit + * @return This Socket + */ + send( ...args: any[] ):Socket; + + /** + * An override of the base emit. If the event is one of: + * connect + * connect_error + * connect_timeout + * disconnect + * error + * reconnect + * reconnect_attempt + * reconnect_failed + * reconnect_error + * reconnecting + * then the event is emitted normally. Otherwise, if we're connected, the + * event is sent. Otherwise, it's buffered. + * + * If the last argument is a function, then it will be called + * as an 'ack' when the response is received. The parameter(s) of the + * ack will be whatever data is returned from the event + * @param event The event that we're emitting + * @param args Optional arguments to send with the event + * @return This Socket + */ + emit( event: string, ...args: any[] ):Socket; + + /** + * Disconnects the socket manually + * @return This Socket + */ + close():Socket; + + /** + * @see close() + */ + disconnect():Socket; + } - interface ManagerStatic { - (url: string, opts: any): SocketIOClient.Manager; - new (url: string, opts: any): SocketIOClient.Manager; - } + /** + * The Manager static interface + */ + interface ManagerStatic { + /** + * Creates a new Manager + * @param uri The URI that we're connecting to (e.g. http://localhost:4000) + * @param opts Any connection options that we want to use (and pass to engine.io) + * @return A Manager + */ + ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Manager; + + /** + * Creates a new Manager with the default URI (window host) + * @param opts Any connection options that we want to use (and pass to engine.io) + */ + ( opts: SocketIOClient.ConnectOpts ):SocketIOClient.Manager; + + /** + * @see default constructor + */ + new ( uri: string, opts?: SocketIOClient.ConnectOpts ): SocketIOClient.Manager; + + /** + * @see default constructor + */ + new ( opts: SocketIOClient.ConnectOpts ):SocketIOClient.Manager; + } - interface Manager { - reconnection(v: boolean): Manager; - reconnectionAttempts(v: boolean): Manager; - reconnectionDelay(v: boolean): Manager; - reconnectionDelayMax(v: boolean): Manager; - timeout(v: boolean): Manager; - } + /** + * The Manager class handles all the Namespaces and Sockets that we're using + */ + interface Manager extends Emitter { + + /** + * All the namespaces currently controlled by this Manager, and the Sockets + * that we're using to communicate with them + */ + nsps: { [namespace:string]: Socket }; + + /** + * The connect options that we used when creating this Manager + */ + opts: SocketIOClient.ConnectOpts; + + /** + * The state of the Manager. Either 'closed', 'opening', or 'open' + */ + readyState: string; + + /** + * The URI that this manager is for (host + port), e.g. 'http://localhost:4000' + */ + uri: string; + + /** + * The currently connected sockets + */ + connected: Socket[]; + + /** + * If we should auto connect (also used when creating Sockets). Set via the + * opts object + */ + autoConnect: boolean; + + /** + * Gets if we should reconnect automatically + * @default true + */ + reconnection(): boolean; + + /** + * Sets if we should reconnect automatically + * @param v True if we should reconnect automatically, false otherwise + * @default true + * @return This Manager + */ + reconnection( v: boolean ): Manager; + + /** + * Gets the number of reconnection attempts we should try before giving up + * @default Infinity + */ + reconnectionAttempts(): number; + + /** + * Sets the number of reconnection attempts we should try before giving up + * @param v The number of attempts we should do before giving up + * @default Infinity + * @return This Manager + */ + reconnectionAttempts( v: number ): Manager; + + /** + * Gets the delay in milliseconds between each reconnection attempt + * @default 1000 + */ + reconnectionDelay(): number; + + /** + * Sets the delay in milliseconds between each reconnection attempt + * @param v The delay in milliseconds + * @default 1000 + * @return This Manager + */ + reconnectionDelay( v: number ): Manager; + + /** + * Gets the max reconnection delay in milliseconds between each reconnection + * attempt + * @default 5000 + */ + reconnectionDelayMax(): number; + + /** + * Sets the max reconnection delay in milliseconds between each reconnection + * attempt + * @param v The max reconnection dleay in milliseconds + * @return This Manager + */ + reconnectionDelayMax( v: number ): Manager; + + /** + * Gets the randomisation factor used in the exponential backoff jitter + * when reconnecting + * @default 0.5 + */ + randomizationFactor(): number; + + /** + * Sets the randomisation factor used in the exponential backoff jitter + * when reconnecting + * @param The reconnection randomisation factor + * @default 0.5 + * @return This Manager + */ + randomizationFactor( v: number ): Manager; + + /** + * Gets the timeout in milliseconds for our connection attempts + * @default 20000 + */ + timeout(): number; + + /** + * Sets the timeout in milliseconds for our connection attempts + * @param The connection timeout milliseconds + * @return This Manager + */ + timeout(v: boolean): Manager; + + /** + * Sets the current transport socket and opens our connection + * @param fn An optional callback to call when our socket has either opened, or + * failed. It can take one optional parameter of type Error + * @return This Manager + */ + open( fn?: (err?: any) => void ): Manager; + + /** + * @see open( fn ); + */ + connect( fn?: (err?: any) => void ): Manager; + + /** + * Creates a new Socket for the given namespace + * @param nsp The namespace that this Socket is for + * @return A new Socket, or if one has already been created for this namespace, + * an existing one + */ + socket( nsp: string ): Socket; + } + + /** + * Options we can pass to the socket when connecting + */ + interface ConnectOpts { + + /** + * Should we force a new Manager for this connection? + * @default false + */ + forceNew?: boolean; + + /** + * Should we multiplex our connection (reuse existing Manager) ? + * @default true + */ + multiplex?: boolean; + + /** + * The path to get our client file from, in the case of the server + * serving it + * @default '/socket.io' + */ + path?: string; + + /** + * Should we allow reconnections? + * @default true + */ + reconnection?: boolean; + + /** + * How many reconnection attempts should we try? + * @default Infinity + */ + reconnectionAttempts?: boolean; + + /** + * The time delay in milliseconds between reconnection attempts + * @default 1000 + */ + reconnectionDelay?: number; + + /** + * The max time delay in milliseconds between reconnection attempts + * @default 5000 + */ + reconnectionDelayMax?: number; + + /** + * Used in the exponential backoff jitter when reconnecting + * @default 0.5 + */ + randomizationFactor?: number; + + /** + * The timeout in milliseconds for our connection attempt + * @default 20000 + */ + timeout?: number; + + /** + * Should we automically connect? + * @default true + */ + autoConnect?: boolean; + + /** + * The host that we're connecting to. Set from the URI passed when connecting + */ + host?: string; + + /** + * The hostname for our connection. Set from the URI passed when connecting + */ + hostname?: string; + + /** + * If this is a secure connection. Set from the URI passed when connecting + */ + secure?: boolean; + + /** + * The port for our connection. Set from the URI passed when connecting + */ + port?: string; + + /** + * Any query parameters in our uri. Set from the URI passed when connecting + */ + query?: Object; + + /** + * `http.Agent` to use, defaults to `false` (NodeJS only) + */ + agent?: string|boolean; + + /** + * Whether the client should try to upgrade the transport from + * long-polling to something better. + * @default true + */ + upgrade?: boolean; + + /** + * Forces JSONP for polling transport. + */ + forceJSONP?: boolean; + + /** + * Determines whether to use JSONP when necessary for polling. If + * disabled (by settings to false) an error will be emitted (saying + * "No transports available") if no other transports are available. + * If another transport is available for opening a connection (e.g. + * WebSocket) that transport will be used instead. + * @default true + */ + jsonp?: boolean; + + /** + * Forces base 64 encoding for polling transport even when XHR2 + * responseType is available and WebSocket even if the used standard + * supports binary. + */ + forceBase64?: boolean; + + /** + * Enables XDomainRequest for IE8 to avoid loading bar flashing with + * click sound. default to `false` because XDomainRequest has a flaw + * of not sending cookie. + * @default false + */ + enablesXDR?: boolean; + + /** + * The param name to use as our timestamp key + * @default 't' + */ + timestampParam?: string; + + /** + * Whether to add the timestamp with each transport request. Note: this + * is ignored if the browser is IE or Android, in which case requests + * are always stamped + * @default false + */ + timestampRequests?: boolean; + + /** + * A list of transports to try (in order). Engine.io always attempts to + * connect directly with the first one, provided the feature detection test + * for it passes. + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * The port the policy server listens on + * @default 843 + */ + policyPost?: number; + + /** + * If true and if the previous websocket connection to the server succeeded, + * the connection attempt will bypass the normal upgrade process and will + * initially try websocket. A connection attempt following a transport error + * will use the normal upgrade process. It is recommended you turn this on + * only when using SSL/TLS connections, or if you know that your network does + * not block websockets. + * @default false + */ + rememberUpgrade?: boolean; + + /** + * Are we only interested in transports that support binary? + */ + onlyBinaryUpgrades?: boolean; + + /** + * (SSL) Certificate, Private key and CA certificates to use for SSL. + * Can be used in Node.js client environment to manually specify + * certificate information. + */ + pfx?: string; + + /** + * (SSL) Private key to use for SSL. Can be used in Node.js client + * environment to manually specify certificate information. + */ + key?: string; + + /** + * (SSL) A string or passphrase for the private key or pfx. Can be + * used in Node.js client environment to manually specify certificate + * information. + */ + passphrase?: string + + /** + * (SSL) Public x509 certificate to use. Can be used in Node.js client + * environment to manually specify certificate information. + */ + cert?: string; + + /** + * (SSL) An authority certificate or array of authority certificates to + * check the remote host against.. Can be used in Node.js client + * environment to manually specify certificate information. + */ + ca?: string|string[]; + + /** + * (SSL) A string describing the ciphers to use or exclude. Consult the + * [cipher format list] + * (http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT) for + * details on the format.. Can be used in Node.js client environment to + * manually specify certificate information. + */ + ciphers?: string; + + /** + * (SSL) If true, the server certificate is verified against the list of + * supplied CAs. An 'error' event is emitted if verification fails. + * Verification happens at the connection level, before the HTTP request + * is sent. Can be used in Node.js client environment to manually specify + * certificate information. + */ + rejectUnauthorized?: boolean; + + } } diff --git a/socket.io/legacy/socket.io-1.2.0.d.ts b/socket.io/legacy/socket.io-1.2.0.d.ts new file mode 100644 index 000000000..3f3c042fe --- /dev/null +++ b/socket.io/legacy/socket.io-1.2.0.d.ts @@ -0,0 +1,96 @@ +// Type definitions for socket.io 1.2.0 +// Project: http://socket.io/ +// Definitions by: PROGRE +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'socket.io' { + var server: SocketIOStatic; + + export = server; +} + +interface SocketIOStatic { + (): SocketIO.Server; + (srv: any, opts?: any): SocketIO.Server; + (port: number, opts?: any): SocketIO.Server; + (opts: any): SocketIO.Server; + + listen: SocketIOStatic; +} + +declare module SocketIO { + interface Server { + serveClient(v: boolean): Server; + path(v: string): Server; + adapter(v: any): Server; + origins(v: string): Server; + sockets: Namespace; + attach(srv: any, opts?: any): Server; + attach(port: number, opts?: any): Server; + listen(srv: any, opts?: any): Server; + listen(port: number, opts?: any): Server; + bind(srv: any): Server; + onconnection(socket: any): Server; + of(nsp: string): Namespace; + emit(name: string, ...args: any[]): Socket; + use(fn: Function): Namespace; + + on(event: 'connection', listener: (socket: Socket) => void): Namespace; + on(event: 'connect', listener: (socket: Socket) => void): Namespace; + on(event: string, listener: Function): Namespace; + } + + interface Namespace extends NodeJS.EventEmitter { + name: string; + connected: { [id: string]: Socket }; + use(fn: Function): Namespace; + in(room: string): Namespace; + + on(event: 'connection', listener: (socket: Socket) => void): Namespace; + on(event: 'connect', listener: (socket: Socket) => void): Namespace; + on(event: string, listener: Function): Namespace; + } + + interface Socket { + rooms: string[]; + client: Client; + conn: any; + request: any; + id: string; + handshake: { + headers: any; + time: string; + address: any; + xdomain: boolean; + secure: boolean; + issued: number; + url: string; + query: any; + }; + + emit(name: string, ...args: any[]): Socket; + join(name: string, fn?: Function): Socket; + leave(name: string, fn?: Function): Socket; + to(room: string): Socket; + in(room: string): Socket; + send(...args: any[]): Socket; + write(...args: any[]): Socket; + + on(event: string, listener: Function): Socket; + once(event: string, listener: Function): Socket; + removeListener(event: string, listener: Function): Socket; + removeAllListeners(event: string): Socket; + broadcast: Socket; + volatile: Socket; + connected: boolean; + disconnect(close?: boolean): Socket; + } + + interface Client { + conn: any; + request: any; + id: string; + } +} diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index 3f3c042fe..045e0007a 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -1,96 +1,823 @@ -// Type definitions for socket.io 1.2.0 +// Type definitions for socket.io 1.3.5 // Project: http://socket.io/ -// Definitions by: PROGRE +// Definitions by: divillysausages // Definitions: https://github.com/borisyankov/DefinitelyTyped /// declare module 'socket.io' { - var server: SocketIOStatic; + var server: SocketIOStatic; - export = server; + export = server; } interface SocketIOStatic { - (): SocketIO.Server; - (srv: any, opts?: any): SocketIO.Server; - (port: number, opts?: any): SocketIO.Server; - (opts: any): SocketIO.Server; + /** + * Default Server constructor + */ + (): SocketIO.Server; + + /** + * Creates a new Server + * @param srv The HTTP server that we're going to bind to + * @param opts An optional parameters object + */ + (srv: any, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param port A port to bind to, as a number, or a string + * @param An optional parameters object + */ + (port: string|number, opts?: SocketIO.ServerOptions): SocketIO.Server; + + /** + * Creates a new Server + * @param A parameters object + */ + (opts: SocketIO.ServerOptions): SocketIO.Server; + /** + * Backwards compatibility + * @see io().listen() + */ listen: SocketIOStatic; } declare module SocketIO { - interface Server { - serveClient(v: boolean): Server; - path(v: string): Server; - adapter(v: any): Server; - origins(v: string): Server; - sockets: Namespace; - attach(srv: any, opts?: any): Server; - attach(port: number, opts?: any): Server; - listen(srv: any, opts?: any): Server; - listen(port: number, opts?: any): Server; - bind(srv: any): Server; - onconnection(socket: any): Server; - of(nsp: string): Namespace; - emit(name: string, ...args: any[]): Socket; - use(fn: Function): Namespace; + + interface Server { + + /** + * A dictionary of all the namespaces currently on this Server + */ + nsps: {[namespace: string]: Namespace}; + + /** + * The default '/' Namespace + */ + sockets: Namespace; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Server; + + /** + * Server request verification function, that checks for allowed origins + * @param req The http.IncomingMessage request + * @param fn The callback to be called. It should take one parameter, err, + * which will be null if there was no problem, and one parameter, success, + * of type boolean + */ + checkRequest( req:any, fn:( err: any, success: boolean ) => void ):void; + + /** + * Gets whether we're serving the client.js file or not + * @default true + */ + serveClient(): boolean; + + /** + * Sets whether we're serving the client.js file or not + * @param v True if we want to serve the file, false otherwise + * @default true + * @return This Server + */ + serveClient( v: boolean ): Server; + + /** + * Gets the client serving path + * @default '/socket.io' + */ + path(): string; + + /** + * Sets the client serving path + * @param v The path to serve the client file on + * @default '/socket.io' + * @return This Server + */ + path( v: string ): Server; + + /** + * Gets the adapter that we're going to use for handling rooms + * @default typeof Adapter + */ + adapter(): any; + + /** + * Sets the adapter (class) that we're going to use for handling rooms + * @param v The class for the adapter to create + * @default typeof Adapter + * @return This Server + */ + adapter( v: any ): Server; + + /** + * Gets the allowed origins for requests + * @default "*:*" + */ + origins(): string; + + /** + * Sets the allowed origins for requests + * @param v The allowed origins, in host:port form + * @default "*:*" + * return This Server + */ + origins( v: string ): Server; + + /** + * Attaches socket.io to a server + * @param srv The http.Server that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( srv: any, opts?: ServerOptions ): Server; + + /** + * Attaches socket.io to a port + * @param port The port that we want to attach to + * @param opts An optional parameters object + * @return This Server + */ + attach( port: number, opts?: ServerOptions ): Server; + + /** + * @see attach( srv, opts ) + */ + listen( srv: any, opts?: ServerOptions ): Server; + + /** + * @see attach( port, opts ) + */ + listen( port: number, opts?: ServerOptions ): Server; + + /** + * Binds socket.io to an engine.io intsance + * @param src The Engine.io (or compatible) server to bind to + * @return This Server + */ + bind( srv: any ): Server; + + /** + * Called with each incoming connection + * @param socket The Engine.io Socket + * @return This Server + */ + onconnection( socket: any ): Server; + + /** + * Looks up/creates a Namespace + * @param nsp The name of the NameSpace to look up/create. Should start + * with a '/' + * @return The Namespace + */ + of( nsp: string ): Namespace; + + /** + * Closes the server connection + */ + close():void; - on(event: 'connection', listener: (socket: Socket) => void): Namespace; - on(event: 'connect', listener: (socket: Socket) => void): Namespace; - on(event: string, listener: Function): Namespace; - } + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return The default '/' Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @return The default '/' Namespace + */ + on( event: string, listener: Function ): Namespace; + + /** + * Targets a room when emitting to the default '/' Namespace + * @param room The name of the room that we're targeting + * @return The default '/' Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket, on the default '/' Namespace + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return The default '/' Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Emits an event to the default Namespace + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return The default '/' Namespace + */ + emit( event: string, ...args: any[]): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return The default '/' Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; + } + + /** + * Options to pass to our server when creating it + */ + interface ServerOptions { + + /** + * The path to server the client file to + * @default '/socket.io' + */ + path?: string; + + /** + * Should we serve the client file? + * @default true + */ + serveClient?: boolean; + + /** + * The adapter to use for handling rooms. NOTE: this should be a class, + * not an object + * @default typeof Adapter + */ + adapter?: Adapter; + + /** + * Accepted origins + * @default '*:*' + */ + origins?: string; + + /** + * How many milliseconds without a pong packed to consider the connection closed (engine.io) + * @default 60000 + */ + pingTimeout?: number; + + /** + * How many milliseconds before sending a new ping packet (keep-alive) (engine.io) + * @default 25000 + */ + pingInterval?: number; + + /** + * How many bytes or characters a message can be when polling, before closing the session + * (to avoid Dos) (engine.io) + * @default 10E7 + */ + maxHttpBufferSize?: number; + + /** + * A function that receives a given handshake or upgrade request as its first parameter, + * and can decide whether to continue or not. The second argument is a function that needs + * to be called with the decided information: fn( err, success ), where success is a boolean + * value where false means that the request is rejected, and err is an error code (engine.io) + * @default null + */ + allowRequest?: (request:any, callback: (err: number, success: boolean) => void) => void; + + /** + * Transports to allow connections to (engine.io) + * @default ['polling','websocket'] + */ + transports?: string[]; + + /** + * Whether to allow transport upgrades (engine.io) + * @default true + */ + allowUpgrades?: boolean; + + /** + * parameters of the WebSocket permessage-deflate extension (see ws module). + * Set to false to disable (engine.io) + * @default true + */ + perMessageDeflate?: Object|boolean; + + /** + * Parameters of the http compression for the polling transports (see zlib). + * Set to false to disable, or set an object with parameter "threshold:number" + * to only compress data if the byte size is above this value (1024) (engine.io) + * @default true|1024 + */ + httpCompression?: Object|boolean; + + /** + * Name of the HTTP cookie that contains the client sid to send as part of + * handshake response headers. Set to false to not send one (engine.io) + * @default "io" + */ + cookie?: string|boolean; + } - interface Namespace extends NodeJS.EventEmitter { - name: string; - connected: { [id: string]: Socket }; - use(fn: Function): Namespace; - in(room: string): Namespace; + /** + * The Namespace, sandboxed environments for sockets, each connection + * to a Namespace requires a new Socket + */ + interface Namespace extends NodeJS.EventEmitter { + + /** + * The name of the NameSpace + */ + name: string; + + /** + * The controller Server for this Namespace + */ + server: Server; + + /** + * A list of all the Sockets connected to this Namespace + */ + sockets: Socket[]; + + /** + * A dictionary of all the Sockets connected to this Namespace, where + * the Socket ID is the key + */ + connected: { [id: string]: Socket }; + + /** + * The Adapter that we're using to handle dealing with rooms etc + */ + adapter: Adapter; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Namespace; + + /** + * Registers a middleware function, which is a function that gets executed + * for every incoming Socket + * @param fn The function to call when we get a new incoming socket. It should + * take one parameter of type Socket, and one callback function to call to + * execute the next middleware function. The callback can take one optional + * parameter, err, if there was an error. Errors passed to middleware callbacks + * are sent as special 'error' packets to clients + * @return This Namespace + */ + use( fn: ( socket:Socket, fn: ( err?: any ) => void ) =>void ): Namespace; + + /** + * Targets a room when emitting + * @param room The name of the room that we're targeting + * @return This Namespace + */ + to( room: string ): Namespace; + + /** + * @see to( room ) + */ + in( room: string ): Namespace; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + * @return This Namespace + */ + send( ...args: any[] ): Namespace; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Namespace; - on(event: 'connection', listener: (socket: Socket) => void): Namespace; - on(event: 'connect', listener: (socket: Socket) => void): Namespace; - on(event: string, listener: Function): Namespace; - } + /** + * The event fired when we get a new connection + * @param event The event being fired: 'connection' + * @param listener A listener that should take one parameter of type Socket + * @return This Namespace + */ + on( event: 'connection', listener: ( socket: Socket ) => void ): Namespace; + + /** + * @see on( 'connection', listener ) + */ + on( event: 'connect', listener: ( socket: Socket ) => void ): Namespace; + + /** + * Base 'on' method to add a listener for an event + * @param event The event that we want to add a listener for + * @param listener The callback to call when we get the event. The parameters + * for the callback depend on the event + * @ This Namespace + */ + on( event: string, listener: Function ): Namespace; + } - interface Socket { - rooms: string[]; - client: Client; - conn: any; - request: any; - id: string; - handshake: { - headers: any; - time: string; - address: any; - xdomain: boolean; - secure: boolean; - issued: number; - url: string; - query: any; - }; + /** + * The socket, which handles our connection for a namespace. NOTE: while + * we technically extend NodeJS.EventEmitter, we're not putting it here + * as we have a problem with the emit() event (as it's overridden with a + * different return) + */ + interface Socket { + + /** + * The namespace that this socket is for + */ + nsp: Namespace; + + /** + * The Server that our namespace is in + */ + server: Server; + + /** + * The Adapter that we use to handle our rooms + */ + adapter: Adapter; + + /** + * The unique ID for this Socket. Regenerated at every connection. This is + * also the name of the room that the Socket automatically joins on connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The Client associated with this Socket + */ + client: Client; + + /** + * The underlying Engine.io Socket instance + */ + conn: { + + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + }; + + /** + * The list of rooms that this Socket is currently in + */ + rooms: string[]; + + /** + * Is the Socket currently connected? + */ + connected: boolean; + + /** + * Is the Socket currently disconnected? + */ + disconnected: boolean; + + /** + * The object used when negociating the handshake + */ + handshake: { + /** + * The headers passed along with the request. e.g. 'host', + * 'connection', 'accept', 'referer', 'cookie' + */ + headers: any; + + /** + * The current time, as a string + */ + time: string; + + /** + * The remote address of the connection request + */ + address: string; + + /** + * Is this a cross-domain request? + */ + xdomain: boolean; + + /** + * Is this a secure request? + */ + secure: boolean; + + /** + * The timestamp for when this was issued + */ + issued: number; + + /** + * The request url + */ + url: string; + + /** + * Any query string parameters in the request url + */ + query: any; + }; + + /** + * Sets the 'json' flag when emitting an event + */ + json: Socket; + + /** + * Sets the 'volatile' flag when emitting an event. Volatile messages are + * messages that can be dropped because of network issues and the like. Use + * for high-volume/real-time messages where you don't need to receive *all* + * of them + */ + volatile: Socket; + + /** + * Sets the 'broadcast' flag when emitting an event. Broadcasting an event + * will send it to all the other sockets in the namespace except for yourself + */ + broadcast: Socket; + + /** + * Emits an event to this client. If the 'broadcast' flag was set, this will + * emit to all other clients, except for this one + * @param event The event that we want to emit + * @param args Any number of optional arguments to pass with the event. If the + * last argument is a function, it will be called as an ack. The ack should + * take whatever data was sent with the packet + * @return This Socket + */ + emit( event: string, ...args: any[]): Socket; + + /** + * Targets a room when broadcasting + * @param room The name of the room that we're targeting + * @return This Socket + */ + to( room: string ): Socket; + + /** + * @see to( room ) + */ + in( room: string ): Socket; + + /** + * Sends a 'message' event + * @see emit( event, ...args ) + */ + send( ...args: any[] ): Socket; + + /** + * @see send( ...args ) + */ + write( ...args: any[] ): Socket; + + /** + * Joins a room. You can join multiple rooms, and by default, on connection, + * you join a room with the same name as your ID + * @param name The name of the room that we want to join + * @param fn An optional callback to call when we've joined the room. It should + * take an optional parameter, err, of a possible error + * @return This Socket + */ + join( name: string, fn?: ( err?: any ) => void ): Socket; + + /** + * Leaves a room + * @param name The name of the room to leave + * @param fn An optional callback to call when we've left the room. It should + * take on optional parameter, err, of a possible error + */ + leave( name: string, fn?: Function ): Socket; + + /** + * Leaves all the rooms that we've joined + */ + leaveAll(): void; + + /** + * Disconnects this Socket + * @param close If true, also closes the underlying connection + * @return This Socket + */ + disconnect( close: boolean ): Socket; + + /** + * Adds a listener for a particular event. Calling multiple times will add + * multiple listeners + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on the + * event in question + * @return This Socket + */ + on( event: string, fn: Function ): Socket; + + /** + * @see on( event, fn ) + */ + addListener( event: string, fn: Function ): Socket; + + /** + * Adds a listener for a particular event that will be invoked + * a single time before being automatically removed + * @param event The event that we're listening for + * @param fn The function to call when we get the event. Parameters depend on + * the event in question + * @return This Socket + */ + once( event: string, fn: Function ): Socket; + + /** + * Removes a listener for a particular type of event. This will either + * remove a specific listener, or all listeners for this type of event + * @param event The event that we want to remove the listener of + * @param fn The function to remove, or null if we want to remove all functions + * @return This Socket + */ + removeListener( event: string, fn?: Function ): Socket; + + /** + * Removes all event listeners on this object + * @return This Socket + */ + removeAllListeners(): Socket; + + /** + * Sets the maximum number of listeners this instance can have + * @param n The max number of listeners we can add to this emitter + * @return This Socket + */ + setMaxListeners( n: number ): Socket; + + /** + * Returns all the callbacks for a particular event + * @param event The event that we're looking for the callbacks of + * @return An array of callback Functions, or an empty array if we don't have any + */ + listeners( event: string ):Function[]; + } + + /** + * The interface used when dealing with rooms etc + */ + interface Adapter extends NodeJS.EventEmitter { + + /** + * The namespace that this adapter is for + */ + nsp: Namespace; + + /** + * A dictionary of all the rooms that we have in this namespace, each room + * a dictionary of all the sockets currently in that room + */ + rooms: {[room: string]: {[id: string]: boolean }}; + + /** + * A dictionary of all the socket ids that we're dealing with, and all + * the rooms that the socket is currently in + */ + sids: {[id: string]: {[room: string]: boolean}}; + + /** + * Adds a socket to a room. If the room doesn't exist, it's created + * @param id The ID of the socket to add + * @param room The name of the room to add the socket to + * @param callback An optional callback to call when the socket has been + * added. It should take an optional parameter, error, if there was a problem + */ + add( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from a room. If there are no more sockets in the room, + * the room is deleted + * @param id The ID of the socket that we're removing + * @param room The name of the room to remove the socket from + * @param callback An optional callback to call when the socket has been + * removed. It should take on optional parameter, error, if there was a problem + */ + del( id: string, room: string, callback?: ( err?: any ) => void ): void; + + /** + * Removes a socket from all the rooms that it's joined + * @param id The ID of the socket that we're removing + */ + delAll( id: string ):void; + + /** + * Broadcasts a packet + * @param packet The packet to broadcast + * @param opts Any options to send along: + * - rooms: An optional list of rooms to broadcast to. If empty, the packet is broadcast to all sockets + * - except: A list of Socket IDs to exclude + * - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast') + */ + broadcast( packet: any, opts: { rooms?: string[], except?: string[], flags?: {[flag: string]: boolean} } ):void; + } - emit(name: string, ...args: any[]): Socket; - join(name: string, fn?: Function): Socket; - leave(name: string, fn?: Function): Socket; - to(room: string): Socket; - in(room: string): Socket; - send(...args: any[]): Socket; - write(...args: any[]): Socket; - - on(event: string, listener: Function): Socket; - once(event: string, listener: Function): Socket; - removeListener(event: string, listener: Function): Socket; - removeAllListeners(event: string): Socket; - broadcast: Socket; - volatile: Socket; - connected: boolean; - disconnect(close?: boolean): Socket; - } - - interface Client { - conn: any; - request: any; - id: string; - } + /** + * The client behind each socket (can have multiple sockets) + */ + interface Client { + /** + * The Server that this client belongs to + */ + server: Server; + + /** + * The underlying Engine.io Socket instance + */ + conn: { + + /** + * The ID for this socket - matches Client.id + */ + id: string; + + /** + * The Engine.io Server for this socket + */ + server: any; + + /** + * The ready state for the client. Either 'opening', 'open', 'closing', or 'closed' + */ + readyState: string; + + /** + * The remote IP for this connection + */ + remoteAddress: string; + }; + + /** + * The ID for this client. Regenerated at every connection + */ + id: string; + + /** + * The http.IncomingMessage request sent with the connection. Useful + * for recovering headers etc + */ + request: any; + + /** + * The list of sockets currently connect via this client (i.e. to different + * namespaces) + */ + sockets: Socket[]; + + /** + * A dictionary of all the namespaces for this client, with the Socket that + * deals with that namespace + */ + nsps: {[nsp: string]: Socket}; + } } From 812ed1d1a8c8f15007234fb64262f4101b115565 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:31:56 +0200 Subject: [PATCH 047/881] Fixed bad link to node.d.ts in the legacy file --- socket.io/legacy/socket.io-1.2.0.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/socket.io/legacy/socket.io-1.2.0.d.ts b/socket.io/legacy/socket.io-1.2.0.d.ts index 3f3c042fe..92f037319 100644 --- a/socket.io/legacy/socket.io-1.2.0.d.ts +++ b/socket.io/legacy/socket.io-1.2.0.d.ts @@ -3,7 +3,7 @@ // Definitions by: PROGRE // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module 'socket.io' { var server: SocketIOStatic; From 9c47c6a65a0542267bb1a7abd1ef602e6d052d97 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:33:48 +0200 Subject: [PATCH 048/881] Added the test files for the legacy socket.io code --- .../legacy/socket.io-client-1.2.0-tests.ts | 57 +++++++ socket.io/legacy/socket.io-1.2.0-tests.ts | 145 ++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 socket.io-client/legacy/socket.io-client-1.2.0-tests.ts create mode 100644 socket.io/legacy/socket.io-1.2.0-tests.ts diff --git a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts new file mode 100644 index 000000000..803a9c786 --- /dev/null +++ b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts @@ -0,0 +1,57 @@ +/// + +function testUsingWithNodeHTTPServer() { + var socket = io('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithExpress() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testUsingWithTheExpressFramework() { + var socket = io.connect('http://localhost'); + socket.on('news', function (data: any) { + console.log(data); + socket.emit('my other event', { my: 'data' }); + }); +} + +function testRestrictingYourselfToANamespace() { + var chat = io.connect('http://localhost/chat') + , news = io.connect('http://localhost/news'); + + chat.on('connect', function () { + chat.emit('hi!'); + }); + + news.on('news', function () { + news.emit('woot'); + }); +} + +function testSendingAndGettingData() { + var socket = io(); + socket.on('connect', function () { + socket.emit('ferret', 'tobi', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var socket = io('http://localhost/'); + socket.on('connect', function () { + socket.emit('hi'); + + socket.on('message', function (msg: any) { + }); + }); +} diff --git a/socket.io/legacy/socket.io-1.2.0-tests.ts b/socket.io/legacy/socket.io-1.2.0-tests.ts new file mode 100644 index 000000000..442e67775 --- /dev/null +++ b/socket.io/legacy/socket.io-1.2.0-tests.ts @@ -0,0 +1,145 @@ +import socketIO = require('socket.io'); + +function testUsingWithNodeHTTPServer() { + var app = require('http').createServer(handler); + var io = socketIO(app); + var fs = require('fs'); + + app.listen(80); + + function handler(req: any, res: any) { + fs.readFile(__dirname + '/index.html', + function (err: any, data: any) { + if (err) { + res.writeHead(500); + return res.end('Error loading index.html'); + } + + res.writeHead(200); + res.end(data); + }); + } + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithExpress() { + var app = require('express')(); + var server = require('http').Server(app); + var io = socketIO(server); + + server.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testUsingWithTheExpressFramework() { + var app = require('express').createServer(); + var io = socketIO(app); + + app.listen(80); + + app.get('/', function (req: any, res: any) { + res.sendfile(__dirname + '/index.html'); + }); + + io.on('connection', function (socket) { + socket.emit('news', { hello: 'world' }); + socket.on('my other event', function (data: any) { + console.log(data); + }); + }); +} + +function testSendingAndReceivingEvents() { + var io = socketIO(80); + + io.on('connection', function (socket) { + io.emit('this', { will: 'be received by everyone' }); + + socket.on('private message', function (from: any, msg: any) { + console.log('I received a private message by ', from, ' saying ', msg); + }); + + socket.on('disconnect', function () { + io.sockets.emit('user disconnected'); + }); + }); +} + +function testRestrictingYourselfToANamespace() { + var io = socketIO.listen(80); + var chat = io + .of('/chat') + .on('connection', function (socket) { + socket.emit('a message', { + that: 'only' + , '/chat': 'will get' + }); + chat.emit('a message', { + everyone: 'in' + , '/chat': 'will get' + }); + }); + + var news = io + .of('/news') + .on('connection', function (socket) { + socket.emit('item', { news: 'item' }); + }); +} + +function testSendingVolatileMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + var tweets = setInterval(function () { + socket.volatile.emit('bieber tweet', {}); + }, 100); + + socket.on('disconnect', function () { + clearInterval(tweets); + }); + }); +} + +function testSendingAndGettingData() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('ferret', function (name: any, fn: any) { + fn('woot'); + }); + }); +} + +function testBroadcastingMessages() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.broadcast.emit('user connected'); + }); +} + +function testUsingItJustAsACrossBrowserWebSocket() { + var io = socketIO.listen(80); + + io.sockets.on('connection', function (socket) { + socket.on('message', function () { }); + socket.on('disconnect', function () { }); + }); +} From 9c07a9d60257a8e1631aee74184617c2eeca401d Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 11 Jul 2015 21:39:25 +0200 Subject: [PATCH 049/881] Added the correct paths for the definition files in the tests --- socket.io-client/legacy/socket.io-client-1.2.0-tests.ts | 2 +- socket.io/legacy/socket.io-1.2.0-tests.ts | 2 ++ socket.io/socket.io-tests.ts | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts index 803a9c786..3ad8db95f 100644 --- a/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts +++ b/socket.io-client/legacy/socket.io-client-1.2.0-tests.ts @@ -1,4 +1,4 @@ -/// +/// function testUsingWithNodeHTTPServer() { var socket = io('http://localhost'); diff --git a/socket.io/legacy/socket.io-1.2.0-tests.ts b/socket.io/legacy/socket.io-1.2.0-tests.ts index 442e67775..93899d0d9 100644 --- a/socket.io/legacy/socket.io-1.2.0-tests.ts +++ b/socket.io/legacy/socket.io-1.2.0-tests.ts @@ -1,3 +1,5 @@ +/// + import socketIO = require('socket.io'); function testUsingWithNodeHTTPServer() { diff --git a/socket.io/socket.io-tests.ts b/socket.io/socket.io-tests.ts index 442e67775..93899d0d9 100644 --- a/socket.io/socket.io-tests.ts +++ b/socket.io/socket.io-tests.ts @@ -1,3 +1,5 @@ +/// + import socketIO = require('socket.io'); function testUsingWithNodeHTTPServer() { From 6169c072eae80fc02e31bc8bd0a2baf3fc4549cb Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sun, 12 Jul 2015 00:04:42 +0200 Subject: [PATCH 050/881] Added the "id" parameter to the client Socket object --- socket.io-client/socket.io-client.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index 7e15773e6..42d366412 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -177,6 +177,12 @@ declare module SocketIOClient { */ nsp: string; + /** + * The ID of the socket; matches the server ID and is set when we're connected, and cleared + * when we're disconnected + */ + id: string; + /** * Are we currently connected? * @default false From 442dbd53b5c3732d77862438bdeba14f0b32bd5b Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Sun, 12 Jul 2015 07:49:00 -0700 Subject: [PATCH 051/881] Initial definition push. --- angular-formly/angular-formly-test.ts | 34 ++ angular-formly/angular-formly.d.ts | 445 ++++++++++++++++++++++++++ 2 files changed, 479 insertions(+) create mode 100644 angular-formly/angular-formly-test.ts create mode 100644 angular-formly/angular-formly.d.ts diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts new file mode 100644 index 000000000..1aae390a5 --- /dev/null +++ b/angular-formly/angular-formly-test.ts @@ -0,0 +1,34 @@ +/// + +var app = angular.module('app', ['formly']); + +class AppController { + fields: AngularFormly.IFieldConfigurationObject[]; + constructor($scope: ng.IScope) { + var vm = this; + vm.fields = [ + { + field: 'label', + type: 'input', + templateOptions: { + maxlength: 8, + minlength: 3 + } + }, + { + field: 'project', + type: 'input', + defaultValue: 'Project 1', + templateOptions: { + placeholder: 'Enter a project name...' + } + }, + { + template: () => 'hello' + } + ] + } +} + +app.controller("AppController", AppController); + diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts new file mode 100644 index 000000000..d0b336bfd --- /dev/null +++ b/angular-formly/angular-formly.d.ts @@ -0,0 +1,445 @@ +// Type definitions for angular-formly 6.17.0 +// Project: https://github.com/formly-js/angular-formly +// Definitions by: Scott Hatcher +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module 'AngularFormly' { + export = AngularFormly; +} + +declare module AngularFormly { + + + /** + * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages + */ + interface IExpresssionFunction { + ($viewValue, $modelValue, scope): any; + } + + + /** + * This is part of the built-in formlyConfig templateManipulator called ngModelAttrsTemplateManipulator. + * This allows you to keep your templates very small and add custom behavior on at the type or field level. + * + * see http://docs.angular-formly.com/docs/ngmodelattrs + */ + interface INGModelAttrs { + [key: string]: { + attribute?: string; + expresssion?: string; + value?: string; + } + } + + + interface ITemplateManipulator { + (template, options, scope): string; + } + + + /** + * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator + */ + interface ITemplateOptions { + + // both attribute or regular attribute + disabled?: boolean | string; + maxlength?: number | string; + minlength?: number | string; + pattern?: string; + required?: boolean | string; + + //attribute only + max?: number; + min?: number; + placeholder?: number | string; + tabindex?: number; + type?: string; + + //expression types + onBlur?: string; + onChange?: string; + onClick?: string; + onFocus?: string; + onKeydown?: string; + onKeypress?: string; + onKeyup?: string; + + [key: string]: any; + + } + + + /** + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + interface IValidator { + expression?: string | { (viewValue, modelValue): boolean }; + } + + + /** + * An object which has at least two properties called expression and listener. The watch.expression + * is added to the formly-form directive's scope (to allow it to run even when hide is true). You + * can specify a type ($watchCollection or $watchGroup) via the watcher.type property (defaults to + * $watch) and whether you want it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + interface IWatcher { + expression?: string | { (field, scope): boolean }; + listener: (field, newValue, oldValue, scope, stopWatching) => void; + type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup + } + + + // see http://docs.angular-formly.com/docs/field-configuration-object + interface IFieldConfigurationObject { + + + /** + * The type of field to be rendered. This is the recommended method + * for defining fields. Types must be pre-defined using formlyConfig. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + */ + type?: string; + + + /** + * Can be set instead of type or templateUrl to use a custom html + * template form field. Recommended to be used with one-liners mostly + * (like a directive), or if you're using webpack with the ability to require templates :-) + * + * If a function is passed, it is invoked with the field configuration object and can return + * either a string for the template or a promise that resolves to a string. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function + */ + template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function + */ + templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#key-string + */ + key?: string; + + + /** + * Use defaultValue to initialize it the model. If this is provided and the value of the + * model at compile-time is undefined, then the value of the model will be assigned to defaultValue. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#defaultvalue-any + */ + defaultValue?: any; + + + /** + * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use + * hideExpression. See below. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hide-boolean + */ + hide?: boolean + + + /** + * This is similar to expressionProperties with a slight difference. You should (hopefully) never + * notice the difference with the most common use case. This is available due to limitations with + * expressionProperties and ng-if not working together very nicely. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#hideexpression-string--function + */ + hideExpression?: string | IExpresssionFunction; + + + /** + * By default, the model passed to the formly-field directive is the same as the model passed to the + * formly-form. However, if the field has a model specified, then it is used for that field (and that + * field only). In addition, a deep watch is added to the formly-field directive's scope to run the + * expressionProperties when the specified model changes. + * + * Note, the formly-form directive will allow you to specify a string which is an (almost) formly + * expression which allows you to define the model as relative to the scope of the form. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#model-object--string + */ + model?: Object | string; + + + /** + * An object where the key is a property to be set on the main field config and the value is an + * expression used to assign that property. The value is a formly expressions. The returned value is + * wrapped in $q.when so you can return a promise from your function :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + */ + expressionProperties?: { + [key: string]: string | IExpresssionFunction; + } + + + /** + * You can specify your own class that will be applied to the formly-field directive (or ng-form of + * a fieldGroup). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string + */ + className?: string; + + + /** + * This allows you to specify the id of your field (which will be used for its name as well unless + * a name is provided). Note, you can also override the id generation code using the formlyConfig + * extra called getFieldId. + * + * AVOID THIS + * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's + * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need + * to concern yourself with making sure that this is unique. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#id-string + */ + id?: string; + + + /** + * If you wish to, you can specify a specific name for your ng-model. This is useful if you're posting + * the form to a server using techniques of yester-year. + * + * AVOID THIS + * If you don't have to do this, don't. It's just extra work. Part of the beauty that angular-formly + * provides is the fact that you don't need to concern yourself with stuff like this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#name-string + */ + name?: string; + + + /** + * This is reserved for the developer. You have our guarantee to be able to use this and not worry about + * future versions of formly overriding your usage and preventing you from upgrading :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#data-object + */ + data?: any; + + + /** + * This is reserved for the templates. Any template-specific options go in here. Look at your specific + * template implementation to know the options required for this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object + */ + templateOptions?: ITemplateOptions; + + + /** + * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a + * type configuration if you want it to apply to all fields of a certain type). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions + */ + templateManipulator?: { + [key: string]: ITemplateManipulator[]; + } + + + /** + * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If + * given an array, the formly field template will be wrapped by the first wrapper, then the second, then + * the third, etc. You can also specify these as part of a type (which is the recommended approach). + * Specifying this property will override the wrappers for the type for this field. + * + * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings + */ + wrapper?: string | string[]; + + + //TODO:Scott Figure out what this really does. + /** + * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element + * of field templates. You will likely not use this often. This object is a little complex, but extremely + * powerful. It's best to explain this api via an example. For more information, see the guide on ngModelAttrs. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object + */ + ngModelAttrs?: any; + + + /** + * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the + * field, and anything else you have in your injector. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f + */ + controller?: string | { ($scope: ng.IScope, ...args): void }; + + + /** + * This allows you to specify a link function. It is invoked after your template has finished compiling. + * You are passed the normal arguments for a normal link function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function + */ + link?: ng.IDirectiveLinkFn; + + + /** + * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority + * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and + * hence will override any duplicates of those properties as well. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings + */ + optionsTypes?: string | string[]; + + + //TODO:Scott Still need to define + /** + * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see + * below) will add this attribute to your ng-model element automatically if this property exists. Note, + * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model + * to options.value which is a getterSetter that formly adds to field options. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions + */ + modelOptions?: any; + + + /** + * Used to tell angular-formly to not attempt to add the formControl property to your object. This is useful + * for things like validation, but not necessary if your "field" doesn't use ng-model (if it's just a horizontal + * line for example). Defaults to undefined. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#noformcontrol-boolean + */ + noFormControl?: boolean; + + + /** + * An object which has at least two properties called expression and listener. The watch.expression is added + * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type + * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want + * it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + watcher?: IWatcher | IWatcher[]; + + + //TODO:Scott Look at defining validators as an Object to see if additional interface needs to be created + /** + * An object where the keys are the name of the validator and the values are Formly Expressions; + * + * Async Validation + * All function validators can return true/false/Promise. A validator passes if it returns true or a promise + * that is resolved. A validator fails if it returns false or a promise that is rejected. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + validators?: { + [key: string]: IValidator | string; + } + + + /** + * An object with a few useful properties mostly handy when used in combination with ng-messages + */ + validation?: { + + + /** + * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages + * like in this example. + */ + messages?: { + [key: string]: IExpresssionFunction; + } + + + /** + * A boolean you as the developer can set to specify to force options.validation.errorExistsAndShouldBeVisible + * to be set to true when there are $errors. This is useful when you're trying to call the user's attention to + * some fields for some reason. + */ + show?: boolean; + + + /** + * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because + * you generally only want to show error messages when the user has interacted with a specific field, this value + * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference + * for pre-angular 1.3 because it doesn't have touched support). + */ + errorExistsAndShouldBeVisible?: boolean; + + } + + /** + * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true + * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, + * it will automagically change your field's ng-model attribute to use options.value. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function + */ + value?(): any; //Getter + value?(val): void; //Setter + + + //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) + + + /** + * This is the NgModelController for the field. It provides you with awesome stuff like $errors :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller + */ + formControl?: ng.IFormController; + + + /** + * Will reset the field's model and the field control to the last initialValue. This is used by the + * formly-form's options.resetModel function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#resetmodel-function + */ + resetModel?: () => void; + + + /** + * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. + * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function + */ + updateInitialValue?: () => void; + + + /** + * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. + * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the + * way it works will result in a major version change, so you can rely on its api. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#runexpressions-function + */ + runExpressions?: () => void; + + } + +} \ No newline at end of file From 1a46ba29e13e1ac1a872ebdae4f3f4b4fc279a0e Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 10:11:18 +0200 Subject: [PATCH 052/881] fixed the Collection- / Composite child view issue. The child view does not necessarily have the same model as the Collection- / CompositeView --- marionette/marionette.d.ts | 88 +++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 44 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 4a2bfac10..258e6b4b4 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -9,49 +9,49 @@ declare module Backbone { // Backbone.BabySitter - class ChildViewContainer { + class ChildViewContainer> { constructor(initialViews?: any[]); - add(view: View, customIndex?: number): void; - findByModel(model: TModel): View; - findByModelCid(modelCid: string): View; - findByCustom(index: number): View; - findByIndex(index: number): View; - findByCid(cid: string): View; - remove(view: View): void; + add(view: TView, customIndex?: number): void; + findByModel(model: TModel): TView; + findByModelCid(modelCid: string): TView; + findByCustom(index: number): TView; + findByIndex(index: number): TView; + findByCid(cid: string): TView; + remove(view: TView): void; call(method: any): void; apply(method: any, args?: any[]): void; //mixins from Collection (copied from Backbone's Collection declaration) - all(iterator: (element: View, index: number) => boolean, context?: any): boolean; - any(iterator: (element: View, index: number) => boolean, context?: any): boolean; + all(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + any(iterator: (element: TView, index: number) => boolean, context?: any): boolean; contains(value: any): boolean; detect(iterator: (item: any) => boolean, context?: any): any; - each(iterator: (element: View, index: number, list?: any) => void, context?: any): any; - every(iterator: (element: View, index: number) => boolean, context?: any): boolean; - filter(iterator: (element: View, index: number) => boolean, context?: any): View[]; - find(iterator: (element: View, index: number) => boolean, context?: any): View; - first(): View; - forEach(iterator: (element: View, index: number, list?: any) => void, context?: any): void; + each(iterator: (element: TView, index: number, list?: any) => void, context?: any): any; + every(iterator: (element: TView, index: number) => boolean, context?: any): boolean; + filter(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + find(iterator: (element: TView, index: number) => boolean, context?: any): TView; + first(): TView; + forEach(iterator: (element: TView, index: number, list?: any) => void, context?: any): void; include(value: any): boolean; - initial(): View; - initial(n: number): View[]; + initial(): TView; + initial(n: number): TView[]; invoke(methodName: string, args?: any[]): any; isEmpty(object: any): boolean; - last(): View; - last(n: number): View[]; - lastIndexOf(element: View, fromIndex?: number): number; - map(iterator: (element: View, index: number, context?: any) => U, context?: any): U[]; + last(): TView; + last(n: number): TView[]; + lastIndexOf(element: TView, fromIndex?: number): number; + map(iterator: (element: TView, index: number, context?: any) => U, context?: any): U[]; pluck(attribute: string): any[]; - reject(iterator: (element: View, index: number) => boolean, context?: any): View[]; - rest(): View; - rest(n: number): View[]; + reject(iterator: (element: TView, index: number) => boolean, context?: any): TView[]; + rest(): TView; + rest(n: number): TView[]; select(iterator: any, context?: any): any[]; - some(iterator: (element: View, index: number) => boolean, context?: any): boolean; + some(iterator: (element: TView, index: number) => boolean, context?: any): boolean; toArray(): any[]; - without(...values: any[]): View[]; + without(...values: any[]): TView[]; } // Backbone.Wreqr @@ -856,7 +856,7 @@ declare module Marionette { * DOM. This behavior can be disabled by specifying {sort: false} on * initialize. */ - class CollectionView extends View { + class CollectionView> extends View { constructor(options?: CollectionViewOptions); /** @@ -864,7 +864,7 @@ declare module Marionette { * Backbone view object definition, not an instance. It can be any * Backbone.View or be derived from Marionette.ItemView */ - childView: any; + childView: new () => TView; /** * There may be scenarios where you need to pass data from your parent @@ -918,14 +918,14 @@ declare module Marionette { * collection view, iterate them, find them by a given indexer such as the * view's model or collection, and more. */ - children: Backbone.ChildViewContainer; + children: Backbone.ChildViewContainer; /** * The render method of the collection view is responsible for rendering the * entire collection. It loops through each of the children in the collection * and renders them individually as an childView. */ - render(): CollectionView; + render(): CollectionView; /** * The addChild method is responsible for rendering the childViews and @@ -933,9 +933,9 @@ declare module Marionette { * responsible for triggering the events per ChildView. In most cases you * should not override this method. */ - addChild(item: any, ChildView: Backbone.View, index: Number): void; + addChild(item: any, ChildView: TView, index: Number): void; - renderChildView(view: Backbone.View, index: Number): void; + renderChildView(view: TView, index: Number): void; /** * When a custom view instance needs to be created for the childView that @@ -943,13 +943,13 @@ declare module Marionette { * takes three parameters and returns a view instance to be used as the * child view. */ - buildChildView(child: any, ItemViewType: any, itemViewOptions: any): View; + buildChildView(child: any, ItemViewType: any, itemViewOptions: any): TView; /** * Remove the child view and destroy it. This function also updates the indices of * later views in the collection in order to keep the children in sync with the collection. */ - removeChildView(view: any): void; + removeChildView(view: TView): void; /** * Determines if the view is empty. If you want to control when the empty @@ -988,14 +988,14 @@ declare module Marionette { * a collection and displaying the sorted list in the correct order on the * screen. */ - attachHtml(collectionView: CollectionView, childView: Backbone.View, index: number): void; + attachHtml(collectionView: CollectionView, childView: TView, index: number): void; /** * The value returned by this method is the ChildView class that will be * instantiated when a Model needs to be initially rendered. This method * also gives you the ability to customize per Model ChildViews. */ - getChildView(item: TModel): any; + getChildView(item: M): new () => TView; /** * If you need the emptyView's class chosen dynamically, specify @@ -1020,27 +1020,27 @@ declare module Marionette { * instance is about to be added to the collection view. It provides * access to the view instance for the child that was added. */ - onBeforeAddChild(view: any): void; + onBeforeAddChild(childView: TView): void; /** * This callback function allows you to know when a child / child view * instance has been added to the collection view. It provides access to * the view instance for the child that was added. */ - onAddChild(childView: any): void; + onAddChild(childView: TView): void; /** * This callback function allows you to know when a childView instance is * about to be removed from the collectionView. It provides access to the * view instance for the child that was removed. */ - onBeforeRemoveChild(childView: any): void; + onBeforeRemoveChild(childView: TView): void; /** * This callback function allows you to know when a child / childView * instance has been deleted or removed from the collection. */ - onRemoveChild(childView: any): void; + onRemoveChild(childView: TView): void; } /** @@ -1049,7 +1049,7 @@ declare module Marionette { * structure, or for scenarios where a collection needs to be rendered within * a wrapper template. */ - class CompositeView extends CollectionView { + class CompositeView> extends CollectionView { constructor(options?: CollectionViewOptions); @@ -1058,7 +1058,7 @@ declare module Marionette { * CompositeView's template is rendered and the childView's templates are * added to this. */ - childView: any; + childView: new () => TView; /** * By default the composite view uses the same attachHtml method that the @@ -1074,7 +1074,7 @@ declare module Marionette { /** * Renders the view. */ - render(): CompositeView; + render(): CompositeView; /** * Invoked before the model has been rendered From 5c5275f57388cf7e2a6bbfc3efc50cf05dbb08ca Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 10:44:07 +0200 Subject: [PATCH 053/881] adjusted the tests. Added the possible arguments to the generic constructor. --- marionette/marionette-tests.ts | 2 +- marionette/marionette.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/marionette/marionette-tests.ts b/marionette/marionette-tests.ts index a37eccc9f..7483c7e2f 100644 --- a/marionette/marionette-tests.ts +++ b/marionette/marionette-tests.ts @@ -179,7 +179,7 @@ module Marionette.Tests { } } - class MyCollectionView extends Marionette.CollectionView { + class MyCollectionView extends Marionette.CollectionView { constructor() { this.childView = MyView; this.childEvents = { diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index 258e6b4b4..154b25434 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -864,7 +864,7 @@ declare module Marionette { * Backbone view object definition, not an instance. It can be any * Backbone.View or be derived from Marionette.ItemView */ - childView: new () => TView; + childView: new (...args:any[]) => TView; /** * There may be scenarios where you need to pass data from your parent @@ -995,7 +995,7 @@ declare module Marionette { * instantiated when a Model needs to be initially rendered. This method * also gives you the ability to customize per Model ChildViews. */ - getChildView(item: M): new () => TView; + getChildView(item: M): new (...args:any[]) => TView; /** * If you need the emptyView's class chosen dynamically, specify @@ -1058,7 +1058,7 @@ declare module Marionette { * CompositeView's template is rendered and the childView's templates are * added to this. */ - childView: new () => TView; + childView: new (...args:any[]) => TView; /** * By default the composite view uses the same attachHtml method that the From 2d2a7cc0d438625617baec849076035896c7a88f Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Mon, 13 Jul 2015 11:07:07 +0200 Subject: [PATCH 054/881] quckfix for the backbone part. To fully support the marionette changes. --- backbone/backbone.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5..c2b77f506 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -311,7 +311,8 @@ declare module Backbone { interface ViewOptions { model?: TModel; - collection?: Backbone.Collection; + // TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view. + collection?: Backbone.Collection; el?: any; id?: string; className?: string; From 700ec57d8b58c08827d2de0813417d77d7feb6f4 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 07:55:15 -0700 Subject: [PATCH 055/881] Allow custom bootstrap layout. --- angular-formly/angular-formly.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index d0b336bfd..0e2c7d920 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -440,6 +440,13 @@ declare module AngularFormly { */ runExpressions?: () => void; + + + ////////////////// BOOTSTRAP SPECIFIC /////////////////////// + fieldGroup?: IFieldConfigurationObject[]; + } + + } \ No newline at end of file From d48e140826129575610983b8e3e7c075c800393c Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 08:00:46 -0700 Subject: [PATCH 056/881] Added a few other field types to test file. --- angular-formly/angular-formly-test.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts index 1aae390a5..4d4053823 100644 --- a/angular-formly/angular-formly-test.ts +++ b/angular-formly/angular-formly-test.ts @@ -15,6 +15,9 @@ class AppController { minlength: 3 } }, + { + template: '
    ' + }, { field: 'project', type: 'input', @@ -25,6 +28,24 @@ class AppController { }, { template: () => 'hello' + }, + { + type: 'input', + key: 'zip', + templateOptions: { + type: 'number', + label: 'Zip', + max: 99999, + min: 0, + pattern: '\\d{5}' + } + }, + { + type: 'checkbox', + key: 'happyUser', + templateOptions: { + label: 'Are you happy?' + } } ] } From 7f7ac2c2b115cff564dacf27225240e2478f954d Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Mon, 13 Jul 2015 08:43:43 -0700 Subject: [PATCH 057/881] Remove implicit any's. --- angular-formly/angular-formly.d.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 0e2c7d920..807171d07 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -16,7 +16,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue, $modelValue, scope): any; + ($viewValue: any, $modelValue: any, scope: ng.IScope): any; } @@ -36,7 +36,7 @@ declare module AngularFormly { interface ITemplateManipulator { - (template, options, scope): string; + (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } @@ -77,7 +77,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object */ interface IValidator { - expression?: string | { (viewValue, modelValue): boolean }; + expression?: string | { (viewValue: any, modelValue: any): boolean }; } @@ -90,8 +90,9 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches */ interface IWatcher { - expression?: string | { (field, scope): boolean }; - listener: (field, newValue, oldValue, scope, stopWatching) => void; + deep?: boolean; //Defaults to false + expression?: string | { (field: string, scope: ng.IScope): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: ng.IScope, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -256,7 +257,8 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions */ templateManipulator?: { - [key: string]: ITemplateManipulator[]; + preWrapper: ITemplateManipulator[]; + postWrapper: ITemplateManipulator[]; } @@ -288,7 +290,7 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f */ - controller?: string | { ($scope: ng.IScope, ...args): void }; + controller?: string | { Function: void }; /** @@ -399,7 +401,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#value-gettersetter-function */ value?(): any; //Getter - value?(val): void; //Setter + value?(val: any): void; //Setter //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) From 31c2a4dc3f9bbb8060ca9d846c03af0aa1a0ac06 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Tue, 14 Jul 2015 00:09:21 +0300 Subject: [PATCH 058/881] Added tests for SharePoint.d.ts --- sharepoint/SharePoint-tests.ts | 2043 +++++++++++++++++++++++++++++++- 1 file changed, 2042 insertions(+), 1 deletion(-) diff --git a/sharepoint/SharePoint-tests.ts b/sharepoint/SharePoint-tests.ts index 83934008c..0e6b53e54 100644 --- a/sharepoint/SharePoint-tests.ts +++ b/sharepoint/SharePoint-tests.ts @@ -1,5 +1,11 @@ /// +/// +/// +/// + +//code from http://sptypescript.codeplex.com/ +//BasicTasksJSOM.ts // Website tasks function retrieveWebsite(resultpanel:HTMLElement) { var clientContext = SP.ClientContext.get_current(); @@ -522,4 +528,2039 @@ function deleteListItem(resultpanel: HTMLElement) { function errorHandler() { resultpanel.innerHTML = "Request failed: " + arguments[1].get_message(); } -} \ No newline at end of file +} + + + +/** Lightweight client-side rendering template overrides.*/ +module CSR { + + export interface UpdatedValueCallback { + (value: any, fieldSchema?: SPClientTemplates.FieldSchema_InForm): void; + } + + /** Creates new overrides. Call .register() at the end.*/ + export function override(listTemplateType?: number, baseViewId?: number|string): ICSR { + return new csr(listTemplateType, baseViewId) + .onPreRender(hookFormContext) + .onPostRender(fixCsrCustomLayout); + + function hookFormContext(ctx: IFormRenderContexWithHook) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + + for (var i = 0; i < ctx.ListSchema.Field.length; i++) { + var fieldSchemaInForm = ctx.ListSchema.Field[i]; + + if (!ctx.FormContextHook) { + ctx.FormContextHook = {} + + var oldRegisterGetValueCallback = ctx.FormContext.registerGetValueCallback; + ctx.FormContext.registerGetValueCallback = (fieldName, callback) => { + ctx.FormContextHook[fieldName].getValue = callback; + oldRegisterGetValueCallback(fieldName, callback); + }; + + var oldUpdateControlValue = ctx.FormContext.updateControlValue; + ctx.FormContext.updateControlValue = (fieldName: string, value: any) => { + oldUpdateControlValue(fieldName, value); + + var hookedContext = ensureFormContextHookField(ctx.FormContextHook, fieldName); + hookedContext.lastValue = value; + + var updatedCallbacks = ctx.FormContextHook[fieldName].updatedValueCallbacks; + for (var i = 0; i < updatedCallbacks.length; i++) { + updatedCallbacks[i](value, hookedContext.fieldSchema); + } + + } + } + ensureFormContextHookField(ctx.FormContextHook, fieldSchemaInForm.Name).fieldSchema = fieldSchemaInForm; + } + } + } + + function fixCsrCustomLayout(ctx: SPClientTemplates.RenderContext_Form) { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + return; + } + + if (ctx.ListSchema.Field.length > 1) { + var wpq = ctx.FormUniqueId; + var webpart = $get('WebPart' + wpq); + var forms = webpart.getElementsByClassName('ms-formtable'); + + if (forms.length > 0) { + var placeholder = $get(wpq + 'ClientFormTopContainer'); + var fragment = document.createDocumentFragment(); + for (var i = 0; i < placeholder.children.length; i++) { + fragment.appendChild(placeholder.children.item(i)); + } + + var form = forms.item(0); + form.parentNode.replaceChild(fragment, form); + } + + var old = ctx.CurrentItem; + ctx.CurrentItem = ctx.ListData.Items[0]; + var fields = ctx.ListSchema.Field; + for (var j = 0; j < fields.length; j++) { + var field = fields[j]; + var pHolderId = wpq + ctx.FormContext.listAttributes.Id + field.Name; + var span = $get(pHolderId); + if (span) { + span.outerHTML = ctx.RenderFieldByName(ctx, field.Name); + } + } + ctx.CurrentItem = old; + } + + } + + + } + + +//typescripttempltes.ts + declare var Strings:any; + export function getFieldValue(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): any { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName] + && contextWithHook.FormContextHook[fieldName].getValue) { + return contextWithHook.FormContextHook[fieldName].getValue(); + } + } + return null; + } + + export function getFieldSchema(ctx: SPClientTemplates.RenderContext_Form, fieldName: string): SPClientTemplates.FieldSchema_InForm { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook + && contextWithHook.FormContextHook[fieldName]) { + return contextWithHook.FormContextHook[fieldName].fieldSchema; + } + } + return null; + } + + export function addUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var f = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName); + var callbacks = f.updatedValueCallbacks; + if (callbacks.indexOf(callback) == -1) { + callbacks.push(callback); + if (f.lastValue) { + callback(f.lastValue, f.fieldSchema); + } + } + } + } + + } + + export function removeUpdatedValueCallback(ctx: SPClientTemplates.RenderContext_Form, fieldName: string, callback: UpdatedValueCallback): void { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var contextWithHook = ctx; + if (contextWithHook.FormContextHook) { + var callbacks = ensureFormContextHookField(contextWithHook.FormContextHook, fieldName).updatedValueCallbacks; + var index = callbacks.indexOf(callback); + if (index != -1) { + callbacks.splice(index, 1); + } + } + } + } + + export function getControl(schema: SPClientTemplates.FieldSchema_InForm): HTMLInputElement { + var id = schema.Name + '_' + schema.Id + '_$' + schema.FieldType + 'Field'; + //TODO: Handle different input types + return $get(id); + } + + export function getFieldTemplate(field: SPClientTemplates.FieldSchema, mode: SPClientTemplates.ClientControlMode): SPClientTemplates.FieldCallback { + var ctx = { ListSchema: { Field: [field] }, FieldControlModes: {} }; + ctx.FieldControlModes[field.Name] = mode; + var templates = SPClientTemplates.TemplateManager.GetTemplates(ctx); + return templates.Fields[field.Name]; + } + + + class csr implements ICSR, SPClientTemplates.TemplateOverridesOptions { + + public Templates: SPClientTemplates.TemplateOverrides; + public OnPreRender: SPClientTemplates.RenderCallback[]; + public OnPostRender: SPClientTemplates.RenderCallback[]; + private IsRegistered: boolean; + + + constructor(public ListTemplateType?: number, public BaseViewID?: any) { + this.Templates = { Fields: {} }; + this.OnPreRender = [] ; + this.OnPostRender = []; + this.IsRegistered = false; + } + + /* tier 1 methods */ + view(template: any): ICSR { + this.Templates.View = template; + return this; + } + + item(template: any): ICSR { + this.Templates.Item = template; + return this; + } + + header(template: any): ICSR { + this.Templates.Header = template; + return this; + } + + body(template: any): ICSR { + this.Templates.Body = template; + return this; + } + + footer(template: any): ICSR { + this.Templates.Footer = template; + return this; + } + + fieldView(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].View = template; + return this; + } + + fieldDisplay(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].DisplayForm = template; + return this; + } + + fieldNew(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].NewForm = template; + return this; + } + + fieldEdit(fieldName: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName].EditForm = template; + return this; + } + + /* tier 2 methods */ + template(name: string, template: any): ICSR { + this.Templates[name] = template; + return this; + } + + fieldTemplate(fieldName: string, name: string, template: any): ICSR { + this.Templates.Fields[fieldName] = this.Templates.Fields[fieldName] || {}; + this.Templates.Fields[fieldName][name] = template; + return this; + } + + /* common */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPreRender.push(callbacks[i]); + } + return this; + } + + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR { + for (var i = 0; i < callbacks.length; i++) { + this.OnPostRender.push(callbacks[i]); + } + return this; + } + + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPreRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR { + return this.onPostRender((ctx: SPClientTemplates.RenderContext) => { + var ctxInView = ctx; + + //ListSchema schma exists in Form and in View render context + var fields = ctxInView.ListSchema.Field; + if (fields) { + for (var i = 0; i < fields.length; i++) { + if (fields[i].Name === field) { + callback(fields[i], ctx); + } + } + } + }); + } + + makeReadOnly(fieldName: string): ICSR { + return this + .onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid + || ctx.ControlMode == SPClientTemplates.ClientControlMode.DisplayForm) return; + (schema).ReadOnlyField = true; + (schema).ReadOnly = "TRUE"; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + if (ctxInView.inGridMode) { + //TODO: Disable editing in grid mode + + } + + } else { + var ctxInForm = ctx; + if (schema.Type != 'User' && schema.Type != 'UserMulti') { + + var template = getFieldTemplate(schema, SPClientTemplates.ClientControlMode.DisplayForm); + ctxInForm.Templates.Fields[fieldName] = template; + ctxInForm.FormContext.registerGetValueCallback(fieldName, () => ctxInForm.ListData.Items[0][fieldName]); + + } + } + + }) + .onPostRenderField(fieldName, (schema: SPClientTemplates.FieldSchema_InForm_User, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + if (schema.Type == 'User' || schema.Type == 'UserMulti') { + SP.SOD.executeFunc('clientpeoplepicker.js', 'SPClientPeoplePicker', () => { + var topSpanId = schema.Name + '_' + schema.Id + '_$ClientPeoplePicker'; + var retryCount = 10; + var callback = () => { + var pp = SPClientPeoplePicker.SPClientPeoplePickerDict[topSpanId]; + if (!pp) { + if (retryCount--) setTimeout(callback, 1); + } else { + pp.SetEnabledState(false); + pp.DeleteProcessedUser = function () { }; + } + }; + callback(); + }); + } + } + }); + } + + makeHidden(fieldName: string): ICSR { + return this.onPreRenderField(fieldName, (schema, ctx) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.Invalid) return; + (schema).Hidden = true; + + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.View) { + var ctxInView = ctx; + + if (ctxInView.inGridMode) { + //TODO: Hide item in grid mode + } else { + ctxInView.ListSchema.Field.splice(ctxInView.ListSchema.Field.indexOf(schema), 1); + } + + } else { + var ctxInForm = ctx; + + var pHolderId = ctxInForm.FormUniqueId + ctxInForm.FormContext.listAttributes.Id + fieldName; + var placeholder = $get(pHolderId); + var current = placeholder; + while (current.tagName.toUpperCase() !== "TR") { + current = current.parentElement; + } + var row = current; + row.style.display = 'none'; + + } + + }); + } + + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR { + + + return this.fieldEdit(fieldName, SPFieldCascadedLookup_Edit) + .fieldNew(fieldName, SPFieldCascadedLookup_Edit); + + + function SPFieldCascadedLookup_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + + var parseRegex = /\{[^\}]+\}/g; + var dependencyExpressions: string[] = []; + var result: RegExpExecArray; + while ((result = parseRegex.exec(camlFilter))) { + dependencyExpressions.push(stripBraces(result[0])); + } + var dependencyValues: { [expr: string]: string } = {}; + + var _dropdownElt: HTMLSelectElement; + var _myData: SPClientTemplates.ClientFormContext; + + + if (rCtx == null) + return ''; + _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + + var _schema = _myData.fieldSchema; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + validators.RegisterValidator(new BooleanValueValidator(() => _optionsLoaded, "Wait until lookup values loaded and try again")); + + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + var _dropdownId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$LookupField'; + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr).LookupId; + var _noValueSelected = _selectedValue == 0; + var _optionsLoaded = false; + var pendingLoads = 0; + + if (_noValueSelected) + _valueStr = ''; + + _myData.registerInitCallback(_myData.fieldName, InitLookupControl); + + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_dropdownElt != null) + _dropdownElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_dropdownId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, GetCurrentLookupValue); + _myData.updateControlValue(_myData.fieldName, _valueStr); + + return BuildLookupDropdownControl(); + + function InitLookupControl() { + _dropdownElt = document.getElementById(_dropdownId); + if (_dropdownElt != null) + AddEvtHandler(_dropdownElt, "onchange", OnLookupValueChanged); + + SP.SOD.executeFunc('sp.js', 'SP.ClientContext', () => { + bindDependentControls(dependencyExpressions); + loadOptions(true); + }); + } + + + function BuildLookupDropdownControl() { + var result = ''; + result += '
    '; + return result; + } + + + function OnLookupValueChanged() { + if (_optionsLoaded) { + if (_dropdownElt != null) { + _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + _selectedValue = parseInt(_dropdownElt.value, 10); + } + } + } + + function GetCurrentLookupValue() { + if (_dropdownElt == null) + return ''; + return _dropdownElt.value == '0' || _dropdownElt.value == '' ? '' : _dropdownElt.value + ';#' + _dropdownElt.options[_dropdownElt.selectedIndex].text; + } + + function stripBraces(input: string): string { + return input.substring(1, input.length - 1); + } + + function getDependencyValue(expr: string, value: string, listId: string, expressionParts: string[], callback: () => void) { + var isLookupValue = !!listId; + if (isLookupValue) { + var lookup = SPClientTemplates.Utility.ParseLookupValue(value); + if (expressionParts.length == 1 && expressionParts[0] == 'Value') { + value = lookup.LookupValue; + expressionParts.shift(); + } else { + value = lookup.LookupId.toString(); + } + } + + if (expressionParts.length == 0) { + dependencyValues[expr] = value; + callback(); + } else { + var ctx = SP.ClientContext.get_current(); + var web = ctx.get_web(); + //TODO: Handle lookup to another web + var list = web.get_lists().getById(listId); + var item = list.getItemById(parseInt(value, 10)); + var field = list.get_fields().getByInternalNameOrTitle(expressionParts.shift()); + ctx.load(item); + ctx.load(field); + + ctx.executeQueryAsync((o, e) => { + var value = item.get_item(field.get_internalName()); + + if (field.get_typeAsString() == 'Lookup') { + field = ctx.castTo(field, SP.FieldLookup); + var lookup = (value); + value = lookup.get_lookupId() + ';#' + lookup.get_lookupValue(); + listId = (field).get_lookupList(); + } + + getDependencyValue(expr, value, listId, expressionParts, callback); + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + function bindDependentControls(dependencyExpressions: string[]) { + dependencyExpressions.forEach(expr => { + var exprParts = expr.split("."); + var field = exprParts.shift(); + + CSR.addUpdatedValueCallback(rCtx, field, + (v, s) => { + getDependencyValue(expr, v, + (s).LookupListId, + exprParts.slice(0), + loadOptions); + }); + + }); + } + + + function loadOptions(isFirstLoad?: boolean) { + _optionsLoaded = false; + pendingLoads++; + + var ctx = SP.ClientContext.get_current(); + //TODO: Handle lookup to another web + var web = ctx.get_web(); + var listId = _schema.LookupListId; + var list = !listname ? web.get_lists().getById(listId) : web.get_lists().getByTitle(listname); + var query = new SP.CamlQuery(); + + var predicate = camlFilter.replace(parseRegex, (v, a) => { + var expr = stripBraces(v); + return dependencyValues[expr] ? dependencyValues[expr] : ''; + }); + + //TODO: Handle ShowField attribure + if (predicate.substr(0, 5) == '' + + predicate + + ' ' + + ''); + } + var results = list.getItems(query); + ctx.load(results); + + + ctx.executeQueryAsync((o, e) => { + var selected = false; + + while (_dropdownElt.options.length) { + _dropdownElt.options.remove(0); + } + + if (!_schema.Required) { + var defaultOpt = new Option(Strings.STS.L_LookupFieldNoneOption, '0', selected, selected); + _dropdownElt.options.add(defaultOpt); + selected = _selectedValue == 0; + } + var isEmptyList = true; + + var enumerator = results.getEnumerator(); + while (enumerator.moveNext()) { + var c = enumerator.get_current(); + var id: number; + var text: string; + + if (!lookupField) { + id = c.get_id(); + text = c.get_item('Title'); + } else { + var value = c.get_item(lookupField); + id = value.get_lookupId(); + text = value.get_lookupValue(); + } + var isSelected = _selectedValue == id; + if (isSelected) { + selected = true; + } + var opt = new Option(text, id.toString(), isSelected, isSelected); + _dropdownElt.options.add(opt); + isEmptyList = false; + } + pendingLoads--; + _optionsLoaded = true; + if (!pendingLoads) { + if (isFirstLoad) { + if (_selectedValue == 0 && !selected) { + _dropdownElt.selectedIndex = 0; + OnLookupValueChanged(); + } + } else { + if (_selectedValue != 0 && !selected) { + _dropdownElt.selectedIndex = 0; + } + OnLookupValueChanged(); + } + } + + + }, (o, args) => { console.log(args.get_message()); }); + } + } + + } + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR { + return this.fieldEdit(fieldName, koEditField_Edit) + .fieldNew(fieldName, koEditField_Edit); + + + function koEditField_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + var elementId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type; + + vm.renderingContext = rCtx; + + + if (dependencyFields) { + dependencyFields.forEach(dependencyField => { + if (!vm[dependencyField]) { + vm[dependencyField] = ko.observable(CSR.getFieldValue(rCtx, dependencyField)); + } + CSR.addUpdatedValueCallback(rCtx, dependencyField, v => { + vm[dependencyField](v); + }); + }); + } + + + if (!vm.value) { + vm.value = ko.observable(); + } + + vm.value.subscribe(v => { _myData.updateControlValue(fieldName, v); }); + _myData.registerGetValueCallback(fieldName, () => vm.value()); + + + _myData.registerInitCallback(fieldName, () => { + ko.applyBindings(vm, $get(elementId)); + }); + + return '
    '+template+'
    '; + } + } + + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR { + var dependentValues: { [field: string]: string } = {}; + + return this.onPostRenderField(targetField, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) { + var targetControl = CSR.getControl(schema); + sourceField.forEach((field) => { + CSR.addUpdatedValueCallback(ctx, field, v => { + dependentValues[field] = v; + targetControl.value = transform.apply(this, + sourceField.map(n => dependentValues[n] || '')); + + }); + }); + } + }); + } + + setInitialValue(fieldName: string, value: any, ignoreNull?: boolean): ICSR { + if (value || !ignoreNull) { + return this.onPreRenderField(fieldName, (schema, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + ctx.ListData.Items[0][fieldName] = value; + }); + } else { + return this; + } + } + + + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR { + return this + .fieldNew(fieldName, SPFieldLookup_Autofill_Edit) + .fieldEdit(fieldName, SPFieldLookup_Autofill_Edit); + + function SPFieldLookup_Autofill_Edit(rCtx: SPClientTemplates.RenderContext_FieldInForm) { + if (rCtx == null) + return ''; + var _myData = SPClientTemplates.Utility.GetFormContextForCurrentField(rCtx); + + if (_myData == null || _myData.fieldSchema == null) + return ''; + + var _autoFillControl: SPClientAutoFill; + var _textInputElt: HTMLInputElement; + var _textInputId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$' + _myData.fieldSchema.Type + 'Field'; + var _autofillContainerId = _myData.fieldName + '_' + _myData.fieldSchema.Id + '_$AutoFill'; + + var validators = new SPClientForms.ClientValidation.ValidatorSet(); + if (_myData.fieldSchema.Required) { + validators.RegisterValidator(new SPClientForms.ClientValidation.RequiredValidator()); + } + _myData.registerClientValidator(_myData.fieldName, validators); + + _myData.registerInitCallback(_myData.fieldName, initAutoFillControl); + _myData.registerFocusCallback(_myData.fieldName, function () { + if (_textInputElt != null) + _textInputElt.focus(); + }); + _myData.registerValidationErrorCallback(_myData.fieldName, function (errorResult) { + SPFormControl_AppendValidationErrorMessage(_textInputId, errorResult); + }); + _myData.registerGetValueCallback(_myData.fieldName, () => _myData.fieldValue); + _myData.updateControlValue(_myData.fieldName, _myData.fieldValue); + + return buildAutoFillControl(); + + function initAutoFillControl() { + _textInputElt = document.getElementById(_textInputId); + + SP.SOD.executeFunc("autofill.js", "SPClientAutoFill", () => { + _autoFillControl = new SPClientAutoFill(_textInputId, _autofillContainerId, (_) => callback()); + var callback = init({ + renderContext: rCtx, + fieldContext: _myData, + autofill: _autoFillControl, + control: _textInputElt, + }); + + //_autoFillControl.AutoFillMinTextLength = 2; + //_autoFillControl.VisibleItemCount = 15; + //_autoFillControl.AutoFillTimeout = 500; + }); + + } + //function OnPopulate(targetElement: HTMLInputElement) { + + //} + + //function OnLookupValueChanged() { + // _myData.updateControlValue(_myData.fieldName, GetCurrentLookupValue()); + //} + //function GetCurrentLookupValue() { + // return _valueStr; + //} + function buildAutoFillControl() { + var result: string[] = []; + result.push('
    '); + result.push(''); + + result.push("
    "); + result.push("
    "); + + return result.join(""); + } + } + + + } + + seachLookup(fieldName: string): ICSR { + return this.autofill(fieldName, (ctx: IAutoFillFieldContext) => { + var _myData = ctx.fieldContext; + var _schema = _myData.fieldSchema; + if (_myData.fieldSchema.Type != 'Lookup') { + return null; + } + + var _valueStr = _myData.fieldValue != null ? _myData.fieldValue : ''; + var _selectedValue = SPClientTemplates.Utility.ParseLookupValue(_valueStr); + var _noValueSelected = _selectedValue.LookupId == 0; + ctx.control.value = _selectedValue.LookupValue; + $addHandler(ctx.control, "blur", _ => { + if (ctx.control.value == '') { + _myData.fieldValue = ''; + _myData.updateControlValue(fieldName, _myData.fieldValue); + } + }); + + if (_noValueSelected) + _myData.fieldValue = ''; + + var _autoFillControl = ctx.autofill; + _autoFillControl.AutoFillMinTextLength = 2; + _autoFillControl.VisibleItemCount = 15; + _autoFillControl.AutoFillTimeout = 500; + + return () => { + var value = ctx.control.value; + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildLoadingItem('Please wait...')], onSelectItem); + + SP.SOD.executeFunc("sp.search.js", "Microsoft.SharePoint.Client.Search.Query", () => { + var Search = Microsoft.SharePoint.Client.Search.Query; + var ctx = SP.ClientContext.get_current(); + var query = new Search.KeywordQuery(ctx); + query.set_rowLimit(_autoFillControl.VisibleItemCount); + query.set_queryText('contentclass:STS_ListItem ListID:{' + _schema.LookupListId + '} ' + value); + var selectProps = query.get_selectProperties(); + selectProps.clear(); + //TODO: Handle ShowField attribute + selectProps.add('Title'); + selectProps.add('ListItemId'); + var executor = new Search.SearchExecutor(ctx); + var result = executor.executeQuery(query); + ctx.executeQueryAsync( + () => { + //TODO: Discover proper way to load collection + var tableCollection = new Search.ResultTableCollection(); + tableCollection.initPropertiesFromJson(result.get_value()); + + var relevantResults = tableCollection.get_item(0); + var rows = relevantResults.get_resultRows(); + + var items = []; + for (var i = 0; i < rows.length; i++) { + items.push(AutoFillOptionBuilder.buildOptionItem(parseInt(rows[i]["ListItemId"], 10), rows[i]["Title"])); + } + + items.push(AutoFillOptionBuilder.buildSeparatorItem()); + + if (relevantResults.get_totalRows() == 0) + items.push(AutoFillOptionBuilder.buildFooterItem("No results. Please refine your query.")); + else + items.push(AutoFillOptionBuilder.buildFooterItem("Showing " + rows.length + " of" + relevantResults.get_totalRows() + " items!")); + + _autoFillControl.PopulateAutoFill(items, onSelectItem); + + }, + (sender, args) => { + _autoFillControl.PopulateAutoFill([AutoFillOptionBuilder.buildFooterItem("Error executing query/ See log for details.")], onSelectItem); + console.log(args.get_message()); + }); + }); + } + + function onSelectItem(targetInputId, item: ISPClientAutoFillData) { + var targetElement = ctx.control; + targetElement.value = item[SPClientAutoFill.DisplayTextProperty]; + _selectedValue.LookupId = item[SPClientAutoFill.KeyProperty]; + _selectedValue.LookupValue = item[SPClientAutoFill.DisplayTextProperty]; + _myData.fieldValue = item[SPClientAutoFill.KeyProperty] + ';#' + item[SPClientAutoFill.TitleTextProperty]; + _myData.updateControlValue(_myData.fieldSchema.Name, _myData.fieldValue); + } + + }); + } + + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR { + return this.onPostRenderField(fieldName, + (schema: SPClientTemplates.FieldSchema_InForm_Lookup, ctx: SPClientTemplates.RenderContext_FieldInForm) => { + if (ctx.ControlMode == SPClientTemplates.ClientControlMode.EditForm + || ctx.ControlMode == SPClientTemplates.ClientControlMode.NewForm) + + var control = CSR.getControl(schema); + if (control) { + var weburl = _spPageContextInfo.webServerRelativeUrl; + if (weburl[weburl.length - 1] == '/') { + weburl = weburl.substring(0, weburl.length - 1); + } + var newFormUrl = weburl + '/_layouts/listform.aspx/listform.aspx?PageType=8' + + "&ListId=" + encodeURIComponent('{' + schema.LookupListId + '}'); + if (contentTypeId) { + newFormUrl += '&ContentTypeId=' + contentTypeId; + } + + var link = document.createElement('a'); + link.href = "javascript:NewItem2(event, \'" + newFormUrl + "&Source=" + encodeURIComponent(document.location.href) + "')"; + link.textContent = prompt; + if (control.nextElementSibling) { + control.parentElement.insertBefore(link, control.nextElementSibling); + } else { + control.parentElement.appendChild(link); + } + + if (showDialog) { + $addHandler(link, "click", (e: Sys.UI.DomEvent) => { + SP.SOD.executeFunc('sp.ui.dialog.js', 'SP.UI.ModalDialog.ShowPopupDialog', () => { + SP.UI.ModalDialog.ShowPopupDialog(newFormUrl); + }); + e.stopPropagation(); + e.preventDefault(); + }); + } + } + }); + } + + register() { + if (!this.IsRegistered) { + SPClientTemplates.TemplateManager.RegisterTemplateOverrides(this); + this.IsRegistered = true; + } + } + } + + export class AutoFillOptionBuilder { + + static buildFooterItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.DisplayTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Footer; + + return item; + } + + static buildOptionItem(id: number, title: string, displayText?: string, subDisplayText?: string): ISPClientAutoFillData { + + var item = {}; + + item[SPClientAutoFill.KeyProperty] = id; + item[SPClientAutoFill.DisplayTextProperty] = displayText || title; + item[SPClientAutoFill.SubDisplayTextProperty] = subDisplayText; + item[SPClientAutoFill.TitleTextProperty] = title; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Option; + + return item; + } + + static buildSeparatorItem(): ISPClientAutoFillData { + var item = {}; + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Separator; + return item; + } + + static buildLoadingItem(title: string): ISPClientAutoFillData { + var item = {}; + + item[SPClientAutoFill.MenuOptionTypeProperty] = SPClientAutoFill.MenuOptionType.Loading; + item[SPClientAutoFill.DisplayTextProperty] = title; + return item; + } + + } + + /** Lightweight client-side rendering template overrides.*/ + export interface ICSR { + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: string): ICSR; + + /** Override rendering template. + @param name Name of template to override. + @param template New template. + */ + template(name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: string): ICSR; + + /** Override field rendering template. + @param name Internal name of field to override. + @param name Name of template to override. + @param template New template. + */ + fieldTemplate(field: string, name: string, template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Sets pre-render callbacks. Callback called before rendering starts. + @param callbacks pre-render callbacks. + */ + onPreRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. + @param callbacks post-render callbacks. + */ + onPostRender(...callbacks: { (ctx: SPClientTemplates.RenderContext): void; }[]): ICSR; + + /** Sets pre-render callbacks for field. Callback called before rendering starts. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks pre-render callbacks. + */ + onPreRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Sets post-render callbacks. Callback called after rendered html inserted to DOM. Correctly handles form rendering. + @param fieldName Internal name of the field. + @param callbacks post-render callbacks. + */ + onPostRenderField(field: string, callback: { (schema: SPClientTemplates.FieldSchema, ctx: SPClientTemplates.RenderContext): void; }): ICSR; + + /** Registers overrides in client-side templating engine.*/ + register(): void; + + /** Override View rendering template. + @param template New view template. + */ + view(template: string): ICSR; + + /** Override View rendering template. + @param template New view template. + */ + view(template: (ctx: SPClientTemplates.RenderContext_InView) => string): ICSR; + view(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: string): ICSR; + + /** Override Item rendering template. + @param template New item template. + */ + item(template: (ctx: SPClientTemplates.RenderContext_ItemInView) => string): ICSR; + item(template: (ctx: SPClientTemplates.RenderContext_Form) => string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: string): ICSR; + + /** Override Header rendering template. + @param template New header template. + */ + header(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: string): ICSR; + + /** Override Body rendering template. + @param template New body template. + */ + body(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: string): ICSR; + + /** Override Footer rendering template. + @param template New footer template. + */ + footer(template: (ctx: SPClientTemplates.RenderContext) => string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: string): ICSR; + + /** Override View rendering template for specified field. + @param fieldName Internal name of the field. + @param template New View template. + */ + fieldView(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInView) => string): ICSR; + + /** Override DisplyForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: string): ICSR; + + /** Override DisplyForm rendering template. + @param fieldName Internal name of the field. + @param template New DisplyForm template. + */ + fieldDisplay(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override EditForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: string): ICSR; + + /** Override EditForm rendering template. + @param fieldName Internal name of the field. + @param template New EditForm template. + */ + fieldEdit(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + /** Override NewForm rendering template for specified field. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: string): ICSR; + + /** Override NewForm rendering template. + @param fieldName Internal name of the field. + @param template New NewForm template. + */ + fieldNew(fieldName: string, template: (ctx: SPClientTemplates.RenderContext_FieldInForm) => string): ICSR; + + + /** Set initial value for field. + @param fieldName Internal name of the field. + @param value Initial value for field. + */ + setInitialValue(fieldName: string, value: any): ICSR; + + /** Make field hidden in list view and standard forms. + @param fieldName Internal name of the field. + */ + makeHidden(fieldName: string): ICSR + + + /** Replace New and Edit templates for field to Display template. + @param fieldName Internal name of the field. + */ + makeReadOnly(fieldName: string): ICSR + + /** Create cascaded Lookup Field. + @param fieldName Internal name of the field. + @param camlFilter CAML predicate expression (inside Where clause). Use {FieldName} tokens for dependency fields substitutions. + */ + filteredLookup(fieldName: string, camlFilter: string, listname?: string, lookupField?: string): ICSR + + /** Auto computes text-based field value based on another fields. + @param targetField Internal name of the field. + @param transform Function combines source field values. + @param sourceField Internal names of source fields. + */ + computedValue(targetField: string, transform: (...values: string[]) => string, ...sourceField: string[]): ICSR + + /** Field text value with autocomplete based on autofill.js + @param fieldName Internal name of the field. + @param ctx AutoFill context. + */ + autofill(fieldName: string, init: (ctx: IAutoFillFieldContext) => () => void): ICSR + + /** Replace defult dropdown to search-based autocomplete for Lookup field. + @param fieldName Internal name of the field. + */ + seachLookup(fieldName: string): ICSR; + + /** Adds link to add new value to lookup list. + @param fieldName Internal name of the field. + @param prompt Text to display as a link to add new value. + @param contentTypeID Default content type for new item. + */ + lookupAddNew(fieldName: string, prompt: string, showDialog?: boolean, contentTypeId?: string): ICSR; + + koEditField(fieldName: string, template: string, vm: IKoFieldInForm, dependencyFields?: string[]): ICSR; + + + } + + export interface IAutoFillFieldContext { + renderContext: SPClientTemplates.RenderContext_FieldInForm; + fieldContext: SPClientTemplates.ClientFormContext; + autofill: SPClientAutoFill; + control: HTMLInputElement; + } + + export interface IKoFieldInForm { + renderingContext?:SPClientTemplates.RenderContext_FieldInForm; + value?:KnockoutObservable; + } + + + interface IFormRenderContexWithHook extends SPClientTemplates.RenderContext_FieldInForm { + FormContextHook: IFormContextHook; + } + + interface IFormContextHook { + [fieldName: string]: IFormContextHookField; + } + + interface IFormContextHookField { + fieldSchema?: SPClientTemplates.FieldSchema_InForm; + lastValue?: any; + getValue?: () => any; + updatedValueCallbacks: UpdatedValueCallback[]; + } + + + function ensureFormContextHookField(hook: IFormContextHook, fieldName: string): IFormContextHookField { + return hook[fieldName] = hook[fieldName] || { + updatedValueCallbacks: [] + }; + + } + + class BooleanValueValidator implements SPClientForms.ClientValidation.IValidator { + constructor(public valueGetter: () => boolean, public validationMessage: string) { } + + Validate(value: any): SPClientForms.ClientValidation.ValidationResult { + return new SPClientForms.ClientValidation.ValidationResult(!this.valueGetter(), this.validationMessage); + } + } + +} + +if (typeof SP == 'object' && SP && typeof SP.SOD == 'object' && SP.SOD) { + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("typescripttemplates.ts"); +} + + +//mquery.ts + + + + +module spdevlab { + export module mQuery { + export class DynamicTable { + + // private fields + _domContainer:HTMLElement; + _tableContainer:MQueryResultSetElements; + + _rowTemplateId:string = null; + _rowTemplateContent:string = null; + + _options = { + tableCnt: '.spdev-rep-tb', + addCnt: '.spdev-rep-tb-add', + removeCnt: '.spdev-rep-tb-del' + }; + + // public methods + init(domContainer: HTMLElement, options) { + + if (m$.isDefinedAndNotNull(options)) { + m$.extend(this._options, options); + } + + this._initContainers(domContainer); + + this._initRowTemplate(); + this._initEvents(); + this._showUI(); + } + + // private methods + _initContainers(domContainer) { + + this._domContainer = domContainer; + this._tableContainer = m$(this._options.tableCnt, this._domContainer); + } + + _showUI() { + m$(this._domContainer).css("display", ""); + } + + _initEvents() { + + m$(this._options.addCnt, this._domContainer).click(() => { + + if (m$.isDefinedAndNotNull(this._rowTemplateContent)) { + + m$(this._tableContainer).append(this._rowTemplateContent); + + m$("tr:last-child " + this._options.removeCnt, this._tableContainer).click( (e) => { + + var targetElement = e.currentTarget; + var parentRow = m$(targetElement).parents("tr").first(); + + m$(parentRow).remove(); + }); + } + + return false; + }); + } + + _initRowTemplate() { + var templateId = m$(this._tableContainer).attr("template-id"); + + if (m$.isDefinedAndNotNull(templateId)) { + this._rowTemplateId = templateId; + this._rowTemplateContent = DynamicTable._templates[templateId]; + } + } + + static _templates:string[] = []; + static initTables() { + // init templates + m$('script').forEach((template:HTMLElement) => { + + var id = m$(template).attr("dynamic-table-template-id"); + + if (m$.isDefinedAndNotNull(id)) { + DynamicTable._templates[id] = template.innerHTML; + } + }); + + // init tables + m$(".spdev-rep-tb-cnt").forEach( divContainer => { + + var dynamicTable = new DynamicTable(); + + dynamicTable.init(divContainer, { + removeCnt: '.spdev-rep-tb-del-override' + }); + }); + } + + }; + + + } +} + +m$.ready(() => { + spdevlab.mQuery.DynamicTable.initTables(); +}); + + +//whoisapppart.ts + + +module _ { + var queryString = parseQueryString(); + var isIframe = queryString['DisplayMode'] == 'iframe' + var spHostUrl = queryString['SPHostUrl']; + var editmode = Number(queryString['editmode']); + var includeDetails = queryString['boolProp'] == 'true'; + + prepareVisual(); + m$.ready(() => { + loadPeoplePicker('peoplePicker'); + partProperties(); + + if (isIframe) { + partResize(); + } + }); + + //Load the people picker + function loadPeoplePicker(peoplePickerElementId: string) { + var schema: ISPClientPeoplePickerSchema = { + PrincipalAccountType: "User", + AllowMultipleValues: false, + Width: 300, + OnUserResolvedClientScript: onUserResolvedClientScript + } + + SPClientPeoplePicker.InitializeStandalonePeoplePicker(peoplePickerElementId, null, schema); + } + + function onUserResolvedClientScript(el: string, users: ISPClientPeoplePickerEntity[]) { + if (users.length > 0) { + var person = users[0]; + var accountName = person.Key; + + var context = SP.ClientContext.get_current(); + + var peopleManager = new SP.UserProfiles.PeopleManager(context); + var personProperties = peopleManager.getPropertiesFor(accountName); + + context.load(personProperties); + context.executeQueryAsync((sender, args) => { + + $get("basicInfo").style.display = 'block'; + + var userPic = personProperties.get_userProfileProperties()["PictureURL"]; + $get("pic").innerHTML = ' + personProperties.get_displayName() + '; + + $get("name").innerHTML = '' + personProperties.get_displayName() + ''; + $get("email").innerHTML = '' + personProperties.get_email() + ''; + $get("title").innerHTML = personProperties.get_title(); + $get("department").innerHTML = person.EntityData.Department; + $get("phone").innerHTML = person.EntityData.MobilePhone; + + var properties = personProperties.get_userProfileProperties(); + var messageText = ""; + for (var key in properties) { + messageText += "
    [" + key + "]: \"" + properties[key] + "\""; + } + $get("detailInfo").innerHTML = messageText; + + if (isIframe) { + partResize(); + } + + }, (sender, args) => { alert('Error: ' + args.get_message()); }); + + } + } + + function partProperties() { + + if (editmode == 1) { + $get("editmodehdr").style.display = "inline"; + $get("content").style.display = "none"; + } + else if (includeDetails) { + $get('detailInfo').style.display = 'block'; + + $get("editmodehdr").style.display = "none"; + $get("content").style.display = "inline"; + } + } + + function partResize() { + var bounds = Sys.UI.DomElement.getBounds(document.body); + parent.postMessage('resize(' + bounds.width + ',' + bounds.height + ')', '*'); + } + + function prepareVisual() { + if (isIframe) { + //Create a Link element for the defaultcss.ashx resource + var linkElement = document.createElement('link'); + linkElement.setAttribute('rel', 'stylesheet'); + linkElement.setAttribute('href', spHostUrl + '/_layouts/15/defaultcss.ashx'); + + //Add the linkElement as a child to the head section of the html + document.head.appendChild(linkElement); + } else { + + m$.ready(() => { + var nav = new SP.UI.Controls.Navigation('navigation', { + appIconUrl: queryString['SPHostLogo'], + appTitle: document.title + }); + nav.setVisible(true); + $get('apppart-notification').style.display = 'block'; + document.body.style.overflow = 'visible'; + }); + } + } + + function parseQueryString() { + var result = {}; + var qs = document.location.search.split('?')[1]; + if (qs) { + var parts = qs.split('&'); + for (var i = 0; i < parts.length; i++) { + if (parts[i]) { + var pair = parts[i].split('='); + result[pair[0]] = decodeURIComponent(pair[1]); + } + } + } + return result; + } +} + +//taxonomy +module SP { + + // Class + export class ClientContextPromise extends SP.ClientContext { + /** To use this function, you must ensure that jQuery and CSOMPromise js files are loaded to the page */ + executeQueryPromise(): JQueryPromise { + var deferred = jQuery.Deferred(); + this.executeQueryAsync(function (sender, args) { + deferred.resolve(sender, args); + }, + function (sender, args) { + deferred.reject(sender, args); + }) + return deferred.promise(); + } + + constructor(serverRelativeUrlOrFullUrl: string) { + super(serverRelativeUrlOrFullUrl); + } + + static get_current(): ClientContextPromise { + return new ClientContextPromise(_spPageContextInfo.siteServerRelativeUrl); + } + + } + +} + +SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CSOMPromise.ts"); + +module _ { + var context: SP.ClientContextPromise; + var web: SP.Web; + var site: SP.Site; + var session: SP.Taxonomy.TaxonomySession; + var termStore: SP.Taxonomy.TermStore; + var groups: SP.Taxonomy.TermGroupCollection; + + // This code runs when the DOM is ready and creates a context object + // which is needed to use the SharePoint object model. + // It also wires up the click handlers for the two HTML buttons in Default.aspx. + $(document).ready(function () { + context = SP.ClientContextPromise.get_current(); + site = context.get_site(); + web = context.get_web(); + $('#listExisting').click(function () { listGroups(); }); + $('#createTerms').click(function () { createTerms(); }); + }); + + // When the listExisting button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function listGroups() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onListTaxonomySession, onFailListTaxonomySession); + } + + // Runs when the executeQueryAsync method in the listGroups function has succeeded. + // In this case, get and load the groups associated with the term store that we + // know we now have a reference to. + function onListTaxonomySession() { + groups = termStore.get_groups(); + context.load(groups); + context.executeQueryAsync(onRetrieveGroups, onFailRetrieveGroups); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has succeeded. + // In this case, loop through all the groups and add a clickable div element to the report area + // for each group. + // NOTE: We clear the report area first to ensure we have a clean place to write to. + // Also note how we create a click event handler for each div on-the-fly, and that we pass in the + // current group ID to that function. So when the user clicks one of these divs, we will know which + // one was clicked. + function onRetrieveGroups() { + $('#report').children().remove(); + + var groupEnum = groups.getEnumerator(); + + // For each group, we'll build a clickable div. + while (groupEnum.moveNext()) { + (() => { + var currentGroup = groupEnum.get_current(); + var groupName = document.createElement("div"); + groupName.setAttribute("style", "float:none;cursor:pointer"); + var groupID = currentGroup.get_id(); + groupName.setAttribute("id", groupID.toString()); + $(groupName).click(() => showTermSets(groupID)); + groupName.appendChild(document.createTextNode(currentGroup.get_name())); + $('#report').append(groupName); + })(); + } + } + + // This is the function that runs when the user clicks one of the divs + // that we created in the onRetrieveGroups function. We can know which + // div was clicked by interrogating the groupID parameter. So what we'll + // do is retrieve a reference to the group with the same ID as the div, and + // then add the term sets that belong to that group under the div that was clicked. + function showTermSets(groupID: SP.Guid) { + + // First thing is to remnove the divs under the group DIV to ensure we have a clean place to write to. + // The reason we don't clear them all is becuase we want to retain the text node of the + // group div. I.E. that's why we use "parentDiv.childNodes.length>1" as our loop + // controller. + var parentDiv = document.getElementById(groupID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // For each term set, we'll build a clickable div + var currentGroup = groups.getById(groupID); + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + context.load(currentGroup); + var termSets: SP.Taxonomy.TermSetCollection; + context.executeQueryPromise() + .then( + () => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise() + }) + .then(() => { + // The term sets are now available becuase this is the + // success callback. So now we'll iterate through the collection + // and create the clickable div. Also note how we create a + // click event handler for each div on-the-fly, and that we pass in the + // current group ID and term set ID to that function. So when the user + // clicks one of these divs, we will know which + // one was clicked by its term set ID, and to which group it belongs by its + // group ID. We also pass in the event object, so that we can cancel the bubble + // because this clickable div will be inside a parent clickable div and we + // don't want the parent's event to fire. + var termSetEnum = termSets.getEnumerator(); + while (termSetEnum.moveNext()) { + (() => { + var currentTermSet = termSetEnum.get_current(); + var termSetName = document.createElement("div"); + termSetName.appendChild(document.createTextNode(" + " + currentTermSet.get_name())); + termSetName.setAttribute("style", "float:none;cursor:pointer;"); + var termSetID = currentTermSet.get_id(); + termSetName.setAttribute("id", termSetID.toString()); + $(termSetName).click(e => showTerms(e, groupID, termSetID)); + parentDiv.appendChild(termSetName); + })(); + } + + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred in loading the term sets for this group"))); + } + + + // This is the function that runs when the user clicks one of the divs + // that we created in the showTermSets function. We can know which + // div was clicked by interrogating the termSetID parameter. So what we'll + // do is retrieve a reference to the term set with the same ID as the div, and + // then add the term that belong to that term set under the div that was clicked. + + function showTerms(event: JQueryEventObject, groupID: SP.Guid, termSetID: SP.Guid) { + + // First, cancel the bubble so that the group div click handler does not also fire + // because that removes all term set divs and we don't want that here. + event.cancelBubble = true; + + // Get a reference to the term set div that was click and + // remove its children (apart from the TextNode that is currently + // showing the term set name. + var parentDiv = document.getElementById(termSetID.toString()); + while (parentDiv.childNodes.length > 1) { + parentDiv.removeChild(parentDiv.lastChild); + } + + // We need to load and populate the matching group first, or the + // term sets that it contains will be inaccessible to our code. + var currentGroup = groups.getById(groupID); + var termSets:SP.Taxonomy.TermSetCollection; + var currentTermSet:SP.Taxonomy.TermSet; + var terms:SP.Taxonomy.TermCollection; + + context.load(currentGroup); + context + .executeQueryPromise() + .then(() => { + // The group is now available becuase this is the + // success callback. So now we'll load and populate the + // term set collection. We have to do this before we can + // iterate through the collection, so we can do this + // with the following nested executeQueryAsync method call. + termSets = currentGroup.get_termSets(); + context.load(termSets); + return context.executeQueryPromise(); + }) + .then(() => { + currentTermSet = termSets.getById(termSetID); + context.load(currentTermSet); + return context.executeQueryPromise(); + }) + .then(() => { + terms = currentTermSet.get_terms(); + context.load(terms); + return context.executeQueryPromise(); + }) + .then(() => { + var termsEnum = terms.getEnumerator(); + while (termsEnum.moveNext()) { + var currentTerm = termsEnum.get_current(); + + var term = document.createElement("div"); + term.appendChild(document.createTextNode(" - " + currentTerm.get_name())); + term.setAttribute("style", "float:none;margin-left:10px;"); + parentDiv.appendChild(term); + } + }) + .fail(() => parentDiv.appendChild(document.createTextNode("An error occurred when trying to retrieve terms in this term set"))); + } + + // Runs when the executeQueryAsync method in the onListTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailRetrieveGroups(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to retrieve groups. Error:" + args.get_message()); + } + + // Runs when the executeQueryAsync method in the listGroups function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailListTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + + + // When the createTerms button is clicked, start by loading + // a TaxonomySession for the current context. Also get and load + // the associated term store. + function createTerms() { + session = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); + termStore = session.getDefaultSiteCollectionTermStore(); + context.load(session); + context.load(termStore); + context.executeQueryAsync(onGetTaxonomySession, onFailTaxonomySession); + } + + + // This function is the success callback for loading the session and store from the createTerms function + function onGetTaxonomySession() { + // Create six GUIDs that we will need when we create a new group, term set, and associated terms + var guidGroupValue = SP.Guid.newGuid(); + var guidTermSetValue = SP.Guid.newGuid(); + var guidTerm1 = SP.Guid.newGuid(); + var guidTerm2 = SP.Guid.newGuid(); + var guidTerm3 = SP.Guid.newGuid(); + var guidTerm4 = SP.Guid.newGuid(); + + // Create a new group + var myGroup = termStore.createGroup("CustomTerms", guidGroupValue); + + // Create a new term set in the newly-created group + var myTermSet = myGroup.createTermSet("Privacy", guidTermSetValue, 1033); + + // Create four new terms in the newly-created term set + myTermSet.createTerm("Top Secret", 1033, guidTerm1); + myTermSet.createTerm("Company Confidential", 1033, guidTerm2); + myTermSet.createTerm("Partners Only", 1033, guidTerm3); + myTermSet.createTerm("Public", 1033, guidTerm4); + + // Ensure the groups variable has been set, because when this all succeeds we will + // effectively run the same code as if the user had clicked the listGroups button + groups = termStore.get_groups(); + context.load(groups); + + // Execute all the preceeding statements in this function + context.executeQueryAsync(onAddTerms, onFailAddTerms); + + } + + // If all is well with creating the terms, then this function will run. + // Effectively this runs the same code as if the user had clicked the listGroups button + // so the user will see their newly-created group + function onAddTerms() { + listGroups(); + } + + // Runs when the executeQueryAsync method in the onGetTaxonomySession function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailAddTerms(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to add terms. Error: " + args.get_message()); + } + + // Runs when the executeQueryAsync method in the createTerms function has failed. + // In this case, clear the report area in the page and tell the user what went wrong. + function onFailTaxonomySession(sender, args) { + $('#report').children().remove(); + $('#report').append("Failed to get session. Error: " + args.get_message()); + } + +}; + +//publishing.ts +// Variables used in various callbacks +JSRequest.EnsureSetup(); + +SP.SOD.execute('mquery.js', 'm$.ready', () => { + var context = SP.ClientContext.get_current(); + var web = context.get_web(); + m$('#CreatePage').click(createPage); +}); + +function createPage(evt) { + SP.SOD.execute('sp.js', 'SP.ClientConext', () => { + SP.SOD.execute('sp.publishing.js', 'SP.Publishing', () => { + var context = SP.ClientContext.get_current(); + + + var hostUrl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]); + var hostcontext = new SP.AppContextSite(context, hostUrl); + var web = hostcontext.get_web(); + var pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, web); + context.load(web); + context.load(pubWeb); + context.executeQueryAsync( + // Success callback after getting the host Web as a PublishingWeb. + // We now want to add a new Publishing Page. + function () { + var pageInfo = new SP.Publishing.PublishingPageInformation(); + var newPage = pubWeb.addPublishingPage(pageInfo); + context.load(newPage); + context.executeQueryAsync( + function () { + + // Success callback after adding a new Publishing Page. + // We want to get the actual list item that is represented by the Publishing Page. + var listItem = newPage.get_listItem(); + context.load(listItem); + context.executeQueryAsync( + + // Success callback after getting the actual list item that is + // represented by the Publishing Page. + // We can now get its FieldValues, one of which is its FileLeafRef value. + // We can then use that value to build the Url to the new page + // and set the href or our link to that Url. + function () { + var link = document.getElementById("linkToPage"); + link.setAttribute("href", web.get_url() + "/Pages/" + listItem.get_fieldValues().FileLeafRef); + link.innerText = "Go to new page!"; + }, + + // Failure callback after getting the actual list item that is + // represented by the Publishing Page. + function (sender, args) { + alert('Failed to get new page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to add a new Publishing Page. + function (sender, args) { + alert('Failed to Add Page: ' + args.get_message()); + } + ); + }, + // Failure callback after trying to get the host Web as a PublishingWeb. + function (sender, args) { + alert('Failed to get the PublishingWeb: ' + args.get_message()); + } + ); + }); + }); +} + +//likes +module SampleReputation { + + interface MyList extends SPClientTemplates.RenderContext_InView { + listId: string; + } + + class MyItem { + + id: number; + title: string; + likesCount: number; + isLikedByCurrentUser: boolean; + + constructor(public row: SPClientTemplates.Item) { + this.id = parseInt(row['ID']); + this.title = row['Title']; + this.likesCount = parseInt(row['LikesCount']) || 0; + this.isLikedByCurrentUser = this.getLike(row['LikedBy']); + } + + private getLike(likedBy): boolean { + if (likedBy && likedBy.length > 0) { + for (var i = 0; i < likedBy.length; i++) { + if (likedBy[i].id == _spPageContextInfo.userId) { + return true; + } + } + } + return false; + } + } + + function init() { + SP.SOD.registerSod('reputation.js', '/_layouts/15/reputation.js'); + SP.SOD.registerSod('typescripttemplates.ts', '/SPTypeScript/Extensions/typescripttemplates.js'); + SP.SOD.executeFunc('typescripttemplates.ts', 'CSR', () => { + CSR.override(10004, 1) + .onPreRender((ctx: MyList) => { + ctx.listId = ctx.listName.substring(1, 37); + }) + .header('
      ') + .body(renderTemplate) + .footer('
    ') + .register(); + }); + + SP.SOD.execute('mQuery.js', 'm$.ready', () => { + RegisterModuleInit('/SPTypeScript/ReputationModule/likes.js', init); + }); + + + SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs('likes.js'); + } + + function renderTemplate(ctx: MyList) { + var rows = ctx.ListData.Row; + var result = ''; + for (var i = 0; i < rows.length; i++) { + var item = new MyItem(rows[i]); + result += '\ +
  • ' + item.title +'\ + \ + ' + getLikeText(item.isLikedByCurrentUser) + '' + item.likesCount + '\ + \ +
  • '; + } + return result; + } + + function getLikeText(isLikedByCurrentUser: boolean) { + return isLikedByCurrentUser ? '\u2665' : '\u2661'; + } + + export function setLike(itemId: number, listId: string): void { + var context = SP.ClientContext.get_current(); + var isLiked = m$('#likesCountText' + itemId)[0].textContent == '\u2661'; + SP.SOD.executeFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function () { + Microsoft.Office.Server.ReputationModel.Reputation.setLike(context, listId, itemId, isLiked); + context.executeQueryAsync( + () => { + m$('#likesCountText' + itemId)[0].textContent = getLikeText(isLiked); + var likesCount = parseInt(m$('#likesCount' + itemId)[0].textContent); + m$('#likesCount' + itemId)[0].textContent = (isLiked ? likesCount + 1 : likesCount - 1).toString(); + }, + (sender, args) => { + alert(args.get_message()); + }); + }); + } + + init(); +} + + + +//code from https://github.com/gandjustas/SharePointAngularTS +module App { + "use strict"; +var app = angular.module("app", []); +} + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + interface Iappcontroller { + title: string; + activate: () => void; + } + + class appcontroller implements Iappcontroller { + title: string = "appcontroller"; + lists: SP.List[]; + + static $inject: string[] = ["$SharePoint", "$spnotify"]; + + constructor(private $SharePoint: App.ISharePoint, private $n:App.ISpNotify) { + this.activate(); + } + + activate() { + var loading = this.$n.showLoading(true) + this.$SharePoint + .getLists() + .then(l => this.lists = l ) + .catch((e: string) => this.$n.show(e, true)) + .finally(() => this.$n.remove(loading) ); + ; + + } + } + + angular.module("app").controller("appcontroller", appcontroller); +} + + + +module App { + "use strict"; + + export interface ISharePoint { + getLists: () => ng.IPromise; + } + + class SharePointServcie implements ISharePoint { + static $inject: string[] = ["$q"]; + + constructor(public $q: ng.IQService) { + } + + getLists() { + var promise = this.$q.defer(); + SP.SOD.executeFunc("sp.js", "SP.ClientContext", () => { + var ctx = SP.ClientContext.get_current(); + var hostUrl = decodeURIComponent(SP.ScriptHelpers.getDocumentQueryPairs()['SPHostUrl']); + var appCtx = new SP.AppContextSite(ctx, hostUrl); + var hostWeb = appCtx.get_web(); + var lists = hostWeb.get_lists(); + ctx.load(lists); + + ctx.executeQueryAsync(() => { + var result: SP.List[] = []; + for (var e = lists.getEnumerator(); e.moveNext();) { + result.push(e.get_current()); + } + promise.resolve(result); + }, + (o, args) => { promise.reject(args.get_message()); }); + }); + return promise.promise; + } + } + + angular.module("app").service("$SharePoint", SharePointServcie); +} + + +// Install the angularjs.TypeScript.DefinitelyTyped NuGet package +module App { + "use strict"; + + export interface ISpNotify { + showLoading(sticky?: boolean) : string; + show(msg: string, sticky?: boolean): string; + remove(id: string):void; + } + + class SpNotify implements ISpNotify { + static $inject: string[] = []; + + + showLoading(sticky: boolean = false) { + return SP.UI.Notify.showLoadingNotification(sticky); + } + + show(msg: string, sticky: boolean = false) { + return SP.UI.Notify.addNotification(msg, sticky); + } + + remove(id: string) { + SP.UI.Notify.removeNotification(id); + } + } + + angular.module("app").service("$spnotify", SpNotify); +} + From d910496ddc910e8e9b15290780505ea3fb45cbd8 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 09:28:38 -0700 Subject: [PATCH 059/881] Extended definitions with info from formlyApiCheck. --- angular-formly/angular-formly-test.ts | 67 ++-- angular-formly/angular-formly.d.ts | 439 ++++++++++++++------------ 2 files changed, 286 insertions(+), 220 deletions(-) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-test.ts index 4d4053823..603840208 100644 --- a/angular-formly/angular-formly-test.ts +++ b/angular-formly/angular-formly-test.ts @@ -2,49 +2,76 @@ var app = angular.module('app', ['formly']); +interface IScope extends ng.IScope { + to: { label: string; } +} + class AppController { fields: AngularFormly.IFieldConfigurationObject[]; constructor($scope: ng.IScope) { var vm = this; vm.fields = [ { - field: 'label', + key: 'email', type: 'input', templateOptions: { - maxlength: 8, - minlength: 3 + label: 'Email', + required: true, + type: 'email', + maxlength: 10, + minlength: 6, + placeholder: 'example@example.com' } }, { - template: '
    ' - }, - { - field: 'project', + key: 'ip', type: 'input', - defaultValue: 'Project 1', + validators: { + ipAddress: { + expression: function(viewValue, modelValue) { + var value = modelValue || viewValue; + return /(\d{1,3}\.){3}\d{1,3}/.test(value); + }, + message: '$viewValue + " is not a valid IP Address"' + } + }, templateOptions: { - placeholder: 'Enter a project name...' + label: 'IP Address', + required: true, + type: 'text', + placeholder: '127.0.0.1', + }, + validation: { + messages: { + required: function($viewValue: any, $modelValue: any, scope: IScope) { + return scope.to.label + ' is required' + } + } } }, { - template: () => 'hello' - }, - { + key: 'mac', type: 'input', - key: 'zip', templateOptions: { - type: 'number', - label: 'Zip', - max: 99999, - min: 0, - pattern: '\\d{5}' + label: 'MAC Address', + required: true, + placeholder: '49-8A-BD-4E-00-1D', + pattern: '([0-9A-F]{2}[:-]){5}([0-9A-F]{2})' } }, { type: 'checkbox', - key: 'happyUser', + key: 'checked', templateOptions: { - label: 'Are you happy?' + label: 'Check this' + } + }, + { + key: 'checked2', + type: 'checkbox', + wrapper: null, + templateOptions: { + label: 'no wrapper here...' } } ] diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 807171d07..b34cb1406 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -12,11 +12,46 @@ declare module 'AngularFormly' { declare module AngularFormly { + interface IFieldGroup { + data?: Object; + className?: string; + elementAttributes?: { [key: string]: string }; + fieldGroup: IFieldConfigurationObject[]; + form?: Object; + hide?: boolean; + hideExpression?: string | IExpresssionFunction; + key?: string | number; + model?: string | Object; + options?: IFormOptionsAPI + } + + + interface IFormOptionsAPI { + data?: Object; + fieldTransform?: Function; + formState?: Object; + removeChromeAutoComplete?: boolean; + resetModel?: Function; + templateManipulators?: ITemplateManipulators; + updateInitialValue?: Function; + wrapper?: string | string[]; + } + + /** * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue: any, $modelValue: any, scope: ng.IScope): any; + ($viewValue: any, $modelValue: any, scope: Object): any; + } + + + interface IModelOptions { + updateOn?: string; + debounce?: number; + allowInvalid?: boolean; + getterSetter?: string; + timezone?: string; } @@ -26,19 +61,24 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/ngmodelattrs */ - interface INGModelAttrs { - [key: string]: { - attribute?: string; - expresssion?: string; - value?: string; - } - } + // interface INGModelAttrs { + // [key: string]: { + // attribute?: string; + // expresssion?: string; + // value?: string; + // } + // } interface ITemplateManipulator { (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } + interface ITemplateManipulators { + preWrapper?: ITemplateManipulator[]; + postWrapper?: ITemplateManipulator[]; + } + /** * see http://docs.angular-formly.com/docs/ngmodelattrstemplatemanipulator @@ -46,11 +86,11 @@ declare module AngularFormly { interface ITemplateOptions { // both attribute or regular attribute - disabled?: boolean | string; - maxlength?: number | string; - minlength?: number | string; + disabled?: boolean; + maxlength?: number; + minlength?: number; pattern?: string; - required?: boolean | string; + required?: boolean; //attribute only max?: number; @@ -68,6 +108,7 @@ declare module AngularFormly { onKeypress?: string; onKeyup?: string; + label?: string; [key: string]: any; } @@ -77,7 +118,8 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object */ interface IValidator { - expression?: string | { (viewValue: any, modelValue: any): boolean }; + expression: string | IExpresssionFunction; + message?: string | IExpresssionFunction; } @@ -91,8 +133,8 @@ declare module AngularFormly { */ interface IWatcher { deep?: boolean; //Defaults to false - expression?: string | { (field: string, scope: ng.IScope): boolean }; - listener: (field: string, newValue: any, oldValue: any, scope: ng.IScope, stopWatching: Function) => void; + expression?: string | { (field: string, scope: Object): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: Object, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -100,45 +142,22 @@ declare module AngularFormly { // see http://docs.angular-formly.com/docs/field-configuration-object interface IFieldConfigurationObject { - /** - * The type of field to be rendered. This is the recommended method - * for defining fields. Types must be pre-defined using formlyConfig. + * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the + * field, and anything else you have in your injector. * - * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f */ - type?: string; + controller?: string | Function; /** - * Can be set instead of type or templateUrl to use a custom html - * template form field. Recommended to be used with one-liners mostly - * (like a directive), or if you're using webpack with the ability to require templates :-) + * This is reserved for the developer. You have our guarantee to be able to use this and not worry about + * future versions of formly overriding your usage and preventing you from upgrading :-) * - * If a function is passed, it is invoked with the field configuration object and can return - * either a string for the template or a promise that resolves to a string. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function + * see http://docs.angular-formly.com/docs/field-configuration-object#data-object */ - template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function - */ - templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; - - - /** - * Can be set instead of type or template to use a custom html template form field. Works - * just like a directive templateUrl and uses the $templateCache - * - * see http://docs.angular-formly.com/docs/field-configuration-object#key-string - */ - key?: string; + data?: Object; /** @@ -150,6 +169,30 @@ declare module AngularFormly { defaultValue?: any; + /** + * You can specify your own class that will be applied to the formly-field directive (or ng-form of + * a fieldGroup). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string + */ + className?: string; + + + elementAttributes?: string; + + + /** + * An object where the key is a property to be set on the main field config and the value is an + * expression used to assign that property. The value is a formly expressions. The returned value is + * wrapped in $q.when so you can return a promise from your function :-) + * + * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + */ + expressionProperties?: { + [key: string]: string | IExpresssionFunction | IValidator; + } + + /** * Uses ng-if. Whether to hide the field. Defaults to false. If you wish this to be conditional, use * hideExpression. See below. @@ -169,6 +212,42 @@ declare module AngularFormly { hideExpression?: string | IExpresssionFunction; + /** + * This allows you to specify the id of your field (which will be used for its name as well unless + * a name is provided). Note, you can also override the id generation code using the formlyConfig + * extra called getFieldId. + * + * AVOID THIS + * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's + * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need + * to concern yourself with making sure that this is unique. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#id-string + */ + id?: string; + + + initialValue?: any; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#key-string + */ + key?: string | number; + + + /** + * This allows you to specify a link function. It is invoked after your template has finished compiling. + * You are passed the normal arguments for a normal link function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function + */ + link?: ng.IDirectiveLinkFn; + + /** * By default, the model passed to the formly-field directive is the same as the model passed to the * formly-form. However, if the field has a model specified, then it is used for that field (and that @@ -184,39 +263,14 @@ declare module AngularFormly { /** - * An object where the key is a property to be set on the main field config and the value is an - * expression used to assign that property. The value is a formly expressions. The returned value is - * wrapped in $q.when so you can return a promise from your function :-) + * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see + * below) will add this attribute to your ng-model element automatically if this property exists. Note, + * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model + * to options.value which is a getterSetter that formly adds to field options. * - * see http://docs.angular-formly.com/docs/field-configuration-object#expressionproperties-object + * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions */ - expressionProperties?: { - [key: string]: string | IExpresssionFunction; - } - - - /** - * You can specify your own class that will be applied to the formly-field directive (or ng-form of - * a fieldGroup). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#classname-string - */ - className?: string; - - - /** - * This allows you to specify the id of your field (which will be used for its name as well unless - * a name is provided). Note, you can also override the id generation code using the formlyConfig - * extra called getFieldId. - * - * AVOID THIS - * If you don't have to do this, don't. Specifying IDs makes it harder to re-use things and it's - * just extra work. Part of the beauty that angular-formly provides is the fact that you don't need - * to concern yourself with making sure that this is unique. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#id-string - */ - id?: string; + modelOptions?: IModelOptions; /** @@ -232,48 +286,6 @@ declare module AngularFormly { name?: string; - /** - * This is reserved for the developer. You have our guarantee to be able to use this and not worry about - * future versions of formly overriding your usage and preventing you from upgrading :-) - * - * see http://docs.angular-formly.com/docs/field-configuration-object#data-object - */ - data?: any; - - - /** - * This is reserved for the templates. Any template-specific options go in here. Look at your specific - * template implementation to know the options required for this. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object - */ - templateOptions?: ITemplateOptions; - - - /** - * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a - * type configuration if you want it to apply to all fields of a certain type). - * - * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions - */ - templateManipulator?: { - preWrapper: ITemplateManipulator[]; - postWrapper: ITemplateManipulator[]; - } - - - /** - * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If - * given an array, the formly field template will be wrapped by the first wrapper, then the second, then - * the third, etc. You can also specify these as part of a type (which is the recommended approach). - * Specifying this property will override the wrappers for the type for this field. - * - * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings - */ - wrapper?: string | string[]; - - - //TODO:Scott Figure out what this really does. /** * This is used by ngModelAttrsTemplateManipulator to automatically add attributes to the ng-model element * of field templates. You will likely not use this often. This object is a little complex, but extremely @@ -281,47 +293,12 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#ngmodelattrs-object */ - ngModelAttrs?: any; - - - /** - * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the - * field, and anything else you have in your injector. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#controller-controller-name-as-string--controller-f - */ - controller?: string | { Function: void }; - - - /** - * This allows you to specify a link function. It is invoked after your template has finished compiling. - * You are passed the normal arguments for a normal link function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#link-link-function - */ - link?: ng.IDirectiveLinkFn; - - - /** - * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority - * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and - * hence will override any duplicates of those properties as well. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings - */ - optionsTypes?: string | string[]; - - - //TODO:Scott Still need to define - /** - * Allows you to take advantage of ng-model-options directive. Formly's built-in templateManipulator (see - * below) will add this attribute to your ng-model element automatically if this property exists. Note, - * if you use the getter/setter option, formly's templateManipulator will change the value of ng-model - * to options.value which is a getterSetter that formly adds to field options. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#modeloptions - */ - modelOptions?: any; + ngModelAttrs?: { + attribute?: any; + bound?: any; + expression?: any; + value?: any; + }; /** @@ -335,29 +312,62 @@ declare module AngularFormly { /** - * An object which has at least two properties called expression and listener. The watch.expression is added - * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type - * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want - * it to be a deep watch via the watcher.deep property (defaults to false). + * Allows you to specify extra types to get options from. Duplicate options are overridden in later priority + * (index 1 will override index 0 properties). Also, these are applied after the type's defaultOptions and + * hence will override any duplicates of those properties as well. * - * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + * see http://docs.angular-formly.com/docs/field-configuration-object#optionstypes-string--array-of-strings */ - watcher?: IWatcher | IWatcher[]; + optionsTypes?: string | string[]; - //TODO:Scott Look at defining validators as an Object to see if additional interface needs to be created /** - * An object where the keys are the name of the validator and the values are Formly Expressions; + * Can be set instead of type or templateUrl to use a custom html + * template form field. Recommended to be used with one-liners mostly + * (like a directive), or if you're using webpack with the ability to require templates :-) * - * Async Validation - * All function validators can return true/false/Promise. A validator passes if it returns true or a promise - * that is resolved. A validator fails if it returns false or a promise that is rejected. + * If a function is passed, it is invoked with the field configuration object and can return + * either a string for the template or a promise that resolves to a string. * - * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + * see http://docs.angular-formly.com/docs/field-configuration-object#template-string--function */ - validators?: { - [key: string]: IValidator | string; - } + template?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * Allows you to specify custom template manipulators for this specific field. (use defaultOptions in a + * type configuration if you want it to apply to all fields of a certain type). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templatemanipulator-object-of-arrays-of-functions + */ + templateManipulators?: ITemplateManipulators; + + + /** + * This is reserved for the templates. Any template-specific options go in here. Look at your specific + * template implementation to know the options required for this. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateoptions-object + */ + templateOptions?: ITemplateOptions; + + + /** + * Can be set instead of type or template to use a custom html template form field. Works + * just like a directive templateUrl and uses the $templateCache + * + * see http://docs.angular-formly.com/docs/field-configuration-object#templateurl-string--function + */ + templateUrl?: string | { (fieldConfiguration: IFieldConfigurationObject): string | ng.IPromise }; + + + /** + * The type of field to be rendered. This is the recommended method + * for defining fields. Types must be pre-defined using formlyConfig. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#type-string + */ + type?: string; /** @@ -365,13 +375,21 @@ declare module AngularFormly { */ validation?: { + /** + * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because + * you generally only want to show error messages when the user has interacted with a specific field, this value + * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference + * for pre-angular 1.3 because it doesn't have touched support). + */ + errorExistsAndShouldBeVisible?: boolean; + /** * A map of Formly Expressions mapped to message names. This is really useful when you're using ng-messages * like in this example. */ messages?: { - [key: string]: IExpresssionFunction; + [key: string]: IExpresssionFunction | string; } @@ -382,17 +400,23 @@ declare module AngularFormly { */ show?: boolean; - - /** - * This is set by angular-formly. This is a boolean indicating whether an error message should be shown. Because - * you generally only want to show error messages when the user has interacted with a specific field, this value - * is set to true based on this rule: field invalid && (field touched || validation.show) (with slight difference - * for pre-angular 1.3 because it doesn't have touched support). - */ - errorExistsAndShouldBeVisible?: boolean; - } + + /** + * An object where the keys are the name of the validator and the values are Formly Expressions; + * + * Async Validation + * All function validators can return true/false/Promise. A validator passes if it returns true or a promise + * that is resolved. A validator fails if it returns false or a promise that is rejected. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#validators-object + */ + validators?: { + [key: string]: string | IExpresssionFunction | IValidator; + } + + /** * This is a getter/setter function for the value that your field is representing. Useful when using getterSetter: true * in the modelOptions (in fact, if you don't disable the ngModelAttrsTemplateManipulator that comes built-in with formly, @@ -404,6 +428,28 @@ declare module AngularFormly { value?(val: any): void; //Setter + /** + * An object which has at least two properties called expression and listener. The watch.expression is added + * to the formly-form directive's scope (to allow it to run even when hide is true). You can specify a type + * ($watchCollection or $watchGroup) via the watcher.type property (defaults to $watch) and whether you want + * it to be a deep watch via the watcher.deep property (defaults to false). + * + * see http://docs.angular-formly.com/docs/field-configuration-object#watcher-objectarray-of-watches + */ + watcher?: IWatcher | IWatcher[]; + + + /** + * This makes reference to setWrapper in formlyConfig. It is expected to be the name of the wrapper. If + * given an array, the formly field template will be wrapped by the first wrapper, then the second, then + * the third, etc. You can also specify these as part of a type (which is the recommended approach). + * Specifying this property will override the wrappers for the type for this field. + * + * http://docs.angular-formly.com/docs/field-configuration-object#wrapper-string--array-of-strings + */ + wrapper?: string | string[]; + + //ALL PROPERTIES BELOW ARE ADDED (So you should not be setting them yourself.) @@ -412,7 +458,7 @@ declare module AngularFormly { * * see http://docs.angular-formly.com/docs/field-configuration-object#formcontrol-ngmodelcontroller */ - formControl?: ng.IFormController; + formControl?: ng.IFormController | ng.IFormController[]; /** @@ -424,15 +470,6 @@ declare module AngularFormly { resetModel?: () => void; - /** - * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. - * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. - * - * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function - */ - updateInitialValue?: () => void; - - /** * It is not likely that you'll ever want to invoke this function. It simply runs the expressionProperties expressions. * It is used internally and you shouldn't have to use it, but you can if you want to, and any breaking changes to the @@ -443,12 +480,14 @@ declare module AngularFormly { runExpressions?: () => void; - - ////////////////// BOOTSTRAP SPECIFIC /////////////////////// - fieldGroup?: IFieldConfigurationObject[]; + /** + * Will reset the field's initialValue to the current state of the model. Useful if you load the model asynchronously. + * Invoke this when the model gets set. This is used by the formly-form's options.updateInitialValue function. + * + * see http://docs.angular-formly.com/docs/field-configuration-object#updateinitialvalue-function + */ + updateInitialValue?: () => void; } - - } \ No newline at end of file From b22932b2efcb0f433b587df4bc6dccd30331c99a Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 09:29:51 -0700 Subject: [PATCH 060/881] Removed unused interface. --- angular-formly/angular-formly.d.ts | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index b34cb1406..48f5c7bad 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -55,25 +55,11 @@ declare module AngularFormly { } - /** - * This is part of the built-in formlyConfig templateManipulator called ngModelAttrsTemplateManipulator. - * This allows you to keep your templates very small and add custom behavior on at the type or field level. - * - * see http://docs.angular-formly.com/docs/ngmodelattrs - */ - // interface INGModelAttrs { - // [key: string]: { - // attribute?: string; - // expresssion?: string; - // value?: string; - // } - // } - - interface ITemplateManipulator { (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; } + interface ITemplateManipulators { preWrapper?: ITemplateManipulator[]; postWrapper?: ITemplateManipulator[]; From 2f073bda43831dc97bbb709028940f14e938f99b Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:08:15 -0700 Subject: [PATCH 061/881] Added in optional bootstrap template option. Will need to pull out and place in bootstrap-templates definition if it expands much further. --- angular-formly/angular-formly.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 48f5c7bad..b2520bc2c 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -94,7 +94,9 @@ declare module AngularFormly { onKeypress?: string; onKeyup?: string; + //Bootstrap types label?: string; + description?: string; [key: string]: any; } From 5f6361e360c2c5176213736eefceab4b77d93c1d Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:45:53 -0700 Subject: [PATCH 062/881] Add asyncValidators. Added in 6.18.0. --- angular-formly/angular-formly.d.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index b2520bc2c..001f53767 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -1,4 +1,4 @@ -// Type definitions for angular-formly 6.17.0 +// Type definitions for angular-formly 6.18.0 // Project: https://github.com/formly-js/angular-formly // Definitions by: Scott Hatcher // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -130,6 +130,17 @@ declare module AngularFormly { // see http://docs.angular-formly.com/docs/field-configuration-object interface IFieldConfigurationObject { + + /** + * Added in 6.18.0 + * + * Demo + * see http://angular-formly.com/#/example/other/unique-value-async-validation + */ + asyncValidators: { + [key: string]: string | IExpresssionFunction | IValidator; + } + /** * This is a great way to add custom behavior to a specific field. It is injectable with the $scope of the * field, and anything else you have in your injector. From 0f38c90093459581a33ab8c84abc903eff1aeaf1 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Tue, 14 Jul 2015 10:48:48 -0700 Subject: [PATCH 063/881] asyncValidators isn't required. --- angular-formly/angular-formly.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 001f53767..8ce552c52 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -137,7 +137,7 @@ declare module AngularFormly { * Demo * see http://angular-formly.com/#/example/other/unique-value-async-validation */ - asyncValidators: { + asyncValidators?: { [key: string]: string | IExpresssionFunction | IValidator; } From 9916fab22d48b85591d811a0d8490dc47269a7bf Mon Sep 17 00:00:00 2001 From: lnlwd Date: Tue, 14 Jul 2015 22:53:55 -0300 Subject: [PATCH 064/881] Update collection to support new crud operations --- mongodb/mongodb.d.ts | 61 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index a1424cb7e..e4ed2e0c1 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -296,21 +296,54 @@ declare module "mongodb" { // Documentation : http://mongodb.github.io/node-mongodb-native/api-generated/collection.html export interface Collection { new (db: Db, collectionName: string, pkFactory?: Object, options?: CollectionCreateOptions): Collection; // is this right? - + /** + * @deprecated use insertOne or insertMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insert + */ insert(query: any, callback: (err: Error, result: any) => void): void; insert(query: any, options: { safe?: any; continueOnError?: boolean; keepGoing?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertOne + inserOne(doc:any, callback: (err: Error, result: any) => void) :void; + insertOne(doc: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMany + insertMany(docs, callback: (err: Error, result: any) => void): void; + insertMany(docs, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + /** + * @deprecated use deleteOne or deleteMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove + */ remove(selector: Object, callback?: (err: Error, result: any) => void): void; remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteOne + deleteOne(filter, callback: (err: Error, result: any) => void): void; + deleteOne(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteMany + deleteMany(filter, callback: (err: Error, result: any) => void): void; + deleteMany(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + rename(newName: String, callback?: (err: Error, result: any) => void): void; save(doc: any, callback : (err: Error, result: any) => void): void; - save(doc: any, options: { safe: any; }, callback : (err: Error, result: any) => void): void; - + save(doc: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback : (err: Error, result: any) => void): void; + /** + * @deprecated use updateOne or updateMany + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#update + */ update(selector: Object, document: any, callback?: (err: Error, result: any) => void): void; update(selector: Object, document: any, options: { safe?: boolean; upsert?: any; multi?: boolean; serializeFunctions?: boolean; }, callback: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateOne + updateOne(filter: Object, update: any, callback: (err: Error, result: any) => void): void; + updateOne(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#updateMany + updateMany(filter: Object, update: any, callback: (err: Error, result: any) => void): void; + updateMany(filter: Object, update: any, options: { upsert?: boolean; w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + distinct(key: string, query: Object, callback: (err: Error, result: any) => void): void; distinct(key: string, query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; @@ -319,13 +352,31 @@ declare module "mongodb" { count(query: Object, options: { readPreference: string; }, callback: (err: Error, result: any) => void): void; drop(callback?: (err: Error, result: any) => void): void; - + /** + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify + */ findAndModify(query: Object, sort: any[], doc: Object, callback: (err: Error, result: any) => void): void; findAndModify(query: Object, sort: any[], doc: Object, options: { safe?: any; remove?: boolean; upsert?: boolean; new?: boolean; }, callback: (err: Error, result: any) => void): void; - + /** + * @deprecated use findOneAndDelete + * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndRemove + */ findAndRemove(query : Object, sort? : any[], callback?: (err: Error, result: any) => void): void; findAndRemove(query : Object, sort? : any[], options?: { safe: any; }, callback?: (err: Error, result: any) => void): void; + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndDelete + findOneAndDelete(filter: any, callback: (err: Error, result: any) => void): void; + findOneAndDelete(filter: any, options: { projection?: any; sort?: any; maxTimeMS?: number; }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndReplace + findOneAndReplace(filter: any, replacement: any, callback: (err: Error, result: any) => void): void; + findOneAndReplace(filter: any, replacement: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback: (err: Error, result: any) => void): void; + + // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findOneAndUpdate + findOneAndUpdate(filter: any, update: any, callback: (err: Error, result: any) => void): void; + findOneAndUpdate(filter: any, update: any, options: { projection?: any; sort?: any; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean }, callback: (err: Error, result: any) => void): void; + find(callback?: (err: Error, result: Cursor) => void): Cursor; find(selector: Object, callback?: (err: Error, result: Cursor) => void): Cursor; find(selector: Object, fields: any, callback?: (err: Error, result: Cursor) => void): Cursor; From d54bab2cbcdd321ac0eca03aae1e81103a57890f Mon Sep 17 00:00:00 2001 From: Michael Jerred Date: Wed, 15 Jul 2015 12:36:17 +0100 Subject: [PATCH 065/881] Correcting .chunk and .size --- lodash/lodash-tests.ts | 10 ++++++---- lodash/lodash.d.ts | 16 +++++++++++++++- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 3a1c51f18..6a0b68075 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -149,13 +149,13 @@ result = <_.Dictionary>_({ a: 1, b: 2}).mapValues(function(num: number) // * Arrays * // *************/ result = _.chunk([1, '2', '3', false]); -result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(); result = _.chunk([1, '2', '3', false], 2); -result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(2); +result = <_.LoDashArrayWrapper>_([1, '2', '3', false]).chunk(2); result = _.chunk([1, 2, 3, 4]); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(); result = _.chunk([1, 2, 3, 4], 2); -result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(2); +result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).chunk(2); result = _.compact([0, 1, false, 2, '', 3]); result = <_.LoDashArrayWrapper>_([0, 1, false, 2, '', 3]).compact(); @@ -622,7 +622,9 @@ result = <_.LoDashArrayWrapper>_([1, 2, 3]).shuffle(); result = <_.LoDashArrayWrapper<_.Dictionary>>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).shuffle(); result = _.size([1, 2]); +result = _([1, 2]).size(); result = _.size({ 'one': 1, 'two': 2, 'three': 3 }); +result = _({ 'one': 1, 'two': 2, 'three': 3 }).size(); result = _.size('curly'); result = _.some([null, 0, 'yes', false], Boolean); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index fcf468577..6a839596d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -279,7 +279,7 @@ declare module _ { /** * @see _.chunk **/ - chunk(size?: number): LoDashArrayWrapper; + chunk(size?: number): LoDashArrayWrapper; } //_.compact @@ -4526,6 +4526,20 @@ declare module _ { size(aString: string): number; } + interface LoDashArrayWrapper { + /** + * @see _.size + **/ + size(): number; + } + + interface LoDashObjectWrapper { + /** + * @see _.size + **/ + size(): number; + } + //_.some interface LoDashStatic { /** From db52e392faaadc8de5e6636d23c3d9c615c61632 Mon Sep 17 00:00:00 2001 From: lnlwd Date: Wed, 15 Jul 2015 11:04:10 -0300 Subject: [PATCH 066/881] Correct param types, for parse build --- mongodb/mongodb.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/mongodb/mongodb.d.ts b/mongodb/mongodb.d.ts index e4ed2e0c1..ed3fc38c4 100644 --- a/mongodb/mongodb.d.ts +++ b/mongodb/mongodb.d.ts @@ -308,8 +308,8 @@ declare module "mongodb" { insertOne(doc: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#insertMany - insertMany(docs, callback: (err: Error, result: any) => void): void; - insertMany(docs, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; + insertMany(docs: any, callback: (err: Error, result: any) => void): void; + insertMany(docs: any, options: { w?: any; wtimeout?: number; j?: boolean; serializeFunctions?: boolean; forceServerObjectId?: boolean }, callback: (err: Error, result: any) => void): void; /** * @deprecated use deleteOne or deleteMany * Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#remove @@ -318,12 +318,12 @@ declare module "mongodb" { remove(selector: Object, options: { safe?: any; single?: boolean; }, callback?: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteOne - deleteOne(filter, callback: (err: Error, result: any) => void): void; - deleteOne(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + deleteOne(filter: any, callback: (err: Error, result: any) => void): void; + deleteOne(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; // Documentation : http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#deleteMany - deleteMany(filter, callback: (err: Error, result: any) => void): void; - deleteMany(filter, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; + deleteMany(filter: any, callback: (err: Error, result: any) => void): void; + deleteMany(filter: any, options: { w?: any; wtimeout?: number; j?: boolean;}, callback: (err: Error, result: any) => void): void; rename(newName: String, callback?: (err: Error, result: any) => void): void; From ea103215ea8fa2493325a1b8d2327f47e6a9d6de Mon Sep 17 00:00:00 2001 From: Frederik Wordenskjold Date: Wed, 15 Jul 2015 16:20:54 +0200 Subject: [PATCH 067/881] Make it possible to initialize a Backbone.Collection from raw objects The following syntax is supported in Backbone, but is currently not compileable in Typescript: var data = [ { id: 1, bar: 'foo' }, { id: 2, bar: 'baz' } ]; var myCollection = new Backbone.Collection(data); As of now, the constructor expects an array of models. I've added the Object[] parameter type, in addition to the TModel[] type to support this syntax. --- backbone/backbone.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 9d54361d5..08cb396b2 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -173,8 +173,8 @@ declare module Backbone { models: TModel[]; length: number; - constructor(models?: TModel[], options?: any); - initialize(models?: TModel[], options?: any): void; + constructor(models?: TModel[] | Object[], options?: any); + initialize(models?: TModel[] | Object[], options?: any): void; fetch(options?: CollectionFetchOptions): JQueryXHR; From 7706ea89164d07e8aca9d6de46111d1f488b17c7 Mon Sep 17 00:00:00 2001 From: Scott Date: Thu, 16 Jul 2015 08:56:54 -0700 Subject: [PATCH 068/881] Rename angular-formly-test.ts to angular-formly-tests.ts Renamed according to comply with repo standards. --- .../{angular-formly-test.ts => angular-formly-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename angular-formly/{angular-formly-test.ts => angular-formly-tests.ts} (100%) diff --git a/angular-formly/angular-formly-test.ts b/angular-formly/angular-formly-tests.ts similarity index 100% rename from angular-formly/angular-formly-test.ts rename to angular-formly/angular-formly-tests.ts From ac1ca868dd29ec8a4e76926692cfbc180fcba4a3 Mon Sep 17 00:00:00 2001 From: Scott Hatcher Date: Thu, 16 Jul 2015 11:52:50 -0700 Subject: [PATCH 069/881] Expanded tests, defined formlyConfig, and defined formlyValidationMessages. --- angular-formly/angular-formly-tests.ts | 30 ++++++++- angular-formly/angular-formly.d.ts | 90 ++++++++++++++++++++++++-- 2 files changed, 114 insertions(+), 6 deletions(-) diff --git a/angular-formly/angular-formly-tests.ts b/angular-formly/angular-formly-tests.ts index 603840208..ef6a38463 100644 --- a/angular-formly/angular-formly-tests.ts +++ b/angular-formly/angular-formly-tests.ts @@ -6,11 +6,37 @@ interface IScope extends ng.IScope { to: { label: string; } } +class FormConfig { + constructor(formlyConfig: AngularFormly.IFormlyConfig, formlyValidationMessages: AngularFormly.IValidationMessages) { + formlyConfig.setWrapper({ + name: 'validation', + types: ['input', 'customInput'], + templateUrl: 'my-messages.html' + }); + + formlyValidationMessages.addStringMessage('required', 'This field is required'); + + formlyConfig.setType({ + name: 'customInput', + extends: 'input' + }); + } +} + class AppController { fields: AngularFormly.IFieldConfigurationObject[]; - constructor($scope: ng.IScope) { + constructor() { var vm = this; vm.fields = [ + { + key: 'firstName', + type: 'customInput', + templateOptions: { + required: true, + label: 'First Name', + foo: 'hi' + } + }, { key: 'email', type: 'input', @@ -43,7 +69,7 @@ class AppController { }, validation: { messages: { - required: function($viewValue: any, $modelValue: any, scope: IScope) { + required: function($viewValue: any, $modelValue: any, scope: AngularFormly.ITemplateScope) { return scope.to.label + ' is required' } } diff --git a/angular-formly/angular-formly.d.ts b/angular-formly/angular-formly.d.ts index 8ce552c52..8f76b3ccf 100644 --- a/angular-formly/angular-formly.d.ts +++ b/angular-formly/angular-formly.d.ts @@ -42,7 +42,7 @@ declare module AngularFormly { * see http://docs.angular-formly.com/docs/formly-expressions#expressionproperties-validators--messages */ interface IExpresssionFunction { - ($viewValue: any, $modelValue: any, scope: Object): any; + ($viewValue: any, $modelValue: any, scope: ITemplateScope): any; } @@ -56,7 +56,7 @@ declare module AngularFormly { interface ITemplateManipulator { - (template: string | HTMLElement, options: Object, scope: ng.IScope): string | HTMLElement; + (template: string | HTMLElement, options: Object, scope: ITemplateScope): string | HTMLElement; } @@ -121,8 +121,8 @@ declare module AngularFormly { */ interface IWatcher { deep?: boolean; //Defaults to false - expression?: string | { (field: string, scope: Object): boolean }; - listener: (field: string, newValue: any, oldValue: any, scope: Object, stopWatching: Function) => void; + expression?: string | { (field: string, scope: ITemplateScope): boolean }; + listener: (field: string, newValue: any, oldValue: any, scope: ITemplateScope, stopWatching: Function) => void; type?: string; //Defaults to $watch but can be set to $watchCollection or $watchGroup } @@ -489,4 +489,86 @@ declare module AngularFormly { } + /** + * + * + * see http://docs.angular-formly.com/docs/custom-templates#section-formlyconfig-settype-options + */ + interface ITypeOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + defaultOptions?: IFieldConfigurationObject | Function; + controller?: Function | string | any[]; + data?: Object; + extends?: string; + link?: ng.IDirectiveLinkFn; + overwriteOk?: boolean; + name: string; + template?: Function | string; + templateUrl?: Function | string; + validateOptions?: Function; + wrapper?: string | string[]; + } + + interface IWrapperOptions { + apiCheck?: { [key: string]: Function }; + apiCheckFunction?: string; //'throw' or 'warn + apiCheckInstance?: any; + apiCheckOptions?: Object; + overwriteOk?: boolean; + name?: string; + template?: string; + templateUrl?: string; + types?: string[]; + validateOptions?: Function; + } + + interface IFormlyConfig { + setType(typeOptions: ITypeOptions): void; + setWrapper(wrapperOptions: IWrapperOptions): void; + + } + + interface ITemplateScopeOptions { + formControl: ng.IFormController | ng.IFormController[]; + templateOptions: ITemplateOptions; + validation: Object; + } + + /** + * see http://docs.angular-formly.com/docs/custom-templates#templates-scope + */ + interface ITemplateScope { + options: ITemplateScopeOptions; + //Shortcut to options.formControl + fc: ng.IFormController | ng.IFormController[]; + //all the fields for the form + fields: IFieldConfigurationObject[]; + //the form controller the field is in + form: any; + //The object passed as options.formState to the formly-form directive. Use this to share state between fields. + formState: Object; + //The id of the field. You shouldn't have to use this. + id: string; + //The index of the field the form is on (in ng-repeat) + index: number; + //the model of the form (or the model specified by the field if it was specified). + model: Object | string; + //Shortcut to options.validation.errorExistsAndShouldBeVisible + showError: boolean; + //Shortcut to options.templateOptions + to: ITemplateOptions; + } + + /** + * see http://docs.angular-formly.com/docs/formlyvalidationmessages#addtemplateoptionvaluemessage + */ + interface IValidationMessages { + addTemplateOptionValueMessage(name: string, prop: string, prefix: string, suffix: string, alternate: string): void; + addStringMessage(name: string, string: string): void; + messages: { [key: string]: ($viewValue: any, $modelValue: any, scope: ITemplateScope) => string }; + } + } \ No newline at end of file From dd0d09a18b09e6089af4b18fa770efa5fc142ed6 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Fri, 17 Jul 2015 21:59:37 +0200 Subject: [PATCH 070/881] Fixed problem with broadcast declaration and added right reference path to the tests file --- socket.io/socket.io-tests.ts | 2 +- socket.io/socket.io.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/socket.io/socket.io-tests.ts b/socket.io/socket.io-tests.ts index 93899d0d9..0f3b26963 100644 --- a/socket.io/socket.io-tests.ts +++ b/socket.io/socket.io-tests.ts @@ -1,4 +1,4 @@ -/// +/// import socketIO = require('socket.io'); diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index 045e0007a..696bd4d9b 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -759,7 +759,7 @@ declare module SocketIO { * - except: A list of Socket IDs to exclude * - flags: Any flags that we want to send along ('json', 'volatile', 'broadcast') */ - broadcast( packet: any, opts: { rooms?: string[], except?: string[], flags?: {[flag: string]: boolean} } ):void; + broadcast( packet: any, opts: { rooms?: string[]; except?: string[]; flags?: {[flag: string]: boolean} } ):void; } /** From 2a04a33b8fc79f79fa358fd341f1b4669f369bf3 Mon Sep 17 00:00:00 2001 From: Raymond Suelzer Date: Fri, 17 Jul 2015 16:04:30 -0400 Subject: [PATCH 071/881] added some api extensions, fixed some types added core, pagination, selection to GridAPI. Also fixed a few types that were incorrect, missing, or should have been nullable. --- ui-grid/ui-grid.d.ts | 78 +++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 9 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index f27700e70..0d7f4e7fe 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -88,11 +88,11 @@ declare module uiGrid { } export interface IGridOptions { aggregationCalcThrottle?: number; - appScopeProvider?: ng.IScope; + appScopeProvider?: ng.IScope | Object; columnDefs?: IColumnDef; columnFooterHeight?: number; columnVirtualizationThreshold?: number; - data?: Array; + data?: Array | string; enableColumnMenus?: boolean; enableFiltering?: boolean; enableHorizontalScrollbar?: boolean; @@ -109,7 +109,7 @@ declare module uiGrid { gridFooterTemplate?: string; gridMenuCustomItems?: Array; gridMenuShowHideColumns?: boolean; - gridMenuTitleFilter: (title: string) => ng.IPromise | string; + gridMenuTitleFilter?: (title: string) => ng.IPromise | string; headerTemplate?: string; horizontalScrollThreshold?: number; infiniteScrollDown?: boolean; @@ -130,12 +130,52 @@ declare module uiGrid { useExternalSorting?: boolean; virtualizationThreshold?: number; wheelScrollThrottle?: number; - getRowIdentity(): any; - rowEquality(entityA: IGridRow, entityB: IGridRow): boolean; - rowIdentity(): any; + getRowIdentity?(): any; + rowEquality?(entityA: IGridRow, entityB: IGridRow): boolean; + rowIdentity? (): any; + totalItems?: number; } + + + export interface IGridCoreApi { + on: { + sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: IColumnDef[]) => void) => void; + columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; + } + } + + export interface IGridSelectionApi { + toggleRowSelection: (rowEntity: IGridRow, event?: Event) => void; + selectRow: (rowEntity: IGridRow, event?: Event) => void; + selectRowByVisibleIndex: (rowEntity: number, event?: Event) => void; + unSelectRow: (rowEntity: IGridRow, event?: Event) => void; + selectAllRows: (event?: Event) => void; + selectAllVisibleRows: (event?: Event) => void; + clearSelectedRows: (event?: Event) => void; + getSelectedRows: () => IGridRow[]; + getSelectedGridRows: () => IGridRow[]; + setMultiSelect: (multiSelect: boolean) => void; + setModifierKeysToMultiSelect: (multiSelect: boolean) => void; + getSelectAllState: () => boolean; + on: { + rowSelectionChanged: (scope: ng.IScope, handler: (row: IGridRow, event?: Event) => void) => void; + rowSelectionChangedBatch: (scope, handler: (row: IGridRow[], event?: Event) => void) => void; + } + } + + export interface IGridPaginationApi { + getPage: () => number; + getTotalPages: () => number; + nextPage: () => void; + previousPage: () => void; + seek: () => void; + on: { + paginationChanged: (scope, handler: (newPage: number, pageSize: number) => void) => void; + } + } + export interface IGridApiConstructor { - new(grid: IGridInstance): IGridApi; + new (grid: IGridInstance): IGridApi; } export interface IGridApi { /** @@ -186,6 +226,26 @@ declare module uiGrid { * @param callBackFn function to execute */ suppressEvents(listenerFuncs: Function | Array, callBackFn: Function): void; + + /** + * Core Api + */ + core: IGridCoreApi; + + /** + * Selection api + */ + + selection: IGridSelectionApi; + + + /** + * Pagination api + */ + pagination: IGridPaginationApi; + + + } export interface IGridRowConstructor { /** @@ -410,7 +470,7 @@ declare module uiGrid { * in this case your function needs to accept the full set of visible rows, * and return a value that should be shown */ - aggregationType: number | Function; + aggregationType?: number | Function; /** * cellClass can be a string specifying the class to append to a cell * or it can be a function(row,rowRenderIndex, col, colRenderIndex) @@ -604,7 +664,7 @@ declare module uiGrid { leaveOpen?: boolean; } export interface ISortInfo { - direction?: number; + direction?: string; ignoreSort?: boolean; priority?: number; } From 370f04bfcd1470b5db0fef0a9d81a8376bd60623 Mon Sep 17 00:00:00 2001 From: Raymond Suelzer Date: Fri, 17 Jul 2015 16:09:33 -0400 Subject: [PATCH 072/881] direction should be a string sort direction should be a string --- ui-grid/ui-grid-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 6bdae2f64..1d0dd3462 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -72,7 +72,7 @@ columnDef.menuItems = [{ columnDef.minWidth = 100; columnDef.name = 'MyColumn'; columnDef.sort = { - direction: 0, + direction: 'ASC', ignoreSort: false, priority: 1 }; From d187f678d1c014d1e04b1489bd50f2c2726fcf39 Mon Sep 17 00:00:00 2001 From: Raymond Suelzer Date: Fri, 17 Jul 2015 16:13:57 -0400 Subject: [PATCH 073/881] fixing missing ng.scope on api callback --- ui-grid/ui-grid.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 0d7f4e7fe..7318b1d79 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -159,7 +159,7 @@ declare module uiGrid { getSelectAllState: () => boolean; on: { rowSelectionChanged: (scope: ng.IScope, handler: (row: IGridRow, event?: Event) => void) => void; - rowSelectionChangedBatch: (scope, handler: (row: IGridRow[], event?: Event) => void) => void; + rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: IGridRow[], event?: Event) => void) => void; } } @@ -170,7 +170,7 @@ declare module uiGrid { previousPage: () => void; seek: () => void; on: { - paginationChanged: (scope, handler: (newPage: number, pageSize: number) => void) => void; + paginationChanged: (scope: ng.IScope, handler: (newPage: number, pageSize: number) => void) => void; } } From 0985544e4f38a20571b9047d568a6d1e5fa370a8 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Sat, 18 Jul 2015 14:15:18 +0200 Subject: [PATCH 074/881] Fixed the legacy code declaring under the same name --- socket.io/legacy/socket.io-1.2.0-tests.ts | 2 +- socket.io/legacy/socket.io-1.2.0.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/socket.io/legacy/socket.io-1.2.0-tests.ts b/socket.io/legacy/socket.io-1.2.0-tests.ts index 93899d0d9..c2664f9cd 100644 --- a/socket.io/legacy/socket.io-1.2.0-tests.ts +++ b/socket.io/legacy/socket.io-1.2.0-tests.ts @@ -1,6 +1,6 @@ /// -import socketIO = require('socket.io'); +import socketIO = require('socket.io-1.2.0'); function testUsingWithNodeHTTPServer() { var app = require('http').createServer(handler); diff --git a/socket.io/legacy/socket.io-1.2.0.d.ts b/socket.io/legacy/socket.io-1.2.0.d.ts index 92f037319..01b5e0836 100644 --- a/socket.io/legacy/socket.io-1.2.0.d.ts +++ b/socket.io/legacy/socket.io-1.2.0.d.ts @@ -5,7 +5,7 @@ /// -declare module 'socket.io' { +declare module 'socket.io-1.2.0' { var server: SocketIOStatic; export = server; From 1e5725eeeea816a0411b9f7015bca78b4f1d1252 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 00:57:57 +0300 Subject: [PATCH 075/881] Reverted file modes --- README.md | 0 angularjs/angular.d.ts | 0 chrome/chrome.d.ts | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 README.md mode change 100644 => 100755 angularjs/angular.d.ts mode change 100644 => 100755 chrome/chrome.d.ts diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100644 new mode 100755 diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts old mode 100644 new mode 100755 From 3cc4192c1a5e00a417541f4beaae854fbb4d319d Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 01:36:19 +0300 Subject: [PATCH 076/881] Fixed tests for microsoft-ajax.d.ts --- microsoft-ajax/microsoft.ajax-tests.ts | 84 +++++++++++++------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/microsoft-ajax/microsoft.ajax-tests.ts b/microsoft-ajax/microsoft.ajax-tests.ts index 763c1e7fb..0f776da09 100644 --- a/microsoft-ajax/microsoft.ajax-tests.ts +++ b/microsoft-ajax/microsoft.ajax-tests.ts @@ -37,33 +37,33 @@ function BaseClassExtensions_Error_Tests() { // Verify the required parameters were defined. if (input === undefined) { // Throw a standard exception type. - var err = (Error).argumentNull("input", "A parameter was undefined."); + var err = Error.argumentNull("input", "A parameter was undefined."); throw err; } else if (min === undefined) { - var err = (Error).argumentNull("min", "A parameter was undefined."); + var err = Error.argumentNull("min", "A parameter was undefined."); throw err; } else if (max === undefined) { - var err = (Error).argumentNull("max", "A parameter was undefined."); + var err = Error.argumentNull("max", "A parameter was undefined."); throw err; } else if (min >= max) { - var err = (Error).invalidOperation("The min parameter must be smaller than max parameter."); + var err = Error.invalidOperation("The min parameter must be smaller than max parameter."); throw err; } else if (isNaN(input)) { var msg = "A number was not entered. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += String.format("Please enter a number between {0} and {1}.", min, max); - var err = (Error).create(msg); + var err = Error.create(msg); throw err; } else if (input < min || input > max) { msg = "The number entered was outside the acceptable range. "; - msg += (String).format("Please enter a number between {0} and {1}.", min, max); + msg += String.format("Please enter a number between {0} and {1}.", min, max); - var err = (Error).create(msg); + var err = Error.create(msg); throw err; } @@ -82,12 +82,12 @@ function BaseClassExtensions_Error_Tests() { function BaseClassExtensions_String_Tests() { - (String).format("Please enter a number between {0} and {1}.", 1, 2); - (String).endsWith("test"); - (String).localeFormat("Please enter a number between {0} and {1}", 1, 2); - (String).trim(); - (String).trimEnd(); - (String).trimStart(); + String.format("Please enter a number between {0} and {1}.", 1, 2); + "test".endsWith("test"); + String.localeFormat("Please enter a number between {0} and {1}", 1, 2); + "test".trim(); + "test".trimEnd(); + "test".trimStart(); } function BaseClassExtensions_Function_Tests() { @@ -95,22 +95,22 @@ function BaseClassExtensions_Function_Tests() { /** Sample code from http://msdn.microsoft.com/en-us/library/dd409287(v=vs.100).aspx */ var createDelegateTest = function () { var context = ""; - var method: MicrosoftAjaxBaseTypeExtensions.Function; - var a = (Function).createCallback(method, context); + var method: Function; + var a = Function.createCallback(method, context); } /** Sample code from http://msdn.microsoft.com/en-us/library/dd393582(v=vs.100).aspx */ var createDelegateTest = function () { var instance = this; - var method: MicrosoftAjaxBaseTypeExtensions.Function; - var a = (Function).createDelegate(instance, method); + var method: Function; + var a = Function.createDelegate(instance, method); } /** Sample code from http://msdn.microsoft.com/en-us/library/dd393712(v=vs.100).aspx */ var validateParametersTest = function () { var arguments = ['test1', 'test2']; var insert = function Array$insert(array: any[], index: number, item: any) { - var e = (Function).validateParameters(arguments, [ + var e = Function.validateParameters(arguments, [ { name: "array", type: Array, elementMayBeNull: true }, { name: "index", mayBeNull: true }, { name: "item", mayBeNull: true } @@ -122,20 +122,20 @@ function BaseClassExtensions_Function_Tests() { function BaseClassExtensions_Array_Tests() { - var arrayVar = Array("one", "two", "three"); + var arrayVar =["one", "two", "three"]; - arrayVar.add(["one"], {}); - arrayVar.addRange({}, ["one", "two", "three"]); - arrayVar.clear(); - arrayVar.clone(); - arrayVar.contains({}); - arrayVar.dequeue(); - arrayVar.enqueue({}); - arrayVar.insert([1, 2, 3], 1, {}); - arrayVar.isArray({}); - arrayVar.parse("1, 2, 3, 4, 5"); - arrayVar.remove([1, 2, 3], 2); - arrayVar.removeAt([1, 2, 3], 1); + Array.add(arrayVar, "four"); + Array.addRange(arrayVar, ["one", "two", "three"]); + Array.clear(arrayVar); + Array.clone(arrayVar); + Array.contains(arrayVar, "zero"); + Array.dequeue(arrayVar); + Array.enqueue(arrayVar, "zero"); + Array.insert([1, 2, 3], 1, {}); + Array.isArray({}); + Array.parse("1, 2, 3, 4, 5"); + Array.remove([1, 2, 3], 2); + Array.removeAt([1, 2, 3], 1); } @@ -144,13 +144,13 @@ function BaseClassExtensions_Date_Tests() { var date = new Date(2014, 5, 25); date.format("g"); date.localeFormat("g"); - date.parseLocale("2014/05/25"); - date.parseInvariant("2014/05/25"); + Date.parseLocale("2014/05/25"); + Date.parseInvariant("2014/05/25"); } function BaseClassExtensions_Boolean_Tests() { - (Boolean).parse("false"); + Boolean.parse("false"); } function BaseClassExtensions_Number_Tests() { @@ -159,8 +159,8 @@ function BaseClassExtensions_Number_Tests() { x.format("d"); x.localeFormat("c"); - x.parseInvariant("1"); - x.parseLocale("1"); + Number.parseInvariant("1"); + Number.parseLocale("1"); } function Sys_Application_Tests() { @@ -374,7 +374,7 @@ function Sys_UI_Control_Tests() { function Sy_UI_Point_Tests() { - var elementRef: Sys.UI.DomElement; + var elementRef: HTMLElement; var result: string; // Get the location of the element var elementLoc = Sys.UI.DomElement.getLocation(elementRef); @@ -417,7 +417,7 @@ function Sys_UI_DomElement_Tests() { // Add CSS class Sys.UI.DomElement.addCssClass($get("Button1"), "redBackgroundColor"); - var elementRef: Sys.UI.DomElement = $get("Label1"); + var elementRef = $get("Label1"); var elementBounds = Sys.UI.DomElement.getBounds(elementRef); var toggleCssClassMethod = () => {}; var removeCssClassMethod = () => {}; @@ -611,7 +611,7 @@ function Sys_Services_Profile_Service_Group_Tests() { function Sys_Net_NetworkRequestEventArgs_Tests() { var value = new Sys.Net.WebRequest(); - var netWorkEventArgs = new Sys.Net.NetWorkRequestEventArgs(value); + var netWorkEventArgs = new Sys.Net.NetworkRequestEventArgs(value); var webRequest = netWorkEventArgs.get_webRequest(); } @@ -660,7 +660,7 @@ function Sys_WebForms_PageRequestManager_Tests() { } var pageLoadingRequestHandler = (sender: any, args: Sys.WebForms.PageLoadingEventArgs) => { var dataItems: any = args.get_dataItems(); - var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleted(); + var panelsDeleted: HTMLDivElement[] = args.get_panelsDeleting(); var panelsUpdating = args.get_panelsUpdating(); var empty: Sys.EventArgs = args.Empty; } @@ -832,7 +832,7 @@ function CreatingCustomNonVisualClientComponentsTests() { _startTimer: function () { // save timer cookie for removal later - this._timer = window.setInterval((Function).createDelegate(this, this._timerCallback), this._interval); + this._timer = window.setInterval(Function.createDelegate(this, this._timerCallback), this._interval); }, _stopTimer: function () { From e768494136764f58af9fb9060a229c3363b1c05e Mon Sep 17 00:00:00 2001 From: Michael Jerred Date: Mon, 20 Jul 2015 14:15:29 +0100 Subject: [PATCH 077/881] Adding JQuery type as allowed type for event target in Bacon.fromEvent --- baconjs/baconjs-tests.ts | 3 +++ baconjs/baconjs.d.ts | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/baconjs/baconjs-tests.ts b/baconjs/baconjs-tests.ts index e542ef1c9..5d5998b70 100644 --- a/baconjs/baconjs-tests.ts +++ b/baconjs/baconjs-tests.ts @@ -28,6 +28,9 @@ function CreatingStreams() { Bacon.fromEvent(process.stdin, "readable", () => { alert("Bacon!"); }); + Bacon.fromEvent($("body"), "click").onValue(() => { + alert("Bacon!"); + }); // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. Bacon.fromCallback(callback => { diff --git a/baconjs/baconjs.d.ts b/baconjs/baconjs.d.ts index 0e3f77c12..a831e74f6 100644 --- a/baconjs/baconjs.d.ts +++ b/baconjs/baconjs.d.ts @@ -117,7 +117,7 @@ declare module Bacon { * alert("Bacon!"); * }); */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter, eventName:string):EventStream; + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; /** * @callback Bacon.fromEvent~eventTransformer @@ -136,7 +136,7 @@ declare module Bacon { * alert("Bacon!"); * }); */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter, eventName:string, eventTransformer:(event:A) => B):EventStream; + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string, eventTransformer:(event:A) => B):EventStream; /** * @callback Bacon.fromCallback1~f From df5dbd84b2b473eab99014b3576b9640538a685e Mon Sep 17 00:00:00 2001 From: Michael Jerred Date: Mon, 20 Jul 2015 17:20:17 +0100 Subject: [PATCH 078/881] Updating JSDocs --- baconjs/baconjs.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/baconjs/baconjs.d.ts b/baconjs/baconjs.d.ts index a831e74f6..2021b3dd7 100644 --- a/baconjs/baconjs.d.ts +++ b/baconjs/baconjs.d.ts @@ -106,7 +106,7 @@ declare module Bacon { /** * @function * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. - * @param {EventTarget|NodeJS.EventEmitter} target + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target * @param {string} eventName * @returns {EventStream} * @example @@ -116,6 +116,9 @@ declare module Bacon { * Bacon.fromEvent(process.stdin, "readable", () => { * alert("Bacon!"); * }); + * Bacon.fromEvent($("body"), "click").onValue(() => { + * alert("Bacon!"); + * }); */ function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; @@ -127,7 +130,7 @@ declare module Bacon { /** * @function Bacon.fromEvent * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. - * @param {EventTarget|NodeJS.EventEmitter} target + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target * @param {string} eventName * @param {Bacon.fromEvent~eventTransformer} eventTransformer * @returns {EventStream} From ae2581f4ce9d1b468089ea3d0652200d17e52af4 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 19:37:28 +0300 Subject: [PATCH 079/881] Fixed Travis-CI build --- microsoft-ajax/microsoft.ajax.d.ts | 2 +- sharepoint/SharePoint.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/microsoft-ajax/microsoft.ajax.d.ts b/microsoft-ajax/microsoft.ajax.d.ts index 19c9f9605..793fdf486 100644 --- a/microsoft-ajax/microsoft.ajax.d.ts +++ b/microsoft-ajax/microsoft.ajax.d.ts @@ -3039,7 +3039,7 @@ declare module Sys { * @param autoRemove * (Optional) A boolean value that determines whether the handler should be removed automatically when the element is disposed. */ - static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean); + static addHandler(element: HTMLElement, eventName: string, handler: (e: DomEvent) => void, autoRemove?: boolean): void; /** * Adds a list of DOM event handlers to the DOM element that exposes the events. This member is static and can be invoked without creating an instance of the class. * Use the addHandlers method to add a list of DOM event handlers to the element that exposes the event. diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index c50100a78..fef652dd3 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -1,6 +1,6 @@ -// Type definitions for sptypescript +// Type definitions for SharePoint 2010 and 2013 // Project: http://sptypescript.codeplex.com -// Definitions by: Stanislav Vyshchepan and Andrey Markeev +// Definitions by: Stanislav Vyshchepan , Andrey Markeev // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 6e279163da0942708c420d0ab259780696585eb9 Mon Sep 17 00:00:00 2001 From: Damian Connolly Date: Tue, 21 Jul 2015 00:10:40 +0200 Subject: [PATCH 080/881] Fixed author attribution --- socket.io-client/socket.io-client.d.ts | 2 +- socket.io/socket.io.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/socket.io-client/socket.io-client.d.ts b/socket.io-client/socket.io-client.d.ts index 42d366412..9f93c1f16 100644 --- a/socket.io-client/socket.io-client.d.ts +++ b/socket.io-client/socket.io-client.d.ts @@ -1,6 +1,6 @@ // Type definitions for socket.io-client 1.3.5 // Project: http://socket.io/ -// Definitions by: divillysausages +// Definitions by: PROGRE , Damian Connolly // Definitions: https://github.com/borisyankov/DefinitelyTyped declare var io: SocketIOClientStatic; diff --git a/socket.io/socket.io.d.ts b/socket.io/socket.io.d.ts index 696bd4d9b..a5b13044f 100644 --- a/socket.io/socket.io.d.ts +++ b/socket.io/socket.io.d.ts @@ -1,6 +1,6 @@ // Type definitions for socket.io 1.3.5 // Project: http://socket.io/ -// Definitions by: divillysausages +// Definitions by: PROGRE , Damian Connolly // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From b27d51b612c734eb41e379654cfe3c63f3cfbdda Mon Sep 17 00:00:00 2001 From: Zoe Tsai Date: Mon, 20 Jul 2015 19:36:52 -0700 Subject: [PATCH 081/881] update d3.d.ts --- d3/d3.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 50d6fbdaa..b3fed8327 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -464,9 +464,9 @@ declare module d3 { * Derive an attribute value for each node in the selection based on bound data. * * @param name The attribute name, optionally prefixed. - * @param value The function of the datum (the bound data item) and index (the position in the subgrouping) which computes the attribute value. If the function returns null, the attribute is removed. + * @param value The function of the datum (the bound data item), index (the position in the subgrouping), and inner index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. */ - attr(name: string, value: (datum: Datum, index: number) => Primitive): Selection; + attr(name: string, value: (datum: Datum, index: number, innerIndex?: number) => Primitive): Selection; /** * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. From ab7f747635543bd21a2bb9fe7f89a89609f91622 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Mon, 20 Jul 2015 21:15:44 -0700 Subject: [PATCH 082/881] Change event in codemirror also have a `origin` field It can take different value depending on where it comes from and gover history merging, various values are `+move` `+insert` `+remove` `setValue`. --- codemirror/codemirror.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 4b0a7ca6d..5fc335ed6 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -601,6 +601,8 @@ declare module CodeMirror { text: string[]; /** Text that used to be between from and to, which is overwritten by this change. */ removed: string; + /** String representing the origin of the change event and wether it can be merged with history */ + origin: string; } interface EditorChangeLinkedList extends CodeMirror.EditorChange { From 774fedc75f2c633674940ea1290c7cf05cd28da9 Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Tue, 21 Jul 2015 15:11:51 +0700 Subject: [PATCH 083/881] Use ES6 style import in typings tests for Atom's event-kit library --- event-kit/event-kit-tests.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/event-kit/event-kit-tests.ts b/event-kit/event-kit-tests.ts index 2c759506a..223ecc507 100644 --- a/event-kit/event-kit-tests.ts +++ b/event-kit/event-kit-tests.ts @@ -1,16 +1,6 @@ /// -// The following line only works in TypeScript 1.5 -//import { Disposable, CompositeDisposable, Emitter } from "event-kit"; -// DefinitelyTyped is still using TypeScript 1.4 to run tests -// so until they upgrade we have to do the following instead -import eventKit = require('event-kit'); -type Disposable = AtomEventKit.Disposable; -var Disposable = eventKit.Disposable; -type CompositeDisposable = AtomEventKit.CompositeDisposable; -var CompositeDisposable = eventKit.CompositeDisposable; -type Emitter = AtomEventKit.Emitter; -var Emitter = eventKit.Emitter; +import { Disposable, CompositeDisposable, Emitter } from "event-kit"; // Emitter From 53c558b8f1648ae02dde0857e49b5be24f223c35 Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Tue, 21 Jul 2015 15:23:15 +0700 Subject: [PATCH 084/881] Use ES6 style import in typings tests for atom-keymap library --- atom-keymap/atom-keymap-tests.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/atom-keymap/atom-keymap-tests.ts b/atom-keymap/atom-keymap-tests.ts index 520327da9..8882f5b38 100644 --- a/atom-keymap/atom-keymap-tests.ts +++ b/atom-keymap/atom-keymap-tests.ts @@ -1,10 +1,6 @@ /// -import atomKeymap = require('atom-keymap'); -var KeymapManager = atomKeymap.KeymapManager; -type ICompleteMatchEvent = AtomKeymap.ICompleteMatchEvent; -// The import and type aliasing above can be done more concisely in TypeScript 1.5+: -//import { KeymapManager, ICompleteMatchEvent } from "atom-keymap"; +import { KeymapManager, ICompleteMatchEvent } from "atom-keymap"; var manager = new KeymapManager(); manager.add('some/unique/path', { From 10aa0488105aadf6d718a9259a2bfc12703095d6 Mon Sep 17 00:00:00 2001 From: Vadim Macagon Date: Tue, 21 Jul 2015 15:27:11 +0700 Subject: [PATCH 085/881] Use ES6 style import in typings tests for Atom's first-mate library --- first-mate/first-mate-tests.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/first-mate/first-mate-tests.ts b/first-mate/first-mate-tests.ts index 1a181de4a..43e584824 100644 --- a/first-mate/first-mate-tests.ts +++ b/first-mate/first-mate-tests.ts @@ -1,11 +1,6 @@ /// -import firstMate = require('first-mate'); -var GrammarRegistry = firstMate.GrammarRegistry; -var Grammar = firstMate.GrammarRegistry; -type IToken = AtomFirstMate.IToken; -// The import and type aliasing above can be done more concisely in TypeScript 1.5+: -//import { GrammarRegistry, Grammar, IToken } from "first-mate"; +import { GrammarRegistry, Grammar, IToken } from "first-mate"; var registry = new GrammarRegistry({ maxTokensPerLine: 100 }); var grammar = registry.loadGrammarSync('javascript.json'); From d2bdc152ac6c35f0273cb3893f8079a0630ecd4c Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Fri, 17 Jul 2015 07:19:39 +0500 Subject: [PATCH 086/881] lodash: added set() method --- lodash/lodash-tests.ts | 3 +++ lodash/lodash.d.ts | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9b4548502..804c8cc36 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1080,6 +1080,9 @@ result = _.pick({ 'name': 'moe', '_userid': 'moe1' }, function (value, return key.charAt(0) != '_'; }); + +result = <{ a: { b: { c: number; }}[]}>_.set({ 'a': [{ 'b': { 'c': 3 } }] }, 'a[0].b.c', 4); + result = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function (r: number[], num: number) { num *= num; if (num % 2) { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f02a4aa97..efefed277 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6235,6 +6235,20 @@ declare module _ { thisArg?: any): Picked; } + //_.set + interface LoDashStatic { + /** + * Sets the property value of path on object. If a portion of path does not exist it is created. + * @param object The object to augment. + * @param path The path of the property to set. + * @param value The value to set. + * @return Returns object. + **/ + set(object: T, + path: string|string[], + value: any): T; + } + //_.transform interface LoDashStatic { /** From e0167145c316b02679f6cbc19883a5ef46ff11b3 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 19 Jul 2015 08:55:07 +0500 Subject: [PATCH 087/881] lodash: added _.value aliases (_.run, _.toJSON) --- lodash/lodash-tests.ts | 12 ++++-------- lodash/lodash.d.ts | 24 +++++++++++++++++------- 2 files changed, 21 insertions(+), 15 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9b4548502..348fbe982 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -135,15 +135,11 @@ result = _('test').toString(); result = _([1, 2, 3]).toString(); result = _({ 'key1': 'test1', 'key2': 'test2' }).toString(); -result = _('test').valueOf(); -result = _([1, 2, 3]).valueOf(); -result = <_.Dictionary>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).valueOf(); - +// _.value (aliases: _.run, _.toJSON, _.valueOf) result = _('test').value(); -result = _([1, 2, 3]).value(); -result = <_.Dictionary>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).value(); - -result = <_.Dictionary>_({ a: 1, b: 2}).mapValues(function(num: number) { return num * 2; }).value(); +result = _([1, 2, 3]).run(); +result = <_.Dictionary>_(<{ [index: string]: string; }>{ 'key1': 'test1', 'key2': 'test2' }).toJSON(); +result = <_.Dictionary>_({ a: 1, b: 2}).mapValues(function(num: number) { return num * 2; }).valueOf(); // /************* // * Arrays * diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f02a4aa97..ddee8b539 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -177,15 +177,25 @@ declare module _ { toString(): string; /** - * Extracts the wrapped value. - * @return The wrapped value. - **/ - valueOf(): T; - - /** - * @see valueOf + * Executes the chained sequence to extract the unwrapped value. + * @return Returns the resolved unwrapped value. **/ value(): T; + + /** + * @see _.value + **/ + run(): T; + + /** + * @see _.value + **/ + toJSON(): T; + + /** + * @see _.value + **/ + valueOf(): T; } interface LoDashWrapper extends LoDashWrapperBase> { } From f02d001d3d809136f507048113369660ee9876ef Mon Sep 17 00:00:00 2001 From: Daisuke Aoki Date: Tue, 21 Jul 2015 18:37:43 +0900 Subject: [PATCH 088/881] Enable data types to specify options * Add call signatures to definition of Sequelize data types * ex. `INTEGER(20)`, `ARRAY(Sequelize.INTEGER)` --- sequelize/sequelize-tests.ts | 213 ++++++++++++++++++++++++++++++++++- sequelize/sequelize.d.ts | 82 ++++++++++++-- 2 files changed, 284 insertions(+), 11 deletions(-) diff --git a/sequelize/sequelize-tests.ts b/sequelize/sequelize-tests.ts index 8766745b8..58d85086d 100644 --- a/sequelize/sequelize-tests.ts +++ b/sequelize/sequelize-tests.ts @@ -213,4 +213,215 @@ promiseMe = myModelInst.increment({}); promiseMe = myModelInst.decrement({}, incrOpts); isBool = myModelInst.equal(myModelInst); isBool = myModelInst.equalsOneOf([myModelInst]); -myModelPojo = myModelInst.toJSON(); \ No newline at end of file +myModelPojo = myModelInst.toJSON(); + + +// data types test +var types:any = Sequelize.STRING; +types = Sequelize.STRING(12); +types = Sequelize.STRING(12, true); +types = Sequelize.STRING.BINARY; +types = Sequelize.STRING(12).BINARY; +types = Sequelize.STRING.BINARY(12); +types = Sequelize.STRING({length:12, binary:true}); +types = Sequelize.STRING({length:12}).BINARY; + +types = Sequelize.CHAR; +types = Sequelize.CHAR(12); +types = Sequelize.CHAR(12, true); +types = Sequelize.CHAR.BINARY; +types = Sequelize.CHAR(12).BINARY; +types = Sequelize.CHAR.BINARY(12); +types = Sequelize.CHAR({length:12, binary:true}); +types = Sequelize.CHAR({length:12}).BINARY; + +types = Sequelize.TEXT; +types = Sequelize.TEXT('tiny'); +types = Sequelize.TEXT({length:'tiny'}); + +types = Sequelize.NUMBER; +var numberOptions = {length:12, zerofill:true, decimals:1, precision:1, scale:1, unsigned:true}; +types = Sequelize.NUMBER(numberOptions); + +types = Sequelize.INTEGER; +types = Sequelize.INTEGER.ZEROFILL; +types = Sequelize.INTEGER.UNSIGNED; +types = Sequelize.INTEGER.ZEROFILL.UNSIGNED; +types = Sequelize.INTEGER.UNSIGNED.ZEROFILL; +types = Sequelize.INTEGER(12); +types = Sequelize.INTEGER(12).ZEROFILL; +types = Sequelize.INTEGER(12).UNSIGNED; +types = Sequelize.INTEGER(12).ZEROFILL.UNSIGNED; +types = Sequelize.INTEGER(12).UNSIGNED.ZEROFILL; +types = Sequelize.INTEGER(numberOptions); +types = Sequelize.INTEGER(numberOptions).ZEROFILL; +types = Sequelize.INTEGER(numberOptions).UNSIGNED; +types = Sequelize.INTEGER(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.INTEGER(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.BIGINT; +types = Sequelize.BIGINT.ZEROFILL; +types = Sequelize.BIGINT.UNSIGNED; +types = Sequelize.BIGINT.ZEROFILL.UNSIGNED; +types = Sequelize.BIGINT.UNSIGNED.ZEROFILL; +types = Sequelize.BIGINT(12); +types = Sequelize.BIGINT(12).ZEROFILL; +types = Sequelize.BIGINT(12).UNSIGNED; +types = Sequelize.BIGINT(12).ZEROFILL.UNSIGNED; +types = Sequelize.BIGINT(12).UNSIGNED.ZEROFILL; +types = Sequelize.BIGINT(numberOptions); +types = Sequelize.BIGINT(numberOptions).ZEROFILL; +types = Sequelize.BIGINT(numberOptions).UNSIGNED; +types = Sequelize.BIGINT(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.BIGINT(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.FLOAT; +types = Sequelize.FLOAT.ZEROFILL; +types = Sequelize.FLOAT.UNSIGNED; +types = Sequelize.FLOAT.ZEROFILL.UNSIGNED; +types = Sequelize.FLOAT.UNSIGNED.ZEROFILL; +types = Sequelize.FLOAT(12); +types = Sequelize.FLOAT(12).ZEROFILL; +types = Sequelize.FLOAT(12).UNSIGNED; +types = Sequelize.FLOAT(12).ZEROFILL.UNSIGNED; +types = Sequelize.FLOAT(12).UNSIGNED.ZEROFILL; +types = Sequelize.FLOAT(12,12); +types = Sequelize.FLOAT(12,12).ZEROFILL; +types = Sequelize.FLOAT(12,12).UNSIGNED; +types = Sequelize.FLOAT(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.FLOAT(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.FLOAT(numberOptions); +types = Sequelize.FLOAT(numberOptions).ZEROFILL; +types = Sequelize.FLOAT(numberOptions).UNSIGNED; +types = Sequelize.FLOAT(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.FLOAT(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.DOUBLE; +types = Sequelize.DOUBLE.ZEROFILL; +types = Sequelize.DOUBLE.UNSIGNED; +types = Sequelize.DOUBLE.ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE.UNSIGNED.ZEROFILL; +types = Sequelize.DOUBLE(12); +types = Sequelize.DOUBLE(12).ZEROFILL; +types = Sequelize.DOUBLE(12).UNSIGNED; +types = Sequelize.DOUBLE(12).ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE(12).UNSIGNED.ZEROFILL; +types = Sequelize.DOUBLE(12,12); +types = Sequelize.DOUBLE(12,12).ZEROFILL; +types = Sequelize.DOUBLE(12,12).UNSIGNED; +types = Sequelize.DOUBLE(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.DOUBLE(numberOptions); +types = Sequelize.DOUBLE(numberOptions).ZEROFILL; +types = Sequelize.DOUBLE(numberOptions).UNSIGNED; +types = Sequelize.DOUBLE(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.TIME; +types = Sequelize.DATE; +types = Sequelize.DATEONLY; +types = Sequelize.BOOLEAN; +types = Sequelize.NOW; + +types = Sequelize.BLOB; +types = Sequelize.BLOB('tiny'); +types = Sequelize.BLOB({length:'tiny'}); + +types = Sequelize.DECIMAL; +types = Sequelize.DECIMAL.ZEROFILL; +types = Sequelize.DECIMAL.UNSIGNED; +types = Sequelize.DECIMAL.ZEROFILL.UNSIGNED; +types = Sequelize.DECIMAL.UNSIGNED.ZEROFILL; +types = Sequelize.DECIMAL(12,12); +types = Sequelize.DECIMAL(12,12).ZEROFILL; +types = Sequelize.DECIMAL(12,12).UNSIGNED; +types = Sequelize.DECIMAL(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.DECIMAL(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.DECIMAL(numberOptions); +types = Sequelize.DECIMAL(numberOptions).ZEROFILL; +types = Sequelize.DECIMAL(numberOptions).UNSIGNED; +types = Sequelize.DECIMAL(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.DECIMAL(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.NUMERIC; +types = Sequelize.NUMERIC.ZEROFILL; +types = Sequelize.NUMERIC.UNSIGNED; +types = Sequelize.NUMERIC.ZEROFILL.UNSIGNED; +types = Sequelize.NUMERIC.UNSIGNED.ZEROFILL; +types = Sequelize.NUMERIC(12,12); +types = Sequelize.NUMERIC(12,12).ZEROFILL; +types = Sequelize.NUMERIC(12,12).UNSIGNED; +types = Sequelize.NUMERIC(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.NUMERIC(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.NUMERIC(numberOptions); +types = Sequelize.NUMERIC(numberOptions).ZEROFILL; +types = Sequelize.NUMERIC(numberOptions).UNSIGNED; +types = Sequelize.NUMERIC(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.NUMERIC(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.UUID; +types = Sequelize.UUIDV1; +types = Sequelize.UUIDV4; +types = Sequelize.HSTORE; +types = Sequelize.JSON; +types = Sequelize.JSONB; +types = Sequelize.VIRTUAL; + +types = Sequelize.ARRAY(Sequelize.INTEGER(12)); +types = Sequelize.ARRAY({type: Sequelize.BLOB}); +var obj = {}; +var isbool:boolean = types.is(obj, obj); + +types = Sequelize.NONE; +types = Sequelize.ENUM("one", "two", 'three'); + +types = Sequelize.RANGE(Sequelize.INTEGER(12)); +types = Sequelize.RANGE({subtype: Sequelize.BLOB}); + +types = Sequelize.REAL; +types = Sequelize.REAL.ZEROFILL; +types = Sequelize.REAL.UNSIGNED; +types = Sequelize.REAL.ZEROFILL.UNSIGNED; +types = Sequelize.REAL.UNSIGNED.ZEROFILL; +types = Sequelize.REAL(12,12); +types = Sequelize.REAL(12,12).ZEROFILL; +types = Sequelize.REAL(12,12).UNSIGNED; +types = Sequelize.REAL(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.REAL(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.REAL(numberOptions); +types = Sequelize.REAL(numberOptions).ZEROFILL; +types = Sequelize.REAL(numberOptions).UNSIGNED; +types = Sequelize.REAL(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.REAL(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize.DOUBLE; +types = Sequelize.DOUBLE.ZEROFILL; +types = Sequelize.DOUBLE.UNSIGNED; +types = Sequelize.DOUBLE.ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE.UNSIGNED.ZEROFILL; +types = Sequelize.DOUBLE(12,12); +types = Sequelize.DOUBLE(12,12).ZEROFILL; +types = Sequelize.DOUBLE(12,12).UNSIGNED; +types = Sequelize.DOUBLE(12,12).ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE(12,12).UNSIGNED.ZEROFILL; +types = Sequelize.DOUBLE(numberOptions); +types = Sequelize.DOUBLE(numberOptions).ZEROFILL; +types = Sequelize.DOUBLE(numberOptions).UNSIGNED; +types = Sequelize.DOUBLE(numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize.DOUBLE(numberOptions).UNSIGNED.ZEROFILL; + +types = Sequelize["DOUBLE PRECISION"]; +types = Sequelize["DOUBLE PRECISION"].ZEROFILL; +types = Sequelize["DOUBLE PRECISION"].UNSIGNED; +types = Sequelize["DOUBLE PRECISION"].ZEROFILL.UNSIGNED; +types = Sequelize["DOUBLE PRECISION"].UNSIGNED.ZEROFILL; +types = Sequelize["DOUBLE PRECISION"](12,12); +types = Sequelize["DOUBLE PRECISION"](12,12).ZEROFILL; +types = Sequelize["DOUBLE PRECISION"](12,12).UNSIGNED; +types = Sequelize["DOUBLE PRECISION"](12,12).ZEROFILL.UNSIGNED; +types = Sequelize["DOUBLE PRECISION"](12,12).UNSIGNED.ZEROFILL; +types = Sequelize["DOUBLE PRECISION"](numberOptions); +types = Sequelize["DOUBLE PRECISION"](numberOptions).ZEROFILL; +types = Sequelize["DOUBLE PRECISION"](numberOptions).UNSIGNED; +types = Sequelize["DOUBLE PRECISION"](numberOptions).ZEROFILL.UNSIGNED; +types = Sequelize["DOUBLE PRECISION"](numberOptions).UNSIGNED.ZEROFILL; \ No newline at end of file diff --git a/sequelize/sequelize.d.ts b/sequelize/sequelize.d.ts index 1bb6be593..eb5b0296f 100644 --- a/sequelize/sequelize.d.ts +++ b/sequelize/sequelize.d.ts @@ -2725,59 +2725,121 @@ declare module "sequelize" interface DataTypeStringBase { BINARY: DataTypeString; + (length:number, binary?:boolean):DataTypeString; + (options:{length?:number; binary?:boolean;}):DataTypeString; } + + interface DataTypeNumberOptions { + length?:number; + zerofill?:boolean; + decimals?:number; + precision?:number; + scale?:number; + unsigned?:boolean; + } + interface DataTypeNumberBase { - UNSIGNED: boolean; - ZEROFILL: boolean; + UNSIGNED: DataTypeNumberBase; + ZEROFILL: DataTypeNumberBase; + (options: DataTypeNumberOptions): DataTypeNumberBase; } interface DataTypeString extends DataTypeStringBase { } interface DataTypeChar extends DataTypeStringBase { } + + interface DataTypeText { + (length:string): DataTypeText; + (options:{length:string}): DataTypeText; + } + interface DataTypeInteger extends DataTypeNumberBase { + (length:number):DataTypeInteger; + (options:DataTypeNumberOptions):DataTypeInteger; } + interface DataTypeBigInt extends DataTypeNumberBase { + (length:number):DataTypeBigInt; + (options:DataTypeNumberOptions):DataTypeBigInt; } + interface DataTypeFloat extends DataTypeNumberBase { + (length:number, decimals?:number):DataTypeFloat; + (options:DataTypeNumberOptions):DataTypeFloat; } + + interface DataTypeReal extends DataTypeNumberBase { + (length:number, decimals?:number):DataTypeReal; + (options:DataTypeNumberOptions):DataTypeReal; + } + + interface DataTypeDouble extends DataTypeNumberBase { + (length:number, decimals?:number):DataTypeDouble; + (options:DataTypeNumberOptions):DataTypeDouble; + } + interface DataTypeBlob { + (length:string):DataTypeBlob; + (options:{length:string}):DataTypeBlob; } - interface DataTypeDecimal { - PRECISION: number; - SCALE: number; + + interface DataTypeDecimal extends DataTypeNumberBase { + (precision:number, scale:number):DataTypeDecimal; + (options:DataTypeNumberOptions):DataTypeDecimal; + } + + interface DataTypeRange { + (subtype?:any):DataTypeRange; + (options:{subtype:any}):DataTypeRange; } interface DataTypeVirtual { } + interface DataTypeEnum { (...values: Array): DataTypeEnum; } interface DataTypeArray { + (type?:any):DataTypeArray; + (options:{type:any}):DataTypeArray; + is(obj:any, type:any):boolean; } + interface DataTypeHstore { } interface DataTypes { + ABSTRACT: string; STRING: DataTypeString; CHAR: DataTypeChar; - TEXT: string; + TEXT: DataTypeText; + NUMBER: DataTypeNumberBase; INTEGER: DataTypeInteger; BIGINT: DataTypeBigInt; - DATE: string; - BOOLEAN: string; FLOAT: DataTypeFloat; + TIME:string; + DATE: string; + DATEONLY:string; + BOOLEAN: string; NOW: string; BLOB: DataTypeBlob; DECIMAL: DataTypeDecimal; + NUMERIC: DataTypeDecimal; UUID: string; UUIDV1: string; UUIDV4: string; + HSTORE: DataTypeHstore; + JSON: string; + JSONB: string; VIRTUAL: DataTypeVirtual; + ARRAY: DataTypeArray; NONE: DataTypeVirtual; ENUM: DataTypeEnum; - ARRAY: DataTypeArray; - HSTORE: DataTypeHstore; + RANGE:DataTypeRange; + REAL: DataTypeReal; + DOUBLE: DataTypeDouble; + "DOUBLE PRECISION": DataTypeDouble; } } From cc978685d954bed4032cf428fc1c57640daf30c7 Mon Sep 17 00:00:00 2001 From: Igor Kriklivetc Date: Tue, 21 Jul 2015 12:49:24 +0300 Subject: [PATCH 089/881] Update to 15.1.5 --- devextreme/dx.devextreme-15.1.4.d.ts | 6448 ++++++++++++++++++++++++++ devextreme/dx.devextreme.d.ts | 67 +- 2 files changed, 6508 insertions(+), 7 deletions(-) create mode 100644 devextreme/dx.devextreme-15.1.4.d.ts diff --git a/devextreme/dx.devextreme-15.1.4.d.ts b/devextreme/dx.devextreme-15.1.4.d.ts new file mode 100644 index 000000000..266da3b12 --- /dev/null +++ b/devextreme/dx.devextreme-15.1.4.d.ts @@ -0,0 +1,6448 @@ +// Type definitions for DevExtreme 15.1.4 +// 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; + /** 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, and a jQuery plugin and Knockout binding for the required component. */ + 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; + /** Sets one or more options of this component. */ + option(options: Object): void; + /** Returns the configuration options of this component. */ + option(): Object; + /** 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 the 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(obj?: { + filter?: Object; + select?: Object; + group?: Object; + sort?: 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?: () => 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 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 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 { + /** 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 for pressing of the specified key. */ + 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; + }; + } +} +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 { + /** 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, which 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 { + /** 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; + } + /** 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; + bounds?: { + northEast?: { + lat?: number; + lng?: number; + }; + southWest?: { + lat?: number; + lng?: number; + }; + /** 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?: number; + /** 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?: number; + /** The zoom level of the map. */ + zoom?: number; + /** Adds a marker to the map. */ + addMarker(markerOptions: Object): JQueryPromise; + /** Adds a route to the map. */ + addRoute(options: Object): JQueryPromise; + /** Removes a marker from the map. */ + removeMarker(marker: Object): JQueryPromise; + /** Removes a route from the map. */ + removeRoute(route: any): JQueryPromise; + }; + } + /** An interactive map widget. */ + export class dxMap extends Widget { + constructor(element: JQuery, options?: dxMapOptions); + constructor(element: Element, options?: dxMapOptions); + } + 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; + /** 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 whether the list supports single item selection or multi-selection. */ + 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; + } + /** 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; + } + /** 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?: Date; + /** The minimum date that can be selected within the widget. */ + min?: Date; + /** 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; + /** A Date object specifying the date and time currently selected using the date box. */ + value?: Date; + /** + * 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; + /** The name of an icon to be displayed on the button. */ + icon?: string; + iconSrc?: string; + /** 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; + /** Specifies 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; + } + /** 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; + } + 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 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; + 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; + 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; + 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; + 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; + } + /** 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: number): PivotGridField; + /** Sets one or more options of a specified field. */ + field(id: number, 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; + /** 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; + /** 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 AppoinmentAdding event. */ + onAppointmentAdding?: Function; + /** A handler for the appointmentAdded event. */ + onAppointmentAdded?: Function; + /** A handler for the AppoinmentUpdating event. */ + onAppointmentUpdating?: Function; + /** A handler for the appointmentUpdated event. */ + onAppointmentUpdated?: Function; + /** A handler for the AppoinmentDeleting 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; + } + 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; + } + /** 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 callback function that determines values for column cells to be used for grouping. */ + calculateGroupValue?: any; + /** Specifies a callback function that returns a value or the name of the field 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 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 brackets of 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: number, optionName: string): any; + /** Sets an option of a specific column. */ + columnOption(id: number, 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 { + /** Specifies a data source for the pivot grid. */ + dataSource?: any; + 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 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 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 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 { + 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 { + /** Specifies how to apply hatching to highlight a selected series. */ + 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; + /** 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; + /** 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 a series when it is hovered over.

    */ + color?: string; + /** Specifies the dash style for the line in a hovered series. */ + dashStyle?: string; + /** Specifies the hatching options to be applied when a series is hovered over. */ + 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; + /** An object defining configuration options for a selected series. */ + 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; + /** Specifies the hatching options to be applied when a series is selected. */ + 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 container that is small enough for the layout to begin adapting. */ + width?: number; + /** Specifies the height of the widget container 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; + }) => void; + /** A handler for the tooltipHidden event. */ + onTooltipHidden?: (e: { + component: BaseChart; + element: Element; + }) => 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 only to the Bar 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 the 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; + } + 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; + /** 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; + /** 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; + } + /** Overridden by descriptions for particular widgets. */ + export class BaseSparkline extends viz.core.BaseWidget { + /** Redraws a widget. */ + render(): void; + } + export interface dxBulletOptions extends BaseSparkline { + /** Specifies a color for the bullet bar. */ + color?: string; + /** Specifies an end value for the invisible scale. */ + endScaleValue?: number; + /** Specifies whether or not to show the target line. */ + showTarget?: boolean; + /** Specifies whether or not to show the line indicating zero on the invisible scale. */ + showZeroLevel?: boolean; + /** Specifies a start value for the invisible scale. */ + startScaleValue?: number; + /** Specifies the value indicated by the target line. */ + target?: number; + /** Specifies a color for both the target and zero level lines. */ + targetColor?: string; + /** Specifies the width of the target line. */ + targetWidth?: number; + /** Specifies the primary value indicated by the bullet bar. */ + value?: number; + } + /** A bullet graph widget. */ + export class dxBullet extends BaseSparkline { + constructor(element: JQuery, options?: dxBulletOptions); + constructor(element: Element, options?: dxBulletOptions); + } + export interface dxSparklineOptions extends BaseSparklineOptions { + /** Specifies the data source field that provides arguments for a sparkline. */ + argumentField?: string; + /** Sets a color for the bars indicating negative values. Available for a sparkline of the bar type only. */ + barNegativeColor?: string; + /** Sets a color for the bars indicating positive values. Available for a sparkline of the bar type only. */ + barPositiveColor?: string; + /** Specifies a data source for the sparkline. */ + dataSource?: Array; + /** Sets a color for the boundary of both the first and last points on a sparkline. */ + firstLastColor?: string; + /** Specifies whether a sparkline ignores null data points or not. */ + ignoreEmptyPoints?: boolean; + /** Sets a color for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineColor?: string; + /** Specifies a width for a line on a sparkline. Available for the sparklines of the line- and area-like types. */ + lineWidth?: number; + /** Sets a color for the bars indicating the values that are less than the winloss threshold. Available for a sparkline of the winloss type only. */ + lossColor?: string; + /** Sets a color for the boundary of the maximum point on a sparkline. */ + maxColor?: string; + /** Sets a color for the boundary of the minimum point on a sparkline. */ + minColor?: string; + /** Sets a color for points on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointColor?: string; + /** Specifies the diameter of sparkline points in pixels. Available for the sparklines of line- and area-like types. */ + pointSize?: number; + /** Specifies a symbol to use as a point marker on a sparkline. Available for the sparklines of the line- and area-like types. */ + pointSymbol?: string; + /** Specifies whether or not to indicate both the first and last values on a sparkline. */ + showFirstLast?: boolean; + /** Specifies whether or not to indicate both the minimum and maximum values on a sparkline. */ + showMinMax?: boolean; + /** Determines the type of a sparkline. */ + type?: string; + /** Specifies the data source field that provides values for a sparkline. */ + valueField?: string; + /** Sets a color for the bars indicating the values greater than a winloss threshold. Available for a sparkline of the winloss type only. */ + winColor?: string; + /** Specifies a value that serves as a threshold for the sparkline of the winloss type. */ + winlossThreshold?: number; + /** Specifies the minimum value of the sparkline value axis. */ + minValue?: number; + /** Specifies the maximum value of the sparkline's value axis. */ + maxValue?: number; + } + /** A sparkline widget. */ + export class dxSparkline extends BaseSparkline { + constructor(element: JQuery, options?: dxSparklineOptions); + constructor(element: Element, options?: dxSparklineOptions); + } +} +interface JQuery { + dxBullet(options?: DevExpress.viz.sparklines.dxBulletOptions): JQuery; + dxBullet(methodName: string, ...params: any[]): any; + dxBullet(methodName: "instance"): DevExpress.viz.sparklines.dxBullet; + dxSparkline(options?: DevExpress.viz.sparklines.dxSparklineOptions): JQuery; + dxSparkline(methodName: string, ...params: any[]): any; + dxSparkline(methodName: "instance"): DevExpress.viz.sparklines.dxSparkline; +} diff --git a/devextreme/dx.devextreme.d.ts b/devextreme/dx.devextreme.d.ts index 266da3b12..26f720f54 100644 --- a/devextreme/dx.devextreme.d.ts +++ b/devextreme/dx.devextreme.d.ts @@ -1,7 +1,11 @@ -// Type definitions for DevExtreme 15.1.4 -// Project: http://js.devexpress.com/ -// Definitions by: DevExpress Inc. -// Definitions: https://github.com/borisyankov/DefinitelyTyped +/*! +* DevExtreme +* Version: 15.1.5 +* Build date: Jul 15, 2015 +* +* Copyright (c) 2012 - 2015 Developer Express Inc. ALL RIGHTS RESERVED +* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml +*/ /// @@ -520,6 +524,8 @@ declare module DevExpress { } /** 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; } @@ -1438,6 +1444,7 @@ declare module DevExpress.ui { 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; @@ -1817,9 +1824,11 @@ declare module DevExpress.ui { /** A handler for the click event. */ onClick?: any; clickAction?: any; - /** The name of an icon to be displayed on the button. */ + /** 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. */ @@ -1867,7 +1876,7 @@ declare module DevExpress.ui { minSearchLength?: number; /** Specifies the maximum count of items displayed by the widget. */ maxItemCount?: number; - /** Specifies the currently selected item. */ + /** Gets the currently selected item. */ selectedItem?: Object; } /** A textbox widget that supports autocompletion. */ @@ -2730,6 +2739,8 @@ declare module DevExpress.ui { onItemExpanded?: Function; /** A handler for the itemCollapsed event. */ onItemCollapsed?: Function; + hoverStateEnabled?: boolean; + focusStateEnabled?: boolean; } /** A widget displaying specified data items as a tree. */ export class dxTreeView extends CollectionWidget { @@ -3339,6 +3350,8 @@ Specifies the message displayed in a group row when the corresponding group cont }) => 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. */ @@ -3589,8 +3602,10 @@ Searches grid records by a search string. 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; @@ -3676,6 +3691,8 @@ Searches grid records by a search string. 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 { @@ -5179,11 +5196,13 @@ declare module DevExpress.viz.charts { 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; @@ -5606,6 +5625,18 @@ declare module DevExpress.viz.gauges { }; /** 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. */ @@ -6252,7 +6283,19 @@ declare module DevExpress.viz.map { center: Array; component: dxVectorMap; element: Element; - }) => void; + }) => 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. */ @@ -6355,6 +6398,16 @@ declare module DevExpress.viz.sparklines { 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 { From a4936421e66c55140afd6a1bf77038e665bd4980 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 21 Jul 2015 11:06:28 +0100 Subject: [PATCH 090/881] Type definitions and tests for dot-case --- dot-case/dot-case-tests.ts | 9 +++++++++ dot-case/dot-case.d.ts | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 dot-case/dot-case-tests.ts create mode 100644 dot-case/dot-case.d.ts diff --git a/dot-case/dot-case-tests.ts b/dot-case/dot-case-tests.ts new file mode 100644 index 000000000..d5713aeba --- /dev/null +++ b/dot-case/dot-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import dotCase = require('dot-case'); + +console.log(dotCase('string')); // => "string" +console.log(dotCase('camelCase')); // => "camel.case" +console.log(dotCase('sentence case')); // => "sentence.case" + +console.log(dotCase('MY STRING', 'tr')); // => "my.strıng" diff --git a/dot-case/dot-case.d.ts b/dot-case/dot-case.d.ts new file mode 100644 index 000000000..5e02a2342 --- /dev/null +++ b/dot-case/dot-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for dot-case +// Project: https://github.com/blakeembrey/dot-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "dot-case" { + function dotCase(string: string, locale?: string): string; + export = dotCase; +} From 07e3d201c037f8f24a0d60379502c7ecc833e46e Mon Sep 17 00:00:00 2001 From: Martin Obert Date: Tue, 21 Jul 2015 12:30:23 +0200 Subject: [PATCH 091/881] added missing getValue() definition for Rx.BehaviorSubject --- rx/rx.binding-lite.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/rx/rx.binding-lite.d.ts b/rx/rx.binding-lite.d.ts index f896e260d..b798f342f 100644 --- a/rx/rx.binding-lite.d.ts +++ b/rx/rx.binding-lite.d.ts @@ -7,6 +7,7 @@ declare module Rx { export interface BehaviorSubject extends Subject { + getValue(): T; } interface BehaviorSubjectStatic { From f695ec7d2458d506fb203b3c0d4aabe523ab2d13 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 21 Jul 2015 15:47:02 +0500 Subject: [PATCH 092/881] lodash: changed _.get() (added to the chainable wrapper) --- lodash/lodash-tests.ts | 15 ++++++++++++++- lodash/lodash.d.ts | 13 +++++++++++-- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9b4548502..78888f871 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -936,7 +936,20 @@ result = _.methods(_); result = <_.LoDashArrayWrapper>_(_).functions(); result = <_.LoDashArrayWrapper>_(_).methods(); -result = _.get({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); +// _.get +result = _.get({ 'a': [{ 'b': { 'c': 3 } }] }, 'a[0].b.c'); +// → 3 +result = _.get({ 'a': [{ 'b': { 'c': 3 } }] }, ['a', '0', 'b', 'c']); +// → 3 +result = _.get({ 'a': [{ 'b': { 'c': 3 } }] }, 'a.b.c', 'default'); +// → 'default' + +result = _({ 'a': [{ 'b': { 'c': 3 } }] }).get('a[0].b.c'); +// → 3 +result = _({ 'a': [{ 'b': { 'c': 3 } }] }).get(['a', '0', 'b', 'c']); +// → 3 +result = _({ 'a': [{ 'b': { 'c': 3 } }] }).get('a.b.c', 'default'); +// → 'default' result = _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f02a4aa97..acb0adc42 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5756,12 +5756,21 @@ declare module _ { * @param defaultValue The value returned if the resolved value is undefined. * @return Returns the resolved value. **/ - get(object : Object, - path:string|string[], + get(object: Object, + path: string|string[], defaultValue?:T ): T; } + interface LoDashObjectWrapper { + /** + * @see _.get + **/ + get(path: string|string[], + defaultValue?: TResult + ): TResult; + } + //_.has interface LoDashStatic { /** From 7cc499a0635cb78d141f75c0511b1a55b821284f Mon Sep 17 00:00:00 2001 From: Igor Kriklivetc Date: Tue, 21 Jul 2015 14:23:59 +0300 Subject: [PATCH 093/881] Header changed --- devextreme/dx.devextreme.d.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/devextreme/dx.devextreme.d.ts b/devextreme/dx.devextreme.d.ts index 26f720f54..aff710888 100644 --- a/devextreme/dx.devextreme.d.ts +++ b/devextreme/dx.devextreme.d.ts @@ -1,11 +1,7 @@ -/*! -* DevExtreme -* Version: 15.1.5 -* Build date: Jul 15, 2015 -* -* Copyright (c) 2012 - 2015 Developer Express Inc. ALL RIGHTS RESERVED -* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml -*/ +// Type definitions for DevExtreme 15.1.5 +// Project: http://js.devexpress.com/ +// Definitions by: DevExpress Inc. +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 15520b4269d3b372947c0b0eaa6564cd118b96ed Mon Sep 17 00:00:00 2001 From: Sascha Thiel Date: Tue, 21 Jul 2015 13:52:47 +0200 Subject: [PATCH 094/881] added LayoutViewOption because the Layout can have regions in it. --- marionette/marionette.d.ts | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/marionette/marionette.d.ts b/marionette/marionette.d.ts index be684d9a8..c60965c98 100644 --- a/marionette/marionette.d.ts +++ b/marionette/marionette.d.ts @@ -1097,6 +1097,13 @@ declare module Marionette { onRenderCollection(): void; } + interface LayoutViewOptions extends Backbone.ViewOptions { + /** + * The LayoutView takes an additional parameter where you can pass the regions as option on creation. + */ + regions?:any; + } + /** * A LayoutView is a hybrid of an ItemView and a collection of Region objects. * They are ideal for rendering application layouts with multiple sub-regions @@ -1119,7 +1126,12 @@ declare module Marionette { * A hash that can contain a regions hash that allows you to specify regions per * LayoutView instance. */ - constructor(options?: any); + constructor(options?: LayoutViewOptions); + + /** + * Regions hash or a method returning the regions hash that maps regions/selectors to methods on your View. + **/ + regions():any; /** Adds a region to the layout view. */ addRegion(name: string, definition: any): Region; @@ -1129,7 +1141,7 @@ declare module Marionette { */ addRegions(regions: any): any; - /** Returns a region from the layout view */ + /** Returns a region from the layout view */ getRegion(name: string): Region; /** @@ -1147,7 +1159,7 @@ declare module Marionette { * for customized region interactions and business specific * view logic for better control over single regions. */ - getRegionManager(): any; + getRegionManager(): RegionManager; } interface AppRouterOptions extends Backbone.RouterOptions { From af3a9fdef7c0523cbdb7e9ed535e2adf4da2ce9d Mon Sep 17 00:00:00 2001 From: Nikhil Tilwalli Date: Tue, 21 Jul 2015 08:38:01 -0400 Subject: [PATCH 095/881] Remove addLayer from mapbox since it is not (no longer) in the mapbox library and is shadowing the equivalent function in the Leaflet library --- mapbox/mapbox.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index d15598cfd..bc2c3c980 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -44,7 +44,6 @@ declare module L.mapbox { legendControl : L.mapbox.LegendControl; shareControl : L.mapbox.ShareControl; - addLayer(layer: any): any; getTileJSON(): any; } From e23467fc87e8bc99345b61416ffea7c0863a67b4 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 Jul 2015 13:00:23 -0400 Subject: [PATCH 096/881] added uigridconstants, and all gridApi.core gridApi.rowEdit definitions. --- ui-grid/ui-grid-tests.ts | 14 +++ ui-grid/ui-grid.d.ts | 187 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 193 insertions(+), 8 deletions(-) diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 1d0dd3462..065bb1a52 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -86,3 +86,17 @@ columnDef.visible = true; columnDef.width = 100; columnDef.width = '*'; + +var gridInstance: uiGrid.IGridInstance; +var menuItem: uiGrid.IMenuItem + +var gridApi: uiGrid.IGridApi +gridApi.core.clearAllFilters(true); +gridApi.core.addToGridMenu(gridInstance, [menuItem]); +gridApi.core.getVisibleRows(gridInstance); +gridApi.core.handleWindowResize(); +gridApi.core.queueGridRefresh() +gridApi.core.queueRefresh(); +var colProcessor: uiGrid.IColumnProcessor; +gridApi.core.registerColumnsProcessor(colProcessor, 100); + diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 7318b1d79..7e5305046 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -12,6 +12,113 @@ /// declare module uiGrid { + export interface UIGridConstants { + LOG_DEBUG_MESSAGES: boolean; + LOG_WARN_MESSAGES: boolean; + LOG_ERROR_MESSAGES: boolean; + CUSTOM_FILTERS: RegExp; + COL_FIELD: RegExp; + MODEL_COL_FIELD: RegExp; + TOOLTIP: RegExp; + DISPLAY_CELL_TEMPLATE: RegExp; + TEMPLATE_REGEXP: RegExp; + FUNC_REGEXP: RegExp; + DOT_REGEXP: RegExp; + APOS_REGEXP: RegExp; + BRACKET_REGEXP: RegExp; + COL_CLASS_PREFIX: string; + events: { + GRID_SCROLL: string; + COLUMN_MENU_SHOWN: string; + ITEM_DRAGGING: string; + COLUMN_HEADER_CLICK: string; + }; + keymap: { + TAB: number; + STRG: number; + CAPSLOCK: number; + CTRL: number; + CTRLRIGHT: number; + CTRLR: number; + SHIFT: number; + RETURN: number; + ENTER: number; + BACKSPACE: number; + BCKSP: number; + ALT: number; + ALTR: number; + ALTRIGHT: number; + SPACE: number; + WIN: number; + MAC: number; + FN: number; + PG_UP: number; + PG_DOWN: number; + UP: number; + DOWN: number; + LEFT: number; + RIGHT: number; + ESC: number; + DEL: number; + F1: number; + F2: number; + F3: number; + F4: number; + F5: number; + F6: number; + F7: number; + F8: number; + F9: number; + F10: number; + F11: number; + F12: number; + }; + ASC: string; + DESC: string; + filter: { + STARTS_WITH: number; + ENDS_WITH: number; + EXACT: number; + CONTAINS: number; + GREATER_THAN: number; + GREATER_THAN_OR_EQUAL: number; + LESS_THAN: number; + LESS_THAN_OR_EQUAL: number; + NOT_EQUAL: number; + SELECT: string; + INPUT: string; + }; + scrollDirection: { + UP: string; + DOWN: string; + LEFT: string; + RIGHT: string; + NONE: string; + }, + aggregationTypes: { + sum: number; + count: number; + avg: number; + min: number; + max: number; + }; + CURRENCY_SYMBOLS: string[]; + dataChange: { + ALL: string; + EDIT: string; + ROW: string; + COLUMN: string; + OPTIONS: string; + } + scrollbars: { + NEVER: number; + ALWAYS: number; + //WHEN_NEEDED: number + } + + } + + export interface IGridInstance { appScope?: ng.IScope; columnFooterHeight?: number; @@ -67,7 +174,7 @@ declare module uiGrid { resetColumnSorting(excludedColumn: IGridColumn): void; scrollTo(rowEntity: any, colDef: IColumnDef): ng.IPromise; scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): ng.IPromise; - sortColumn(column: IGridColumn, direction?: number, add?: boolean): ng.IPromise; + sortColumn(column: IGridColumn, direction?: string, add?: boolean): ng.IPromise; updateCanvasHeight(): void; updateFooterHeightCallback(name: string): void; } @@ -94,6 +201,7 @@ declare module uiGrid { columnVirtualizationThreshold?: number; data?: Array | string; enableColumnMenus?: boolean; + enablePagiationControls?: boolean; enableFiltering?: boolean; enableHorizontalScrollbar?: boolean; enableMinHeightCheck?: boolean; @@ -118,7 +226,7 @@ declare module uiGrid { maxVisibleColumnCount?: number; minRowsToShow?: number; minimumColumnSize?: number; - onRegisterApi: (gridApi: IGridApi) => void; + onRegisterApi?: (gridApi: IGridApi) => void; rowHeight?: number; rowTemplate?: string; scrollDebounce?: number; @@ -134,13 +242,47 @@ declare module uiGrid { rowEquality?(entityA: IGridRow, entityB: IGridRow): boolean; rowIdentity? (): any; totalItems?: number; + paginationPageSize?: number; + } export interface IGridCoreApi { + addRowHeaderColumn(column: IColumnDef): void; + addToGridMenu(grid: IGridInstance, items: IMenuItem[]): void; + clearAllFilters(refreshRows?: boolean, clearConditions?: boolean, clearFlags?: boolean): ng.IPromise; + clearRowInvisible(rowEntity: IGridRow): void; + getVisibleRows(grid: IGridInstance): IGridRow[]; + handleWindowResize(): void; + notifiyDataChange(type): void; + refreshRows(): ng.IPromise; + registerColumnsProcessor(processorFunction: IColumnProcessor, priority: number): void; + registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; + removeFromGridMenu(grid: IGridInstance, id: string): void; + scrollTo(entity: any, colDef: IColumnDef): void; /*A row entity can be anything?*/ + scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): void; + setRowInvisible(rowEntity: IGridRow): void; + sortHandleNulls(a: any,b: any): number; + queueGridRefresh(): void; + queueRefresh(); on: { sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: IColumnDef[]) => void) => void; - columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; + columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; + canvasHeightChanged: (scope: ng.IScope, handler: (oldHeight: number, newHeight: number) => void) => void; + /* filterChangedis raised after the filter is changed. The nature of the watch expression doesn't allow notification + of what changed, so the receiver of this event will need to re-extract the filter conditions from the columns. + http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi*/ + filterChanged: (scope: ng.IScope, handler: () => void) => void; + rowsRendered: (scope: ng.IScope, handler: () => void) => void; + /* rowsVisibleChanged + is raised after the rows that are visible change. The filtering is zero-based, + so it isn't possible to say which rows changed (unlike in the selection feature). + We can plausibly know which row was changed when setRowInvisible is called, but in + that situation the user already knows which row they changed. + When a filter runs we don't know what changed, and that is the one that would have been useful. */ + rowsVisibleChanged: (scope: ng.IScope, handler: () => void) => void; + scrollBegin: (scope: ng.IScope, handler: () => void) => void; + scrollEnd: (scope: ng.IScope, handler: () => void) => void; } } @@ -173,6 +315,26 @@ declare module uiGrid { paginationChanged: (scope: ng.IScope, handler: (newPage: number, pageSize: number) => void) => void; } } + + export interface IGridRowEditApi { + flushDirtyRows(grid?: IGridInstance): ng.IPromise; + getDirtyRows(grid?: IGridInstance): IGridRow[]; + getErrorRows(grid?: IGridInstance): IGridRow[]; + /** + * NOTE: The items below expect the entities not the grid row instance + * http://ui-grid.info/docs/#/api/ui.grid.rowEdit.api:PublicApi + */ + setRowsClean(dataRows: any[]): any[]; + setRowsDirty(dataRows: any[]): any[]; + /** + * Sets the promise associated with the row save, + * mandatory that the saveRow event handler calls this method somewhere before returning. + */ + setSavePromise(rowEntity: any, saveProvies: ng.IPromise): void; + on: { + saveRow: (scope: ng.IScope, handler: (rowEntity: any) => void) => void + } + } export interface IGridApiConstructor { new (grid: IGridInstance): IGridApi; @@ -234,8 +396,7 @@ declare module uiGrid { /** * Selection api - */ - + */ selection: IGridSelectionApi; @@ -243,9 +404,17 @@ declare module uiGrid { * Pagination api */ pagination: IGridPaginationApi; - - - + + + /** + * Grid Row Edit Api + */ + rowEdit: IGridRowEditApi; + + /** + * A grid instance is made available in the gridApi. + */ + grid: IGridInstance; } export interface IGridRowConstructor { /** @@ -390,6 +559,8 @@ declare module uiGrid { /** Filters for this column. Includes 'term' property bound to filter input elements */ filters?: Array; name?: string; + /** Sort on this column */ + sort?: ISortInfo /** Algorithm to use for sorting this column. Takes 'a' and 'b' parameters like any normal sorting function. */ sortingAlgorithm?: (a: any, b: any) => number; /** From 02aea2857af62399bf1f8b48ef24fc39864399aa Mon Sep 17 00:00:00 2001 From: zenorbi Date: Tue, 21 Jul 2015 19:58:02 +0200 Subject: [PATCH 097/881] Nodemailer subject typo --- nodemailer/nodemailer-types.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nodemailer/nodemailer-types.d.ts b/nodemailer/nodemailer-types.d.ts index bffa6b301..fa11ac0e2 100644 --- a/nodemailer/nodemailer-types.d.ts +++ b/nodemailer/nodemailer-types.d.ts @@ -74,7 +74,7 @@ declare module nodemailer { /** * The subject of the e-mail */ - sbject?: string; + subject?: string; /** * The plaintext version of the message as an Unicode string, Buffer, Stream or an object {path: '...'} */ From 5ea2c74b9d84e1905e66ae3e5c2c9e1693224c7a Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 Jul 2015 17:14:21 -0400 Subject: [PATCH 098/881] fixing missing ";" --- ui-grid/ui-grid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 7e5305046..30a2b2037 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -94,7 +94,7 @@ declare module uiGrid { LEFT: string; RIGHT: string; NONE: string; - }, + }; aggregationTypes: { sum: number; count: number; From 67fdc1b0407a7d76a3662a9d01338eb3fdf18368 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 Jul 2015 17:25:32 -0400 Subject: [PATCH 099/881] fixing comments, line breaks, and typos, fixing T[] -> Array --- ui-grid/ui-grid-tests.ts | 8 +++--- ui-grid/ui-grid.d.ts | 54 ++++++++++++++++++---------------------- 2 files changed, 28 insertions(+), 34 deletions(-) diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 065bb1a52..151d0436f 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -87,16 +87,16 @@ columnDef.width = 100; columnDef.width = '*'; -var gridInstance: uiGrid.IGridInstance; -var menuItem: uiGrid.IMenuItem - var gridApi: uiGrid.IGridApi +var gridInstance: uiGrid.IGridInstance; +var menuItem: uiGrid.IMenuItem; +var colProcessor: uiGrid.IColumnProcessor; + gridApi.core.clearAllFilters(true); gridApi.core.addToGridMenu(gridInstance, [menuItem]); gridApi.core.getVisibleRows(gridInstance); gridApi.core.handleWindowResize(); gridApi.core.queueGridRefresh() gridApi.core.queueRefresh(); -var colProcessor: uiGrid.IColumnProcessor; gridApi.core.registerColumnsProcessor(colProcessor, 100); diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 30a2b2037..42f8e7e0f 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -102,7 +102,7 @@ declare module uiGrid { min: number; max: number; }; - CURRENCY_SYMBOLS: string[]; + CURRENCY_SYMBOLS: Array; dataChange: { ALL: string; EDIT: string; @@ -112,10 +112,8 @@ declare module uiGrid { } scrollbars: { NEVER: number; - ALWAYS: number; - //WHEN_NEEDED: number + ALWAYS: number; } - } @@ -242,17 +240,16 @@ declare module uiGrid { rowEquality?(entityA: IGridRow, entityB: IGridRow): boolean; rowIdentity? (): any; totalItems?: number; - paginationPageSize?: number; - + paginationPageSize?: number; + paginationCurrentPage?: number; } - export interface IGridCoreApi { addRowHeaderColumn(column: IColumnDef): void; - addToGridMenu(grid: IGridInstance, items: IMenuItem[]): void; - clearAllFilters(refreshRows?: boolean, clearConditions?: boolean, clearFlags?: boolean): ng.IPromise; + addToGridMenu(grid: IGridInstance, items: Array): void; + clearAllFilters(refreshRows?: boolean, clearConditions?: boolean, clearFlags?: boolean): ng.IPromise>; clearRowInvisible(rowEntity: IGridRow): void; - getVisibleRows(grid: IGridInstance): IGridRow[]; + getVisibleRows(grid: IGridInstance): Array; handleWindowResize(): void; notifiyDataChange(type): void; refreshRows(): ng.IPromise; @@ -266,20 +263,17 @@ declare module uiGrid { queueGridRefresh(): void; queueRefresh(); on: { - sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: IColumnDef[]) => void) => void; + sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: Array) => void) => void; columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; canvasHeightChanged: (scope: ng.IScope, handler: (oldHeight: number, newHeight: number) => void) => void; - /* filterChangedis raised after the filter is changed. The nature of the watch expression doesn't allow notification - of what changed, so the receiver of this event will need to re-extract the filter conditions from the columns. - http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi*/ + + /** + * filterChangedis raised after the filter is changed. The nature of the watch expression doesn't allow notification + * of what changed, so the receiver of this event will need to re-extract the filter conditions from the columns. + * http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi + */ filterChanged: (scope: ng.IScope, handler: () => void) => void; - rowsRendered: (scope: ng.IScope, handler: () => void) => void; - /* rowsVisibleChanged - is raised after the rows that are visible change. The filtering is zero-based, - so it isn't possible to say which rows changed (unlike in the selection feature). - We can plausibly know which row was changed when setRowInvisible is called, but in - that situation the user already knows which row they changed. - When a filter runs we don't know what changed, and that is the one that would have been useful. */ + rowsRendered: (scope: ng.IScope, handler: () => void) => void; rowsVisibleChanged: (scope: ng.IScope, handler: () => void) => void; scrollBegin: (scope: ng.IScope, handler: () => void) => void; scrollEnd: (scope: ng.IScope, handler: () => void) => void; @@ -294,14 +288,14 @@ declare module uiGrid { selectAllRows: (event?: Event) => void; selectAllVisibleRows: (event?: Event) => void; clearSelectedRows: (event?: Event) => void; - getSelectedRows: () => IGridRow[]; - getSelectedGridRows: () => IGridRow[]; + getSelectedRows: () => Array; + getSelectedGridRows: () => Array; setMultiSelect: (multiSelect: boolean) => void; setModifierKeysToMultiSelect: (multiSelect: boolean) => void; getSelectAllState: () => boolean; on: { rowSelectionChanged: (scope: ng.IScope, handler: (row: IGridRow, event?: Event) => void) => void; - rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: IGridRow[], event?: Event) => void) => void; + rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: Array, event?: Event) => void) => void; } } @@ -318,21 +312,21 @@ declare module uiGrid { export interface IGridRowEditApi { flushDirtyRows(grid?: IGridInstance): ng.IPromise; - getDirtyRows(grid?: IGridInstance): IGridRow[]; - getErrorRows(grid?: IGridInstance): IGridRow[]; + getDirtyRows(grid?: IGridInstance): Array; + getErrorRows(grid?: IGridInstance): Array; /** * NOTE: The items below expect the entities not the grid row instance * http://ui-grid.info/docs/#/api/ui.grid.rowEdit.api:PublicApi */ - setRowsClean(dataRows: any[]): any[]; - setRowsDirty(dataRows: any[]): any[]; + setRowsClean(dataRows: Array): Array; + setRowsDirty(dataRows: Array): Array; /** * Sets the promise associated with the row save, * mandatory that the saveRow event handler calls this method somewhere before returning. */ - setSavePromise(rowEntity: any, saveProvies: ng.IPromise): void; + setSavePromise(rowEntity: Object, savePromise: ng.IPromise): void; on: { - saveRow: (scope: ng.IScope, handler: (rowEntity: any) => void) => void + saveRow: (scope: ng.IScope, handler: (rowEntity: Array) => void) => void } } From 21c47b36e25eaf1601781d866e23c70b2f0f26cf Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 Jul 2015 17:29:23 -0400 Subject: [PATCH 100/881] fixing missing return types. thanks Travis! --- ui-grid/ui-grid-tests.ts | 2 +- ui-grid/ui-grid.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ui-grid/ui-grid-tests.ts b/ui-grid/ui-grid-tests.ts index 151d0436f..21d42c021 100644 --- a/ui-grid/ui-grid-tests.ts +++ b/ui-grid/ui-grid-tests.ts @@ -87,7 +87,7 @@ columnDef.width = 100; columnDef.width = '*'; -var gridApi: uiGrid.IGridApi +var gridApi: uiGrid.IGridApi; var gridInstance: uiGrid.IGridInstance; var menuItem: uiGrid.IMenuItem; var colProcessor: uiGrid.IColumnProcessor; diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 42f8e7e0f..50b1033b0 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -251,7 +251,7 @@ declare module uiGrid { clearRowInvisible(rowEntity: IGridRow): void; getVisibleRows(grid: IGridInstance): Array; handleWindowResize(): void; - notifiyDataChange(type): void; + notifiyDataChange(type: string): void; refreshRows(): ng.IPromise; registerColumnsProcessor(processorFunction: IColumnProcessor, priority: number): void; registerRowsProcessor(rowProcessor: IRowProcessor, priority: number): void; @@ -261,7 +261,7 @@ declare module uiGrid { setRowInvisible(rowEntity: IGridRow): void; sortHandleNulls(a: any,b: any): number; queueGridRefresh(): void; - queueRefresh(); + queueRefresh(): void; on: { sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: Array) => void) => void; columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; From 8b706fb1c66c6e0a5a283f9b2b3f444f48b616b7 Mon Sep 17 00:00:00 2001 From: Salehen Shovon Rahman Date: Tue, 21 Jul 2015 15:09:23 -0700 Subject: [PATCH 101/881] Added slice to Backbone.Collection Without it, TypeScript throws a type error, stating that `Collection` does not have a method called `slice`. --- backbone/backbone.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index 275dba237..132db865c 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -247,6 +247,7 @@ declare module Backbone { select(iterator: any, context?: any): any[]; size(): number; shuffle(): any[]; + slice(min: number, max?: number): TModel[]; some(iterator: (element: TModel, index: number) => boolean, context?: any): boolean; sortBy(iterator: (element: TModel, index: number) => number, context?: any): TModel[]; sortBy(attribute: string, context?: any): TModel[]; From d268fbc77a951ec4521b396ce491cf99816fb156 Mon Sep 17 00:00:00 2001 From: Zoe Tsai Date: Tue, 21 Jul 2015 15:16:13 -0700 Subject: [PATCH 102/881] update d3.d.ts --- d3/d3.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index b3fed8327..6e453084f 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -74,9 +74,9 @@ declare module d3 { * Derive an attribute value for each node in the selection based on bound data. * * @param name The attribute name, optionally prefixed. - * @param value The function of the datum (the bound data item) and index (the position in the subgrouping) which computes the attribute value. If the function returns null, the attribute is removed. + * @param value The function of the datum (the bound data item), and inner index (overall position in nested selections) which computes the attribute value. If the function returns null, the attribute is removed. */ - attr(name: string, value: (datum: Datum, index: number) => Primitive): Update; + attr(name: string, value: (datum: Datum, index: number, innerIndex?: number) => Primitive): Update; /** * Set multiple properties at once using an Object. D3 iterates over all enumerable properties and either sets or computes the attribute's value based on the corresponding entry in the Object. From addd4957b03ccb3b4e6c68d241ddcc7bc9b4de61 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Tue, 21 Jul 2015 15:30:27 -0700 Subject: [PATCH 103/881] updated angular-odata-resources definitions to have support count and inlinecount --- .../angular-odata-resources-tests.ts | 12 +++++++++++- angular-odata-resources/angular-odata-resources.d.ts | 7 +++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/angular-odata-resources/angular-odata-resources-tests.ts b/angular-odata-resources/angular-odata-resources-tests.ts index 0149533fa..5b8dbcc52 100644 --- a/angular-odata-resources/angular-odata-resources-tests.ts +++ b/angular-odata-resources/angular-odata-resources-tests.ts @@ -186,4 +186,14 @@ var combination2 = Predicate.and([combination1, predicate2]); var predicate = new Predicate("FirstName", "John") .or(new Predicate("LastName", '!=', "Doe")) - .and(new Predicate("Age", '>', 10)); \ No newline at end of file + .and(new Predicate("Age", '>', 10)); + + +users = odataResourceClass.odata() + .withInlineCount() + .query(); + + +var countResult = odataResourceClass.odata().count(); +var total = countResult.result; + diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index 87b89687f..06cabdd3b 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -264,6 +264,11 @@ declare module OData { (queryString: string, success: () => any, error: () => any): T[]; (queryString: string, success: () => any, error: () => any, isSingleElement?: boolean, forceSingleElement?: boolean): T; } + + interface ICountResult{ + result: number; + } + class Provider { private callback; private filters; @@ -281,6 +286,8 @@ declare module OData { single(success?: any, error?: any): T; get(data: any, success?: any, error?: any): T; expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider; + count(success?: (result: ICountResult) => any, error?: () => any); + withInlineCount(); } interface ValueFactory { From 5937bdd91a0f45a6d4c2f8a5692990fbce573764 Mon Sep 17 00:00:00 2001 From: basarat Date: Wed, 22 Jul 2015 10:07:55 +1000 Subject: [PATCH 104/881] feat(node) _debugger API --- _debugger/_debugger-tests.ts | 10 +++ _debugger/_debugger.d.ts | 135 +++++++++++++++++++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 _debugger/_debugger-tests.ts create mode 100644 _debugger/_debugger.d.ts diff --git a/_debugger/_debugger-tests.ts b/_debugger/_debugger-tests.ts new file mode 100644 index 000000000..e6d7cf998 --- /dev/null +++ b/_debugger/_debugger-tests.ts @@ -0,0 +1,10 @@ +/// +import _debugger = require("_debugger"); +var {Client} = _debugger; + +var client = new Client(); + +client.connect(8888, 'localhost'); +client.listbreakpoints((err, res) => { + +}); diff --git a/_debugger/_debugger.d.ts b/_debugger/_debugger.d.ts new file mode 100644 index 000000000..15ed8bfcf --- /dev/null +++ b/_debugger/_debugger.d.ts @@ -0,0 +1,135 @@ +// Type definitions for Node.js debugger API +// Project: http://nodejs.org/ +// Definitions by: Basarat Ali Syed +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module NodeJS { + export module _debugger { + export interface Packet { + raw: string; + headers: string[]; + body: Message; + } + + export interface Message { + seq: number; + type: string; + } + + export interface RequestInfo { + command: string; + arguments: any; + } + + export interface Request extends Message, RequestInfo { + } + + export interface Event extends Message { + event: string; + body?: any; + } + + export interface Response extends Message { + request_seq: number; + success: boolean; + /** Contains error message if success === false. */ + message?: string; + /** Contains message body if success === true. */ + body?: any; + } + + export interface BreakpointMessageBody { + type: string; + target: number; + line: number; + } + + export class Protocol { + res: Packet; + state: string; + execute(data: string): void; + serialize(rq: Request): string; + onResponse: (pkt: Packet) => void; + } + + export var NO_FRAME: number; + export var port: number; + + export interface ScriptDesc { + name: string; + id: number; + isNative?: boolean; + handle?: number; + type: string; + lineOffset?: number; + columnOffset?: number; + lineCount?: number; + } + + export interface Breakpoint { + id: number; + scriptId: number; + script: ScriptDesc; + line: number; + condition?: string; + scriptReq?: string; + } + + export interface RequestHandler { + (err: boolean, body: Message, res: Packet): void; + request_seq?: number; + } + + export interface ResponseBodyHandler { + (err: boolean, body?: any): void; + request_seq?: number; + } + + export interface ExceptionInfo { + text: string; + } + + export interface BreakResponse { + script?: ScriptDesc; + exception?: ExceptionInfo; + sourceLine: number; + sourceLineText: string; + sourceColumn: number; + } + + export function SourceInfo(body: BreakResponse): string; + + export interface ClientInstance extends EventEmitter { + protocol: Protocol; + scripts: ScriptDesc[]; + handles: ScriptDesc[]; + breakpoints: Breakpoint[]; + currentSourceLine: number; + currentSourceColumn: number; + currentSourceLineText: string; + currentFrame: number; + currentScript: string; + + connect(port: number, host: string): void; + req(req: any, cb: RequestHandler): void; + reqFrameEval(code: string, frame: number, cb: RequestHandler): void; + mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void; + setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void; + clearBreakpoint(rq: Request, cb: RequestHandler): void; + listbreakpoints(cb: RequestHandler): void; + reqSource(from: number, to: number, cb: RequestHandler): void; + reqScripts(cb: any): void; + reqContinue(cb: RequestHandler): void; + } + + export var Client : { + new (): ClientInstance + } + } +} + +declare module "_debugger"{ + export = NodeJS._debugger; +} From cc42d530f8f3319f2cf76f49bd80cbb32bcb2729 Mon Sep 17 00:00:00 2001 From: Xiaohan Zhang Date: Tue, 21 Jul 2015 21:36:09 -0700 Subject: [PATCH 105/881] add preprocessors to plugins --- less/less-tests.ts | 24 ++++++++++++++++++++++++ less/less.d.ts | 18 ++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/less/less-tests.ts b/less/less-tests.ts index 589250d0b..b6326b4a4 100644 --- a/less/less-tests.ts +++ b/less/less-tests.ts @@ -11,3 +11,27 @@ less.render("fail").then((output) => { }, (error: Less.RenderError) => { console.log("rejected as expected on line number " + error.line); }); + +var preProcessor: Less.PreProcessor = { + process: (src, extra) => { + console.log(extra.imports, extra.context); + if (extra.fileInfo.filename === "foo.less") { + return ".other-rule { width: (1 + 1); }\n " + src; + } else { + return src; + } + } +}; + +var myPlugin: Less.Plugin = { + install: (less, pluginManager) => { + alert(less.version[2]); + pluginManager.addPreProcessor(preProcessor, 1000); + } +}; + +var options: Less.Options = { + plugins: [myPlugin] +}; + +less.render("h1 { background: red; }", options); diff --git a/less/less.d.ts b/less/less.d.ts index f329dd48e..c8a83fbc8 100644 --- a/less/less.d.ts +++ b/less/less.d.ts @@ -30,12 +30,30 @@ declare module Less { class PluginManager { constructor(less: LessStatic); + + addPreProcessor(preProcessor: PreProcessor, priority?: number): void; } interface Plugin { install: (less: LessStatic, pluginManager: PluginManager) => void; } + interface PreProcessor { + process: (src: string, extra: PreProcessorExtraInfo) => string; + } + + interface PreProcessorExtraInfo { + context: { + pluginManager: PluginManager; + }; + + fileInfo: RootFileInfo; + + imports: { + [key: string]: any; + }; + } + interface SourceMapOption { sourceMapURL: string; sourceMapBasepath: string; From 2c389556cc5e54c82e641120a7af153fa5be5427 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Wed, 22 Jul 2015 10:36:59 +0200 Subject: [PATCH 106/881] angular.js bugfix - interface ILogProvider extends IServiceProvider (missing .$get method) There is a [`$logProvider`](https://docs.angularjs.org/api/ng/provider/$logProvider) in angular, here are the relevant source lines: https://github.com/angular/angular.js/blob/master/src/ng/log.js#L47-L67. It contains `.$get` method. in Denifitely Typed, there is only: ``` interface ILogProvider { debugEnabled(): boolean; debugEnabled(enabled: boolean): ILogProvider; } ``` (https://github.com/borisyankov/DefinitelyTyped/blob/master/angularjs/angular.d.ts#L865-L868). Note, there is no `.$get` method. THe interface should have extended ``IServiceProvider , i.e. `interface ILogProvider extends IServiceProvider`. --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 018ecbaaf..746fbb0e0 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -862,7 +862,7 @@ declare module angular { warn: ILogCall; } - interface ILogProvider { + interface ILogProvider extends IServiceProvider { debugEnabled(): boolean; debugEnabled(enabled: boolean): ILogProvider; } From b8ef7d0efdd17bc938206f9365d6726779ebe785 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Castre?= Date: Wed, 22 Jul 2015 12:00:15 +0200 Subject: [PATCH 107/881] Updating durandal.d.ts Using union type for route, Add missing parent property (only present if the current router is a child router) Fix queryParams type Fix guardRoute return type cleanup mixed tab/spaces --- durandal/durandal.d.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 8250a3325..86f988cbe 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -295,7 +295,7 @@ interface DurandalViewEngineModule { * @param {string} id The view id whose view should be cached. * @param {DOMElement} view The view to cache. */ - putViewInCache(id:string, view:HTMLElement); + putViewInCache(id: string, view: HTMLElement); /** * Creates the view associated with the view id. @@ -1107,7 +1107,7 @@ declare module 'plugins/serializer' { * @param {object} [settings] Settings can specify any of the options allowed by the serialize or deserialize methods. * @return {object} The new clone. */ - export function clone(obj:T, settings?:Object): T; + export function clone(obj: T, settings?: Object): T; } /** @@ -1262,8 +1262,8 @@ interface DurandalEventModule { } interface DialogButton { - text: string; - value: any; + text: string; + value: any; } interface DurandalAppModule extends DurandalEventSupport { @@ -1509,13 +1509,12 @@ interface DurandalRouteConfiguration { title?: any; moduleId?: string; hash?: string; - /** string or string[] */ - route?: any; + route?: string|string[]; routePattern?: RegExp; isActive?: KnockoutComputed; nav?: any; hasChildRoutes?: boolean; - viewUrl?:string; + viewUrl?: string; } interface DurandalRouteInstruction { @@ -1523,7 +1522,7 @@ interface DurandalRouteInstruction { queryString: string; config: DurandalRouteConfiguration; params: any[]; - queryParams: Object; + queryParams: { [index: string]: any }; } interface DurandalRelativeRouteSettings { @@ -1766,7 +1765,12 @@ interface DurandalRouterBase extends DurandalEventSupport { * @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties. * @returns {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types. */ - guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => any; + guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => JQueryPromise|boolean|string; + + /** + * Parent router of the current child router. + */ + parent?: DurandalRouter; } interface DurandalRouter extends DurandalRouterBase { } @@ -1792,4 +1796,4 @@ interface DurandalRootRouter extends DurandalRouterBase { * Installs the router's custom ko binding handler. */ install(): void; -} \ No newline at end of file +} From da27def5624cdf4768c4595effb529f715a4ae91 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 22 Jul 2015 15:27:43 +0100 Subject: [PATCH 108/881] Add lodash types for chainable contains/include/includes --- lodash/lodash-tests.ts | 15 ++++++++++++ lodash/lodash.d.ts | 53 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9b4548502..f61ba1573 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -370,16 +370,31 @@ result = _.contains([1, 2, 3], 1, 2); result = _.contains({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.contains('curly', 'ur'); +result = _([1, 2, 3]).contains(1); +result = _([1, 2, 3]).contains(1, 2); +result = _({ 'moe': 30, 'larry': 40, 'curly': 67 }).contains(40); +result = _('curly').contains('ur'); + result = _.include([1, 2, 3], 1); result = _.include([1, 2, 3], 1, 2); result = _.include({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.include('curly', 'ur'); +result = _([1, 2, 3]).include(1); +result = _([1, 2, 3]).include(1, 2); +result = _({ 'moe': 30, 'larry': 40, 'curly': 67 }).include(40); +result = _('curly').include('ur'); + result = _.includes([1, 2, 3], 1); result = _.includes([1, 2, 3], 1, 2); result = _.includes({ 'moe': 30, 'larry': 40, 'curly': 67 }, 40); result = _.includes('curly', 'ur'); +result = _([1, 2, 3]).includes(1); +result = _([1, 2, 3]).includes(1, 2); +result = _({ 'moe': 30, 'larry': 40, 'curly': 67 }).includes(40); +result = _('curly').includes('ur'); + result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return Math.floor(num); }); result = <_.Dictionary>_.countBy([4.3, 6.1, 6.4], function (num) { return this.floor(num); }, Math); result = <_.Dictionary>_.countBy(['one', 'two', 'three'], 'length'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f02a4aa97..d2e83e111 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -39,7 +39,7 @@ declare module _ { * Explicit chaining can be enabled by using the _.chain method. **/ (value: number): LoDashWrapper; - (value: string): LoDashWrapper; + (value: string): LoDashStringWrapper; (value: boolean): LoDashWrapper; (value: Array): LoDashNumberArrayWrapper; (value: Array): LoDashArrayWrapper; @@ -2149,6 +2149,57 @@ declare module _ { fromIndex?: number): boolean; } + interface LoDashArrayWrapper { + /** + * @see _.contains + **/ + contains(target: T, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + include(target: T, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes(target: T, fromIndex?: number): boolean; + } + + interface LoDashObjectWrapper { + /** + * @see _.contains + **/ + contains(target: any, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + include(target: any, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes(target: any, fromIndex?: number): boolean; + } + + interface LoDashStringWrapper extends LoDashWrapper { + /** + * @see _.contains + **/ + contains(target: string, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + include(target: string, fromIndex?: number): boolean; + + /** + * @see _.contains + **/ + includes(target: string, fromIndex?: number): boolean; + } + //_.countBy interface LoDashStatic { /** From a9a55446fc4f5641b9f0c30c439ffbca9fdc0032 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 22 Jul 2015 15:32:15 +0100 Subject: [PATCH 109/881] Make lodash object _().contains type clearer (no any) --- lodash/lodash.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index d2e83e111..d116a2514 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -2170,17 +2170,17 @@ declare module _ { /** * @see _.contains **/ - contains(target: any, fromIndex?: number): boolean; + contains(target: TValue, fromIndex?: number): boolean; /** * @see _.contains **/ - include(target: any, fromIndex?: number): boolean; + include(target: TValue, fromIndex?: number): boolean; /** * @see _.contains **/ - includes(target: any, fromIndex?: number): boolean; + includes(target: TValue, fromIndex?: number): boolean; } interface LoDashStringWrapper extends LoDashWrapper { From 72a6d57c065e9c6f64b187634be4ff6d9d8cffdf Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 Jul 2015 11:21:01 -0400 Subject: [PATCH 110/881] make entities 'any' and remove extra spaces. --- ui-grid/ui-grid.d.ts | 30 ++++++++---------------------- 1 file changed, 8 insertions(+), 22 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 50b1033b0..15c65e50d 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -115,8 +115,6 @@ declare module uiGrid { ALWAYS: number; } } - - export interface IGridInstance { appScope?: ng.IScope; columnFooterHeight?: number; @@ -170,7 +168,7 @@ declare module uiGrid { registerStyleComputation(styleComputation: ($scope: ng.IScope) => string): void; removeRowsProcessor(rows: IRowProcessor): void; resetColumnSorting(excludedColumn: IGridColumn): void; - scrollTo(rowEntity: any, colDef: IColumnDef): ng.IPromise; + scrollTo(rowEntity: IGridRow, colDef: IColumnDef): ng.IPromise; scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): ng.IPromise; sortColumn(column: IGridColumn, direction?: string, add?: boolean): ng.IPromise; updateCanvasHeight(): void; @@ -243,12 +241,11 @@ declare module uiGrid { paginationPageSize?: number; paginationCurrentPage?: number; } - export interface IGridCoreApi { addRowHeaderColumn(column: IColumnDef): void; addToGridMenu(grid: IGridInstance, items: Array): void; clearAllFilters(refreshRows?: boolean, clearConditions?: boolean, clearFlags?: boolean): ng.IPromise>; - clearRowInvisible(rowEntity: IGridRow): void; + clearRowInvisible(rowEntity: any): void; getVisibleRows(grid: IGridInstance): Array; handleWindowResize(): void; notifiyDataChange(type: string): void; @@ -258,7 +255,7 @@ declare module uiGrid { removeFromGridMenu(grid: IGridInstance, id: string): void; scrollTo(entity: any, colDef: IColumnDef): void; /*A row entity can be anything?*/ scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): void; - setRowInvisible(rowEntity: IGridRow): void; + setRowInvisible(rowEntity: any): void; sortHandleNulls(a: any,b: any): number; queueGridRefresh(): void; queueRefresh(): void; @@ -279,7 +276,6 @@ declare module uiGrid { scrollEnd: (scope: ng.IScope, handler: () => void) => void; } } - export interface IGridSelectionApi { toggleRowSelection: (rowEntity: IGridRow, event?: Event) => void; selectRow: (rowEntity: IGridRow, event?: Event) => void; @@ -298,7 +294,6 @@ declare module uiGrid { rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: Array, event?: Event) => void) => void; } } - export interface IGridPaginationApi { getPage: () => number; getTotalPages: () => number; @@ -308,25 +303,16 @@ declare module uiGrid { on: { paginationChanged: (scope: ng.IScope, handler: (newPage: number, pageSize: number) => void) => void; } - } - + } export interface IGridRowEditApi { flushDirtyRows(grid?: IGridInstance): ng.IPromise; getDirtyRows(grid?: IGridInstance): Array; - getErrorRows(grid?: IGridInstance): Array; - /** - * NOTE: The items below expect the entities not the grid row instance - * http://ui-grid.info/docs/#/api/ui.grid.rowEdit.api:PublicApi - */ - setRowsClean(dataRows: Array): Array; - setRowsDirty(dataRows: Array): Array; - /** - * Sets the promise associated with the row save, - * mandatory that the saveRow event handler calls this method somewhere before returning. - */ + getErrorRows(grid?: IGridInstance): Array; + setRowsClean(dataRows: Array): Array; + setRowsDirty(dataRows: Array): Array; setSavePromise(rowEntity: Object, savePromise: ng.IPromise): void; on: { - saveRow: (scope: ng.IScope, handler: (rowEntity: Array) => void) => void + saveRow: (scope: ng.IScope, handler: (rowEntity: Array) => void) => void } } From d82912b20963d6cbc37511b8ad615499378a116c Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Wed, 22 Jul 2015 09:38:53 -0600 Subject: [PATCH 111/881] Added additional type information to the `calls` object for Jasmine Spies --- jasmine/jasmine.d.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/jasmine/jasmine.d.ts b/jasmine/jasmine.d.ts index bcbf986a1..581353b34 100644 --- a/jasmine/jasmine.d.ts +++ b/jasmine/jasmine.d.ts @@ -442,14 +442,21 @@ declare module jasmine { /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ allArgs(): any[]; /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ - all(): any; + all(): CallInfo[]; /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ - mostRecent(): any; + mostRecent(): CallInfo; /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ - first(): any; + first(): CallInfo; /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ reset(): void; } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + } interface Util { inherit(childClass: Function, parentClass: Function): any; From 2051e7754bb83505e9c02997cdcbb33e960781a5 Mon Sep 17 00:00:00 2001 From: arueckle Date: Wed, 22 Jul 2015 17:59:57 +0200 Subject: [PATCH 112/881] fixing types of underscore pick function --- underscore/underscore.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 2b3818c3e..31e59bc63 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -2162,8 +2162,8 @@ interface Underscore { * Wrapped type `object`. * @see _.pick **/ - pick(...keys: string[]): any; - pick(keys: string[]): any; + pick(...keys: any[]): any; + pick(keys: any[]): any; pick(fn: (value: any, key: any, object: any) => any): any; /** @@ -3019,8 +3019,8 @@ interface _Chain { * Wrapped type `object`. * @see _.pick **/ - pick(...keys: string[]): _Chain; - pick(keys: string[]): _Chain; + pick(...keys: any[]): _Chain; + pick(keys: any[]): _Chain; pick(fn: (value: any, key: any, object: any) => any): _Chain; /** From bb4217796ddb9d75778786607176efb1d468c513 Mon Sep 17 00:00:00 2001 From: Raphael ATALLAH Date: Wed, 22 Jul 2015 09:42:57 -0700 Subject: [PATCH 113/881] updated count return type from any to ICountResult --- angular-odata-resources/angular-odata-resources.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-odata-resources/angular-odata-resources.d.ts b/angular-odata-resources/angular-odata-resources.d.ts index 06cabdd3b..0a83df2c3 100644 --- a/angular-odata-resources/angular-odata-resources.d.ts +++ b/angular-odata-resources/angular-odata-resources.d.ts @@ -286,8 +286,8 @@ declare module OData { single(success?: any, error?: any): T; get(data: any, success?: any, error?: any): T; expand(params: any, otherParam1?: any, otherParam2?: any, otherParam3?: any, otherParam4?: any, otherParam5?: any, otherParam6?: any, otherParam7?: any): Provider; - count(success?: (result: ICountResult) => any, error?: () => any); - withInlineCount(); + count(success?: (result: ICountResult) => any, error?: () => any):ICountResult; + withInlineCount(): Provider; } interface ValueFactory { From 1f7273c7fb1cc494b2a077b56117b2cc8eb3652e Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 21 Jul 2015 22:32:00 +0500 Subject: [PATCH 114/881] lodash: added _.ceil() method --- lodash/lodash-tests.ts | 14 ++++++++++++++ lodash/lodash.d.ts | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 03253f463..627dda565 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -506,6 +506,20 @@ result = _([1, 2, 3]).collect(function (num) { return num * 3; }).valu result = _({ 'one': 1, 'two': 2, 'three': 3 }).collect(function (num: number) { return num * 3; }).value(); result = _(stoogesAges).collect('name').value(); +// _.ceil +result = _.ceil(4.006); +// → 5 +result = _.ceil(6.004, 2); +// → 6.01 +result = _.ceil(6040, -2); +// → 6100 +result = _(4.006).ceil(); +// → 5 +result = _(6.004).ceil(2); +// → 6.01 +result = _(6040).ceil(-2); +// → 6100 + result = _.max([4, 2, 8, 6]); result = _.max(stoogesAges, function (stooge) { return stooge.age; }); result = _.max(stoogesAges, 'age'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 0cbdd9f4f..7bc1df648 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -3554,6 +3554,24 @@ declare module _ { thisArg?: any): LoDashArrayWrapper; } + //_.ceil + interface LoDashStatic { + /** + * Calculates n rounded up to precision. + * @param n The number to round up. + * @param precision The precision to round up to. + * @return Returns the rounded up number. + */ + ceil(n: number, precision?: number): number; + } + + interface LoDashWrapper { + /** + * @see _.ceil + */ + ceil(precision?: number): number; + } + //_.max interface LoDashStatic { /** From a259303c854dab194d0c6ae6ceba27cc5a2e493e Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Wed, 22 Jul 2015 17:00:48 -0400 Subject: [PATCH 115/881] Adds _.sortByAll and _.sortByOrder --- lodash/lodash-tests.ts | 14 +++++ lodash/lodash.d.ts | 138 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 147 insertions(+), 5 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 9b4548502..6eec6e259 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -639,6 +639,20 @@ result = _.sortBy([1, 2, 3], function (num) { return Math.sin(num); }) result = _.sortBy([1, 2, 3], function (num) { return this.sin(num); }, Math); result = _.sortBy(['banana', 'strawberry', 'apple'], 'length'); +result = _.sortByAll(stoogesAges, function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }); +result = _.sortByAll(stoogesAges, ['name', 'age']); +result = _.sortByAll(stoogesAges, 'name', function(stooge) { return Math.sin(stooge.age); }); + +result = _.sortByOrder(stoogesAges, [function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }]); +result = _.sortByOrder(stoogesAges, ['name', 'age']); +result = _.sortByOrder(stoogesAges, ['name', function(stooge) { return Math.sin(stooge.age); }]); +result = _.sortByOrder(stoogesAges, [function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }], ['asc', 'desc']); +result = _.sortByOrder(stoogesAges, ['name', 'age'], ['asc', 'desc']); +result = _.sortByOrder(stoogesAges, ['name', function(stooge) { return Math.sin(stooge.age); }], ['asc', 'desc']); +result = _.sortByOrder(stoogesAges, [function(stooge) { return Math.sin(stooge.age); }, function(stooge) { return stooge.name.slice(1); }], [true, false]); +result = _.sortByOrder(stoogesAges, ['name', 'age'], [true, false]); +result = _.sortByOrder(stoogesAges, ['name', function(stooge) { return Math.sin(stooge.age); }], [true, false]); + result = _([1, 2, 3]).sortBy(function (num) { return Math.sin(num); }).value(); result = _([1, 2, 3]).sortBy(function (num) { return this.sin(num); }, Math).value(); result = _(['banana', 'strawberry', 'apple']).sortBy('length').value(); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index f02a4aa97..865ff280d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -4711,8 +4711,11 @@ declare module _ { * * 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 + * + * 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 an iteratee the created "_.matches" style callback returns * true for elements that have the properties of the given object, else false. * @param collection The collection to iterate over. * @param callback The function called per iteration. @@ -4721,7 +4724,7 @@ declare module _ { **/ sortBy( collection: Array, - callback?: ListIterator, + iteratee?: ListIterator, thisArg?: any): T[]; /** @@ -4729,7 +4732,7 @@ declare module _ { **/ sortBy( collection: List, - callback?: ListIterator, + iteratee?: ListIterator, thisArg?: any): T[]; /** @@ -4770,7 +4773,7 @@ declare module _ { * @see _.sortBy **/ sortBy( - callback?: ListIterator, + iteratee?: ListIterator, thisArg?: any): LoDashArrayWrapper; /** @@ -4786,6 +4789,131 @@ declare module _ { sortBy(whereValue: W): LoDashArrayWrapper; } + //_.sortByAll + interface LoDashStatic { + /** + * This method is like "_.sortBy" except that it can sort by multiple iteratees or + * property names. + * + * If a property name is provided for an 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 an iteratee the created "_.matches" style callback returns + * true for elements that have the properties of the given object, else false. + * + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @param thisArg The this binding of callback. + * @return A new array of sorted elements. + **/ + sortByAll( + collection: Array, + iteratees: (ListIterator|string|Object)[]): T[]; + + /** + * @see _.sortByAll + **/ + sortByAll( + collection: List, + iteratees: (ListIterator|string|Object)[]): T[]; + + /** + * @see _.sortByAll + **/ + sortByAll( + collection: Array, + ...iteratees: (ListIterator|string|Object)[]): T[]; + + /** + * @see _.sortByAll + **/ + sortByAll( + collection: List, + ...iteratees: (ListIterator|string|Object)[]): T[]; + } + + interface LoDashArrayWrapper { + /** + * @see _.sortByAll + **/ + sortByAll( + iteratees: (ListIterator|string|Object)[]): LoDashArrayWrapper; + + /** + * @see _.sortByAll + **/ + sortByAll( + ...iteratees: (ListIterator|string|Object)[]): LoDashArrayWrapper; + } + + //_.sortByOrder + interface LoDashStatic { + /** + * This method is like "_.sortByAll" except that it allows specifying the sort orders of the + * iteratees to sort by. If orders is unspecified, all values are sorted in ascending order. + * Otherwise, a value is sorted in ascending order if its corresponding order is "asc", and + * descending if "desc". + * + * If a property name is provided for an iteratee the created "_.property" style callback + * returns the property value of the given element. + * + * If an object is provided for an iteratee the created "_.matches" style callback returns + * true for elements that have the properties of the given object, else false. + * + * @param collection The collection to iterate over. + * @param callback The function called per iteration. + * @param thisArg The this binding of callback. + * @return A new array of sorted elements. + **/ + sortByOrder( + collection: Array, + iteratees: (ListIterator|string|Object)[], + orders?: boolean[]): T[]; + + /** + * @see _.sortByOrder + **/ + sortByOrder( + collection: List, + iteratees: (ListIterator|string|Object)[], + orders?: boolean[]): T[]; + + /** + * @see _.sortByOrder + **/ + sortByOrder( + collection: Array, + iteratees: (ListIterator|string|Object)[], + orders?: string[]): T[]; + + /** + * @see _.sortByOrder + **/ + sortByOrder( + collection: List, + iteratees: (ListIterator|string|Object)[], + orders?: string[]): T[]; + } + + interface LoDashArrayWrapper { + /** + * @see _.sortByOrder + **/ + sortByOrder( + iteratees: (ListIterator|string|Object)[], + orders?: boolean[]): LoDashArrayWrapper; + + /** + * @see _.sortByOrder + **/ + sortByOrder( + iteratees: (ListIterator|string|Object)[], + orders?: string[]): LoDashArrayWrapper; + } + //_.toArray interface LoDashStatic { /** From b83eea746f8583a6c9956c19d8b553f2b66ce577 Mon Sep 17 00:00:00 2001 From: Daniel Beckwith Date: Wed, 22 Jul 2015 19:58:52 -0400 Subject: [PATCH 116/881] Updates colors for new features and chaining --- colors/colors-tests.ts | 19 ++---- colors/colors.d.ts | 138 +++++++++++++++++++++++++++++++++-------- 2 files changed, 118 insertions(+), 39 deletions(-) diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index a7f595fdf..15fd5ab4e 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -3,16 +3,9 @@ import colors = require("colors"); -var test:string = 'test'; -var arr:string[] = ['color', 'odd'.italic.zebra, 'radical'.bold.rainbow, test.underline + 'super'.green]; - -colors.black("abc").trim(); -colors.red("abc").trim(); -colors.green("abc").trim(); -colors.yellow("abc").trim(); -colors.blue("abc").trim(); -colors.magenta("abc").trim(); -colors.cyan("abc").trim(); -colors.white("abc").trim(); -colors.gray("abc").trim(); -colors.grey("abc").trim(); +console.log(colors.black.underline('test')); +console.log(colors.rainbow.black.blue.gray('test')); +console.log(colors.random.reset.bgWhite.dim('test')); +console.log('test'.black.underline); +console.log('test'.rainbow.black.blue.gray); +console.log('test'.random.reset.bgWhite.dim); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 8332ac5bb..5aa28553a 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -4,34 +4,120 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "colors" { - export function setTheme(theme:any):any; + interface Color { + (text: string): string; - export function black(text: string): string; - export function red(text: string): string; - export function green(text: string): string; - export function yellow(text: string): string; - export function blue(text: string): string; - export function magenta(text: string): string; - export function cyan(text: string): string; - export function white(text: string): string; - export function gray(text: string): string; - export function grey(text: string): string; + black: Color; + red: Color; + green: Color; + yellow: Color; + blue: Color; + magenta: Color; + cyan: Color; + white: Color; + gray: Color; + grey: Color; + + bgBlack: Color; + bgRed: Color; + bgGreen: Color; + bgYellow: Color; + bgBlue: Color; + bgMagenta: Color; + bgCyan: Color; + bgWhite: Color; + + reset: Color; + bold: Color; + dim: Color; + italic: Color; + underline: Color; + inverse: Color; + hidden: Color; + strikethrough: Color; + + rainbow: Color; + zebra: Color; + america: Color; + trap: Color; + random: Color; + } + + module e { + export function setTheme(theme:any): void; + + export var black: Color; + export var red: Color; + export var green: Color; + export var yellow: Color; + export var blue: Color; + export var magenta: Color; + export var cyan: Color; + export var white: Color; + export var gray: Color; + export var grey: Color; + + export var bgBlack: Color; + export var bgRed: Color; + export var bgGreen: Color; + export var bgYellow: Color; + export var bgBlue: Color; + export var bgMagenta: Color; + export var bgCyan: Color; + export var bgWhite: Color; + + export var reset: Color; + export var bold: Color; + export var dim: Color; + export var italic: Color; + export var underline: Color; + export var inverse: Color; + export var hidden: Color; + export var strikethrough: Color; + + export var rainbow: Color; + export var zebra: Color; + export var america: Color; + export var trap: Color; + export var random: Color; + } + + export = e; } interface String { - bold:string; - italic:string; - underline:string; - inverse:string; - yellow:string; - cyan:string; - white:string; - magenta:string; - green:string; - red:string; - grey:string; - blue:string; - rainbow:string; - zebra:string; - random:string; + black: string; + red: string; + green: string; + yellow: string; + blue: string; + magenta: string; + cyan: string; + white: string; + gray: string; + grey: string; + + bgBlack: string; + bgRed: string; + bgGreen: string; + bgYellow: string; + bgBlue: string; + bgMagenta: string; + bgCyan: string; + bgWhite: string; + + reset: string; + bold: string; + dim: string; + italic: string; + underline: string; + inverse: string; + hidden: string; + strikethrough: string; + + rainbow: string; + zebra: string; + america: string; + trap: string; + random: string; } From 4a489b209bdedaaa7b181ef1d28fc5e0639c577a Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 23 Jul 2015 14:14:38 +0100 Subject: [PATCH 117/881] Create magic-number.d.ts --- magic-number/magic-number.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 magic-number/magic-number.d.ts diff --git a/magic-number/magic-number.d.ts b/magic-number/magic-number.d.ts new file mode 100644 index 000000000..8f095d63c --- /dev/null +++ b/magic-number/magic-number.d.ts @@ -0,0 +1,8 @@ +// Type definitions for magic-number +// Project: https://github.com/stpettersens/magic-number +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "magic-number" { + export function detectFile(file: string): string; +} From 6e40518360bf37a449bdea819888ee5faf15c5e8 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 23 Jul 2015 14:15:07 +0100 Subject: [PATCH 118/881] Create magic-number-tests.ts --- magic-number/magic-number-tests.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 magic-number/magic-number-tests.ts diff --git a/magic-number/magic-number-tests.ts b/magic-number/magic-number-tests.ts new file mode 100644 index 000000000..ac0b59982 --- /dev/null +++ b/magic-number/magic-number-tests.ts @@ -0,0 +1,12 @@ +/// +/// + +import fs = require('fs'); +import magic = require('magic-number'); + +var buffer: any = new Buffer(100); +buffer.write('7z', 'binary'); +fs.writeFile('test.love', buffer, function(err: any) { + console.log(magic.detectFile('test.love')); // => 'application/7z-x-compressed' + fs.unlinkSync('test.love'); +}); From 2a0fa344c114b78ba9bf5b85ac25865318346155 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 23 Jul 2015 14:17:13 +0100 Subject: [PATCH 119/881] Update magic-number.d.ts --- magic-number/magic-number.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/magic-number/magic-number.d.ts b/magic-number/magic-number.d.ts index 8f095d63c..295bb1d43 100644 --- a/magic-number/magic-number.d.ts +++ b/magic-number/magic-number.d.ts @@ -1,5 +1,5 @@ // Type definitions for magic-number -// Project: https://github.com/stpettersens/magic-number +// Project: https://github.com/stpettersens/node-magic-number // Definitions by: Sam Saint-Pettersen // Definitions: https://github.com/borisyankov/DefinitelyTyped From 18a39c19b8f18daeea65c1aa03c4fa8be4ac3f56 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 23 Jul 2015 14:17:20 +0100 Subject: [PATCH 120/881] Update magic-number.d.ts From 66cf2992aa35498e04b6d088b3673fcfa004fe12 Mon Sep 17 00:00:00 2001 From: Aviel Fedida Date: Thu, 23 Jul 2015 20:03:24 +0300 Subject: [PATCH 121/881] Adding the type definitions for ISO8601-Localizer framework --- iso8601-localizer/iso8601-localizer-tests.ts | 5 +++++ iso8601-localizer/iso8601-localizer.d.ts | 15 +++++++++++++++ 2 files changed, 20 insertions(+) create mode 100644 iso8601-localizer/iso8601-localizer-tests.ts create mode 100644 iso8601-localizer/iso8601-localizer.d.ts diff --git a/iso8601-localizer/iso8601-localizer-tests.ts b/iso8601-localizer/iso8601-localizer-tests.ts new file mode 100644 index 000000000..592799388 --- /dev/null +++ b/iso8601-localizer/iso8601-localizer-tests.ts @@ -0,0 +1,5 @@ +/// + +new ISO8601Localizer('2015-06-02T14:13:12').localize(); + +new ISO8601Localizer('2015-06-02T14:13:12').to(-5).localize(); diff --git a/iso8601-localizer/iso8601-localizer.d.ts b/iso8601-localizer/iso8601-localizer.d.ts new file mode 100644 index 000000000..0fdc1b4cb --- /dev/null +++ b/iso8601-localizer/iso8601-localizer.d.ts @@ -0,0 +1,15 @@ +// Type definitions for ISO8601-Localizer v1.0.5 +// Project: https://github.com/avielfedida/ISO8601-Localizer +// Definitions by: Aviel Fedida +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface localizer { + to(offset: number): localizer, + localize(): string; +} + +declare class ISO8601Localizer implements localizer { + constructor(userISO8601: string); + to(offset: number): localizer; + localize(): string; +} From 80ee73de668a4f773aa6691dc088929df0ed7d55 Mon Sep 17 00:00:00 2001 From: Maciej Kowalski Date: Thu, 23 Jul 2015 19:09:09 +0200 Subject: [PATCH 122/881] fix request.d.ts CookieJar signature --- request/request.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/request/request.d.ts b/request/request.d.ts index e16eafadb..e01ba2cc7 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -12,6 +12,7 @@ declare module 'request' { import stream = require('stream'); import http = require('http'); import FormData = require('form-data'); + import url = require('url'); export = RequestAPI; @@ -160,9 +161,9 @@ declare module 'request' { } export interface CookieJar { - add(cookie: Cookie): void; - get(req: Request): Cookie; - cookieString(req: Request): string; + setCookie(cookie: Cookie, uri: string|url.Url, options?: any): void + getCookieString(uri: string|url.Url): string + getCookies(uri: string|url.Url): Cookies[] } export interface CookieValue { From 5cbfd00b618e5089c7ee31a8c2d77e955c7ffed9 Mon Sep 17 00:00:00 2001 From: Maciej Kowalski Date: Thu, 23 Jul 2015 19:09:09 +0200 Subject: [PATCH 123/881] fix request.d.ts CookieJar signature --- request/request-tests.ts | 6 +++--- request/request.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/request/request-tests.ts b/request/request-tests.ts index 64aef2a04..9d7cbf3bc 100644 --- a/request/request-tests.ts +++ b/request/request-tests.ts @@ -46,9 +46,9 @@ str = cookie.path; str = cookie.toString(); var jar: request.CookieJar; -jar.add(cookie); -cookie = jar.get(req); -str = jar.cookieString(req); +jar.setCookie(cookie, uri); +str = jar.getCookieString(uri); +var cookies: request.Cookie[] = jar.getCookies(uri); var aws: request.AWSOptions; str = aws.secret; diff --git a/request/request.d.ts b/request/request.d.ts index e01ba2cc7..7b625241c 100644 --- a/request/request.d.ts +++ b/request/request.d.ts @@ -163,7 +163,7 @@ declare module 'request' { export interface CookieJar { setCookie(cookie: Cookie, uri: string|url.Url, options?: any): void getCookieString(uri: string|url.Url): string - getCookies(uri: string|url.Url): Cookies[] + getCookies(uri: string|url.Url): Cookie[] } export interface CookieValue { From 83af898254689400de8fb6495c34119ae57ec3fe Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 23 Jul 2015 10:45:23 -0700 Subject: [PATCH 124/881] systemjs: type definitions for System universal dynamic module loader https://github.com/systemjs/systemjs/issues/321 --- systemjs/systemjs-tests.ts | 12 ++++++++++++ systemjs/systemjs.d.ts | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 systemjs/systemjs-tests.ts create mode 100644 systemjs/systemjs.d.ts diff --git a/systemjs/systemjs-tests.ts b/systemjs/systemjs-tests.ts new file mode 100644 index 000000000..689543849 --- /dev/null +++ b/systemjs/systemjs-tests.ts @@ -0,0 +1,12 @@ +/// + +import System = require('systemjs'); + +System.config({ + baseURL: '/', + paths: {'*': '*.js?v=0.18.4'} +}); + +System.import('app') + .catch(e => console.error(e, + 'There was an error loading.')); \ No newline at end of file diff --git a/systemjs/systemjs.d.ts b/systemjs/systemjs.d.ts new file mode 100644 index 000000000..c63a79158 --- /dev/null +++ b/systemjs/systemjs.d.ts @@ -0,0 +1,21 @@ +// Type definitions for System.js 0.18.4 +// Project: https://github.com/systemjs/systemjs +// Definitions by: Ludovic HENIN , Nathan Walker +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface System { + import(name: string): any; + defined: any; + amdDefine: () => void; + amdRequire: () => void; + baseURL: string; + paths: { [key: string]: string }; + meta: { [key: string]: Object }; + config: any; +} + +declare var System: System; + +declare module "systemjs" { + export = System; +} \ No newline at end of file From bd03c6ea51abde7d13e354908716c6373fc38b1f Mon Sep 17 00:00:00 2001 From: Nathan Walker Date: Thu, 23 Jul 2015 11:13:45 -0700 Subject: [PATCH 125/881] systemjs: fix tests --- systemjs/systemjs-tests.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/systemjs/systemjs-tests.ts b/systemjs/systemjs-tests.ts index 689543849..7a56ef8dc 100644 --- a/systemjs/systemjs-tests.ts +++ b/systemjs/systemjs-tests.ts @@ -7,6 +7,4 @@ System.config({ paths: {'*': '*.js?v=0.18.4'} }); -System.import('app') - .catch(e => console.error(e, - 'There was an error loading.')); \ No newline at end of file +System.import('app'); \ No newline at end of file From 149fde9438c59bd98ab8479ba46ae9db70ffb109 Mon Sep 17 00:00:00 2001 From: Cy Brown Date: Thu, 23 Jul 2015 22:52:56 +0200 Subject: [PATCH 126/881] mariasql: Added string based function signature and MariaInfo interface --- mariasql/mariasql-tests.ts | 3 +++ mariasql/mariasql.d.ts | 35 ++++++++++++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/mariasql/mariasql-tests.ts b/mariasql/mariasql-tests.ts index c9173058c..76819feba 100644 --- a/mariasql/mariasql-tests.ts +++ b/mariasql/mariasql-tests.ts @@ -92,6 +92,9 @@ c.query('SELECT * FROM users WHERE id = ? AND name = ?', console.log('Result error: ' + inspect(err)); }) .on('end', function (info) { + console.log(info.affectedRows); + console.log(info.insertId); + console.log(info.numRows); console.log('Result finished successfully'); }); }) diff --git a/mariasql/mariasql.d.ts b/mariasql/mariasql.d.ts index 05d7fa062..9eb80068f 100644 --- a/mariasql/mariasql.d.ts +++ b/mariasql/mariasql.d.ts @@ -24,6 +24,10 @@ declare module mariasql { (result:Object):void } + export interface MariaCallBackInfo { + (result:MariaInfo):void + } + export interface MariaCallBackVoid { ():void } @@ -32,6 +36,12 @@ declare module mariasql { [index: string]: any; } + export interface MariaInfo { + affectedRows: number; + insertId: number; + numRows: number + } + export interface MariaPreparedQuery { (values:Dictionary):string; (values:Array):string; @@ -57,18 +67,20 @@ declare module mariasql { } export interface MariaResult { - on(signal:string, cb:MariaCallBackObject):MariaResult; // signal 'end' - on(signal:string, cb:MariaCallBackError):MariaResult; // signal 'error' - on(signal:string, cb:MariaCallBackRow):MariaResult; // signal 'row' - on(signal:string, cb:MariaCallBackVoid):MariaResult; // signal 'abort' + on(signal:'end', cb:MariaCallBackInfo):MariaResult; + on(signal:'error', cb:MariaCallBackError):MariaResult; + on(signal:'row', cb:MariaCallBackRow):MariaResult; + on(signal:'abort', cb:MariaCallBackVoid):MariaResult; + on(signal:string, cb:MariaCallBackVoid):MariaResult; abort():void; } export interface MariaQuery { - on(signal:string, cb:MariaCallBackResult):MariaQuery; // signal 'result' - on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'end' - on(signal:string, cb:MariaCallBackVoid):MariaQuery; // signal 'abort' - on(signal:string, cb:MariaCallBackError):MariaQuery; // signal 'error' + on(signal:'result', cb:MariaCallBackResult):MariaQuery; + on(signal:'end', cb:MariaCallBackVoid):MariaQuery; + on(signal:'abort', cb:MariaCallBackVoid):MariaQuery; + on(signal:'error', cb:MariaCallBackError):MariaQuery; + on(signal:string, cb:MariaCallBackVoid):MariaQuery; abort():void; } @@ -82,9 +94,10 @@ declare module mariasql { query(q:string, useArray?:boolean):MariaQuery; prepare(query:string): MariaPreparedQuery; isMariaDB():boolean; - on(signal:string, cb:MariaCallBackError): MariaClient; // signal 'error' - on(signal:string, cb:MariaCallBackObject): MariaClient; // signal 'close' - on(signal:string, cb:MariaCallBackVoid): MariaClient; // signal 'connect' + on(signal:'error', cb:MariaCallBackError): MariaClient; + on(signal:'close', cb:MariaCallBackObject): MariaClient; + on(signal:'connect', cb:MariaCallBackVoid): MariaClient; + on(signal:string, cb:MariaCallBackVoid): MariaClient; connected: boolean; threadId: string; } From 77104a9f9f554f0247f42e245db1179dbc210c8e Mon Sep 17 00:00:00 2001 From: RathaR Date: Fri, 24 Jul 2015 04:02:29 +0300 Subject: [PATCH 127/881] fix asElementFinders_ method declaration --- angular-protractor/angular-protractor-tests.ts | 2 +- angular-protractor/angular-protractor.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-protractor/angular-protractor-tests.ts b/angular-protractor/angular-protractor-tests.ts index b8b9585f4..45a5d7edc 100644 --- a/angular-protractor/angular-protractor-tests.ts +++ b/angular-protractor/angular-protractor-tests.ts @@ -374,7 +374,7 @@ function TestElementArrayFinder() { var b: boolean = elementArrayFinder.isPending(); var locator: webdriver.Locator = elementArrayFinder.locator(); - var findersArray: protractor.ElementFinder[] = elementArrayFinder.asElementFinders_(); + var findersArrayPromise: protractor.promise.Promise = elementArrayFinder.asElementFinders_(); var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42); diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index 76f0b5f10..2b86864cd 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -927,7 +927,7 @@ declare module protractor { * @return {Array.} Return a promise, which resolves to a list * of ElementFinders specified by the locator. */ - asElementFinders_(): ElementFinder[]; + asElementFinders_(): webdriver.promise.Promise; /** * Create a shallow copy of ElementArrayFinder. From 395696e588fd402063dbc7752afc57a6caf9f013 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Sa=C5=82kowski?= Date: Fri, 24 Jul 2015 10:58:40 +0200 Subject: [PATCH 128/881] Add bxslider-4 type definitions --- bxslider-4/bxslider-4-tests.ts | 214 +++++++++++ bxslider-4/bxslider-4.d.ts | 623 +++++++++++++++++++++++++++++++++ 2 files changed, 837 insertions(+) create mode 100644 bxslider-4/bxslider-4-tests.ts create mode 100644 bxslider-4/bxslider-4.d.ts diff --git a/bxslider-4/bxslider-4-tests.ts b/bxslider-4/bxslider-4-tests.ts new file mode 100644 index 000000000..09d48f2a8 --- /dev/null +++ b/bxslider-4/bxslider-4-tests.ts @@ -0,0 +1,214 @@ +/// +/// + +// examples from http://bxslider.com/examples + +$(document).ready(function() { + $('.bxslider1').bxSlider({ + mode: 'fade', + captions: true + }); + + $('.bxslider2').bxSlider({ + auto: true, + autoControls: true + }); + + $('.bxslider3').bxSlider({ + infiniteLoop: false, + hideControlOnEnd: true + }); + + $('.bxslider4').bxSlider({ + adaptiveHeight: true, + mode: 'fade' + }); + + $('.slider1').bxSlider({ + slideWidth: 200, + minSldies: 2, + maxSlides: 3, + slideMargin: 10 + }); + + $('.slider2').bxSlider({ + slideWidth: 300, + minSlides: 2, + maxSlides: 2, + slideMargin: 10 + }); + + $('.slider3').bxSlider({ + slideWidth: 5000, + minSlides: 2, + maxSlides: 4, + slideMargin: 10 + }); + + $('.slider4').bxSlider({ + slideWidth: 300, + minSlides: 2, + maxSlides: 3, + moveSlides: 1, + slideMargin: 10 + }); + + $('.slider5').bxSlider({ + slideWidth: 300, + minSlides: 3, + maxSlides: 3, + moveSlides: 3, + slideMargin: 10 + }); + + $('.slider6').bxSlider({ + slideWidth: 300, + minSlides: 2, + maxSlides: 3, + startSlide: 2, + slideMargin: 10 + }); + + $('.slider7').bxSlider({ + slideWidth: 200, + minSlides: 4, + maxSlides: 5, + slideMargin: 10 + }); + + $('.slider8').bxSlider({ + mode: 'vertical', + slideWidth: 300, + minSlides: 2, + slideMargin: 10 + }); + + $('.bxslider6').bxSlider({ + minSlides: 2, + maxSlides: 2, + slideWidth: 360, + slideMargin: 10 + }); + + $('.bxslider7').bxSlider({ + minSlides: 3, + maxSlides: 4, + slideWidth: 170, + slideMargin: 10 + }); + + $('.bxslider8').bxSlider({ + pagerCustom: '#bx-pager' + }); + $('.bxslider9').bxSlider({ + buildPager: function(slideIndex) { + switch (slideIndex) { + case 0: + return ''; + case 1: + return ''; + case 2: + return ''; + } + } + }); + + $('.bxslider10').bxSlider({ + mode: 'vertical', + slideMargin: 5 + }); + + $('.bxslider11').bxSlider({ + nextSelector: '#slider-next', + prevSelector: '#slider-prev', + nextText: 'Onward →', + prevText: '← Go back' + }); + + $('.bxslider12a').bxSlider({ + mode: 'fade', + auto: true, + autoControls: true, + pause: 2000 + }); + + $('.bxslider12b').bxSlider({ + auto: true, + autoControls: true, + pause: 3000, + slideMargin: 20 + }); + + $('.bxslider13').bxSlider({ + onSliderLoad: function() { + // do funky JS stuff here + alert('Slider has finished loading. Click OK to continue!'); + }, + onSlideAfter: function() { + // do mind-blowing JS stuff here + alert('A slide has finished transitioning. Bravo. Click OK to continue!'); + } + }); + + var slider = $('.bxslider14').bxSlider({ + mode: 'fade' + }); + + $('#slider-next').click(function() { + slider.goToNextSlide(); + return false; + }); + + $('#slider-count').click(function() { + var count = slider.getSlideCount(); + alert('Slide count: ' + count); + return false; + }); + + $('.bxslider15').bxSlider({ + video: true, + useCSS: false + }); + + $('.bxslider16').bxSlider({ + minSlides: 4, + maxSlides: 4, + slideWidth: 170, + slideMargin: 10, + ticker: true, + speed: 6000 + }); + + $('.bxslider17').bxSlider({ + mode: 'horizontal', + useCSS: false, + infiniteLoop: false, + hideControlOnEnd: true, + easing: 'easeOutElastic', + speed: 2000 + }); + + var slider = $('.bxslider18').bxSlider({ + mode: 'horizontal' + }); + + $('#reload-slider').click(function(e) { + e.preventDefault(); + $('.bxslider').append('
  • '); + slider.reloadSlider(); + }); + + var slider = $('.bxslider19').bxSlider({ + mode: 'horizontal' + }); + + $('#reload-slider').click(function(e) { + e.preventDefault(); + slider.reloadSlider({ + mode: 'fade', + auto: true, + pause: 1000, + speed: 500 + }); + }); +}); \ No newline at end of file diff --git a/bxslider-4/bxslider-4.d.ts b/bxslider-4/bxslider-4.d.ts new file mode 100644 index 000000000..26aece2d7 --- /dev/null +++ b/bxslider-4/bxslider-4.d.ts @@ -0,0 +1,623 @@ +// Type definitions for bxSlider v4.2.5 +// Project: https://github.com/stevenwanderski/bxslider-4 +// Definitions by: Piotr Sałkowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface bxSliderOptions { + /** + * mode Type of transition between slides + * + * default: 'horizontal' + * options: 'horizontal', 'vertical', 'fade' + */ + mode?: string + + /** + * speed Slide transition duration (in ms) + * + * default: 500 + * options: integer + */ + speed?: number + + /** + * slideMargin Margin between each slide + * + * default: 0 + * options: integer + */ + slideMargin?: number + + /** + * startSlide Starting slide index (zero-based) + * + * default: 0 + * options: integer + */ + startSlide?: number + + /** + * randomStart Start slider on a random slide + * + * default: false + * options: boolean (true / false) + */ + randomStart?: boolean + + /** + * slideSelector Element to use as slides (ex. 'div.slide'). + * Note: by default, bxSlider will use all immediate children of the slider element + * + * default: '' + * options: jQuery selector + */ + slideSelector?: string + + /** + * infiniteLoop If true, clicking "Next" while on the last slide will transition to the first slide and vice-versa + * + * default: true + * options: boolean (true / false) + */ + infiniteLoop?: boolean + + /** + * hideControlOnEnd If true, "Prev" and "Next" controls will receive a class disabled when slide is the first or the last + * Note: Only used when infiniteLoop: false + * + * default: false + * options: boolean (true / false) + */ + hideControlOnEnd?: boolean + + /** + * easing The type of "easing" to use during transitions. If using CSS transitions, include a value for the transition-timing-function property. If not using CSS transitions, you may include plugins/jquery.easing.1.3.js for many options. + * See http://gsgd.co.uk/sandbox/jquery/easing/ for more info. + * + * default: null + * options: if using CSS: 'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out', 'cubic-bezier(n,n,n,n)'. If not using CSS: 'swing', 'linear' (see the above file for more options) + */ + easing?: string + + /** + * captions Include image captions. Captions are derived from the image's title attribute + * + * default: false + * options: boolean (true / false) + */ + captions?: boolean + + /** + * ticker Use slider in ticker mode (similar to a news ticker) + * + * default: false + * options: boolean (true / false) + */ + ticker?: boolean + + /** + * tickerHover Ticker will pause when mouse hovers over slider. Note: this functionality does NOT work if using CSS transitions! + * + * default: false + * options: boolean (true / false) + */ + tickerHover?: boolean + + /** + * adaptiveHeight Dynamically adjust slider height based on each slide's height + * + * default: false + * options: boolean (true / false) + */ + adaptiveHeight?: boolean + + /** + * adaptiveHeightSpeed Slide height transition duration (in ms). Note: only used if adaptiveHeight: true + * + * default: 500 + * options: integer + */ + adaptiveHeightSpeed?: number + + /** + * video If any slides contain video, set this to true. Also, include plugins/jquery.fitvids.js + * See http://fitvidsjs.com/ for more info + * + * default: false + * options: boolean (true / false) + */ + video?: boolean + + /** + * responsive Enable or disable auto resize of the slider. Useful if you need to use fixed width sliders. + * + * default: true + * options: boolean (true / false) + */ + responsive?: boolean + + /** + * useCSS If true, CSS transitions will be used for horizontal and vertical slide animations (this uses native hardware acceleration). If false, jQuery animate() will be used. + * + * default: true + * options: boolean (true / false) + */ + useCSS?: boolean + + /** + * preloadImages If 'all', preloads all images before starting the slider. If 'visible', preloads only images in the initially visible slides before starting the slider (tip: use 'visible' if all slides are identical dimensions) + * + * default: 'visible' + * options: 'all', 'visible' + */ + preloadImages?: string + + /** + * touchEnabled If true, slider will allow touch swipe transitions + * + * default: true + * options: boolean (true / false) + */ + touchEnabled?: boolean + + /** + * swipeThreshold Amount of pixels a touch swipe needs to exceed in order to execute a slide transition. Note: only used if touchEnabled: true + * + * default: 50 + * options: integer + */ + swipeThreshold?: number + + /** + * oneToOneTouch If true, non-fade slides follow the finger as it swipes + * + * default: true + * options: boolean (true / false) + */ + oneToOneTouch?: boolean + + /** + * preventDefaultSwipeX If true, touch screen will not move along the x-axis as the finger swipes + * + * default: true + * options: boolean (true / false) + */ + preventDefaultSwipeX?: boolean + + /** + * preventDefaultSwipeY If true, touch screen will not move along the y-axis as the finger swipes + * + * default: false + * options: boolean (true / false) + */ + preventDefaultSwipeY?: boolean + + /** + * wrapperClass Class to wrap the slider in. Change to prevent from using default bxSlider styles. + * + * default: 'bx-wrapper' + * options: string + */ + wrapperClass?: string + + /** + * pager If true, a pager will be added + * + * default: true + * options: boolean (true / false) + */ + pager?: boolean + + /** + * pagerType If 'full', a pager link will be generated for each slide. If 'short', a x / y pager will be used (ex. 1 / 5) + * + * default: 'full' + * options: 'full', 'short' + */ + pagerType?: string + + /** + * pagerShortSeparator If pagerType: 'short', pager will use this value as the separating character + * + * default: ' / ' + * options: string + */ + pagerShortSeparator?: string + + /** + * pagerSelector Element used to populate the populate the pager. By default, the pager is appended to the bx-viewport + * + * default: '' + * options: jQuery selector + */ + pagerSelector?: string + + /** + * pagerCustom Parent element to be used as the pager. Parent element must contain a element for each slide. See example here. Not for use with dynamic carousels. + * + * default: null + * options: jQuery selector + */ + pagerCustom?: string + + /** + * buildPager If supplied, function is called on every slide element, and the returned value is used as the pager item markup. + * See examples for detailed implementation + * + * default: null + * options: functoin(slideIndex) + */ + buildPager?: (slideIndex: number) => void; + + + /** + * controls If true, "Next" / "Prev" controls will be added + * + * default: true + * options: boolean (true / false) + */ + controls?: boolean + + /** + * nextText Text to be used for the "Next" control + * + * default: 'Next' + * options: string + */ + nextText?: string + + /** + * prevText Text to be used for the "Prev" control + * + * default: 'Prev' + * options: string + */ + prevText?: string + + /** + * nextSelector Element used to populate the "Next" control + * + * default: null + * options: jQuery selector + */ + nextSelector?: string + + /** + * prevSelector Element used to populate the "Prev" control + * + * default: null + * options: jQuery selector + */ + prevSelector?: string + + /** + * autoControls If true, "Start" / "Stop" controls will be added + * + * default: false + * options: boolean (true / false) + */ + autoControls?: boolean + + /** + * startText Text to be used for the "Start" control + * + * default: 'Start' + * options: string + */ + startText?: string + + /** + * stopText Text to be used for the "Stop" control + * + * default: 'Stop' + * options: string + */ + stopText?: string + + /** + * autoControlsCombine When slideshow is playing only "Stop" control is displayed and vice-versa + * + * default: false + * options: boolean (true / false) + */ + autoControlsCombine?: boolean + + /** + * autoControlsSelector Element used to populate the auto controls + * + * default: null + * options: jQuery selector + */ + autoControlsSelector?: string + + /** + * keyboardEnabled Allows for keyboard control of visible slider. Keypress ignored if slider not visible. + * + * default: false + * options: boolean (true / false) + */ + keyboardEnabled?: boolean + + /** + * auto Slides will automatically transition + * + * default: false + * options: boolean (true / false) + */ + auto?: boolean + + /** + * stopAutoOnClick Auto will stop on interaction with controls + * + * default: false + * options: boolean (true / false) + */ + stopAutoOnClick?: boolean + + /** + * pause The amount of time (in ms) between each auto transition + * + * default: 4000 + * options: integer + */ + pause?: number + + /** + * autoStart Auto show starts playing on load. If false, slideshow will start when the "Start" control is clicked + * + * default: true + * options: boolean (true / false) + */ + autoStart?: boolean + + /** + * autoDirection The direction of auto show slide transitions + * + * default: 'next' + * options: 'next', 'prev' + */ + autoDirection?: string + + /** + * autoHover Auto show will pause when mouse hovers over slider + * + * default: false + * options: boolean (true / false) + */ + autoHover?: boolean + + /** + * autoDelay Time (in ms) auto show should wait before starting + * + * default: 0 + * options: integer + */ + autoDelay?: number + + /** + * minSlides The minimum number of slides to be shown. Slides will be sized down if carousel becomes smaller than the original size. + * + * default: 1 + * options: integer + */ + minSlides?: number + + /** + * maxSlides The maximum number of slides to be shown. Slides will be sized up if carousel becomes larger than the original size. + * + * default: 1 + * options: integer + */ + maxSlides?: number + + /** + * moveSlides The number of slides to move on transition. This value must be >= minSlides, and <= maxSlides. If zero (default), the number of fully-visible slides will be used. + * + * default: 0 + * options: integer + */ + moveSlides?: number + + /** + * slideWidth The width of each slide. This setting is required for all horizontal carousels! + * + * default: 0 + * options: integer + */ + slideWidth?: number + + /** + * shrinkItems The Carousel will only show whole items and shrink the images to fit the viewport based on maxSlides/MinSlides. + * + * default: false + * options: boolean (true / false) + */ + shrinkItems?: boolean + + /** + * ariaLive Adds Aria Live attribute to slider. + * + * default: true + * options: boolean (true / false) + */ + ariaLive?: boolean + + /** + * ariaHidden Adds Aria Hidden attribute to any nonvisible slides. + * + * default: true + * options: boolean (true / false) + */ + ariaHidden?: boolean + + /** + * onSliderLoad Executes immediately after the slider is fully loaded + * + * default: function(){} + * options: function(currentIndex){ // your code here } + * arguments: + * currentIndex: element index of the current slide + */ + onSliderLoad?: (currentIndex?: number) => void; + + /** + * onSliderResize Executes immediately after the slider is resized + * + * default: function(){} + * options: function(currentIndex){ // your code here } + * arguments: + * currentIndex: element index of the current slide + */ + onSliderResize?: (currentIndex?: number) => void; + + /** + * onSlideBefore Executes immediately before each slide transition. + * + * default: function(){} + * options: function($slideElement, oldIndex, newIndex){ // your code here } + * arguments: + * $slideElement: jQuery element of the destination element + * oldIndex: element index of the previous slide (before the transition) + * newIndex: element index of the destination slide (after the transition) + */ + onSlideBefore?: ($slideElement?: JQuery, oldIndex?: number, newIndex?: number) => void; + + /** + * onSlideAfter Executes immediately after each slide transition. Function argument is the current slide element (when transition completes). + * + * default: function(){} + * options: function($slideElement, oldIndex, newIndex){ // your code here } + * arguments: + * $slideElement: jQuery element of the destination element + * oldIndex: element index of the previous slide (before the transition) + * newIndex: element index of the destination slide (after the transition) + */ + onSlideAfter?: ($slideElement?: JQuery, oldIndex?: number, newIndex?: number) => void; + + /** + * onSlideNext Executes immediately before each "Next" slide transition. Function argument is the target (next) slide element. + * + * default: function(){} + * options: function($slideElement, oldIndex, newIndex){ // your code here } + * arguments: + * $slideElement: jQuery element of the destination element + * oldIndex: element index of the previous slide (before the transition) + * newIndex: element index of the destination slide (after the transition) + */ + onSlideNext?: ($slideElement?: JQuery, oldIndex?: number, newIndex?: number) => void; + + /** + * onSlidePrev Executes immediately before each "Prev" slide transition. Function argument is the target (prev) slide element. + * + * default: function(){} + * options: function($slideElement, oldIndex, newIndex){ // your code here } + * arguments: + * $slideElement: jQuery element of the destination element + * oldIndex: element index of the previous slide (before the transition) + * newIndex: element index of the destination slide (after the transition) + */ + onSlidePrev?: ($slideElement?: JQuery, oldIndex?: number, newIndex?: number) => void; +} + +interface bxSlider { + + /** + * goToSlide Performs a slide transition to the supplied slide index (zero-based) + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.goToSlide(3); + */ + goToSlide: (index: number) => void; + + /** + * goToNextSlide Performs a "Next" slide transition + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.goToNextSlide(); + */ + goToNextSlide: () => void; + + /** + * goToPrevSlide Performs a "Prev" slide transition + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.goToPrevSlide(); + */ + goToPrevSlide: () => void; + + /** + * startAuto Starts the auto show. Provide an argument false to prevent the auto controls from being updated. + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.startAuto(); + */ + startAuto: (preventControlUpdate?: boolean) => void; + + /** + * stopAuto Stops the auto show. Provide an argument false to prevent the auto controls from being updated. + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.stopAuto(); + */ + stopAuto: (preventControlUpdate?: boolean) => void; + + /** + * getCurrentSlide Returns the current active slide + * + * example: + * slider = $('.bxslider').bxSlider(); + * var current = slider.getCurrentSlide(); + */ + getCurrentSlide: () => number; + + /** + * getSlideCount Returns the total number of slides in the slider + * + * example: + * slider = $('.bxslider').bxSlider(); + * var slideQty = slider.getSlideCount(); + */ + getSlideCount: () => number; + + /** + * redrawSlider Redraw the slider. Useful when needing to redraw a hidden slider after it is unhidden. + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.redrawSlider(); + */ + redrawSlider: () => void; + + /** + * reloadSlider Reload the slider. Useful when adding slides on the fly. Accepts an optional settings object. See here for an example. + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.reloadSlider(); + */ + reloadSlider: (settings?: bxSliderOptions) => void; + + /** + * destroySlider Destroy the slider. This reverts all slider elements back to their original state (before calling the slider). + * + * example: + * slider = $('.bxslider').bxSlider(); + * slider.destroySlider(); + */ + destroySlider: () => void; +} + +interface JQuery { + /** + * Creates a bxSlider from the current element. + * @param options + */ + bxSlider(options?:bxSliderOptions): bxSlider; +} \ No newline at end of file From 5fef36255dad56330ef801d7893fcae29bd24a32 Mon Sep 17 00:00:00 2001 From: Filipe Date: Fri, 24 Jul 2015 10:54:44 +0100 Subject: [PATCH 129/881] added Transition.transitin() and optional 'i' on Arc --- d3/d3.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 50d6fbdaa..b3a365cdf 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -805,6 +805,9 @@ declare module d3 { } interface Transition { + + transition(): Transition; + delay(): number; delay(delay: number): Transition; delay(delay: (datum: Datum, index: number) => number): Transition; @@ -2358,7 +2361,7 @@ declare module d3 { } interface Arc { - (d: T, i: number): string; + (d: T, i?: number): string; innerRadius(): (d: T, i: number) => number; innerRadius(radius: number): Arc; From 75a3573ee51a5a7e9e30caa3e833c2e3aa398933 Mon Sep 17 00:00:00 2001 From: matsievskyav Date: Fri, 24 Jul 2015 17:12:55 +0300 Subject: [PATCH 130/881] Changes to Bacon.js 1. changing `EventStream#map`; 2. changing `Bus#error`; 3. changing `Bacon.update`; 4. expanding `Bacon.when` `JSDoc`s; 5. switching from `node-0.10.d.ts` to `node-0.11.d.ts`; 6. creating `.editorconfig` file. --- baconjs/.editorconfig | 9 + baconjs/baconjs-tests.ts | 719 ++--- baconjs/baconjs.d.ts | 5642 ++++++++++++++++++++------------------ 3 files changed, 3419 insertions(+), 2951 deletions(-) create mode 100644 baconjs/.editorconfig diff --git a/baconjs/.editorconfig b/baconjs/.editorconfig new file mode 100644 index 000000000..8649cc5c3 --- /dev/null +++ b/baconjs/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*.ts] +indent_style = space +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/baconjs/baconjs-tests.ts b/baconjs/baconjs-tests.ts index 5d5998b70..9557e37cd 100644 --- a/baconjs/baconjs-tests.ts +++ b/baconjs/baconjs-tests.ts @@ -1,389 +1,464 @@ /// function CreatingStreams() { - $("#my-div").asEventStream("click"); - $("#my-div").asEventStream("click", ".more-specific-selector"); - $("#my-div").asEventStream("click", (event, args) => args[0]); - $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); + $("#my-div").asEventStream("click"); + $("#my-div").asEventStream("click", ".more-specific-selector"); + $("#my-div").asEventStream("click", (event, args) => args[0]); + $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); - Bacon.fromPromise($.ajax("https://baconjs.github.io/")); - Bacon.fromPromise(Promise.resolve(1)); + Bacon.fromPromise($.ajax("https://baconjs.github.io/")); + Bacon.fromPromise(Promise.resolve(1)); - Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); - Bacon.fromPromise(Promise.resolve(1), false); + Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); + Bacon.fromPromise(Promise.resolve(1), false); - Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { - return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - }); - Bacon.fromPromise(Promise.resolve(1), false, n => { - return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - }); - - Bacon.fromEvent(document.body, "click").onValue(() => { - alert("Bacon!"); - }); - Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { - alert("Bacon!"); - }); - Bacon.fromEvent(process.stdin, "readable", () => { - alert("Bacon!"); - }); - Bacon.fromEvent($("body"), "click").onValue(() => { - alert("Bacon!"); - }); - - // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. - Bacon.fromCallback(callback => { - setTimeout(() => { - callback("Bacon!"); - }, 1000); - }); - - // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": - Bacon.fromCallback((a, b, callback) => { - callback(a + " " + b); - }, Bacon.constant("bacon"), "rules").log(); - - { - var fs = require("fs"), - read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); - read.onError(error => { - console.log("Reading failed: " + error); + Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { + return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; }); - read.onValue(value => { - console.log("Read contents: " + value); + Bacon.fromPromise(Promise.resolve(1), false, n => { + return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; }); - } - Bacon.once(new Bacon.Error("fail")); + Bacon.fromEvent(document.body, "click").onValue(() => { + alert("Bacon!"); + }); + Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { + alert("Bacon!"); + }); + Bacon.fromEvent(process.stdin, "readable", () => { + alert("Bacon!"); + }); + Bacon.fromEvent($("body"), "click").onValue(() => { + alert("Bacon!"); + }); - // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: - Bacon.fromArray([1, new Bacon.Error("")]); + // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. + Bacon.fromCallback(callback => { + setTimeout(() => { + callback("Bacon!"); + }, 1000); + }); - Bacon.repeatedly(10, [1, 2, 3]); + // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": + Bacon.fromCallback((a, b, callback) => { + callback(a + " " + b); + }, Bacon.constant("bacon"), "rules").log(); - // The following will produce values `0,1,2`. - Bacon.repeat(i => { - if (i < 3) { - return Bacon.once(i); - } else { - return false; + { + var fs = require("fs"), + read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); + read.onError(error => { + console.log("Reading failed: " + error); + }); + read.onValue(value => { + console.log("Read contents: " + value); + }); } - }).log(); - { - var stream = Bacon.fromBinder(sink => { - sink("first value"); - sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); - sink(new Bacon.Next(() => { - return "This one will be evaluated lazily" - })); - sink(new Bacon.Error("oops, an error")); - sink(new Bacon.End()); - return () => { - // unsub functionality here, this one's a no-op - }; - }); - stream.log(); - } + Bacon.once(new Bacon.Error("fail")); - new Bacon.Next("value"); - new Bacon.Next(() => "value"); + // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: + Bacon.fromArray([1, new Bacon.Error("")]); + + Bacon.repeatedly(10, [1, 2, 3]); + + // The following will produce values `0,1,2`. + Bacon.repeat(i => { + if (i < 3) { + return Bacon.once(i); + } else { + return false; + } + }).log(); + + { + var stream = Bacon.fromBinder(sink => { + sink("first value"); + sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); + sink(new Bacon.Next(() => { + return "This one will be evaluated lazily" + })); + sink(new Bacon.Error("oops, an error")); + sink(new Bacon.End()); + return () => { + // unsub functionality here, this one's a no-op + }; + }); + stream.log(); + } + + new Bacon.Next("value"); + new Bacon.Next(() => "value"); } function CommonMethodsInEventStreamsAndProperties() { - // Converting strings to integers, skipping empty values: - Bacon.once("").flatMap(text => { - return text != "" ? parseInt(text) : Bacon.never(); - }); + // Converting strings to integers, skipping empty values: + Bacon.once("").flatMap(text => { + return text != "" ? parseInt(text) : Bacon.never(); + }); - Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); + Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); - Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); + Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); - // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: - Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); - // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: - Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); + // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: + Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); + // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: + Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); - { - var x = Bacon.fromArray([1, 2]), y = Bacon.fromArray([3, 4]); - x.zip(y, (x, y) => x + y); - } - - { - var stream = Bacon.fromArray([1, 2]); - stream.log("New event in myStream"); - stream.log(); - } - - Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { - if (event.hasValue()) { - // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> - return [sum + event.value(), []]; + { + var x = Bacon.fromArray([1, 2]), y = Bacon.fromArray([3, 4]); + x.zip(y, (x, y) => x + y); } - else if (event.isEnd()) { - return [undefined, [new Bacon.Next(sum), event]]; + + { + var stream = Bacon.fromArray([1, 2]); + stream.log("New event in myStream"); + stream.log(); } - else { - return [sum, [event]]; + + Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { + if (event.hasValue()) { + // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> + return [sum + event.value(), []]; + } + else if (event.isEnd()) { + return [undefined, [new Bacon.Next(sum), event]]; + } + else { + return [sum, [event]]; + } + }); + + { + var property = Bacon.fromArray([1, 2, 3]).toProperty(), + who = Bacon.fromArray(["A", "B", "C"]).toProperty(); + property.decode({1: "mike", 2: who}); + + property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); } - }); - { - var property = Bacon.fromArray([1, 2, 3]).toProperty(), - who = Bacon.fromArray(["A", "B", "C"]).toProperty(); - property.decode({1: "mike", 2: who}); - - property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); - } - - { - // This is handy for keeping track whether we are currently awaiting an AJAX response: - var ajaxRequest = >{}, - ajaxResponse = >{}, - showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); - } - - Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { - if (event.hasValue() && event.value() < 0) { - this.push(new Bacon.Error("Value below zero")); - return this.push(new Bacon.End()); - } else { - return this.push(event); + { + // This is handy for keeping track whether we are currently awaiting an AJAX response: + var ajaxRequest = >{}, + ajaxResponse = >{}, + showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); } - }); - { - var src = Bacon.once(1), - obs = src.map(x => -x); - console.log(obs.toString()); // > "Bacon.once(1).map(function)" + Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + if (event.hasValue() && event.value() < 0) { + this.push(new Bacon.Error("Value below zero")); + return this.push(new Bacon.End()); + } else { + return this.push(event); + } + }); - obs.withDescription(src, "times", -1); - console.log(obs.toString()); // > "Bacon.once(1).times(-1)" - } + { + var src = Bacon.once(1), + obs = src.map(x => -x); + console.log(obs.toString()); // > "Bacon.once(1).map(function)" - { - // Calculator for grouped consecutive values until group is cancelled: - var events = [ - {id: 1, type: "add", val: 3}, - {id: 2, type: "add", val: -1}, - {id: 1, type: "add", val: 2}, - {id: 2, type: "cancel"}, - {id: 3, type: "add", val: 2}, - {id: 3, type: "cancel"}, - {id: 1, type: "add", val: 1}, - {id: 1, type: "add", val: 2}, - {id: 1, type: "cancel"} - ], - keyF = (event:{id:number}) => event.id, - limitF = (groupedStream:Bacon.EventStream) => { - var cancel = groupedStream.filter(x => x.type === "cancel").take(1), - adds = groupedStream.filter(x => x.type === "add"); - return adds.takeUntil(cancel).map(x => x.val); - }; + obs.withDescription(src, "times", -1); + console.log(obs.toString()); // > "Bacon.once(1).times(-1)" + } - Bacon.sequentially(2, events) - .groupBy(keyF, limitF) - .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) - .onValue(sum => { - console.log(sum); // returns [-1, 2, 8] in an order - }); - } + { + // Calculator for grouped consecutive values until group is cancelled: + var events = [ + {id: 1, type: "add", val: 3}, + {id: 2, type: "add", val: -1}, + {id: 1, type: "add", val: 2}, + {id: 2, type: "cancel"}, + {id: 3, type: "add", val: 2}, + {id: 3, type: "cancel"}, + {id: 1, type: "add", val: 1}, + {id: 1, type: "add", val: 2}, + {id: 1, type: "cancel"} + ], + keyF = (event:{id:number}) => event.id, + limitF = (groupedStream:Bacon.EventStream) => { + var cancel = groupedStream.filter(x => x.type === "cancel").take(1), + adds = groupedStream.filter(x => x.type === "add"); + return adds.takeUntil(cancel).map(x => x.val); + }; + + Bacon.sequentially(2, events) + .groupBy(keyF, limitF) + .flatMap(groupedStream => groupedStream.fold(0, (acc, x) => acc + x)) + .onValue(sum => { + console.log(sum); // returns [-1, 2, 8] in an order + }); + } } function EventStream() { - // This creates the stream which doesn't produce any events and never ends: - Bacon.interval(1e1, 0).last(); + // This creates the stream which doesn't produce any events and never ends: + Bacon.interval(1e1, 0).last(); - Bacon.fromArray([1, 2, 2, 1]) - .skipDuplicates().log(); // > returns [1, 2, 1] in an order + Bacon.fromArray([1, 2, 2, 1]) + .skipDuplicates().log(); // > returns [1, 2, 1] in an order - // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: - Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); + // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: + Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); - // Here's an equivalent to `stream.bufferWithTime(10)`: - { - var stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); - stream.bufferWithTime(f => { - setTimeout(f, 10); - }); - } + // Here's an equivalent to `stream.bufferWithTime(10)`: + { + var stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); + stream.bufferWithTime(f => { + setTimeout(f, 10); + }); + } - // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. - Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); + // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. + Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); } function Property() { - // This creates the property which doesn't produce any events and never ends: - Bacon.interval(1e1, 0).toProperty().last(); + // This creates the property which doesn't produce any events and never ends: + Bacon.interval(1e1, 0).toProperty().last(); - { - var property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); - // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: - property.assign($("#my-button"), "attr", "disabled"); + { + var property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); + // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: + property.assign($("#my-button"), "attr", "disabled"); - // A simpler example would be to toggle the visibility of an element based on a Property: - property.assign($("#my-button"), "toggle"); - } + // A simpler example would be to toggle the visibility of an element based on a Property: + property.assign($("#my-button"), "toggle"); + } - Bacon.fromArray([1, 2, 2, 1]).toProperty() - .skipDuplicates().log(); // > returns [1, 2, 1] in an order + Bacon.fromArray([1, 2, 2, 1]).toProperty() + .skipDuplicates().log(); // > returns [1, 2, 1] in an order } function CombiningMultipleStreamsAndProperties() { - { - var property = Bacon.constant(1), - stream = Bacon.once(2), - constant = 3; - Bacon.combineAsArray(property, stream, constant) - .log(); // > returns [1, 2, 3] - } + { + var property = Bacon.constant(1), + stream = Bacon.once(2), + constant = 3; + Bacon.combineAsArray(property, stream, constant) + .log(); // > returns [1, 2, 3] + } - { - // To calculate the current sum of three numeric Properties, you can do: - var property = Bacon.constant(1), - stream = Bacon.once(2), - constant = 3; - // NOTE: had to explicitly specify the typing for `x:number, y:number, z:number` - Bacon.combineWith((x:number, y:number, z:number) => x + y + z, property, stream, constant); - } + { + // To calculate the current sum of three numeric Properties, you can do: + var property = Bacon.constant(1), + stream = Bacon.once(2), + constant = 3; + // NOTE: had to explicitly specify the typing for `x:number, y:number, z:number` + Bacon.combineWith((x:number, y:number, z:number) => x + y + z, property, stream, constant); + } - { - // Assuming you've got streams or properties named `password`, `username`, `firstname` and `lastname`, you can do: - var password = Bacon.constant("easy"), - username = Bacon.constant("juha"), - firstname = Bacon.constant("juha"), - lastname = Bacon.constant("paananen"), - // NOTE: you should provide `combineTemplate` typing explicitly! - loginInfo = Bacon.combineTemplate({ - magicNumber: 3, - userid: username, - passwd: password, - name: {first: firstname, last: lastname} - }).onValue(loginInfo => { - // and your new `loginInfo` property will combine values from all these streams using that template, whenever any of the streams/properties get a new value. It would yield a value: - console.log("`loginInfo` expected", { - magicNumber: 3, - userid: "juha", - passwd: "easy", - name: {first: "juha", last: "paananen"} - }); - console.log("`loginInfo` actual", loginInfo); - }); + { + // Assuming you've got streams or properties named `password`, `username`, `firstname` and `lastname`, you can do: + var password = Bacon.constant("easy"), + username = Bacon.constant("juha"), + firstname = Bacon.constant("juha"), + lastname = Bacon.constant("paananen"), + // NOTE: you should provide `combineTemplate` typing explicitly! + loginInfo = Bacon.combineTemplate({ + magicNumber: 3, + userid: username, + passwd: password, + name: {first: firstname, last: lastname} + }).onValue(loginInfo => { + // and your new `loginInfo` property will combine values from all these streams using that template, whenever any of the streams/properties get a new value. It would yield a value: + console.log("`loginInfo` expected", { + magicNumber: 3, + userid: "juha", + passwd: "easy", + name: {first: "juha", last: "paananen"} + }); + console.log("`loginInfo` actual", loginInfo); + }); - // Note that all Bacon.combine* methods produce a `Property` instead of an `EventStream`. If you need the result as an `EventStream` you might want to use `property.changes()`: - Bacon.combineWith((firstname, lastname) => `${firstname} ${lastname}`, firstname, lastname).changes(); - } + // Note that all Bacon.combine* methods produce a `Property` instead of an `EventStream`. If you need the result as an `EventStream` you might want to use `property.changes()`: + Bacon.combineWith((firstname, lastname) => `${firstname} ${lastname}`, firstname, lastname).changes(); + } - { - var x = Bacon.fromArray([1, 2, 3]), - y = Bacon.fromArray([10, 20, 30]), - z = Bacon.fromArray([100, 200, 300]); - Bacon.zipAsArray(x, y, z) - .log(); // > returns values `[1, 10, 100]`, `[2, 20, 200]` and `[3, 30, 300]` - } + { + var x = Bacon.fromArray([1, 2, 3]), + y = Bacon.fromArray([10, 20, 30]), + z = Bacon.fromArray([100, 200, 300]); + Bacon.zipAsArray(x, y, z) + .log(); // > returns values `[1, 10, 100]`, `[2, 20, 200]` and `[3, 30, 300]` + } - // The following example would log the number 3. - // NOTE: had to explicitly specify the typing for `a:number, b:number` - Bacon.onValues(Bacon.constant(1), Bacon.constant(2), (a:number, b:number) => { - console.log(a + b); - }); + // The following example would log the number 3. + // NOTE: had to explicitly specify the typing for `a:number, b:number` + Bacon.onValues(Bacon.constant(1), Bacon.constant(2), (a:number, b:number) => { + console.log(a + b); + }); } function $Event() { - new Bacon.Next("value"); - new Bacon.Next(() => "value"); + new Bacon.Next("value"); + new Bacon.Next(() => "value"); } function Errors() { - // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: - // NOTE: had to explicitly specify the typing for `flatMap` - Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { - return x > 2 ? new Bacon.Error("too big") : x; - }); + // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: + // NOTE: had to explicitly specify the typing for `flatMap` + Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + return x > 2 ? new Bacon.Error("too big") : x; + }); - // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: - Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { - var isNonCriticalError = (error:string) => Math.random() < .5, - handleNonCriticalError = (error:string) => 42; - return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); - }); + // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: + Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { + var isNonCriticalError = (error:string) => Math.random() < .5, + handleNonCriticalError = (error:string) => 42; + return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); + }); - // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: - Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { - var dangerousFunction = (x:number) => { - throw new Error("dangerous function!"); - }; - try { - return dangerousFunction(x); - } catch (e) { - return new Bacon.Error(e); - } - }); + // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: + Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + var dangerousFunction = (x:number) => { + throw new Error("dangerous function!"); + }; + try { + return dangerousFunction(x); + } catch (e) { + return new Bacon.Error(e); + } + }); - Bacon.once("https://baconjs.github.io/").flatMap(url => { - // `ajaxCall` gives `Error`s on network or server `Error`s. - var ajaxCall = (url:string) => { - return Bacon.fromPromise($.ajax(url)); - }; - return Bacon.retry({ - source: () => ajaxCall(url), - retries: 5, - isRetryable: (error:JQueryXHR) => error.status !== 404, - delay: context => 100 // Just use the same delay always + Bacon.once("https://baconjs.github.io/").flatMap(url => { + // `ajaxCall` gives `Error`s on network or server `Error`s. + var ajaxCall = (url:string) => { + return Bacon.fromPromise($.ajax(url)); + }; + return Bacon.retry({ + source: () => ajaxCall(url), + retries: 5, + isRetryable: (error:JQueryXHR) => error.status !== 404, + delay: context => 100 // Just use the same delay always + }); }); - }); } function JoinPatterns() { - { - // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - var tick = Bacon.interval(1e2, 0), - keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - handleTick = (_:number) => `timestamp: NONE`, - handleKeyEvent = (timestamp:number) => `timestamp: ${timestamp}`; - Bacon.when( - [tick, keyEvent], (_:number, timestamp:number) => handleKeyEvent(timestamp), - [tick], handleTick - ); - // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - } + { + // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + var tick = Bacon.interval(1e2, 0), + keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + handleTick = (_:number) => `timestamp: NONE`, + handleKeyEvent = (timestamp:number) => `timestamp: ${timestamp}`; + Bacon.when( + [tick, keyEvent], (_:number, timestamp:number) => handleKeyEvent(timestamp), + [tick], handleTick + ); + // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + } - { - // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - var a = Bacon.once("a"), - b = Bacon.once("b"), - c = Bacon.once("c"), - f = (a:string, b:string, c:string) => `a = ${a}; b = ${b}; c = ${c}.`; - Bacon.zipWith(f, a, b, c); - Bacon.when([a, b, c], f); - } - { - // The inputs to `Bacon.update` are defined like this: - var initial = 0, - x = Bacon.interval(1e3, 1), - y = Bacon.interval(2e3, 1), - z = Bacon.interval(1.5e3, 1); - // NOTE: had to explicitly specify the typing for `previous:number` - Bacon.update(initial, - [x, y, z], (previous:number, x:number, y:number, z:number) => previous + x + y + z, - [x, y], (previous:number, x:number, y:number) => previous + x + y - ); - // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - } - { - // Here's a simple gaming example: - var scoreMultiplier = Bacon.constant(1), - hitUfo = new Bacon.Bus(), - hitMotherShip = new Bacon.Bus(), - score = Bacon.update(0, - [hitUfo, scoreMultiplier], (score:number, _:number, multiplier:number) => score + 100 * multiplier, - [hitMotherShip], (score:number, _:number) => score + 2000 - ); - // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - } + { + // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + var a = Bacon.once("a"), + b = Bacon.once("b"), + c = Bacon.once("c"), + f = (a:string, b:string, c:string) => `a = ${a}; b = ${b}; c = ${c}.`; + Bacon.zipWith(f, a, b, c); + Bacon.when([a, b, c], f); + } + { + // The inputs to `Bacon.update` are defined like this: + var initial = 0, + x = Bacon.interval(1e3, 1), + y = Bacon.interval(2e3, 1), + z = Bacon.interval(1.5e3, 1); + // NOTE: had to explicitly specify the typing for `previous:number` + Bacon.update(initial, + [x, y, z], (previous:number, x:number, y:number, z:number) => previous + x + y + z, + [x, y], (previous:number, x:number, y:number) => previous + x + y + ); + // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + } + { + // Here's a simple gaming example: + var scoreMultiplier = Bacon.constant(1), + hitUfo = new Bacon.Bus(), + hitMotherShip = new Bacon.Bus(), + score = Bacon.update(0, + [hitUfo, scoreMultiplier], (score:number, _:number, multiplier:number) => score + 100 * multiplier, + [hitMotherShip], (score:number, _:number) => score + 2000 + ); + // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + } + { + // Join patterns as a "chemical machine". A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + let oxygen = Bacon.interval(1e3, "O"), + hydrogen = Bacon.interval(2e3, "H"), + carbon = Bacon.interval(1.5e3, "C"), + makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + + Bacon.when( + [oxygen, hydrogen, hydrogen], makeWater, + [oxygen, carbon], makeCarbonMonoxide + ); + // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + } +} + +function JoinPatternsAndProperties() { + { + // Join patterns and properties + //Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that + // -- updating price sets total to price * quantity; + // -- updating quantity sets total to price * quantity; + // -- updating total sets price to total / quantity. + let random = (x:number) => Math.round(x * Math.random()), + id = (x:A):A => x; + let $quantity = Bacon.interval(1e3, 10).map(random), + $price = Bacon.interval(2e3, 100).map(random), + $total = Bacon.interval(1.5e3, 1000).map(random); + let quantity = $quantity.toProperty(1), + price = Bacon.when( + [$price], id, + [$total, quantity], (x, y) => x / y + ).toProperty(0), + total = Bacon.when( + [$total], id, + [$price, quantity], (x, y) => x * y, + [price, $quantity], (x, y) => x * y + ).toProperty(0); + } +} + +function JoinPatternsAndBaconBus() { + { + // Join patterns and `Bacon.Bus` + // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + // Availability of chopsticks are implemented using bus. + let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + // Hungry could be any type of observable, but we'll use bus here. + hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + eat = (i:number) => () => { + setTimeout(() => { + console.log("done!"); + chopsticks[i].push({}); + chopsticks[(i + 1) % 3].push({}); + }, 1e3); + return `philosopher ${i} eating`; + }, + // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + dining = Bacon.when( + [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + ).log("dining"); + // Make all chopsticks initially available. + chopsticks[0].push({}); + chopsticks[1].push({}); + chopsticks[2].push({}); + // Make philosophers hungry in some way, in this case we just push to their bus. + for (var i = 0; i < 3; i++) { + hungry[0].push({}); + hungry[1].push({}); + hungry[2].push({}); + } + } } diff --git a/baconjs/baconjs.d.ts b/baconjs/baconjs.d.ts index 2021b3dd7..4717d0e95 100644 --- a/baconjs/baconjs.d.ts +++ b/baconjs/baconjs.d.ts @@ -4,2070 +4,2074 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// +/// /// interface JQuery { - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. - * @param {string} eventName - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click"); - */ - asEventStream(eventName:string):Bacon.EventStream; + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. + * @param {string} eventName + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click"); + */ + asEventStream(eventName:string):Bacon.EventStream; - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector`. - * @param {string} eventName - * @param {string} selector - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click", ".more-specific-selector"); - */ - asEventStream(eventName:string, selector:string):Bacon.EventStream; + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector`. + * @param {string} eventName + * @param {string} selector + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector"); + */ + asEventStream(eventName:string, selector:string):Bacon.EventStream; - /** - * @callback JQuery#asEventStream1~f - * @param {JQueryEventObject} event - * @param {*[]} args - * @returns {A} - */ - /** - * @method JQuery#asEventStream1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a function `f` that processes the jQuery event and its parameters. - * @param {string} eventName - * @param {JQuery#asEventStream1~f} f - * @returns {EventStream} - * @example - * $("#my-div").asEventStream("click", (event, args) => args[0]); - */ - asEventStream(eventName:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; + /** + * @callback JQuery#asEventStream1~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {JQuery#asEventStream1~f} f + * @returns {EventStream} + * @example + * $("#my-div").asEventStream("click", (event, args) => args[0]); + */ + asEventStream(eventName:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; - /** - * @callback JQuery#asEventStream2~f - * @param {JQueryEventObject} event - * @param {*[]} args - * @returns {A} - */ - /** - * @method JQuery#asEventStream2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector` and a function `f` that processes the jQuery event and its parameters. - * @param {string} eventName - * @param {string} selector - * @param {JQuery#asEventStream2~f} f - * @returns {Bacon.EventStream} - * @example - * $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); - */ - asEventStream(eventName:string, selector:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; + /** + * @callback JQuery#asEventStream2~f + * @param {JQueryEventObject} event + * @param {*[]} args + * @returns {A} + */ + /** + * @method JQuery#asEventStream2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a jQuery or Zepto.js object. You can pass an argument to add a jQuery live `selector` and a function `f` that processes the jQuery event and its parameters. + * @param {string} eventName + * @param {string} selector + * @param {JQuery#asEventStream2~f} f + * @returns {Bacon.EventStream} + * @example + * $("#my-div").asEventStream("click", ".more-specific-selector", (event, args) => args[0]); + */ + asEventStream(eventName:string, selector:string, f:(event:JQueryEventObject, args:any[]) => A):Bacon.EventStream; } /** @module Bacon */ declare module Bacon { - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. - * @param {Promise|JQueryXHR} promise - * @param {boolean} [abort] - * @returns {EventStream} - * @example - * Bacon.fromPromise($.ajax("https://baconjs.github.io/")); - * Bacon.fromPromise(Promise.resolve(1)); - * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); - * Bacon.fromPromise(Promise.resolve(1), false); - */ - function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; - - /** - * @callback Bacon.fromPromise~eventTransformer - * @param {A} value - * @returns {(Initial|Next|End|Error)[]} - */ - /** - * @function Bacon.fromPromise - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. - * @param {Promise|JQueryXHR} promise - * @param {boolean} abort - * @param {Bacon.fromPromise~eventTransformer} eventTransformer - * @returns {EventStream} - * @example - * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { - * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - * }); - * Bacon.fromPromise(Promise.resolve(1), false, n => { - * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; - * }); - */ - function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. - * @param {EventTarget|NodeJS.EventEmitter|JQuery} target - * @param {string} eventName - * @returns {EventStream} - * @example - * Bacon.fromEvent(document.body, "click").onValue(() => { - * alert("Bacon!"); - * }); - * Bacon.fromEvent(process.stdin, "readable", () => { - * alert("Bacon!"); - * }); - * Bacon.fromEvent($("body"), "click").onValue(() => { - * alert("Bacon!"); - * }); - */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; - - /** - * @callback Bacon.fromEvent~eventTransformer - * @param {A} event - * @returns {B} - */ - /** - * @function Bacon.fromEvent - * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. - * @param {EventTarget|NodeJS.EventEmitter|JQuery} target - * @param {string} eventName - * @param {Bacon.fromEvent~eventTransformer} eventTransformer - * @returns {EventStream} - * @example - * Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { - * alert("Bacon!"); - * }); - */ - function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string, eventTransformer:(event:A) => B):EventStream; - - /** - * @callback Bacon.fromCallback1~f - * @param {Bacon.fromCallback1~callback} callback - * @returns {void} - */ - /** - * @callback Bacon.fromCallback1~callback - * @param {...*} args - * @returns {void} - */ - /** - * @function Bacon.fromCallback1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. - * @param {Bacon.fromCallback1~f} f - * @returns {EventStream} - * @example - * // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. - * Bacon.fromCallback(callback => { - * setTimeout(() => { - * callback("Bacon!"); - * }, 1000); - * }); - */ - function fromCallback(f:(callback:(...args:any[]) => void) => void):EventStream; - - /** - * @callback Bacon.fromCallback2~f - * @param {...*} args - * @returns {void} - */ - /** - * @function Bacon.fromCallback2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. - * @param {Bacon.fromCallback2~f} f - * @param {...*} args - * @returns {EventStream} - * @example - * // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": - * Bacon.fromCallback((a, b, callback) => { - * callback(a + " " + b); - * }, Bacon.constant("bacon"), "rules").log(); - */ - function fromCallback(f:(...args:any[]) => void, ...args:any[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. The function is supposed to call its callback just once. - * @param {Object} object - * @param {string} methodName - * @param {...*} args - * @returns {EventStream} - */ - function fromCallback(object:Object, methodName:string, ...args:any[]):EventStream; - - /** - * @callback Bacon.fromNodeCallback~f - * @param {Bacon.fromNodeCallback~callback} callback - * @returns {void} - */ - /** - * @callback Bacon.fromNodeCallback~callback - * @param {E} error - * @param {A} data - * @returns {void} - */ - /** - * @function Bacon.fromNodeCallback - * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a Node.js `callback`: callback(error, data), where error is `null` if everything is fine. The function is supposed to call its callback just once. - * @param {Bacon.fromNodeCallback~f} f - * @param {...*} args - * @returns {EventStream} - * @example - * { - * let fs = require("fs"), - * read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); - * read.onError(error => { - * console.log("Reading failed: " + error); - * }); - * read.onValue(value => { - * console.log("Read contents: " + value); - * }); - * } - */ - function fromNodeCallback(f:(callback:(error:E, data:A) => void) => void, ...args:any[]):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. - * @param {Object} object - * @param {string} methodName - * @param {...*} args - * @returns {EventStream} - */ - function fromNodeCallback(object:Object, methodName:string, ...args:any[]):EventStream; - - /** - * @callback Bacon.fromPoll~f - * @returns {Next|End} - */ - /** - * @function Bacon.fromPoll - * @description Polls given function `f` with given `interval`. Function should return events: either [Next]{@link Bacon.Next} or [End]{@link Bacon.End}. Polling occurs only when there are subscribers to the stream. Polling ends permanently when `f` returns [End]{@link Bacon.End}. - * @param {number} interval - * @param {Bacon.fromPoll~f} f - * @returns {EventStream} - */ - function fromPoll(interval:number, f:() => Next|End):EventStream; - - /** - * @function Bacon.once - * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given single `value` for the first subscriber. The stream will end immediately after this value. You can also send an [Error]{@link Bacon.Error} event instead of a `value`. - * @param {A|Error} value - * @returns {EventStream} - * @example - * Bacon.once(new Bacon.Error("fail")); - */ - function once(value:A|Error):EventStream; - - /** - * @function - * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given series of `values` (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [Error]{@link Bacon.Error} events, or any combination of pure values and error events. - * @param {(A|Error)[]} values - * @returns {EventStream} - * @example - * Bacon.fromArray([1, new Bacon.Error("")]); - */ - function fromArray(values:(A|Error)[]):EventStream; - - /** - * @function - * @description Repeats the single `value` indefinitely with the given `interval` (in milliseconds). - * @param {number} interval - * @param {A} value - * @returns {EventStream} - */ - function interval(interval:number, value:A):EventStream; - - /** - * @function - * @description Creates a [EventStream]{@link Bacon.EventStream} containing given `values` (given as array) with the given `interval` (in milliseconds). - * @param {number} interval - * @param {A[]} values - * @returns {EventStream} - */ - function sequentially(interval:number, values:A[]):EventStream; - - /** - * @function - * @description Repeats given `values` indefinitely with then given `interval` (in milliseconds). - * @param {number} interval - * @param {A[]} values - * @returns {EventStream} - * @example - * // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: - * Bacon.fromArray([1, new Bacon.Error("")]); - */ - function repeatedly(interval:number, values:A[]):EventStream; - - /** - * @callback Bacon.repeat~f - * @param {number} iteration - * @returns {boolean|Observable} - */ - /** - * @function Bacon.repeat - * @description Calls generator function `f` which is expected to return an [Observable]{@link Bacon.Observable}. The returned [EventStream]{@link Bacon.EventStream} contains values and errors from the spawned observable. When the spawned Observable ends, the generator `f` is called again to spawn a new Observable. This is repeated until the generator `f` returns a falsy value (such as `undefined` or `false`). The generator `f` is called with one argument — `iteration` number starting from `0`. - * @param {Bacon.repeat~f} f - * @returns {EventStream} - * @example - * // The following will produce values `0,1,2`. - * Bacon.repeat(i => { - * if (i < 3) { - * return Bacon.once(i); - * } else { - * return false; - * } - * }).log(); - */ - function repeat(f:(iteration:number) => boolean|Observable):EventStream; - - /** - * @function Bacon.never - * @description Creates an [EventStream]{@link Bacon.EventStream} that immediately ends. - * @returns {EventStream} - */ - function never():EventStream; - - /** - * @function - * @description Creates a single-element [EventStream]{@link Bacon.EventStream} that produces given `value` after a given `delay` (in milliseconds). - * @param {number} delay - * @param {A} value - * @returns {EventStream} - */ - function later(delay:number, value:A):EventStream; - - /** - * @function - * @description Creates a constant [Property]{@link Bacon.Property} with value `x`. - * @param {A} x - * @returns {Property} - */ - function constant(x:A):Property; - - /** - * @callback Bacon.fromBinder~subscribe - * @param {Bacon.fromBinder~sink} sink - * @returns {Bacon.fromBinder~unsubscribe} - */ - /** - * @callback Bacon.fromBinder~sink - * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value - * @returns {void} - */ - /** - * @callback Bacon.fromBinder~unsubscribe - * @returns {void} - */ - /** - * @function Bacon.fromBinder - * @description Creates an [EventStream]{@link Bacon.EventStream} with the given [subscribe]{@link Bacon.fromBinder~subscribe} function. The parameter `subscribe` is a function that accepts a [sink]{@link Bacon.fromBinder~sink} which is a function that your `subscribe` function can "push" events to. You can push: a plain value, like `"first value"`; an [Event]{@link Bacon.Event} object including [Error]{@link Bacon.Error} (wraps an error) and [End]{@link Bacon.End} (indicates stream end); an array of event objects at once. The `subscribe` function must return a function. Let's call that function [unsubscribe]{@link Bacon.fromBinder~unsubscribe}. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the `subscribe` function reserved. The `sink` function may return [noMore]{@link Bacon.noMore} (as well as [more]{@link Bacon.more} or any other value). If it returns `noMore`, no further events will be consumed by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g., by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored, but doing so can increase performance in rare cases. The EventStream will wrap your `subscribe` function so that it will only be called when the first stream listener is added, and the `unsubscribe` function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the `subscribe` function. - * @param {Bacon.fromBinder~subscribe} subscribe - * @returns {EventStream} - * @example - * let stream = Bacon.fromBinder(sink => { - * sink("first value"); - * sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); - * sink(new Bacon.Next(() => { - * return "This one will be evaluated lazily" - * })); - * sink(new Bacon.Error("oops, an error")); - * sink(new Bacon.End()); - * return () => { - * // unsub functionality here, this one's a no-op - * }; - * }); - * stream.log(); - */ - function fromBinder(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; - - /** - * @interface - * @see Bacon.more - */ - interface More { - } - /** - * @property more - * @constant - * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. - */ - var more:More; - - /** - * @interface - * @see Bacon.noMore - */ - interface NoMore { - } - /** - * @property noMore - * @constant - * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. - */ - var noMore:NoMore; - - /** - * @class Observable - * @description A superclass for [EventStream]{@link Bacon.EventStream} and [Property]{@link Bacon.Property}. - * */ - interface Observable { /** - * @callback Observable#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback Observable#onValue~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onValue - * @description Subscribes a given handler function `f` to the [Observable]{@link Bacon.Observable}. Function will be called for each new value. This is the simplest way to assign a side-effect to an Observable. The difference to the [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe} methods is that the actual stream `value`s are received, instead of [Event]{@link Bacon.Event} objects. [EventStream.onValue]{@link Bacon.EventStream#onValue} and [Property.onValue]{@link Bacon.Property#onValue} behave similarly, except that the latter also pushes the initial value of the Property, in case there is one. - * @param {Observable#onValue~f} f - * @returns {Observable#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback Observable#onError~f - * @param {E} error - * @returns {void} - */ - /** - * @callback Observable#onError~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onError - * @description Subscribes a given handler function `f` to [Error]{@link Bacon.Error} events. The function `f` will be called for each error in the [Observable]{@link Bacon.Observable}. - * @param {Observable#onError~f} f - * @returns {Observable#onError~unsubscribe} - */ - onError(f:(error:E) => void):() => void; - - /** - * @callback Observable#onEnd~f - * @returns {void} - */ - /** - * @callback Observable#onEnd~unsubscribe - * @returns {void} - */ - /** - * @method Observable#onEnd - * @description Subscribes a given handler function `f` to [End]{@link Bacon.End} event. The function `f` will be called when the [Observable]{@link Bacon.Observable} ends. Just like [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. - * @param {Observable#onEnd~f} f - * @returns {Observable#onEnd~unsubscribe} - */ - onEnd(f:() => void):() => void; - - /** - * @callback Observable#toPromise~promiseCtr - * @param {A} value - * @returns {Promise} - */ - /** - * @method Observable#toPromise - * @description Returns a Promise which will be resolved with the last event coming from an [Observable]{@link Bacon.Observable}. The global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. Use a shim if you need to support legacy browsers or platforms. - * @param {Observable#toPromise~promiseCtr} [promiseCtr] - * @returns {Promise} - */ - toPromise(promiseCtr?:(value:A) => Promise):Promise; - - /** - * @callback Observable#firstToPromise~promiseCtr - * @param {A} value - * @returns {Promise} - */ - /** - * @method Observable#firstToPromise - * @description Returns a Promise which will be resolved with the first event coming from an [Observable]{@link Bacon.Observable}. Like [Observable.toPromise]{@link Bacon.Observable#toPromise}, the global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. - * @param {Observable#firstToPromise~promiseCtr} [promiseCtr] - * @returns {Promise} - */ - firstToPromise(promiseCtr?:(value:A) => Promise):Promise; - - /** - * @method - * @description Throttles the [Observable]{@link Bacon.Observable} using a buffer so that at most one value event in `minimumInteval` is issued. Unlike [EventStream.throttle]{@link Bacon.EventStream#throttle} and [Property.throttle]{@link Bacon.Property#throttle}, it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per `minimumInterval`. - * @param {number} minimumInterval + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. + * @param {Promise|JQueryXHR} promise + * @param {boolean} [abort] * @returns {EventStream} + * @example + * Bacon.fromPromise($.ajax("https://baconjs.github.io/")); + * Bacon.fromPromise(Promise.resolve(1)); + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); + * Bacon.fromPromise(Promise.resolve(1), false); */ - bufferingThrottle(minimumInterval:number):EventStream; + function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; /** - * @callback Observable#flatMap~f + * @callback Bacon.fromPromise~eventTransformer * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} + * @returns {(Initial|Next|End|Error)[]} */ /** - * @method Observable#flatMap - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMap]{@link Bacon.Observable#flatMap} is always an EventStream. The "Function Construction rules" apply here. `flatMap` can be used conveniently with [Bacon.once]{@link Bacon.once} and [Bacon.never]{@link Bacon.never} for converting and filtering at the same time, including only some of the results. - * @param {Observable#flatMap~f} f + * @function Bacon.fromPromise + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. + * @param {Promise|JQueryXHR} promise + * @param {boolean} abort + * @param {Bacon.fromPromise~eventTransformer} eventTransformer * @returns {EventStream} * @example - * // Converting strings to integers, skipping empty values: - * Bacon.once("").flatMap(text => { - * return text != "" ? parseInt(text) : Bacon.never(); + * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true, (n:string) => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; + * }); + * Bacon.fromPromise(Promise.resolve(1), false, n => { + * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; * }); */ - flatMap(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; /** - * @callback Observable#flatMapLatest~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapLatest - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, but instead of including events from all spawned streams, only includes them from the latest spawned stream into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapLatest]{@link Bacon.Observable#flatMapLatest} is always an EventStream. - * @param {Observable#flatMapLatest~f} f - * @returns {EventStream} - */ - flatMapLatest(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapFirst~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapFirst - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f` only if the previously spawned stream has ended, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapFirst]{@link Bacon.Observable#flatMapFirst} is always an EventStream. - * @param {Observable#flatMapFirst~f} f - * @returns {EventStream} - */ - flatMapFirst(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapError~f - * @param {E} error - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapError - * @description For each [Error]{@link Bacon.Error} event in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapError]{@link Bacon.Observable#flatMapError} is always an EventStream. - * @param {Observable#flatMapError~f} f - * @returns {EventStream} - */ - flatMapError(f:(error:E) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapWithConcurrencyLimit~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapWithConcurrencyLimit - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events by `limit` amount. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. [flatMapConcat]{@link Bacon.Observable#flatMapConcat} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(1) (only one input active), and [flatMap]{@link Bacon.Observable#flatMap} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(∞) (all inputs are piped to output). The result of `flatMapWithConcurrencyLimit` is always an EventStream. - * @param {number} limit - * @param {Observable#flatMapWithConcurrencyLimit~f} f - * @returns {EventStream} - */ - flatMapWithConcurrencyLimit(limit:number, f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#flatMapConcat~f - * @param {A} value - * @returns {B|Initial|Next|End|Error|Observable} - */ - /** - * @method Observable#flatMapConcat - * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events to 1. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of `flatMapConcat` is always an EventStream. - * @param {Observable#flatMapConcat~f} f - * @returns {EventStream} - */ - flatMapConcat(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; - - /** - * @callback Observable#scan~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#scan - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, resulting to a [Property]{@link Bacon.Property}. For example, you might use zero as `seed` and a "plus" function as the accumulator to create an "integral" Property. When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch: the starting value for `r` depends on whether `p` has an initial value when `scan` is applied. If there's no initial value, this works identically to `[EventStream]{@link Bacon.EventStream}.scan`: the `seed` will be the initial value of `r`. However, if `r` already has a current/initial value `x`, the seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense, because there can only be 1 initial value for a Property at a time. - * @param {B} seed - * @param {Observable#scan~f} f - * @returns {Property} + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target + * @param {string} eventName + * @returns {EventStream} * @example - * Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); - */ - scan(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#fold~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#fold - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. - * @param {B} seed - * @param {Observable#fold~f} f - * @returns {Property} - */ - fold(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#reduce~f - * @param {B} acc - * @param {A} next - * @returns {B} - */ - /** - * @method Observable#reduce - * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. - * @param {B} seed - * @param {Observable#reduce~f} f - * @returns {Property} - */ - reduce(seed:B, f:(acc:B, next:A) => B):Property; - - /** - * @callback Observable#diff~f - * @param {A} a - * @param {B} b - * @returns {B} - */ - /** - * @method Observable#diff - * @description Returns a [Property]{@link Bacon.Property} that represents the result of a comparison `f` between the previous and current value of the [Observable]{@link Bacon.Observable}. For the initial value of the Observable, the previous value will be the given `start`. - * @param {A} start - * @param {Observable#diff~f} f - * @returns {Property} - * @example - * Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); - */ - diff(start:A, f:(a:A, b:A) => B):Property; - - /** - * @callback Observable#zip~f - * @param {A} a - * @param {B} b - * @returns {C} - */ - /** - * @method Observable#zip - * @description Returns an [EventStream]{@link Bacon.EventStream} with elements pair-wise lined up with events from this and the `other` EventStream. A zipped EventStream will publish only when it has a value from each EventStream and will only produce values up to when any single EventStream ends. The given function `f` is used to create the result value from value in the two source EventStream. If no function `f` is given, the values are zipped into an array. Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable. - * @param {EventStream} other - * @param {Observable#zip~f} f - * @returns {EventStream} - * @example - * { - * let x = Bacon.fromArray([1, 2]), - * y = Bacon.fromArray([3, 4]); - * x.zip(y, (x, y) => x + y); - * } - */ - zip(other:EventStream, f:(a:A, b:B) => C):EventStream; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} that represents a "sliding window" into the history of the values of the [Observable]{@link Bacon.Observable}. The resulting Property will have a value that is an array containing the last `n` values of the original Observable, where `n` is at most the value of the `max` argument, and at least the value of the `min` argument. If the `min` argument is omitted, there's no lower limit of values. - * @param {number} max - * @param {number} [min] - * @returns {Property} - * @example - * // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: - * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); - * // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: - * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); - */ - slidingWindow(max:number, min?:number):Property; - - /** - * @callback Observable#combine~f - * @param {A} a - * @param {B} b - * @returns {C} - */ - /** - * @method Observable#combine - * @description Combines the latest values of the two [EventStream]{@link Bacon.EventStream}s or [Property]{@link Bacon.Property}s using a two-arg function `f`. The result is a Property. - * @param {Property} property2 - * @param {Observable#combine~f} f - * @returns {Property} - */ - combine(property2:Property, f:(a:A, b:B) => C):Property; - - /** - * @callback Observable#withStateMachine~f - * @param {B} state - * @param {Initial|Next|End|Error} event - * @returns {[B, (Initial|Next|End|Error)[]]} - */ - /** - * @method Observable#withStateMachine - * @description Lets you run a state machine on an [Observable]{@link Bacon.Observable}. Give it an initial state `initState` object and a state transformation function `f` that processes each incoming [Event]{@link Bacon.Event} and returns and array containing the next `state` and an array of output Event's. - * @param {B} initState - * @param {Observable#withStateMachine~f} f - * @returns {EventStream} - * @example - * // Calculate the total sum of all numbers in the stream and output the value on stream end: - * Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { - * if (event.hasValue()) { - * had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> - * return [sum + event.value(), []]; - * } else if (event.isEnd()) { - * return [undefined, [new Bacon.Next(sum), event]]; - * } else { - * return [sum, [event]]; - * } + * Bacon.fromEvent(document.body, "click").onValue(() => { + * alert("Bacon!"); + * }); + * Bacon.fromEvent(process.stdin, "readable", () => { + * alert("Bacon!"); + * }); + * Bacon.fromEvent($("body"), "click").onValue(() => { + * alert("Bacon!"); * }); */ - withStateMachine(initState:B, f:(state:B, event:Initial|Next|End|Error) => [B, (Initial|Next|End|Error)[]]):EventStream; + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string):EventStream; /** - * @method - * @description Decodes input [Observable]{@link Bacon.Observable} using the given `mapping`. Is a bit like a switch-case or the decode function in Oracle SQL. The return value of `decode` is always a [Property]{@link Bacon.Property}. - * @param {Object} mapping - * @returns {Property} - * @example - * let property = Bacon.fromArray([1, 2, 3]).toProperty(), - * who = Bacon.fromArray(["A", "B", "C"]).toProperty(); - * // The following would map the value 1 into the string "mike" and the value 2 into the value of the `who` property: - * property.decode({1: "mike", 2: who}); - * - * // You can compose static and dynamic data quite freely, as in: - * property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); - */ - decode(mapping:Object):Property; - - /** - * @method - * @description Creates a [Property]{@link Bacon.Property} that indicates whether Observable is awaiting `otherObservable`, i.e. has produced a value after the latest value from `otherObservable`. - * @param {Observable} otherObservable - * @returns {Property} - * @example - * // This is handy for keeping track whether we are currently awaiting an AJAX response: - * let ajaxRequest = >{}, - * ajaxResponse = >{}, - * showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); - */ - awaiting(otherObservable:Observable):Property; - } - - /** - * @class EventStream - * @augments Bacon.Observable - * @description A stream of events. - * */ - interface EventStream extends Observable { - /** - * @callback EventStream#map~f - * @param {A} value + * @callback Bacon.fromEvent~eventTransformer + * @param {A} event * @returns {B} */ /** - * @method EventStream#map - * @description Maps [EventStream]{@link Bacon.EventStream} values using given function `f`, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. - * @param {EventStream#map~f} f + * @function Bacon.fromEvent + * @description Creates an [EventStream]{@link Bacon.EventStream} from events on a DOM EventTarget or Node.JS EventEmitter object, or an object that supports event listeners using `on`/`off` methods. You can pass a function `eventTransformer` that transforms the emitted events' parameters. + * @param {EventTarget|NodeJS.EventEmitter|JQuery} target + * @param {string} eventName + * @param {Bacon.fromEvent~eventTransformer} eventTransformer * @returns {EventStream} - * */ - map(f:(value:A) => B):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} values using given `constant` value, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. - * @param {B} constant - * @returns {EventStream} - * */ - map(constant:B):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} values using given `propertyExtractor` string like ".keyCode", returning a new EventStream. So, if `propertyExtractor` is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If `keyCode` was a function, the result EventStream would contain the values returned by the function. The "Function Construction rules" apply here. The `map` method, among many others, uses lazy evaluation. - * @param {string} propertyExtractor - * @returns {EventStream} - * */ - map(propertyExtractor:string):EventStream; - - /** - * @method - * @description Maps [EventStream]{@link Bacon.EventStream} events to the current value of the given [Property]{@link Bacon.Property} `property`. This is equivalent to [Property.sampledBy]{@link Bacon.Property#sampledBy}. - * @param {Property} property - * @returns {EventStream} - */ - map(property:Property):EventStream; - - /** - * @callback EventStream#mapError~f - * @param {E} error - * @returns {B} - */ - /** - * @method EventStream#mapError - * @description Maps [EventStream]{@link Bacon.EventStream} [Error]{@link Bacon.Error}s using given function `f`. More specifically, feeds the "error" field of the Error event to the function and produces a [Next]{@link Bacon.Next} event based on the return value. The "Function Construction rules" apply here. - * @param {EventStream#mapError~f} f - * @returns {EventStream} - */ - mapError(f:(error:E) => B):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns `false`. - * @returns {EventStream} - */ - errors():EventStream; - - /** - * @method - * @description Skips all [Error]{@link Bacon.Error}s. - * @returns {EventStream} - */ - skipErrors():EventStream; - - /** - * @callback EventStream#mapEnd~f - * @returns {A} - */ - /** - * @method EventStream#mapEnd - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. The value is created by calling the given function `f` when the source [EventStream]{@link Bacon.EventStream} ends. - * @param {EventStream#mapEnd~f} f - * @returns {EventStream} - */ - mapEnd(f:() => A):EventStream; - - /** - * @method - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. A static `value` is used. - * @param {A} value - * @returns {EventStream} - */ - mapEnd(value:A):EventStream; - - /** - * @callback EventStream#filter~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#filter - * @description Filters [EventStream]{@link Bacon.EventStream} `value`s using a given predicate function `f`. - * @param {EventStream#filter~f} f - * @returns {EventStream} - */ - filter(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `constant` value (`true` to include all, `false` to exclude all). - * @param {boolean} bool - * @returns {EventStream} - */ - filter(bool:boolean):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `propertyExtractor` string (like ".isValuable"). - * @param {string} propertyExtractor - * @returns {EventStream} - */ - filter(propertyExtractor:string):EventStream; - - /** - * @method - * @description Filters [EventStream]{@link Bacon.EventStream} values based on the value of a [Property]{@link Bacon.Property} `property`. [Event]{@link Bacon.Event} will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. - * @param {Property} property - * @returns {EventStream} - */ - filter(property:Property):EventStream; - - /** - * @callback EventStream#takeWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#takeWhile - * @description Takes [EventStream]{@link Bacon.EventStream} values while given predicate function `f` holds `true`, and then ends. - * @param {EventStream#takeWhile} f - * @returns {EventStream} - */ - takeWhile(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Takes [EventStream]{@link Bacon.EventStream} values while the value of a `property` holds `true`, and then ends. - * @param {Property} property - * @returns {EventStream} - */ - takeWhile(property:Property):EventStream; - - /** - * @method - * @description Takes at most n elements from the [EventStream]{@link Bacon.EventStream}. Equal to `Bacon.never()` if `n <= 0`. - * @param {number} n - * @returns {EventStream} - */ - take(n:number):EventStream; - - /** - * @method - * @description Takes elements from [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in the EventStream `stream`. If `stream` ends without value, it is ignored. - * @param {EventStream} stream - * @returns {EventStream} - */ - takeUntil(stream:EventStream):EventStream; - - /** - * @method - * @description Takes the first element from the [EventStream]{@link Bacon.EventStream}. Essentially [Observable.take]{@link Bacon.EventStream#take}(1). - * @returns {EventStream} - */ - first():EventStream; - - /** - * @method - * @description Takes the last element from the [EventStream]{@link Bacon.EventStream}. None, if EventStream is empty. - * @returns {EventStream} * @example - * // This creates the stream which doesn't produce any events and never ends: - * Bacon.interval(1e1, 0).last(); - */ - last():EventStream; - - /** - * @method - * @description Skips the first `n` elements from the [EventStream]{@link Bacon.EventStream}. - * @param {number} n - * @returns {EventStream} - */ - skip(n:number):EventStream; - - /** - * @method - * @description Delays the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). - * @param {number} delay - * @returns {EventStream} - */ - delay(delay:number):EventStream; - - /** - * @method EventStream#throttle - * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. - * @param {number} delay - * @returns {EventStream} - */ - throttle(delay:number):EventStream; - - /** - * @method EventStream#debounce - * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". The difference of [throttle]{@link Bacon.EventStream#throttle} and [debounce]{@link Bacon.EventStream#debounce} is the same as it is in the same methods in jQuery. - * @param {number} delay - * @returns {EventStream} - */ - debounce(delay:number):EventStream; - - /** - * @method - * @description Passes the first event in the [EventStream]{@link Bacon.EventStream} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. - * @param {number} delay - * @returns {EventStream} - */ - debounceImmediate(delay:number):EventStream; - - /** - * @callback EventStream#doAction~f - * @param {A} value - * @returns {void} - */ - /** - * @method EventStream#doAction - * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {EventStream#doAction~f} f - * @returns {EventStream} - */ - doAction(f:(value:A) => void):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {string} propertyExtractor - * @returns {EventStream} - */ - doAction(propertyExtractor:string):EventStream; - - /** - * @callback EventStream#doError~f - * @param {E} error - * @returns {void} - */ - /** - * @method EventStream#doError - * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as `doAction` but for errors. - * @param {EventStream#doError~f} f - * @returns {EventStream} - */ - doError(f:(error:E) => void):EventStream; - - /** - * @method - * @description Returns an [EventStream]{@link Bacon.EventStream} that inverts boolean values. - * @returns {EventStream} - */ - not():EventStream; - - /** - * @method EventStream#log - * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original EventStream. Note that as a side-effect, the EventStream will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. - * @param {string} [label] - * @returns {EventStream} - */ - log(label?:string):EventStream; - - /** - * @method EventStream#doLog - * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. - * @returns {EventStream} - */ - doLog():EventStream; - - /** - * @method - * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned EventStream. - * @returns {EventStream} - */ - endOnError():EventStream; - - /** - * @callback EventStream#endOnError~f - * @param {E} error - * @returns {boolean} - */ - /** - * @method EventStream#endOnError - * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned EventStream. - * @param {EventStream#endOnError} f - * @returns {EventStream} - */ - endOnError(f:(error:E) => boolean):EventStream; - - /** - * @callback EventStream#withHandler~f - * @param {Initial|Next|End|Error} event - * @returns {*} - */ - /** - * @method EventStream#withHandler - * @description Lets you do more custom event handling on [EventStream]{@link Bacon.EventStream}: you get all events to your function `f` and you can output any number of events and end the stream if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. - * @param {EventStream#withHandler~f} f - * @returns {EventStream} - * @example - * // Send an error and end the stream in case a value is below zero: - * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { - * if (event.hasValue() && event.value() < 0) { - * this.push(new Bacon.Error("Value below zero")); - * return this.push(new Bacon.End()); - * } else { - * return this.push(event); - * } + * Bacon.fromEvent(document.body, "click", (event:MouseEvent) => event.clientX).onValue(clientX => { + * alert("Bacon!"); * }); */ - withHandler(f:(event:Initial|Next|End|Error) => any):EventStream; + function fromEvent(target:EventTarget|NodeJS.EventEmitter|JQuery, eventName:string, eventTransformer:(event:A) => B):EventStream; /** - * @method - * @description Sets the name of the [EventStream]{@link Bacon.EventStream}. Overrides the default implementation of `toString` and `inspect`. Returns itself. - * @param {string} newName - * @returns {EventStream} - */ - name(newName:string):EventStream; - - /** - * @method - * @description Sets the structured description of the [EventStream]{@link Bacon.EventStream}. The `toString` and `inspect` methods use this data recursively to create a string representation for the `EventStream`. This method is probably useful for Bacon core/library/plugin development only. - * @param {...*} param - * @returns {EventStream} - * @example - * let src = Bacon.once(1), - * obs = src.map(x => -x); - * - * console.log(obs.toString()); - * // Bacon.once(1).map(function) - * - * obs.withDescription(src, "times", -1); - * console.log(obs.toString()); - * // Bacon.once(1).times(-1) - */ - withDescription(...param:any[]):EventStream; - - /** - * @callback EventStream#groupBy1~keyF - * @param {A} value - * @returns {B} - */ - /** - * @method EventStream#groupBy1 - * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. - * @param {EventStream#groupBy1~keyF} keyF - * @returns {EventStream>} - */ - groupBy(keyF:(value:A) => B):EventStream>; - - /** - * @callback keyF - * @param {A} value - * @returns {B} - */ - /** - * @callback limitF - * @param {EventStream} groupedStream - * @param {Initial|Next|End|Error} groupStartingEvent - * @returns {EventStream} - */ - /** - * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. `limitF` is provided to limit grouped stream life. EventStream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream and the original [Event]{@link Bacon.Event} causing the EventStream to start as parameters. - * @param {keyF} keyF - * @param {limitF} limitF - * @returns {EventStream>} Grouped streams. - */ - groupBy(keyF:(value:A) => B, limitF:(groupedStream:EventStream, groupStartingEvent:Initial|Next|End|Error) => EventStream):EventStream>; - - /** - * @callback EventStream#subscribe~f - * @param {Event} event - * @returns {void|NoMore} - */ - /** - * @callback EventStream#subscribe~unsubscribe + * @callback Bacon.fromCallback1~f + * @param {Bacon.fromCallback1~callback} callback * @returns {void} */ /** - * @method EventStream#subscribe - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will receive [Event]{@link Bacon.Event} objects. The [subscribe]{@link EventStream#subscribe} call returns an [unsubscribe function]{@link EventStream#subscribe~unsubscribe} that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore]{@link Bacon.noMore} from the handler function as a reply to an Event. - * @param {EventStream#subscribe~f} f - * @returns {EventStream#subscribe~unsubscribe} - */ - subscribe(f:(event:Event) => void|NoMore):() => void; - - /** - * @callback EventStream#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback EventStream#onValue~unsubscribe - * @returns {void} - */ - /** - * @method EventStream#onValue - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will be called for each new value in the EventStream. This is the simplest way to assign a side-effect to a EventStream. The difference to the [subscribe]{@link Bacon.EventStream#subscribe} method is that the actual EventStream values are received, instead of [Event]{@link Bacon.Event} objects. Just like `subscribe`, this method returns a function for `unsubscribe`ing. - * @param {EventStream#onValue~f} f - * @returns {EventStream#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback EventStream#onValues~f - * @param {*[]} args - * @returns {void} - */ - /** - * @callback EventStream#onValues~unsubscribe - * @returns {void} - */ - /** - * @method EventStream#onValues - * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Like [EventStream.onValue]{@link Bacon.EventStream#onValue}, but splits the value (assuming its an array) as function arguments to `f`. - * @param {EventStream#onValues~f} f - * @returns {EventStream#onValues~unsubscribe} - */ - onValues(f:(...args:any[]) => void):() => void; - - /** - * @callback EventStream#skipDuplicates~isEqual - * @param {A} oldValue - * @param {A} newValue - * @returns {boolean} - */ - /** - * @method EventStream#skipDuplicates - * @description Drops consecutive equal elements of the [EventStream]{@link Bacon.EventStream}. Uses the === operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling [isEqual]{@link EventStream#skipDuplicates~isEqual}. For instance, to do a deep comparison, you can use the `isEqual` function from underscore.js like `stream.skipDuplicates(_.isEqual)`. - * @param {EventStream#skipDuplicates~isEqual} [isEqual] - * @returns {EventStream} - * @example - * Bacon.fromArray([1, 2, 2, 1]).skipDuplicates().log(); - * // > returns [1, 2, 1] in an order - */ - skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):EventStream; - - /** - * @method - * @description Concatenates two [EventStream]{@link Bacon.EventStream}s into one so that it will deliver events from EventStream until it ends and then deliver events from `otherStream`. This means too that events from `otherStream`, occurring before the end of EventStream will not be included in the result EventStream. - * @param {EventStream} otherStream - * @returns {EventStream} - */ - concat(otherStream:EventStream):EventStream; - - /** - * @method - * @description Merges two [EventStream]{@link Bacon.EventStream}s into one that delivers events from both. - * @param {EventStream} otherStream - * @returns {EventStream} - */ - merge(otherStream:EventStream):EventStream; - - /** - * @method - * @description Pauses and buffers the [EventStream]{@link Bacon.EventStream} if last event in `valve` is truthy. All buffered events are released when `valve` becomes falsy. - * @param {Observable} valve - * @returns {EventStream} - */ - holdWhen(valve:Observable):EventStream; - - /** - * @method - * @description Adds a starting `value` to the [EventStream]{@link Bacon.EventStream}, i.e. concats a EventStream containing a single `value` with this EventStream. - * @param {A} value - * @returns {EventStream} - */ - startWith(value:A):EventStream; - - /** - * @callback EventStream#skipWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method EventStream#skipWhile - * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the given predicate function `f` returns falsy once, and then lets all events pass through. - * @param {EventStream#skipWhile~f} f - * @returns {EventStream} - */ - skipWhile(f:(value:A) => boolean):EventStream; - - /** - * @method - * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the value of the given [Property]{@link Bacon.Property} `property` is falsy once, and then lets all events pass through. - * @param {Property} property - * @returns {EventStream} - */ - skipWhile(property:Property):EventStream; - - /** - * @method - * @description Skips elements from the [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in `stream2`. In other words, starts delivering values from `stream` after first event appears in `stream2`. - * @param {EventStream} stream2 - * @returns {EventStream} - */ - skipUntil(stream2:EventStream):EventStream; - - /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} with given `delay` (in milliseconds). The buffer is flushed at most once in the given `delay`. - * @param {number} delay - * @returns {EventStream} - * @example - * // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: - * Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); - */ - bufferWithTime(delay:number):EventStream; - - /** - * @callback EventStream#bufferWithTime~f - * @param {EventStream#bufferWithTime~defer} defer - * @returns {void} - */ - /** - * @callback EventStream#bufferWithTime~defer + * @callback Bacon.fromCallback1~callback * @param {...*} args * @returns {void} */ /** - * @method EventStream#bufferWithTime - * @description Buffers the [EventStream]{@link Bacon.EventStream} with given "defer-function" `f`. - * @param {EventStream#bufferWithTime~f} f - * @returns {EventStream} + * @function Bacon.fromCallback1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback1~f} f + * @returns {EventStream} * @example - * // Here's an equivalent to `stream.bufferWithTime(10)`: - * let stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); - * stream.bufferWithTime(f => { setTimeout(f, 10); }); } + * // This would create a stream that outputs a single value "Bacon!" and ends after that. The use of setTimeout causes the value to be delayed by 1 second. + * Bacon.fromCallback(callback => { + * setTimeout(() => { + * callback("Bacon!"); + * }, 1000); + * }); */ - bufferWithTime(f:(defer:(...args:any[]) => void) => void):EventStream; + function fromCallback(f:(callback:(...args:any[]) => void) => void):EventStream; /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} events with given `count`. The buffer is flushed when it contains the given `count` of elements. - * @param {number} count - * @returns {EventStream} - * @example - * // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. - * Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); + * @callback Bacon.fromCallback2~f + * @param {...*} args + * @returns {void} */ - bufferWithCount(count:number):EventStream; + /** + * @function Bacon.fromCallback2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a `callback`. The function is supposed to call its callback just once. + * @param {Bacon.fromCallback2~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * // You can also give any number of arguments to `fromCallback`, which will be passed to the function. These arguments can be simple variables, Bacon EventStreams or Properties. For example the following will output "Bacon rules": + * Bacon.fromCallback((a, b, callback) => { + * callback(a + " " + b); + * }, Bacon.constant("bacon"), "rules").log(); + */ + function fromCallback(f:(...args:any[]) => void, ...args:any[]):EventStream; /** - * @method - * @description Buffers the [EventStream]{@link Bacon.EventStream} events and flushes when either the buffer contains the given `count` of elements or the given `delay` (in milliseconds) has passed since last buffered event. + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. The function is supposed to call its callback just once. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromNodeCallback~f + * @param {Bacon.fromNodeCallback~callback} callback + * @returns {void} + */ + /** + * @callback Bacon.fromNodeCallback~callback + * @param {E} error + * @param {A} data + * @returns {void} + */ + /** + * @function Bacon.fromNodeCallback + * @description Creates an [EventStream]{@link Bacon.EventStream} from a function `f` that accepts a Node.js `callback`: callback(error, data), where error is `null` if everything is fine. The function is supposed to call its callback just once. + * @param {Bacon.fromNodeCallback~f} f + * @param {...*} args + * @returns {EventStream} + * @example + * { + * let fs = require("fs"), + * read = Bacon.fromNodeCallback(fs.readFile, "input.txt"); + * read.onError(error => { + * console.log("Reading failed: " + error); + * }); + * read.onValue(value => { + * console.log("Read contents: " + value); + * }); + * } + */ + function fromNodeCallback(f:(callback:(error:E, data:A) => void) => void, ...args:any[]):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} from a `methodName` method of a given `object`. + * @param {Object} object + * @param {string} methodName + * @param {...*} args + * @returns {EventStream} + */ + function fromNodeCallback(object:Object, methodName:string, ...args:any[]):EventStream; + + /** + * @callback Bacon.fromPoll~f + * @returns {Next|End} + */ + /** + * @function Bacon.fromPoll + * @description Polls given function `f` with given `interval`. Function should return events: either [Next]{@link Bacon.Next} or [End]{@link Bacon.End}. Polling occurs only when there are subscribers to the stream. Polling ends permanently when `f` returns [End]{@link Bacon.End}. + * @param {number} interval + * @param {Bacon.fromPoll~f} f + * @returns {EventStream} + */ + function fromPoll(interval:number, f:() => Next|End):EventStream; + + /** + * @function Bacon.once + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given single `value` for the first subscriber. The stream will end immediately after this value. You can also send an [Error]{@link Bacon.Error} event instead of a `value`. + * @param {A|Error} value + * @returns {EventStream} + * @example + * Bacon.once(new Bacon.Error("fail")); + */ + function once(value:A|Error):EventStream; + + /** + * @function + * @description Creates an [EventStream]{@link Bacon.EventStream} that delivers the given series of `values` (given as array) to the first subscriber. The stream ends after these values have been delivered. You can also send [Error]{@link Bacon.Error} events, or any combination of pure values and error events. + * @param {(A|Error)[]} values + * @returns {EventStream} + * @example + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function fromArray(values:(A|Error)[]):EventStream; + + /** + * @function + * @description Repeats the single `value` indefinitely with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A} value + * @returns {EventStream} + */ + function interval(interval:number, value:A):EventStream; + + /** + * @function + * @description Creates a [EventStream]{@link Bacon.EventStream} containing given `values` (given as array) with the given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + */ + function sequentially(interval:number, values:A[]):EventStream; + + /** + * @function + * @description Repeats given `values` indefinitely with then given `interval` (in milliseconds). + * @param {number} interval + * @param {A[]} values + * @returns {EventStream} + * @example + * // The following would lead to `1,2,3,1,2,3...` to be repeated indefinitely: + * Bacon.fromArray([1, new Bacon.Error("")]); + */ + function repeatedly(interval:number, values:A[]):EventStream; + + /** + * @callback Bacon.repeat~f + * @param {number} iteration + * @returns {boolean|Observable} + */ + /** + * @function Bacon.repeat + * @description Calls generator function `f` which is expected to return an [Observable]{@link Bacon.Observable}. The returned [EventStream]{@link Bacon.EventStream} contains values and errors from the spawned observable. When the spawned Observable ends, the generator `f` is called again to spawn a new Observable. This is repeated until the generator `f` returns a falsy value (such as `undefined` or `false`). The generator `f` is called with one argument — `iteration` number starting from `0`. + * @param {Bacon.repeat~f} f + * @returns {EventStream} + * @example + * // The following will produce values `0,1,2`. + * Bacon.repeat(i => { + * if (i < 3) { + * return Bacon.once(i); + * } else { + * return false; + * } + * }).log(); + */ + function repeat(f:(iteration:number) => boolean|Observable):EventStream; + + /** + * @function Bacon.never + * @description Creates an [EventStream]{@link Bacon.EventStream} that immediately ends. + * @returns {EventStream} + */ + function never():EventStream; + + /** + * @function + * @description Creates a single-element [EventStream]{@link Bacon.EventStream} that produces given `value` after a given `delay` (in milliseconds). * @param {number} delay - * @param {number} count - * @returns {EventStream} + * @param {A} value + * @returns {EventStream} */ - bufferWithTimeOrCount(delay:number, count:number):EventStream; + function later(delay:number, value:A):EventStream; /** - * @method EventStream#toProperty - * @description Creates a [Property]{@link Bacon.Property} based on the [EventStream]{@link Bacon.EventStream}. Without arguments, you'll get a Property without an initial value and will get its first actual value from the EventStream, and after that it'll always have a current value. Given `initialValue` will be used as the current value until the first value comes from the EventStream. - * @param {A} [initialValue] + * @function + * @description Creates a constant [Property]{@link Bacon.Property} with value `x`. + * @param {A} x * @returns {Property} */ - toProperty(initialValue?:A):Property; - } + function constant(x:A):Property; - var EventStream:{ /** - * @callback EventStream#new~subscribe - * @param {EventStream#new~sink} sink - * @returns {EventStream#new~unsubscribe} + * @callback Bacon.fromBinder~subscribe + * @param {Bacon.fromBinder~sink} sink + * @returns {Bacon.fromBinder~unsubscribe} */ /** - * @callback EventStream#new~sink + * @callback Bacon.fromBinder~sink * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value * @returns {void} */ /** - * @callback EventStream#new~unsubscribe + * @callback Bacon.fromBinder~unsubscribe * @returns {void} */ /** - * @constructor EventStream#new - * @constructs Bacon.EventStream - * @description Creates an [EventStream]{@link Bacon.EventStream} with the given `subscribe` function. - * @param {EventStream#new~subscribe} subscribe + * @function Bacon.fromBinder + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given [subscribe]{@link Bacon.fromBinder~subscribe} function. The parameter `subscribe` is a function that accepts a [sink]{@link Bacon.fromBinder~sink} which is a function that your `subscribe` function can "push" events to. You can push: a plain value, like `"first value"`; an [Event]{@link Bacon.Event} object including [Error]{@link Bacon.Error} (wraps an error) and [End]{@link Bacon.End} (indicates stream end); an array of event objects at once. The `subscribe` function must return a function. Let's call that function [unsubscribe]{@link Bacon.fromBinder~unsubscribe}. The returned function can be used by the subscriber (directly or indirectly) to unsubscribe from the EventStream. It should release all resources that the `subscribe` function reserved. The `sink` function may return [noMore]{@link Bacon.noMore} (as well as [more]{@link Bacon.more} or any other value). If it returns `noMore`, no further events will be consumed by the subscriber. The `subscribe` function may choose to clean up all resources at this point (e.g., by calling `unsubscribe`). This is usually not necessary, because further calls to `sink` are ignored, but doing so can increase performance in rare cases. The EventStream will wrap your `subscribe` function so that it will only be called when the first stream listener is added, and the `unsubscribe` function is called only after the last listener has been removed. The subscribe-unsubscribe cycle may of course be repeated indefinitely, so prepare for multiple calls to the `subscribe` function. + * @param {Bacon.fromBinder~subscribe} subscribe * @returns {EventStream} - */ - new(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; - }; - - /** - * @class Property - * @augments Bacon.Observable - * @description A reactive property. Has the concept of "current value". You can create a Property from an [EventStream]{@link Bacon.EventStream} by using either [EventStream.toProperty]{@link Bacon.EventStream#toProperty} or [Observable.scan]{@link Bacon.Observable#scan} method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the EventStream has ended. - * */ - interface Property extends Observable { - /** - * @callback Property#map~f - * @param {A} value - * @returns {B} - */ - /** - * @method Property#map - * @description Maps the [Property]{@link Bacon.Property} values using given function `f`, returning a new Property. This method, among many others, uses lazy evaluation. - * @param {Property#map~f} f - * @returns {Property} - * */ - map(f:(value:A) => B):Property; - - /** - * @method - * @description Maps the [Property]{@link Bacon.Property} values using given `constant` value, returning a new Property. This method, among many others, uses lazy evaluation. - * @param {B} constant - * @returns {Property} - * */ - map(constant:B):Property; - - /** - * @method - * @description Maps the [Property]{@link Bacon.Property} values using given `propertyExtractor` string like ".keyCode", returning a new Property. So, if f is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If "keyCode" was a function, the resulting Property would contain the values returned by the function. This method, among many others, uses lazy evaluation. - * @param {string} propertyExtractor - * @returns {Property} - * */ - map(propertyExtractor:string):Property; - - /** - * @callback Property#mapError~f - * @param {E} error - * @returns {B} - */ - /** - * @method Property#mapError - * @description Maps the [Property]{@link Bacon.Property} errors using given function `f`. More specifically, feeds the "error" field of the [Error]{@link Bacon.Error} event to the function `f` and produces a [Next]{@link Bacon.Next} event based on the return value. - * @param {Property#mapError~f} f - * @returns {Property} - */ - mapError(f:(error:E) => B):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns false. - * @returns {Property} - */ - errors():Property; - - /** - * @method - * @description Skips all [Error]{@link Bacon.Error}s. - * @returns {Property} - */ - skipErrors():Property; - - /** - * @callback Property#mapEnd~f - * @returns {A} - */ - /** - * @method Property#mapEnd - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. The value is created by calling the given function `f` when the source Property ends. - * @param {Property#mapEnd~f} f - * @returns {Property} - */ - mapEnd(f:() => A):Property; - - /** - * @method - * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. A static `value` is used. - * @param {A} value - * @returns {Property} - */ - mapEnd(value:A):Property; - - /** - * @callback Property#filter~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method Property#filter - * @description Filters the [Property]{@link Bacon.Property} values using a given predicate function `f`. - * @param {Property#filter~f} f - * @returns {Property} - */ - filter(f:(value:A) => boolean):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values using a given constant `bool` value (`true` to include all, `false` to exclude all). - * @param {boolean} bool - * @returns {Property} - */ - filter(bool:boolean):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values using a given `propertyExtractor` string (like ".isValuable"). - * @param {string} propertyExtractor - * @returns {Property} - */ - filter(propertyExtractor:string):Property; - - /** - * @method - * @description Filters the [Property]{@link Bacon.Property} values based on the value of the Property `property`. Event will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. - * @param {Property} property - * @returns {Property} - */ - filter(property:Property):Property; - - /** - * @callback Property#takeWhile~f - * @param {A} value - * @returns {boolean} - */ - /** - * @method Property#takeWhile - * @description Takes the [Property]{@link Bacon.Property} values while given predicate function `f` holds `true`, and then ends. - * @param {Property#takeWhile~f} f - * @returns {Property} - */ - takeWhile(f:(value:A) => boolean):Property; - - /** - * @method - * @description Takes the [Property]{@link Bacon.Property} values while the value of a `property` holds `true`, and then ends. - * @param {Property} property - * @returns {Property} - */ - takeWhile(property:Property):Property; - - /** - * @method Property#take - * @description Takes at most `n` elements from the [Property]{@link Bacon.Property}. Equal to `Bacon.never()` if `n <= 0`. - * @param {number} n - * @returns {Property} - */ - take(n:number):Property; - - /** - * @method - * @description Takes elements from the [Property]{@link Bacon.Property} until a [Next]{@link Bacon.Next} event appears in the `stream`. If `stream` ends without value, it is ignored. - * @param {EventStream} stream - * @returns {Property} - */ - takeUntil(stream:EventStream):Property; - - /** - * @method - * @description Takes the first element from the [Property]{@link Bacon.Property}. Essentially [Property.take]{@link Bacon.Property#take}(1). - * @returns {Property} - */ - first():Property; - - /** - * @method - * @description Takes the last element from the [Property]{@link Bacon.Property}. None, if Property is empty. - * @returns {Property} * @example - * // This creates the property which doesn't produce any events and never ends: - * Bacon.interval(1e1, 0).toProperty().last(); - */ - last():Property; - - /** - * @method - * @description Skips the first `n` elements from the [Property]{@link Bacon.Property}. - * @param {number} n - * @returns {Property} - */ - skip(n:number):Property; - - /** - * @method - * @description Delays the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Does not delay the initial value of a Property. - * @param {number} delay - * @returns {Property} - */ - delay(delay:number):Property; - - /** - * @method Property#throttle - * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. Does not affect emitting the initial value of a Property. - * @param {number} delay - * @returns {Property} - */ - throttle(delay:number):Property; - - /** - * @method Property#debounce - * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a Property. The difference of [throttle]{@link Bacon.Property#throttle} and [debounce]{@link Bacon.Property#debounce} is the same as it is in the same methods in jQuery. - * @param {number} delay - * @returns {Property} - */ - debounce(delay:number):Property; - - /** - * @method - * @description Passes the first event in the [Property]{@link Bacon.Property} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. - * @param {number} delay - * @returns {Property} - */ - debounceImmediate(delay:number):Property; - - /** - * @callback Property#doAction~f - * @param {A} value - * @returns {void} - */ - /** - * @method Property#doAction - * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {Property#doAction~f} f - * @returns {Property} - */ - doAction(f:(value:A) => void):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. - * @param {string} propertyExtractor - * @returns {Property} - */ - doAction(propertyExtractor:string):Property; - - /** - * @callback Property#doError~f - * @param {E} error - * @returns {void} - */ - /** - * @method Property#doError - * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as [doAction]{@link Bacon.Property#doAction} but for [Error]{@link Bacon.Error}s. - * @param {Property#doError~f} f - * @returns {Property} - */ - doError(f:(error:E) => void):Property; - - /** - * @method - * @description Returns a [Property]{@link Bacon.Property} that inverts boolean values. - * @returns {Property} - */ - not():Property; - - /** - * @method Property#log - * @description Logs each value of the [Property]{@link Bacon.Property} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original Property. Note that as a side-effect, the Property will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. - * @param {string} [label] - * @returns {Property} - */ - log(label?:string):Property; - - /** - * @method Property#doLog - * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. - * @returns {Property} - */ - doLog():Property; - - /** - * @method - * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned Property. - * @returns {Property} - */ - endOnError():Property; - - /** - * @callback Property#endOnError~f - * @param {E} error - * @returns {boolean} - */ - /** - * @method Property#endOnError - * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned Property. - * @param {Property#endOnError~f} f - * @returns {Property} - */ - endOnError(f:(error:E) => boolean):Property; - - /** - * @callback Property#withHandler~f - * @param {Initial|Next|End|Error} event - * @returns {*} - */ - /** - * @method Property#withHandler - * @description Lets you do more custom event handling on the [Property]{@link Bacon.Property}: you get all events to your function `f` and you can output any number of [Event]{@link Bacon.Event}s and end the Property if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. - * @param {Property#withHandler~f} f - * @returns {Property} - * @example - * // Send an error and end the stream in case a value is below zero: - * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { - * if (event.hasValue() && event.value() < 0) { - * this.push(new Bacon.Error("Value below zero")); - * return this.push(new Bacon.End()); - * } else { - * return this.push(event); - * } + * let stream = Bacon.fromBinder(sink => { + * sink("first value"); + * sink([new Bacon.Next("2nd"), new Bacon.Next("3rd")]); + * sink(new Bacon.Next(() => { + * return "This one will be evaluated lazily" + * })); + * sink(new Bacon.Error("oops, an error")); + * sink(new Bacon.End()); + * return () => { + * // unsub functionality here, this one's a no-op + * }; * }); + * stream.log(); */ - withHandler(f:(event:Initial|Next|End|Error) => any):Property; + function fromBinder(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; /** - * @method - * @description Sets the `newName` of the [Property]{@link Bacon.Property}. Overrides the default implementation of `toString` and `inspect`. Returns itself. - * @param {string} newName - * @returns {Property} + * @interface + * @see Bacon.more */ - name(newName:string):Property; + interface More { + } + /** + * @property more + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var more:More; /** - * @method - * @description Sets the structured description of the [Property]{@link Bacon.Property}. The `toString` and `inspect` methods use this data recursively to create a string representation for the Property. This method is probably useful for Bacon core/library/plugin development only. - * @param {...*} param + * @interface + * @see Bacon.noMore + */ + interface NoMore { + } + /** + * @property noMore + * @constant + * @description The opaque value `sink` function may return. See [Bacon.fromBinder]{@link Bacon.fromBinder}. + */ + var noMore:NoMore; + + /** + * @class Observable + * @description A superclass for [EventStream]{@link Bacon.EventStream} and [Property]{@link Bacon.Property}. + * */ + interface Observable { + /** + * @callback Observable#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Observable#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onValue + * @description Subscribes a given handler function `f` to the [Observable]{@link Bacon.Observable}. Function will be called for each new value. This is the simplest way to assign a side-effect to an Observable. The difference to the [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe} methods is that the actual stream `value`s are received, instead of [Event]{@link Bacon.Event} objects. [EventStream.onValue]{@link Bacon.EventStream#onValue} and [Property.onValue]{@link Bacon.Property#onValue} behave similarly, except that the latter also pushes the initial value of the Property, in case there is one. + * @param {Observable#onValue~f} f + * @returns {Observable#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Observable#onError~f + * @param {E} error + * @returns {void} + */ + /** + * @callback Observable#onError~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onError + * @description Subscribes a given handler function `f` to [Error]{@link Bacon.Error} events. The function `f` will be called for each error in the [Observable]{@link Bacon.Observable}. + * @param {Observable#onError~f} f + * @returns {Observable#onError~unsubscribe} + */ + onError(f:(error:E) => void):() => void; + + /** + * @callback Observable#onEnd~f + * @returns {void} + */ + /** + * @callback Observable#onEnd~unsubscribe + * @returns {void} + */ + /** + * @method Observable#onEnd + * @description Subscribes a given handler function `f` to [End]{@link Bacon.End} event. The function `f` will be called when the [Observable]{@link Bacon.Observable} ends. Just like [EventStream.subscribe]{@link Bacon.EventStream#subscribe} and [Property.subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Observable#onEnd~f} f + * @returns {Observable#onEnd~unsubscribe} + */ + onEnd(f:() => void):() => void; + + /** + * @callback Observable#toPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#toPromise + * @description Returns a Promise which will be resolved with the last event coming from an [Observable]{@link Bacon.Observable}. The global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. Use a shim if you need to support legacy browsers or platforms. + * @param {Observable#toPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + toPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @callback Observable#firstToPromise~promiseCtr + * @param {A} value + * @returns {Promise} + */ + /** + * @method Observable#firstToPromise + * @description Returns a Promise which will be resolved with the first event coming from an [Observable]{@link Bacon.Observable}. Like [Observable.toPromise]{@link Bacon.Observable#toPromise}, the global ES6 promise implementation will be used unless a promise constructor `promiseCtr` is given. + * @param {Observable#firstToPromise~promiseCtr} [promiseCtr] + * @returns {Promise} + */ + firstToPromise(promiseCtr?:(value:A) => Promise):Promise; + + /** + * @method + * @description Throttles the [Observable]{@link Bacon.Observable} using a buffer so that at most one value event in `minimumInteval` is issued. Unlike [EventStream.throttle]{@link Bacon.EventStream#throttle} and [Property.throttle]{@link Bacon.Property#throttle}, it doesn't discard the excessive events but buffers them instead, outputting them with a rate of at most one value per `minimumInterval`. + * @param {number} minimumInterval + * @returns {EventStream} + */ + bufferingThrottle(minimumInterval:number):EventStream; + + /** + * @callback Observable#flatMap~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMap + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMap]{@link Bacon.Observable#flatMap} is always an EventStream. The "Function Construction rules" apply here. `flatMap` can be used conveniently with [Bacon.once]{@link Bacon.once} and [Bacon.never]{@link Bacon.never} for converting and filtering at the same time, including only some of the results. + * @param {Observable#flatMap~f} f + * @returns {EventStream} + * @example + * // Converting strings to integers, skipping empty values: + * Bacon.once("").flatMap(text => { + * return text != "" ? parseInt(text) : Bacon.never(); + * }); + */ + flatMap(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapLatest~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapLatest + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, but instead of including events from all spawned streams, only includes them from the latest spawned stream into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapLatest]{@link Bacon.Observable#flatMapLatest} is always an EventStream. + * @param {Observable#flatMapLatest~f} f + * @returns {EventStream} + */ + flatMapLatest(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapFirst~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapFirst + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f` only if the previously spawned stream has ended, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapFirst]{@link Bacon.Observable#flatMapFirst} is always an EventStream. + * @param {Observable#flatMapFirst~f} f + * @returns {EventStream} + */ + flatMapFirst(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapError~f + * @param {E} error + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapError + * @description For each [Error]{@link Bacon.Error} event in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of [flatMapError]{@link Bacon.Observable#flatMapError} is always an EventStream. + * @param {Observable#flatMapError~f} f + * @returns {EventStream} + */ + flatMapError(f:(error:E) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapWithConcurrencyLimit~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapWithConcurrencyLimit + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events by `limit` amount. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. [flatMapConcat]{@link Bacon.Observable#flatMapConcat} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(1) (only one input active), and [flatMap]{@link Bacon.Observable#flatMap} is [flatMapWithConcurrencyLimit]{@link Bacon.Observable#flatMapWithConcurrencyLimit}(∞) (all inputs are piped to output). The result of `flatMapWithConcurrencyLimit` is always an EventStream. + * @param {number} limit + * @param {Observable#flatMapWithConcurrencyLimit~f} f + * @returns {EventStream} + */ + flatMapWithConcurrencyLimit(limit:number, f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#flatMapConcat~f + * @param {A} value + * @returns {B|Initial|Next|End|Error|Observable} + */ + /** + * @method Observable#flatMapConcat + * @description For each element in the source [Observable]{@link Bacon.Observable}, spawn a new stream using the function `f`, and collect events from each of the spawned streams into the result [EventStream]{@link Bacon.EventStream}, but limit the number of open spawned streams and buffers incoming events to 1. The return value of function `f` can be either an Observable (EventStream/[Property]{@link Bacon.Property}) or a constant value. The result of `flatMapConcat` is always an EventStream. + * @param {Observable#flatMapConcat~f} f + * @returns {EventStream} + */ + flatMapConcat(f:(value:A) => B|Initial|Next|End|Error|Observable):EventStream; + + /** + * @callback Observable#scan~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#scan + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, resulting to a [Property]{@link Bacon.Property}. For example, you might use zero as `seed` and a "plus" function as the accumulator to create an "integral" Property. When applied to a Property as in `r = p.scan(seed, f)`, there's a (hopefully insignificant) catch: the starting value for `r` depends on whether `p` has an initial value when `scan` is applied. If there's no initial value, this works identically to `[EventStream]{@link Bacon.EventStream}.scan`: the `seed` will be the initial value of `r`. However, if `r` already has a current/initial value `x`, the seed won't be output as is. Instead, the initial value of `r` will be `f(seed, x)`. This makes sense, because there can only be 1 initial value for a Property at a time. + * @param {B} seed + * @param {Observable#scan~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).scan(0, (a, b) => a + b); + */ + scan(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#fold~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#fold + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#fold~f} f + * @returns {Property} + */ + fold(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#reduce~f + * @param {B} acc + * @param {A} next + * @returns {B} + */ + /** + * @method Observable#reduce + * @description Scans [Observable]{@link Bacon.Observable} with given `seed` value and accumulator function `f`, but only emits the final value, i.e. the value just before the Observable ends. Returns a [Property]{@link Bacon.Property}. + * @param {B} seed + * @param {Observable#reduce~f} f + * @returns {Property} + */ + reduce(seed:B, f:(acc:B, next:A) => B):Property; + + /** + * @callback Observable#diff~f + * @param {A} a + * @param {B} b + * @returns {B} + */ + /** + * @method Observable#diff + * @description Returns a [Property]{@link Bacon.Property} that represents the result of a comparison `f` between the previous and current value of the [Observable]{@link Bacon.Observable}. For the initial value of the Observable, the previous value will be the given `start`. + * @param {A} start + * @param {Observable#diff~f} f + * @returns {Property} + * @example + * Bacon.sequentially(1, [1, 2, 3]).diff(0, (a, b) => Math.abs(b - a)); + */ + diff(start:A, f:(a:A, b:A) => B):Property; + + /** + * @callback Observable#zip~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#zip + * @description Returns an [EventStream]{@link Bacon.EventStream} with elements pair-wise lined up with events from this and the `other` EventStream. A zipped EventStream will publish only when it has a value from each EventStream and will only produce values up to when any single EventStream ends. The given function `f` is used to create the result value from value in the two source EventStream. If no function `f` is given, the values are zipped into an array. Be careful not to have too much "drift" between streams. If one stream produces many more values than some other excessive buffering will occur inside the zipped observable. + * @param {EventStream} other + * @param {Observable#zip~f} f + * @returns {EventStream} + * @example + * { + * let x = Bacon.fromArray([1, 2]), + * y = Bacon.fromArray([3, 4]); + * x.zip(y, (x, y) => x + y); + * } + */ + zip(other:EventStream, f:(a:A, b:B) => C):EventStream; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that represents a "sliding window" into the history of the values of the [Observable]{@link Bacon.Observable}. The resulting Property will have a value that is an array containing the last `n` values of the original Observable, where `n` is at most the value of the `max` argument, and at least the value of the `min` argument. If the `min` argument is omitted, there's no lower limit of values. + * @param {number} max + * @param {number} [min] + * @returns {Property} + * @example + * // If you have a EventStream `s` with a value sequence `1,2,3,4,5`, the respective values in `s.slidingWindow(2)` would be `[],[1],[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2); + * // The values of `s.slidingWindow(2,2)`would be `[1,2],[2,3],[3,4],[4,5]`: + * Bacon.fromArray([1, 2, 3, 4, 5]).slidingWindow(2, 2); + */ + slidingWindow(max:number, min?:number):Property; + + /** + * @callback Observable#combine~f + * @param {A} a + * @param {B} b + * @returns {C} + */ + /** + * @method Observable#combine + * @description Combines the latest values of the two [EventStream]{@link Bacon.EventStream}s or [Property]{@link Bacon.Property}s using a two-arg function `f`. The result is a Property. + * @param {Property} property2 + * @param {Observable#combine~f} f + * @returns {Property} + */ + combine(property2:Property, f:(a:A, b:B) => C):Property; + + /** + * @callback Observable#withStateMachine~f + * @param {B} state + * @param {Initial|Next|End|Error} event + * @returns {[B, (Initial|Next|End|Error)[]]} + */ + /** + * @method Observable#withStateMachine + * @description Lets you run a state machine on an [Observable]{@link Bacon.Observable}. Give it an initial state `initState` object and a state transformation function `f` that processes each incoming [Event]{@link Bacon.Event} and returns and array containing the next `state` and an array of output Event's. + * @param {B} initState + * @param {Observable#withStateMachine~f} f + * @returns {EventStream} + * @example + * // Calculate the total sum of all numbers in the stream and output the value on stream end: + * Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { + * if (event.hasValue()) { + * // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> + * return [sum + event.value(), []]; + * } else if (event.isEnd()) { + * return [undefined, [new Bacon.Next(sum), event]]; + * } else { + * return [sum, [event]]; + * } + * }); + */ + withStateMachine(initState:B, f:(state:B, event:Initial|Next|End|Error) => [B, (Initial|Next|End|Error)[]]):EventStream; + + /** + * @method + * @description Decodes input [Observable]{@link Bacon.Observable} using the given `mapping`. Is a bit like a switch-case or the decode function in Oracle SQL. The return value of `decode` is always a [Property]{@link Bacon.Property}. + * @param {Object} mapping + * @returns {Property} + * @example + * { + * let property = Bacon.fromArray([1, 2, 3]).toProperty(), + * who = Bacon.fromArray(["A", "B", "C"]).toProperty(); + * // The following would map the value 1 into the string "mike" and the value 2 into the value of the `who` property: + * property.decode({1: "mike", 2: who}); + * // You can compose static and dynamic data quite freely, as in: + * property.decode({1: {type: "mike"}, 2: {type: "other", whoThen: who}}); + * } + */ + decode(mapping:Object):Property; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} that indicates whether Observable is awaiting `otherObservable`, i.e. has produced a value after the latest value from `otherObservable`. + * @param {Observable} otherObservable + * @returns {Property} + * @example + * { + * // This is handy for keeping track whether we are currently awaiting an AJAX response: + * let ajaxRequest = >{}, + * ajaxResponse = >{}, + * showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); + * } + */ + awaiting(otherObservable:Observable):Property; + } + + /** + * @class EventStream + * @augments Bacon.Observable + * @description A stream of events. + * */ + interface EventStream extends Observable { + /** + * @callback EventStream#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#map + * @description Maps [EventStream]{@link Bacon.EventStream} values using given function `f`, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {EventStream#map~f} f + * @returns {EventStream} + * */ + map(f:(value:A) => B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `constant` value, returning a new EventStream. The `map` method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {EventStream} + * */ + map(constant:B):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} values using given `propertyExtractor` string like ".keyCode", returning a new EventStream. So, if `propertyExtractor` is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If `keyCode` was a function, the result EventStream would contain the values returned by the function. The "Function Construction rules" apply here. The `map` method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {EventStream} + * */ + map(propertyExtractor:string):EventStream; + + /** + * @method + * @description Maps [EventStream]{@link Bacon.EventStream} events to the current value of the given [Property]{@link Bacon.Property} `property`. This is equivalent to [Property.sampledBy]{@link Bacon.Property#sampledBy}. + * @param {Property} property + * @returns {EventStream} + */ + map(property:Property):EventStream; + + /** + * @callback EventStream#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method EventStream#mapError + * @description Maps [EventStream]{@link Bacon.EventStream} [Error]{@link Bacon.Error}s using given function `f`. More specifically, feeds the "error" field of the Error event to the function and produces a [Next]{@link Bacon.Next} event based on the return value. The "Function Construction rules" apply here. + * @param {EventStream#mapError~f} f + * @returns {EventStream} + */ + mapError(f:(error:E) => B):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns `false`. + * @returns {EventStream} + */ + errors():EventStream; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {EventStream} + */ + skipErrors():EventStream; + + /** + * @callback EventStream#mapEnd~f + * @returns {A} + */ + /** + * @method EventStream#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. The value is created by calling the given function `f` when the source [EventStream]{@link Bacon.EventStream} ends. + * @param {EventStream#mapEnd~f} f + * @returns {EventStream} + */ + mapEnd(f:() => A):EventStream; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} to [EventStream]{@link Bacon.EventStream}. A static `value` is used. + * @param {A} value + * @returns {EventStream} + */ + mapEnd(value:A):EventStream; + + /** + * @callback EventStream#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#filter + * @description Filters [EventStream]{@link Bacon.EventStream} `value`s using a given predicate function `f`. + * @param {EventStream#filter~f} f + * @returns {EventStream} + */ + filter(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `constant` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {EventStream} + */ + filter(bool:boolean):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {EventStream} + */ + filter(propertyExtractor:string):EventStream; + + /** + * @method + * @description Filters [EventStream]{@link Bacon.EventStream} values based on the value of a [Property]{@link Bacon.Property} `property`. [Event]{@link Bacon.Event} will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {EventStream} + */ + filter(property:Property):EventStream; + + /** + * @callback EventStream#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#takeWhile + * @description Takes [EventStream]{@link Bacon.EventStream} values while given predicate function `f` holds `true`, and then ends. + * @param {EventStream#takeWhile} f + * @returns {EventStream} + */ + takeWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Takes [EventStream]{@link Bacon.EventStream} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {EventStream} + */ + takeWhile(property:Property):EventStream; + + /** + * @method + * @description Takes at most n elements from the [EventStream]{@link Bacon.EventStream}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {EventStream} + */ + take(n:number):EventStream; + + /** + * @method + * @description Takes elements from [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in the EventStream `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {EventStream} + */ + takeUntil(stream:EventStream):EventStream; + + /** + * @method + * @description Takes the first element from the [EventStream]{@link Bacon.EventStream}. Essentially [Observable.take]{@link Bacon.EventStream#take}(1). + * @returns {EventStream} + */ + first():EventStream; + + /** + * @method + * @description Takes the last element from the [EventStream]{@link Bacon.EventStream}. None, if EventStream is empty. + * @returns {EventStream} + * @example + * // This creates the stream which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).last(); + */ + last():EventStream; + + /** + * @method + * @description Skips the first `n` elements from the [EventStream]{@link Bacon.EventStream}. + * @param {number} n + * @returns {EventStream} + */ + skip(n:number):EventStream; + + /** + * @method + * @description Delays the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). + * @param {number} delay + * @returns {EventStream} + */ + delay(delay:number):EventStream; + + /** + * @method EventStream#throttle + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. + * @param {number} delay + * @returns {EventStream} + */ + throttle(delay:number):EventStream; + + /** + * @method EventStream#debounce + * @description Throttles the [EventStream]{@link Bacon.EventStream} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". The difference of [throttle]{@link Bacon.EventStream#throttle} and [debounce]{@link Bacon.EventStream#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {EventStream} + */ + debounce(delay:number):EventStream; + + /** + * @method + * @description Passes the first event in the [EventStream]{@link Bacon.EventStream} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {EventStream} + */ + debounceImmediate(delay:number):EventStream; + + /** + * @callback EventStream#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method EventStream#doAction + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {EventStream#doAction~f} f + * @returns {EventStream} + */ + doAction(f:(value:A) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {EventStream} + */ + doAction(propertyExtractor:string):EventStream; + + /** + * @callback EventStream#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method EventStream#doError + * @description Returns an [EventStream]{@link Bacon.EventStream} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as `doAction` but for errors. + * @param {EventStream#doError~f} f + * @returns {EventStream} + */ + doError(f:(error:E) => void):EventStream; + + /** + * @method + * @description Returns an [EventStream]{@link Bacon.EventStream} that inverts boolean values. + * @returns {EventStream} + */ + not():EventStream; + + /** + * @method EventStream#log + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original EventStream. Note that as a side-effect, the EventStream will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {EventStream} + */ + log(label?:string):EventStream; + + /** + * @method EventStream#doLog + * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {EventStream} + */ + doLog():EventStream; + + /** + * @method + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned EventStream. + * @returns {EventStream} + */ + endOnError():EventStream; + + /** + * @callback EventStream#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method EventStream#endOnError + * @description Ends the [EventStream]{@link Bacon.EventStream} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned EventStream. + * @param {EventStream#endOnError} f + * @returns {EventStream} + */ + endOnError(f:(error:E) => boolean):EventStream; + + /** + * @callback EventStream#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method EventStream#withHandler + * @description Lets you do more custom event handling on [EventStream]{@link Bacon.EventStream}: you get all events to your function `f` and you can output any number of events and end the stream if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {EventStream#withHandler~f} f + * @returns {EventStream} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):EventStream; + + /** + * @method + * @description Sets the name of the [EventStream]{@link Bacon.EventStream}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {EventStream} + */ + name(newName:string):EventStream; + + /** + * @method + * @description Sets the structured description of the [EventStream]{@link Bacon.EventStream}. The `toString` and `inspect` methods use this data recursively to create a string representation for the `EventStream`. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {EventStream} + * @example + * { + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):EventStream; + + /** + * @callback EventStream#groupBy1~keyF + * @param {A} value + * @returns {B} + */ + /** + * @method EventStream#groupBy1 + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. + * @param {EventStream#groupBy1~keyF} keyF + * @returns {EventStream>} + */ + groupBy(keyF:(value:A) => B):EventStream>; + + /** + * @callback keyF + * @param {A} value + * @returns {B} + */ + /** + * @callback limitF + * @param {EventStream} groupedStream + * @param {Initial|Next|End|Error} groupStartingEvent + * @returns {EventStream} + */ + /** + * @description Groups [EventStream]{@link Bacon.EventStream} events to new EventStream's by `keyF`. `limitF` is provided to limit grouped stream life. EventStream transformed by `limitF` is passed on if provided. `limitF` gets grouped stream and the original [Event]{@link Bacon.Event} causing the EventStream to start as parameters. + * @param {keyF} keyF + * @param {limitF} limitF + * @returns {EventStream>} Grouped streams. + */ + groupBy(keyF:(value:A) => B, limitF:(groupedStream:EventStream, groupStartingEvent:Initial|Next|End|Error) => EventStream):EventStream>; + + /** + * @callback EventStream#subscribe~f + * @param {Event} event + * @returns {void|NoMore} + */ + /** + * @callback EventStream#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#subscribe + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will receive [Event]{@link Bacon.Event} objects. The [subscribe]{@link EventStream#subscribe} call returns an [unsubscribe function]{@link EventStream#subscribe~unsubscribe} that you can call to unsubscribe. You can also unsubscribe by returning [Bacon.noMore]{@link Bacon.noMore} from the handler function as a reply to an Event. + * @param {EventStream#subscribe~f} f + * @returns {EventStream#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void|NoMore):() => void; + + /** + * @callback EventStream#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback EventStream#onValue~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValue + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Function will be called for each new value in the EventStream. This is the simplest way to assign a side-effect to a EventStream. The difference to the [subscribe]{@link Bacon.EventStream#subscribe} method is that the actual EventStream values are received, instead of [Event]{@link Bacon.Event} objects. Just like `subscribe`, this method returns a function for `unsubscribe`ing. + * @param {EventStream#onValue~f} f + * @returns {EventStream#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback EventStream#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback EventStream#onValues~unsubscribe + * @returns {void} + */ + /** + * @method EventStream#onValues + * @description Subscribes a given handler function `f` to [EventStream]{@link Bacon.EventStream}. Like [EventStream.onValue]{@link Bacon.EventStream#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {EventStream#onValues~f} f + * @returns {EventStream#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @callback EventStream#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method EventStream#skipDuplicates + * @description Drops consecutive equal elements of the [EventStream]{@link Bacon.EventStream}. Uses the === operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling [isEqual]{@link EventStream#skipDuplicates~isEqual}. For instance, to do a deep comparison, you can use the `isEqual` function from underscore.js like `stream.skipDuplicates(_.isEqual)`. + * @param {EventStream#skipDuplicates~isEqual} [isEqual] + * @returns {EventStream} + * @example + * Bacon.fromArray([1, 2, 2, 1]).skipDuplicates().log(); + * // > returns [1, 2, 1] in an order + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):EventStream; + + /** + * @method + * @description Concatenates two [EventStream]{@link Bacon.EventStream}s into one so that it will deliver events from EventStream until it ends and then deliver events from `otherStream`. This means too that events from `otherStream`, occurring before the end of EventStream will not be included in the result EventStream. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + concat(otherStream:EventStream):EventStream; + + /** + * @method + * @description Merges two [EventStream]{@link Bacon.EventStream}s into one that delivers events from both. + * @param {EventStream} otherStream + * @returns {EventStream} + */ + merge(otherStream:EventStream):EventStream; + + /** + * @method + * @description Pauses and buffers the [EventStream]{@link Bacon.EventStream} if last event in `valve` is truthy. All buffered events are released when `valve` becomes falsy. + * @param {Observable} valve + * @returns {EventStream} + */ + holdWhen(valve:Observable):EventStream; + + /** + * @method + * @description Adds a starting `value` to the [EventStream]{@link Bacon.EventStream}, i.e. concats a EventStream containing a single `value` with this EventStream. + * @param {A} value + * @returns {EventStream} + */ + startWith(value:A):EventStream; + + /** + * @callback EventStream#skipWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method EventStream#skipWhile + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the given predicate function `f` returns falsy once, and then lets all events pass through. + * @param {EventStream#skipWhile~f} f + * @returns {EventStream} + */ + skipWhile(f:(value:A) => boolean):EventStream; + + /** + * @method + * @description Skips elements in the [EventStream]{@link Bacon.EventStream} until the value of the given [Property]{@link Bacon.Property} `property` is falsy once, and then lets all events pass through. + * @param {Property} property + * @returns {EventStream} + */ + skipWhile(property:Property):EventStream; + + /** + * @method + * @description Skips elements from the [EventStream]{@link Bacon.EventStream} until a [Next]{@link Bacon.Next} event appears in `stream2`. In other words, starts delivering values from `stream` after first event appears in `stream2`. + * @param {EventStream} stream2 + * @returns {EventStream} + */ + skipUntil(stream2:EventStream):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given `delay` (in milliseconds). The buffer is flushed at most once in the given `delay`. + * @param {number} delay + * @returns {EventStream} + * @example + * // You might get two events containing [1,2,3,4] and [5,6,7] respectively, given that the flush occurs between numbers 4 and 5: + * Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]).bufferWithTime(0); + */ + bufferWithTime(delay:number):EventStream; + + /** + * @callback EventStream#bufferWithTime~f + * @param {EventStream#bufferWithTime~defer} defer + * @returns {void} + */ + /** + * @callback EventStream#bufferWithTime~defer + * @param {...*} args + * @returns {void} + */ + /** + * @method EventStream#bufferWithTime + * @description Buffers the [EventStream]{@link Bacon.EventStream} with given "defer-function" `f`. + * @param {EventStream#bufferWithTime~f} f + * @returns {EventStream} + * @example + * // Here's an equivalent to `stream.bufferWithTime(10)`: + * let stream = Bacon.fromArray([1, 2, 3, 4, 5, 6, 7]); + * stream.bufferWithTime(f => { setTimeout(f, 10); }); } + */ + bufferWithTime(f:(defer:(...args:any[]) => void) => void):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events with given `count`. The buffer is flushed when it contains the given `count` of elements. + * @param {number} count + * @returns {EventStream} + * @example + * // You will get output events with values `[1, 2]`, `[3, 4]` and `[5]`. + * Bacon.fromArray([1, 2, 3, 4, 5]).bufferWithCount(2); + */ + bufferWithCount(count:number):EventStream; + + /** + * @method + * @description Buffers the [EventStream]{@link Bacon.EventStream} events and flushes when either the buffer contains the given `count` of elements or the given `delay` (in milliseconds) has passed since last buffered event. + * @param {number} delay + * @param {number} count + * @returns {EventStream} + */ + bufferWithTimeOrCount(delay:number, count:number):EventStream; + + /** + * @method EventStream#toProperty + * @description Creates a [Property]{@link Bacon.Property} based on the [EventStream]{@link Bacon.EventStream}. Without arguments, you'll get a Property without an initial value and will get its first actual value from the EventStream, and after that it'll always have a current value. Given `initialValue` will be used as the current value until the first value comes from the EventStream. + * @param {A} [initialValue] + * @returns {Property} + */ + toProperty(initialValue?:A):Property; + } + + var EventStream:{ + /** + * @callback EventStream#new~subscribe + * @param {EventStream#new~sink} sink + * @returns {EventStream#new~unsubscribe} + */ + /** + * @callback EventStream#new~sink + * @param {More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]} value + * @returns {void} + */ + /** + * @callback EventStream#new~unsubscribe + * @returns {void} + */ + /** + * @constructor EventStream#new + * @constructs Bacon.EventStream + * @description Creates an [EventStream]{@link Bacon.EventStream} with the given `subscribe` function. + * @param {EventStream#new~subscribe} subscribe + * @returns {EventStream} + */ + new(subscribe:(sink:(value:More|NoMore|(A|Initial|Next|End|Error)|(A|Initial|Next|End|Error)[]) => void) => (() => void)):EventStream; + }; + + /** + * @class Property + * @augments Bacon.Observable + * @description A reactive property. Has the concept of "current value". You can create a Property from an [EventStream]{@link Bacon.EventStream} by using either [EventStream.toProperty]{@link Bacon.EventStream#toProperty} or [Observable.scan]{@link Bacon.Observable#scan} method. Note: depending on how a Property is created, it may or may not have an initial value. The current value stays as its last value after the EventStream has ended. + * */ + interface Property extends Observable { + /** + * @callback Property#map~f + * @param {A} value + * @returns {B} + */ + /** + * @method Property#map + * @description Maps the [Property]{@link Bacon.Property} values using given function `f`, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {Property#map~f} f + * @returns {Property} + * */ + map(f:(value:A) => B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `constant` value, returning a new Property. This method, among many others, uses lazy evaluation. + * @param {B} constant + * @returns {Property} + * */ + map(constant:B):Property; + + /** + * @method + * @description Maps the [Property]{@link Bacon.Property} values using given `propertyExtractor` string like ".keyCode", returning a new Property. So, if f is a string starting with a dot, the elements will be mapped to the corresponding field/function in the event value. For instance map(".keyCode") will pluck the keyCode field from the input values. If "keyCode" was a function, the resulting Property would contain the values returned by the function. This method, among many others, uses lazy evaluation. + * @param {string} propertyExtractor + * @returns {Property} + * */ + map(propertyExtractor:string):Property; + + /** + * @callback Property#mapError~f + * @param {E} error + * @returns {B} + */ + /** + * @method Property#mapError + * @description Maps the [Property]{@link Bacon.Property} errors using given function `f`. More specifically, feeds the "error" field of the [Error]{@link Bacon.Error} event to the function `f` and produces a [Next]{@link Bacon.Next} event based on the return value. + * @param {Property#mapError~f} f + * @returns {Property} + */ + mapError(f:(error:E) => B):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} containing [Error]{@link Bacon.Error} events only. Same as filtering with a function that always returns false. + * @returns {Property} + */ + errors():Property; + + /** + * @method + * @description Skips all [Error]{@link Bacon.Error}s. + * @returns {Property} + */ + skipErrors():Property; + + /** + * @callback Property#mapEnd~f + * @returns {A} + */ + /** + * @method Property#mapEnd + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. The value is created by calling the given function `f` when the source Property ends. + * @param {Property#mapEnd~f} f + * @returns {Property} + */ + mapEnd(f:() => A):Property; + + /** + * @method + * @description Adds an extra [Next]{@link Bacon.Next} event just before [End]{@link Bacon.End} of the [Property]{@link Bacon.Property}. A static `value` is used. + * @param {A} value + * @returns {Property} + */ + mapEnd(value:A):Property; + + /** + * @callback Property#filter~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#filter + * @description Filters the [Property]{@link Bacon.Property} values using a given predicate function `f`. + * @param {Property#filter~f} f + * @returns {Property} + */ + filter(f:(value:A) => boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given constant `bool` value (`true` to include all, `false` to exclude all). + * @param {boolean} bool + * @returns {Property} + */ + filter(bool:boolean):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values using a given `propertyExtractor` string (like ".isValuable"). + * @param {string} propertyExtractor + * @returns {Property} + */ + filter(propertyExtractor:string):Property; + + /** + * @method + * @description Filters the [Property]{@link Bacon.Property} values based on the value of the Property `property`. Event will be included in output IF AND ONLY IF the `property` holds `true` at the time of the event. + * @param {Property} property + * @returns {Property} + */ + filter(property:Property):Property; + + /** + * @callback Property#takeWhile~f + * @param {A} value + * @returns {boolean} + */ + /** + * @method Property#takeWhile + * @description Takes the [Property]{@link Bacon.Property} values while given predicate function `f` holds `true`, and then ends. + * @param {Property#takeWhile~f} f + * @returns {Property} + */ + takeWhile(f:(value:A) => boolean):Property; + + /** + * @method + * @description Takes the [Property]{@link Bacon.Property} values while the value of a `property` holds `true`, and then ends. + * @param {Property} property + * @returns {Property} + */ + takeWhile(property:Property):Property; + + /** + * @method Property#take + * @description Takes at most `n` elements from the [Property]{@link Bacon.Property}. Equal to `Bacon.never()` if `n <= 0`. + * @param {number} n + * @returns {Property} + */ + take(n:number):Property; + + /** + * @method + * @description Takes elements from the [Property]{@link Bacon.Property} until a [Next]{@link Bacon.Next} event appears in the `stream`. If `stream` ends without value, it is ignored. + * @param {EventStream} stream + * @returns {Property} + */ + takeUntil(stream:EventStream):Property; + + /** + * @method + * @description Takes the first element from the [Property]{@link Bacon.Property}. Essentially [Property.take]{@link Bacon.Property#take}(1). + * @returns {Property} + */ + first():Property; + + /** + * @method + * @description Takes the last element from the [Property]{@link Bacon.Property}. None, if Property is empty. + * @returns {Property} + * @example + * // This creates the property which doesn't produce any events and never ends: + * Bacon.interval(1e1, 0).toProperty().last(); + */ + last():Property; + + /** + * @method + * @description Skips the first `n` elements from the [Property]{@link Bacon.Property}. + * @param {number} n + * @returns {Property} + */ + skip(n:number):Property; + + /** + * @method + * @description Delays the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Does not delay the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + delay(delay:number):Property; + + /** + * @method Property#throttle + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds). Events are emitted with the minimum interval of `delay`. The implementation is based on [EventStream.bufferWithTime]{@link Bacon.EventStream#bufferWithTime}. Does not affect emitting the initial value of a Property. + * @param {number} delay + * @returns {Property} + */ + throttle(delay:number):Property; + + /** + * @method Property#debounce + * @description Throttles the [Property]{@link Bacon.Property} by given `delay` (in milliseconds), but so that event is only emitted after the given "quiet period". Does not affect emitting the initial value of a Property. The difference of [throttle]{@link Bacon.Property#throttle} and [debounce]{@link Bacon.Property#debounce} is the same as it is in the same methods in jQuery. + * @param {number} delay + * @returns {Property} + */ + debounce(delay:number):Property; + + /** + * @method + * @description Passes the first event in the [Property]{@link Bacon.Property} through, but after that, only passes events after a given `delay` (in milliseconds) have passed since previous output. + * @param {number} delay + * @returns {Property} + */ + debounceImmediate(delay:number):Property; + + /** + * @callback Property#doAction~f + * @param {A} value + * @returns {void} + */ + /** + * @method Property#doAction + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {Property#doAction~f} f + * @returns {Property} + */ + doAction(f:(value:A) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} where the `propertyExtractor` string is applied to each value, before dispatching to subscribers. This is useful for debugging, but also for stuff like calling the `preventDefault()` method for events. + * @param {string} propertyExtractor + * @returns {Property} + */ + doAction(propertyExtractor:string):Property; + + /** + * @callback Property#doError~f + * @param {E} error + * @returns {void} + */ + /** + * @method Property#doError + * @description Returns a [Property]{@link Bacon.Property} where the function `f` is executed for each error, before dispatching to subscribers. That is, same as [doAction]{@link Bacon.Property#doAction} but for [Error]{@link Bacon.Error}s. + * @param {Property#doError~f} f + * @returns {Property} + */ + doError(f:(error:E) => void):Property; + + /** + * @method + * @description Returns a [Property]{@link Bacon.Property} that inverts boolean values. + * @returns {Property} + */ + not():Property; + + /** + * @method Property#log + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. It optionally takes a `label` argument to pass to `console.log()` alongside each value. To assist with chaining, it returns the original Property. Note that as a side-effect, the Property will have a constant listener and will not be garbage-collected. So, use this for debugging only and remove from production code. + * @param {string} [label] + * @returns {Property} + */ + log(label?:string):Property; + + /** + * @method Property#doLog + * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @returns {Property} + */ + doLog():Property; + + /** + * @method + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event. The error is included in the output of the returned Property. + * @returns {Property} + */ + endOnError():Property; + + /** + * @callback Property#endOnError~f + * @param {E} error + * @returns {boolean} + */ + /** + * @method Property#endOnError + * @description Ends the [Property]{@link Bacon.Property} on first [Error]{@link Bacon.Error} event for which the given predicate function `f` returns `true`. The error is included in the output of the returned Property. + * @param {Property#endOnError~f} f + * @returns {Property} + */ + endOnError(f:(error:E) => boolean):Property; + + /** + * @callback Property#withHandler~f + * @param {Initial|Next|End|Error} event + * @returns {*} + */ + /** + * @method Property#withHandler + * @description Lets you do more custom event handling on the [Property]{@link Bacon.Property}: you get all events to your function `f` and you can output any number of [Event]{@link Bacon.Event}s and end the Property if you choose. Note that it's important to return the value from `this.push` so that the connection to the underlying stream will be closed when no more events are needed. + * @param {Property#withHandler~f} f + * @returns {Property} + * @example + * // Send an error and end the stream in case a value is below zero: + * Bacon.fromArray([1, 2, -3, 3]).withHandler(function (event) { + * if (event.hasValue() && event.value() < 0) { + * this.push(new Bacon.Error("Value below zero")); + * return this.push(new Bacon.End()); + * } else { + * return this.push(event); + * } + * }); + */ + withHandler(f:(event:Initial|Next|End|Error) => any):Property; + + /** + * @method + * @description Sets the `newName` of the [Property]{@link Bacon.Property}. Overrides the default implementation of `toString` and `inspect`. Returns itself. + * @param {string} newName + * @returns {Property} + */ + name(newName:string):Property; + + /** + * @method + * @description Sets the structured description of the [Property]{@link Bacon.Property}. The `toString` and `inspect` methods use this data recursively to create a string representation for the Property. This method is probably useful for Bacon core/library/plugin development only. + * @param {...*} param + * @returns {Property} + * @example + * let src = Bacon.once(1), + * obs = src.map(x => -x); + * + * console.log(obs.toString()); + * // Bacon.once(1).map(function) + * + * obs.withDescription(src, "times", -1); + * console.log(obs.toString()); + * // Bacon.once(1).times(-1) + */ + withDescription(...param:any[]):Property; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} based on this [Property]{@link Bacon.Property}. The EventStream contains also an event for the current value of this Property at the time this method was called. + * @returns {EventStream} + */ + toEventStream():EventStream; + + /** + * @callback Property#subscribe~f + * @param {Event} event + * @returns {void} + */ + /** + * @callback Property#subscribe~unsubscribe + * @returns {void} + */ + /** + * @method Property#subscribe + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. If there's a current value, an [Initial]{@link Bacon.Initial} event will be pushed immediately. [Next]{@link Bacon.Next} event will be pushed on updates and an [End]{@link Bacon.End} event in case the source Property ends. Returns a function that you call to `unsubscribe`. + * @param {Property#subscribe~f} f + * @returns {Property#subscribe~unsubscribe} + */ + subscribe(f:(event:Event) => void):() => void; + + /** + * @callback Property#onValue~f + * @param {A} value + * @returns {void} + */ + /** + * @callback Property#onValue~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValue + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Similar to [EventStream.onValue]{@link Bacon.EventStream#onValue}, except that also pushes the initial value of the Property, in case there is one. Just like [subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. + * @param {Property#onValue~f} f + * @returns {Property#onValue~unsubscribe} + */ + onValue(f:(value:A) => void):() => void; + + /** + * @callback Property#onValues~f + * @param {*[]} args + * @returns {void} + */ + /** + * @callback Property#onValues~unsubscribe + * @returns {void} + */ + /** + * @method Property#onValues + * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Like [onValue]{@link Bacon.Property#onValue}, but splits the value (assuming its an array) as function arguments to `f`. + * @param {Property#onValues~f} f + * @returns {Property#onValues~unsubscribe} + */ + onValues(f:(...args:any[]) => void):() => void; + + /** + * @method Property#assign + * @description Calls the `method` of the given `object` with each value of this [Property]{@link Bacon.Property}. You can optionally supply `params` which will be used as the first arguments of the `method` call. Note that the [assign]{@link Bacon.Property#assign} method is actually just a synonym for [onValue]{@link Bacon.Property#onValue}. + * @param {Object} obj + * @param {string} method + * @param {...*} params + * @returns {void} + * @example + * let property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); + * // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: + * property.assign($("#my-button"), "attr", "disabled"); + * // A simpler example would be to toggle the visibility of an element based on a Property: + * property.assign($("#my-button"), "toggle"); + */ + assign(obj:Object, method:string, ...params:any[]):void; + + /** + * @method + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at given `interval` (in milliseconds). + * @param {number} interval + * @returns {EventStream} + */ + sample(interval:number):EventStream; + + /** + * @method Property#sampledBy + * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at each event from the given `stream`. The result EventStream will contain the value at each event in the source Property. + * @param {EventStream} stream + * @returns {EventStream} + */ + sampledBy(stream:EventStream):EventStream; + + /** + * @method + * @description Creates a [Property]{@link Bacon.Property} by sampling the value at each event from the given [Property]{@link Bacon.Property} `property`. The result Property will contain the value at each event in the source Property. + * @param {Property} property + * @returns {Property} + */ + sampledBy(property:Property):Property; + + /** + * @callback Property#sampledBy~f + * @param {A} propertyValue + * @param {B} samplerValue + * @returns {C} + */ + /** + * @method Property#sampledBy + * @description Samples the [Property]{@link Bacon.Property} on `streamOrProperty` events. The result values will be formed using the given function `f`. + * @param {Observable} streamOrProperty + * @param {Property#sampledBy~f} f + * @returns {EventStream} + */ + sampledBy(streamOrProperty:Observable, f:(propertyValue:A, samplerValue:B) => C):EventStream; + + /** + * @callback Property#skipDuplicates~isEqual + * @param {A} oldValue + * @param {A} newValue + * @returns {boolean} + */ + /** + * @method Property#skipDuplicates + * @description Drops consecutive equal elements. Uses the `===` operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling `isEqual(oldValue, newValue)`. The old name for this method was `distinctUntilChanged`. + * @param {Property#skipDuplicates~isEqual} [isEqual] + * @returns {Property} + */ + skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):Property; + + /** + * @method Property#changes + * @description Returns an [EventStream]{@link Bacon.EventStream} of [Property]{@link Bacon.Property} value changes. Returns exactly the same events as the Property itself, except any [Initial]{@link Bacon.Initial} events (the stream DOES NOT include an event for the current value of the Property at the time this method was called). Note that [Property.changes]{@link Bacon.Property#changes} DOES NOT skip duplicate values, use [Property.skipDuplicates]{@link Bacon.Property#skipDuplicates} for that. + * @returns {EventStream} + */ + changes():EventStream; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the && operator. + * @param {Property} other + * @returns {Property} + */ + and(other:Property):Property; + + /** + * @method + * @description Combines [Property]{@link Bacon.Property}s with the || operator. + * @param {Property} other + * @returns {Property} + */ + or(other:Property):Property; + + /** + * @method + * @description Adds an initial "default" value for the [Property]{@link Bacon.Property}. If the Property doesn't have an initial value of it's own, the given `value` will be used as the initial value. If the property has an initial value of its own, the given `value` will be ignored. + * @param {A} value + * @returns {Property} + */ + startWith(value:A):Property; + } + + /** + * @function Bacon.combineAsArray + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. The input array may contain both Properties and EventStreams. In the latter case, the stream is first converted into a Property and then combined with the other Property's. + * @param {(A|Observable)[]} streams + * @returns {Property} + */ + function combineAsArray(streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. Like [Bacon.combineAsArray]{@link Bacon.combineAsArray}, but `streams` are provided as a list of arguments as opposed to a single array. + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineAsArray(...streams:(A|Observable)[]):Property; + + /** + * @callback Property#combineWith~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Property#combineWith + * @description Combines given n [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using the given n-ary function `f`. + * @param {Property#combineWith~f} f + * @param {...(A|Observable)} streams + * @returns {Property} + */ + function combineWith(f:(...args:A[]) => B, ...streams:(A|Observable)[]):Property; + + /** + * @function + * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using a `template` object. + * @param {{string:number|boolean|string|Object|Observable}} template * @returns {Property} + */ + function combineTemplate(template:{[label:string]:number|boolean|string|Object|Observable}):Property; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function mergeAll(streams:EventStream[]):EventStream; + + /** + * @function + * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function mergeAll(...streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @returns {EventStream} + */ + function zipAsArray(streams:EventStream[]):EventStream; + + /** + * @function + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. EventStream's are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipAsArray(...streams:EventStream[]):EventStream; + + /** + * @callback Bacon.zipWith1~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith1 + * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {EventStream[]} streams + * @param {Bacon.zipWith1~f} f + * @returns {EventStream} + */ + function zipWith(streams:EventStream[], f:(...args:A[]) => B):EventStream; + + /** + * @callback Bacon.zipWith2~f + * @param {...A} args + * @returns {B} + */ + /** + * @function Bacon.zipWith2 + * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Streams are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. + * @param {Bacon.zipWith2~f} f + * @param {...EventStream} streams + * @returns {EventStream} + */ + function zipWith(f:(...args:A[]) => B, ...streams:EventStream[]):EventStream; + + /** + * @function + * @description Is a shorthand for combining multiple sources ([EventStream]{@link Bacon.EventStream}s, [Property]{@link Bacon.Property}s, constants) as array and assigning the side-effect function `f` for the values. + * @param {...*} args + * @returns {void} + */ + function onValues(...args:any[]):void; + + /** + * @class Bus + * @augments Bacon.EventStream + * @description An [EventStream]{@link Bacon.EventStream} that allows you to [push]{@link Bacon.Bus#push} values into the EventStream. It also allows [plug]{@link Bacon.Bus#plug}ging other EventStream's into the Bus. The Bus practically merges all plugged-in streams and the values pushed using the [push]{@link Bacon.Bus#push} method. + */ + interface Bus extends EventStream { + /** + * @method Bus#push + * @description Pushes the given `value` to the [Bus]{@link Bacon.Bus}. + * @param {A} value + * @returns {void} + */ + push(value:A):void; + + /** + * @method + * @description Ends the [Bus]{@link Bacon.Bus}. Sends an [End]{@link Bacon.End} event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [Bus.push]{@link Bacon.Bus#push} and [Bus.plug]{@link Bacon.Bus#plug} methods have no effect. + * @returns {void} + */ + end():void; + + /** + * @method + * @description Sends an [Error]{@link Bacon.Error} with given `error` message to all subscribers. + * @param {E} error + * @returns {void} + */ + error(error:E):void; + + /** + * @callback Bus#plug~unplug + * @returns {void} + */ + /** + * @method Bus#plug + * @description Plugs the given [EventStream]{@link Bacon.EventStream} to the [Bus]{@link Bacon.Bus}. All events from the given `stream` will be delivered to the subscribers of the Bus. Returns a function `unplug` that can be used to unplug the same stream. The [plug]{@link Bacon.Bus#plug} method practically allows you to merge in other EventStream's after the creation of the Bus. + * @param {EventStream} stream + * @returns {Bus#plug~unplug} + */ + plug(stream:EventStream):() => void; + } + + var Bus:{ + /** + * @constructor + * @constructs Bacon.Bus + * @description Returns a new [Bus]{@link Bacon.Bus}. + * @returns {Bus} + */ + new():Bus; + }; + + /** + * @class Event + * @description Has subclasses [Initial]{@link Bacon.Initial}, [Next]{@link Bacon.Next}, [End]{@link Bacon.End} and [Error]{@link Bacon.Error}. + * */ + class Event { + /** + * @method + * @description Returns the value associated with a [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next} event. + * @returns {A} + */ + value():A; + + /** + * @method + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + hasValue():boolean; + + /** + * @method Error#isInitial + * @description Returns `true` for events of type [Initial]{@link Bacon.Initial}. + * @returns {boolean} + */ + isInitial():boolean; + + /** + * @method Error#isNext + * @description Returns `true` for events of type [Next]{@link Bacon.Next}. + * @returns {boolean} + */ + isNext():boolean; + + /** + * @method Error#isError + * @description Returns `true` for events of type [Error]{@link Bacon.Error}. + * @returns {boolean} + */ + isError():boolean; + + /** + * @method Error#isEnd + * @description Returns `true` for events of type [End]{@link Bacon.End}. + * @returns {boolean} + */ + isEnd():boolean; + } + + /** + * @class Error + * @augments Bacon.Event + * @description An error event. Call [Event.isError]{@link Bacon.Event#isError} to distinguish these events in your subscriber, or use [onError]{@link Bacon.Observable#onError} to react to error events only. [Error.error]{@link Bacon.Error#error} returns the associated error object (usually string). [Error]{@link Bacon.Error} events are always passed through all stream combinators. So, even if you filter all values out, the error events will pass through. If you use [Observable.flatMap]{@link Bacon.Observable#flatMap}, the result stream will contain Error events from the source as well as all the spawned stream. You can take action on errors by using the [Observable.onError]{@link Bacon.Observable#onError}. See documentation on [Observable.onError]{@link Bacon.Observable#onError}, [EventStream.mapError]{@link Bacon.EventStream#mapError}, [Property.mapError]{@link Bacon.Property#mapError}, [EventStream.errors]{@link Bacon.EventStream#errors}, [Property.errors]{@link Bacon.Property#errors}, [EventStream.skipErrors]{@link Bacon.EventStream#skipErrors}, [Property.skipErrors]{@link Bacon.Property#skipErrors}, [Bacon.retry]{@link Bacon.retry} and [Observable.flatMapError]{@link Bacon.Observable#flatMapError}. An Error does not terminate the stream. The methods [EventStream.endOnError]{@link Bacon.EventStream#endOnError} and [EventStream.endOnError]{@link Bacon.EventStream#endOnError} returns a stream/property that ends immediately after first error. Bacon.js doesn't currently generate any Error events itself (except when converting errors using [Bacon.fromPromise]{@link Bacon.fromPromise}). Error events definitely would be generated by streams derived from IO sources such as AJAX calls. * @example - * let src = Bacon.once(1), - * obs = src.map(x => -x); - * - * console.log(obs.toString()); - * // Bacon.once(1).map(function) - * - * obs.withDescription(src, "times", -1); - * console.log(obs.toString()); - * // Bacon.once(1).times(-1) - */ - withDescription(...param:any[]):Property; - - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} based on this [Property]{@link Bacon.Property}. The EventStream contains also an event for the current value of this Property at the time this method was called. - * @returns {EventStream} - */ - toEventStream():EventStream; - - /** - * @callback Property#subscribe~f - * @param {Event} event - * @returns {void} - */ - /** - * @callback Property#subscribe~unsubscribe - * @returns {void} - */ - /** - * @method Property#subscribe - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. If there's a current value, an [Initial]{@link Bacon.Initial} event will be pushed immediately. [Next]{@link Bacon.Next} event will be pushed on updates and an [End]{@link Bacon.End} event in case the source Property ends. Returns a function that you call to `unsubscribe`. - * @param {Property#subscribe~f} f - * @returns {Property#subscribe~unsubscribe} - */ - subscribe(f:(event:Event) => void):() => void; - - /** - * @callback Property#onValue~f - * @param {A} value - * @returns {void} - */ - /** - * @callback Property#onValue~unsubscribe - * @returns {void} - */ - /** - * @method Property#onValue - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Similar to [EventStream.onValue]{@link Bacon.EventStream#onValue}, except that also pushes the initial value of the Property, in case there is one. Just like [subscribe]{@link Bacon.Property#subscribe}, this method returns a function for `unsubscribe`ing. - * @param {Property#onValue~f} f - * @returns {Property#onValue~unsubscribe} - */ - onValue(f:(value:A) => void):() => void; - - /** - * @callback Property#onValues~f - * @param {*[]} args - * @returns {void} - */ - /** - * @callback Property#onValues~unsubscribe - * @returns {void} - */ - /** - * @method Property#onValues - * @description Subscribes a handler function `f` to [Property]{@link Bacon.Property}. Like [onValue]{@link Bacon.Property#onValue}, but splits the value (assuming its an array) as function arguments to `f`. - * @param {Property#onValues~f} f - * @returns {Property#onValues~unsubscribe} - */ - onValues(f:(...args:any[]) => void):() => void; - - /** - * @method Property#assign - * @description Calls the `method` of the given `object` with each value of this [Property]{@link Bacon.Property}. You can optionally supply `params` which will be used as the first arguments of the `method` call. Note that the [assign]{@link Bacon.Property#assign} method is actually just a synonym for [onValue]{@link Bacon.Property#onValue}. - * @param {Object} obj - * @param {string} method - * @param {...*} params - * @returns {void} - * @example - * let property = Bacon.fromArray([1, 2, 3, 4, 5]).toProperty(); - * // If you want to assign your Property to the "disabled" attribute of a JQuery object, you can do this: - * property.assign($("#my-button"), "attr", "disabled"); - * // A simpler example would be to toggle the visibility of an element based on a Property: - * property.assign($("#my-button"), "toggle"); - */ - assign(obj:Object, method:string, ...params:any[]):void; - - /** - * @method - * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at given `interval` (in milliseconds). - * @param {number} interval - * @returns {EventStream} - */ - sample(interval:number):EventStream; - - /** - * @method Property#sampledBy - * @description Creates an [EventStream]{@link Bacon.EventStream} by sampling the [Property]{@link Bacon.Property} value at each event from the given `stream`. The result EventStream will contain the value at each event in the source Property. - * @param {EventStream} stream - * @returns {EventStream} - */ - sampledBy(stream:EventStream):EventStream; - - /** - * @method - * @description Creates a [Property]{@link Bacon.Property} by sampling the value at each event from the given [Property]{@link Bacon.Property} `property`. The result Property will contain the value at each event in the source Property. - * @param {Property} property - * @returns {Property} - */ - sampledBy(property:Property):Property; - - /** - * @callback Property#sampledBy~f - * @param {A} propertyValue - * @param {B} samplerValue - * @returns {C} - */ - /** - * @method Property#sampledBy - * @description Samples the [Property]{@link Bacon.Property} on `streamOrProperty` events. The result values will be formed using the given function `f`. - * @param {Observable} streamOrProperty - * @param {Property#sampledBy~f} f - * @returns {EventStream} - */ - sampledBy(streamOrProperty:Observable, f:(propertyValue:A, samplerValue:B) => C):EventStream; - - /** - * @callback Property#skipDuplicates~isEqual - * @param {A} oldValue - * @param {A} newValue - * @returns {boolean} - */ - /** - * @method Property#skipDuplicates - * @description Drops consecutive equal elements. Uses the `===` operator for equality checking by default. If the `isEqual` argument is supplied, checks by calling `isEqual(oldValue, newValue)`. The old name for this method was `distinctUntilChanged`. - * @param {Property#skipDuplicates~isEqual} [isEqual] - * @returns {Property} - */ - skipDuplicates(isEqual?:(oldValue:A, newValue:A) => boolean):Property; - - /** - * @method Property#changes - * @description Returns an [EventStream]{@link Bacon.EventStream} of [Property]{@link Bacon.Property} value changes. Returns exactly the same events as the Property itself, except any [Initial]{@link Bacon.Initial} events (the stream DOES NOT include an event for the current value of the Property at the time this method was called). Note that [Property.changes]{@link Bacon.Property#changes} DOES NOT skip duplicate values, use [Property.skipDuplicates]{@link Bacon.Property#skipDuplicates} for that. - * @returns {EventStream} - */ - changes():EventStream; - - /** - * @method - * @description Combines [Property]{@link Bacon.Property}s with the && operator. - * @param {Property} other - * @returns {Property} - */ - and(other:Property):Property; - - /** - * @method - * @description Combines [Property]{@link Bacon.Property}s with the || operator. - * @param {Property} other - * @returns {Property} - */ - or(other:Property):Property; - - /** - * @method - * @description Adds an initial "default" value for the [Property]{@link Bacon.Property}. If the Property doesn't have an initial value of it's own, the given `value` will be used as the initial value. If the property has an initial value of its own, the given `value` will be ignored. - * @param {A} value - * @returns {Property} - */ - startWith(value:A):Property; - } - - /** - * @function Bacon.combineAsArray - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. The input array may contain both Properties and EventStreams. In the latter case, the stream is first converted into a Property and then combined with the other Property's. - * @param {(A|Observable)[]} streams - * @returns {Property} - */ - function combineAsArray(streams:(A|Observable)[]):Property; - - /** - * @function - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values so that the result Property will have an array of all property values as its value. Like [Bacon.combineAsArray]{@link Bacon.combineAsArray}, but `streams` are provided as a list of arguments as opposed to a single array. - * @param {...(A|Observable)} streams - * @returns {Property} - */ - function combineAsArray(...streams:(A|Observable)[]):Property; - - /** - * @callback Property#combineWith~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Property#combineWith - * @description Combines given n [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using the given n-ary function `f`. - * @param {Property#combineWith~f} f - * @param {...(A|Observable)} streams - * @returns {Property} - */ - function combineWith(f:(...args:A[]) => B, ...streams:(A|Observable)[]):Property; - - /** - * @function - * @description Combines [Property]{@link Bacon.Property}s, [EventStream]{@link Bacon.EventStream}s and constant values using a `template` object. - * @param {{string:number|boolean|string|Object|Observable}} template - * @returns {Property} - */ - function combineTemplate(template:{[label:string]:number|boolean|string|Object|Observable}):Property; - - /** - * @function - * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. - * @param {EventStream[]} streams - * @returns {EventStream} - */ - function mergeAll(streams:EventStream[]):EventStream; - - /** - * @function - * @description Merges given array of [EventStream]{@link Bacon.EventStream}s. - * @param {...EventStream} streams - * @returns {EventStream} - */ - function mergeAll(...streams:EventStream[]):EventStream; - - /** - * @function - * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {EventStream[]} streams - * @returns {EventStream} - */ - function zipAsArray(streams:EventStream[]):EventStream; - - /** - * @function - * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will have an array of values from each source EventStream as its value. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. EventStream's are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {...EventStream} streams - * @returns {EventStream} - */ - function zipAsArray(...streams:EventStream[]):EventStream; - - /** - * @callback Bacon.zipWith1~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Bacon.zipWith1 - * @description Zips the array of `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {EventStream[]} streams - * @param {Bacon.zipWith1~f} f - * @returns {EventStream} - */ - function zipWith(streams:EventStream[], f:(...args:A[]) => B):EventStream; - - /** - * @callback Bacon.zipWith2~f - * @param {...A} args - * @returns {B} - */ - /** - * @function Bacon.zipWith2 - * @description Zips the `streams` in to a new [EventStream]{@link Bacon.EventStream} that will combine the n values from EventStream's with n-ary function `f`. Zipping means that events from each EventStream are combine pairwise so that the 1st event from each EventStream is published first, then the 2nd event from each. The results will be published as soon as there is a value from each source EventStream. Streams are provided as a list of arguments as opposed to a single array. Be careful not to have too much "drift" between EventStream's. If one EventStream produces many more values than some other excessive buffering will occur inside the zipped [Observable]{@link Bacon.Observable}. - * @param {Bacon.zipWith2~f} f - * @param {...EventStream} streams - * @returns {EventStream} - */ - function zipWith(f:(...args:A[]) => B, ...streams:EventStream[]):EventStream; - - /** - * @function - * @description Is a shorthand for combining multiple sources ([EventStream]{@link Bacon.EventStream}s, [Property]{@link Bacon.Property}s, constants) as array and assigning the side-effect function `f` for the values. - * @param {...*} args - * @returns {void} - */ - function onValues(...args:any[]):void; - - /** - * @class Bus - * @augments Bacon.EventStream - * @description An [EventStream]{@link Bacon.EventStream} that allows you to [push]{@link Bacon.Bus#push} values into the EventStream. It also allows [plug]{@link Bacon.Bus#plug}ging other EventStream's into the Bus. The Bus practically merges all plugged-in streams and the values pushed using the [push]{@link Bacon.Bus#push} method. - */ - interface Bus extends EventStream { - /** - * @method Bus#push - * @description Pushes the given `value` to the [Bus]{@link Bacon.Bus}. - * @param {A} value - * @returns {void} - */ - push(value:A):void; - - /** - * @method - * @description Ends the [Bus]{@link Bacon.Bus}. Sends an [End]{@link Bacon.End} event to all subscribers. After this call, there'll be no more events to the subscribers. Also, the [Bus.push]{@link Bacon.Bus#push} and [Bus.plug]{@link Bacon.Bus#plug} methods have no effect. - * @returns {void} - */ - end():void; - - /** - * @method - * @description Sends an [Error]{@link Bacon.Error} with given `error` message to all subscribers. - * @param {Error} error - * @returns {void} - */ - error(error:Error):void; - - /** - * @callback Bus#plug~unplug - * @returns {void} - */ - /** - * @method Bus#plug - * @description Plugs the given [EventStream]{@link Bacon.EventStream} to the [Bus]{@link Bacon.Bus}. All events from the given `stream` will be delivered to the subscribers of the Bus. Returns a function `unplug` that can be used to unplug the same stream. The [plug]{@link Bacon.Bus#plug} method practically allows you to merge in other EventStream's after the creation of the Bus. - * @param {EventStream} stream - * @returns {Bus#plug~unplug} - */ - plug(stream:EventStream):() => void; - } - - var Bus:{ - /** - * @constructor - * @constructs Bacon.Bus - * @description Returns a new [Bus]{@link Bacon.Bus}. - * @returns {Bus} - */ - new():Bus; - }; - - /** - * @class Event - * @description Has subclasses [Initial]{@link Bacon.Initial}, [Next]{@link Bacon.Next}, [End]{@link Bacon.End} and [Error]{@link Bacon.Error}. - * */ - class Event { - /** - * @method - * @description Returns the value associated with a [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next} event. - * @returns {A} - */ - value():A; - - /** - * @method - * @description Returns `true` for events of type [Initial]{@link Bacon.Initial} or [Next]{@link Bacon.Next}. - * @returns {boolean} - */ - hasValue():boolean; - - /** - * @method Error#isInitial - * @description Returns `true` for events of type [Initial]{@link Bacon.Initial}. - * @returns {boolean} - */ - isInitial():boolean; - - /** - * @method Error#isNext - * @description Returns `true` for events of type [Next]{@link Bacon.Next}. - * @returns {boolean} - */ - isNext():boolean; - - /** - * @method Error#isError - * @description Returns `true` for events of type [Error]{@link Bacon.Error}. - * @returns {boolean} - */ - isError():boolean; - - /** - * @method Error#isEnd - * @description Returns `true` for events of type [End]{@link Bacon.End}. - * @returns {boolean} - */ - isEnd():boolean; - } - - /** - * @class Error - * @augments Bacon.Event - * @description An error event. Call [Event.isError]{@link Bacon.Event#isError} to distinguish these events in your subscriber, or use [onError]{@link Bacon.Observable#onError} to react to error events only. [Error.error]{@link Bacon.Error#error} returns the associated error object (usually string). [Error]{@link Bacon.Error} events are always passed through all stream combinators. So, even if you filter all values out, the error events will pass through. If you use [Observable.flatMap]{@link Bacon.Observable#flatMap}, the result stream will contain Error events from the source as well as all the spawned stream. You can take action on errors by using the [Observable.onError]{@link Bacon.Observable#onError}. See documentation on [Observable.onError]{@link Bacon.Observable#onError}, [EventStream.mapError]{@link Bacon.EventStream#mapError}, [Property.mapError]{@link Bacon.Property#mapError}, [EventStream.errors]{@link Bacon.EventStream#errors}, [Property.errors]{@link Bacon.Property#errors}, [EventStream.skipErrors]{@link Bacon.EventStream#skipErrors}, [Property.skipErrors]{@link Bacon.Property#skipErrors}, [Bacon.retry]{@link Bacon.retry} and [Observable.flatMapError]{@link Bacon.Observable#flatMapError}. An Error does not terminate the stream. The methods [EventStream.endOnError]{@link Bacon.EventStream#endOnError} and [EventStream.endOnError]{@link Bacon.EventStream#endOnError} returns a stream/property that ends immediately after first error. Bacon.js doesn't currently generate any Error events itself (except when converting errors using [Bacon.fromPromise]{@link Bacon.fromPromise}). Error events definitely would be generated by streams derived from IO sources such as AJAX calls. - * @example - * // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: - * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * // In case you want to convert (some) value events into Error events, you may use `flatMap` like this: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { * NOTE: had to explicitly specify the `` typing for `flatMap`. * return x > 2 ? new Bacon.Error("too big") : x; * }); - * - * // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: - * Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { + * + * // Conversely, if you want to convert some Error events into value events, you may use `flatMapError`: + * Bacon.fromArray([1, 2, 3, 4]).flatMapError(error => { * let isNonCriticalError = error => Math.random() < .5, * handleNonCriticalError = error => 42; * return isNonCriticalError(error) ? handleNonCriticalError(error) : new Bacon.Error(error); * }); - * - * // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: - * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { + * + * // Note also that Bacon.js combinators do not catch errors that are thrown. Especially `map` doesn't do so. If you want to map things and wrap caught errors into Error events, you can do the following: + * Bacon.fromArray([1, 2, 3, 4]).flatMap(x => { * let dangerousFunction = x => { * throw new Error("dangerous function!"); * }; @@ -2077,673 +2081,1053 @@ declare module Bacon { * return new Bacon.Error(e); * } * }); - */ - class Error extends Event { + */ + class Error extends Event { + /** + * @constructor + * @constructs Error + * @param {E} error + * */ + constructor(error:E); + + /** + * @property Error#error + * @description Returns the `error` associated with an [Error]{@link Bacon.Error} event. + * @returns {E} + */ + error:E; + } + /** - * @constructor - * @constructs Error + * @class End + * @augments Bacon.Event + * @description An end-of-stream event of [EventStream]{@link Bacon.EventStream} or [Property]{@link Bacon.Property}. Call [Event.isEnd]{@link Bacon.Event#isEnd} to distinguish an End from other events. + * */ + class End extends Event { + /** + * @constructor + * @constructs Bacon.End + * */ + constructor(); + } + + /** + * @class Initial + * @augments Bacon.Event + * @description The initial (current) value of a [Property]{@link Bacon.Property}. Call [Event.isInitial]{@link Bacon.Event#isInitial} to distinguish from other events. Only sent immediately after subscription to a Property. + * */ + class Initial extends Event { + /** + * @constructor + * @constructs Bacon.Initial + * @param {A} value + * */ + constructor(value:A); + } + + /** + * @class Next + * @augments Bacon.Event + * @description Next value in an [EventStream]{@link Bacon.EventStream} or a [Property]{@link Bacon.Property}. Call [Event.isNext]{@link Bacon.Event#isNext} to distinguish a Next event from other events. + * */ + class Next extends Event { + /** + * @constructor + * @constructs Bacon.Next + * @param {A} value + * @example + * new Bacon.Next("value"); + * */ + constructor(value:A); + + /** + * @callback Next#constructor + * @returns {A} + */ + /** + * @constructor Next#constructor + * @constructs Bacon.Next + * @description This version is safe only when you know that the actual value in the stream is not a function. The idea in using a function `f` instead of a plain value is that the internals on Bacon.js take advantage of lazy evaluation by deferring the evaluations of values created by `map`, `combine`. + * @param {Next#constructor} f + * @example + * new Bacon.Next(() => "value"); + * */ + constructor(f:() => A); + } + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [EventStream]{@link Bacon.EventStream}. + * @returns {EventStream} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. * @param {E} error - * */ - constructor(error:E); - - /** - * @property Error#error - * @description Returns the `error` associated with an [Error]{@link Bacon.Error} event. - * @returns {E} - */ - error:E; - } - - /** - * @class End - * @augments Bacon.Event - * @description An end-of-stream event of [EventStream]{@link Bacon.EventStream} or [Property]{@link Bacon.Property}. Call [Event.isEnd]{@link Bacon.Event#isEnd} to distinguish an End from other events. - * */ - class End extends Event { - /** - * @constructor - * @constructs Bacon.End - * */ - constructor(); - } - - /** - * @class Initial - * @augments Bacon.Event - * @description The initial (current) value of a [Property]{@link Bacon.Property}. Call [Event.isInitial]{@link Bacon.Event#isInitial} to distinguish from other events. Only sent immediately after subscription to a Property. - * */ - class Initial extends Event { - /** - * @constructor - * @constructs Bacon.Initial - * @param {A} value - * */ - constructor(value:A); - } - - /** - * @class Next - * @augments Bacon.Event - * @description Next value in an [EventStream]{@link Bacon.EventStream} or a [Property]{@link Bacon.Property}. Call [Event.isNext]{@link Bacon.Event#isNext} to distinguish a Next event from other events. - * */ - class Next extends Event { - /** - * @constructor - * @constructs Bacon.Next - * @param {A} value - * @example - * new Bacon.Next("value"); - * */ - constructor(value:A); - - /** - * @callback Next#constructor - * @returns {A} + * @returns {boolean} */ /** - * @constructor Next#constructor - * @constructs Bacon.Next - * @description This version is safe only when you know that the actual value in the stream is not a function. The idea in using a function `f` instead of a plain value is that the internals on Bacon.js take advantage of lazy evaluation by deferring the evaluations of values created by `map`, `combine`. - * @param {Next#constructor} f + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [EventStream]{@link Bacon.EventStream} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [EventStream]{@link Bacon.EventStream} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {EventStream} + */ + function retry(options:{ + source:() => EventStream; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):EventStream; + + /** + * @callback Bacon.retry1~source + * @description Function that produces an [Property]{@link Bacon.Property}. + * @returns {Property} + */ + /** + * @callback Bacon.retry1~isRetryable + * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. + * @param {E} error + * @returns {boolean} + */ + /** + * @callback Bacon.retry1~delay + * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. + * @param {Object} context + * @param {E} context.error [Error]{@link Bacon.Error} that occurred + * @param {number} context.retriesDone number of retries already performed + * @returns {number} + */ + /** + * @function Bacon.retry1 + * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [Property]{@link Bacon.Property} produced by the `source` function. + * @param {Object} options + * @param {Bacon.retry1~source} options.source function that produces an [Property]{@link Bacon.Property} + * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt + * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. + * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. + * @returns {Property} + */ + function retry(options:{ + source:() => Property; + retries:number; + isRetryable?:(error:E) => boolean; + delay?:(context:{error:E; retriesDone:number}) => number; + }):Property; + + /** + * @callback Bacon.when1~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.when1 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when1~f1} f1 + * @returns {EventStream} * @example - * new Bacon.Next(() => "value"); - * */ - constructor(f:() => A); - } + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B):EventStream; - /** - * @callback Bacon.retry1~source - * @description Function that produces an [EventStream]{@link Bacon.EventStream}. - * @returns {EventStream} - */ - /** - * @callback Bacon.retry1~isRetryable - * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. - * @param {E} error - * @returns {boolean} - */ - /** - * @callback Bacon.retry1~delay - * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. - * @param {Object} context - * @param {E} context.error [Error]{@link Bacon.Error} that occurred - * @param {number} context.retriesDone number of retries already performed - * @returns {number} - */ - /** - * @function Bacon.retry1 - * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [EventStream]{@link Bacon.EventStream} produced by the `source` function. - * @param {Object} options - * @param {Bacon.retry1~source} options.source function that produces an [EventStream]{@link Bacon.EventStream} - * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt - * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. - * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. - * @returns {EventStream} - */ - function retry(options:{ - source:() => EventStream; - retries:number; - isRetryable?:(error:E) => boolean; - delay?:(context:{error:E; retriesDone:number}) => number; - }):EventStream; + /** + * @callback Bacon.when2~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when2~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.when2 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when2~f2} f2 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B):EventStream; - /** - * @callback Bacon.retry1~source - * @description Function that produces an [Property]{@link Bacon.Property}. - * @returns {Property} - */ - /** - * @callback Bacon.retry1~isRetryable - * @description Function returning `true` to continue retrying, `false` to stop. Defaults to `true`. The [Error]{@link Bacon.Error} that occurred is given as a parameter. For example, there is usually no reason to retry a 404 HTTP error, whereas a 500 or a timeout might work on the next attempt. - * @param {E} error - * @returns {boolean} - */ - /** - * @callback Bacon.retry1~delay - * @description Function that returns the time in milliseconds to wait before retrying. Defaults to `0`. The function is given a `context` object with the keys `error` (the [Error]{@link Bacon.Error} that occurred) and `retriesDone` (the number of retries already performed) to help determine the appropriate delay, e.g. for an incremental backoff. - * @param {Object} context - * @param {E} context.error [Error]{@link Bacon.Error} that occurred - * @param {number} context.retriesDone number of retries already performed - * @returns {number} - */ - /** - * @function Bacon.retry1 - * @description Is used to retry the call when there is an [Error]{@link Bacon.Error} event in the [Property]{@link Bacon.Property} produced by the `source` function. - * @param {Object} options - * @param {Bacon.retry1~source} options.source function that produces an [Property]{@link Bacon.Property} - * @param {number} options.retries number of times to retry the `source` function in addition to the initial attempt - * @param {Bacon.retry1~isRetryable} [options.isRetryable] function returning `true` to continue retrying, `false` to stop. Defaults to `true`. - * @param {Bacon.retry1~delay} [options.delay] - function that returns the time in milliseconds to wait before retrying. Defaults to `0`. - * @returns {Property} - */ - function retry(options:{ - source:() => Property; - retries:number; - isRetryable?:(error:E) => boolean; - delay?:(context:{error:E; retriesDone:number}) => number; - }):Property; + /** + * @callback Bacon.when3~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when3~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.when3 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when3~f3} f3 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B):EventStream; - /** - * @callback Bacon.when1~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @method Bacon.when1 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when1~f1} f1 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B):EventStream; + /** + * @callback Bacon.when4~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when4~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.when4 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when4~f4} f4 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B):EventStream; - /** - * @callback Bacon.when2~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when2~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @method Bacon.when2 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when2~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when2~f2} f2 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B):EventStream; + /** + * @callback Bacon.when5~f1 + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f2 + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f3 + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f4 + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.when5~f5 + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.when5 + * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. + * @param {Observable[]} pattern1 + * @param {Bacon.when5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.when5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.when5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.when5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.when5~f5} f5 + * @returns {EventStream} + * @example + * { + * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: + * let tick = Bacon.interval(1e2, 0), + * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), + * handleTick = _ => `timestamp: NONE`, + * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; + * Bacon.when( + * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), + * [tick], handleTick + * ); + * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. + * } + * + * { + * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: + * let a = Bacon.once("a"), + * b = Bacon.once("b"), + * c = Bacon.once("c"), + * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; + * Bacon.zipWith(f, a, b, c); + * Bacon.when([a, b, c], f); + * } + * + * { + * // Join patterns as a "chemical machine". + * // A quick way to get some intuition for join patterns is to understand them through an analogy in terms of atoms and molecules. A join pattern can here be regarded as a recipe for a chemical reaction. Lets say we have observables `oxygen`, `carbon` and `hydrogen`, where an event in these spawns an 'atom' of that type into a mixture. We can state reactions: + * let oxygen = Bacon.interval(1e3, "O"), + * hydrogen = Bacon.interval(2e3, "H"), + * carbon = Bacon.interval(1.5e3, "C"), + * makeWater = (oxygen:string, hydrogen1:string, hydrogen2:string) => `${hydrogen1}${[hydrogen1, hydrogen2].length}${oxygen}`, + * makeCarbonMonoxide = (oxygen:string, carbon:string) => `${carbon}${oxygen}`; + * Bacon.when( + * [oxygen, hydrogen, hydrogen], makeWater, + * [oxygen, carbon], makeCarbonMonoxide + * ); + * // Now, every time a new 'atom' is spawned from one of the observables, this atom is added to the mixture. If at any time there are two hydrogen atoms, and an oxygen atom, the corresponding atoms are *consumed*, and output is produced via `makeWater`. The same semantics apply for the second rule to create carbon monoxide. The rules are tried at each point from top to bottom. + * } + * + * { + * // Join patterns and properties. + * // Properties are not part of the synchronization pattern, but are instead just sampled. The following example take three input streams `$price`, `$quantity` and `$total`, e.g. coming from input fields, and defines mutally recursive behaviours in properties `price`, `quantity` and `total` such that: + * // -- updating `quantity` sets `total` to `price * quantity`; + * // -- updating `total` sets `price` to `total / quantity`. + * let random = (x:number) => Math.round(x * Math.random()), + * id = (x:A):A => x; + * let $quantity = Bacon.interval(1e3, 10).map(random), + * $price = Bacon.interval(2e3, 100).map(random), + * $total = Bacon.interval(1.5e3, 1000).map(random); + * let quantity = $quantity.toProperty(1), + * price = Bacon.when( + * [$price], id, + * [$total, quantity], (x, y) => x / y + * ).toProperty(0), + * total = Bacon.when( + * [$total], id, + * [$price, quantity], (x, y) => x * y, + * [price, $quantity], (x, y) => x * y + * ).toProperty(0); + * } + * + * { + * // Join patterns and `Bacon.Bus`. + * // The result functions of join patterns are allowed to push values onto a `Bus` that may in turn be in one of its patterns. For instance, an implementation of the dining philosophers problem can be written as follows: + * // Availability of chopsticks are implemented using bus. + * let chopsticks = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // Hungry could be any type of observable, but we'll use bus here. + * hungry = [new Bacon.Bus(), new Bacon.Bus(), new Bacon.Bus()], + * // A philosopher eats for one second, then makes the chopsticks available again by pushing values onto their bus. + * eat = (i:number) => () => { + * setTimeout(() => { + * console.log("done!"); + * chopsticks[i].push({}); + * chopsticks[(i + 1) % 3].push({}); + * }, 1e3); + * return `philosopher ${i} eating`; + * }, + * // We use Bacon.when to make sure a hungry philosopher can eat only when both his chopsticks are available. + * dining = Bacon.when( + * [hungry[0], chopsticks[0], chopsticks[1]], eat(0), + * [hungry[1], chopsticks[1], chopsticks[2]], eat(1), + * [hungry[2], chopsticks[2], chopsticks[0]], eat(2) + * ).log("dining"); + * // Make all chopsticks initially available. + * chopsticks[0].push({}); + * chopsticks[1].push({}); + * chopsticks[2].push({}); + * // Make philosophers hungry in some way, in this case we just push to their bus. + * for (let i = 0; i < 3; i++) { + * hungry[0].push({}); + * hungry[1].push({}); + * hungry[2].push({}); + * } + * } + */ + function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B, pattern5:Observable[], f5:(...args:A5[]) => B):EventStream; - /** - * @callback Bacon.when3~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when3~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when3~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @method Bacon.when3 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when3~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when3~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when3~f3} f3 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B):EventStream; + /** + * @callback Bacon.update1~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @method Bacon.update1 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update1~f1} f1 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B):Property; - /** - * @callback Bacon.when4~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.when4~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @method Bacon.when4 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when4~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when4~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when4~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.when4~f4} f4 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B):EventStream; + /** + * @callback Bacon.update2~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update2~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @method Bacon.update2 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update2~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update2~f2} f2 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B):Property; - /** - * @callback Bacon.when5~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @callback Bacon.when5~f5 - * @param {...A5} args - * @returns {B} - */ - /** - * @method Bacon.when5 - * @description Creates an [EventStream]{@link Bacon.EventStream} from join-pattern system. - * @param {Observable[]} pattern1 - * @param {Bacon.when5~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.when5~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.when5~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.when5~f4} f4 - * @param {Observable[]} pattern5 - * @param {Bacon.when5~f5} f5 - * @returns {EventStream} - * @example - * { - * // Consider implementing a game with discrete time ticks. We want to handle key-events synchronized on tick-events, with at most one key event handled per tick. If there are no key events, we want to just process a tick: - * let tick = Bacon.interval(1e2, 0), - * keyEvent = Bacon.fromEvent(document.body, "click", _ => Date.now()), - * handleTick = _ => `timestamp: NONE`, - * handleKeyEvent = timestamp => `timestamp: ${timestamp}`; - * Bacon.when( - * [tick, keyEvent], (_, timestamp) => handleKeyEvent(timestamp), - * [tick], handleTick - * ); - * // Order is important here. If the [tick] patterns had been written first, this would have been tried first, and preferred at each tick. - * } - * { - * // Join patterns are indeed a generalization of `zip`, and `zip` is equivalent to a single-rule join pattern. The following `Observable`s have the same output: - * let a = Bacon.once("a"), - * b = Bacon.once("b"), - * c = Bacon.once("c"), - * f = (a, b, c) => `a = ${a}; b = ${b}; c = ${c}.`; - * Bacon.zipWith(f, a, b, c); - * Bacon.when([a, b, c], f); - * } - */ - function when(pattern1:Observable[], f1:(...args:A1[]) => B, pattern2:Observable[], f2:(...args:A2[]) => B, pattern3:Observable[], f3:(...args:A3[]) => B, pattern4:Observable[], f4:(...args:A4[]) => B, pattern5:Observable[], f5:(...args:A5[]) => B):EventStream; + /** + * @callback Bacon.update3~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update3~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @method Bacon.update3 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update3~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update3~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update3~f3} f3 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B):Property; - /** - * @callback Bacon.update1~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @method Bacon.update1 - * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update1~f1} f1 - * @returns {EventStream} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C):Property; + /** + * @callback Bacon.update4~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update4~f4 + * @param {B} initial + * @param {...A4} args + * @returns {B} + */ + /** + * @method Bacon.update4 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update4~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update4~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update4~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update4~f4} f4 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B):Property; - /** - * @callback Bacon.update2~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update2~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @method Bacon.update2 - * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update2~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update2~f2} f2 - * @returns {EventStream} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C):Property; - - /** - * @callback Bacon.update3~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update3~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update3~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @method Bacon.update3 - * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update3~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update3~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update3~f3} f3 - * @returns {EventStream} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C):Property; - - /** - * @callback Bacon.update4~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.update4~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @method Bacon.update4 - * @description Creates an [Property]{@link Bacon.EventStream} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update4~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update4~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update4~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.update4~f4} f4 - * @returns {EventStream} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => C):Property; - - /** - * @callback Bacon.update5~f1 - * @param {...A1} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f2 - * @param {...A2} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f3 - * @param {...A3} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f4 - * @param {...A4} args - * @returns {B} - */ - /** - * @callback Bacon.update5~f5 - * @param {...A5} args - * @returns {B} - */ - /** - * @method Bacon.update5 - * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. - * @param {B} initial - * @param {Observable[]} pattern1 - * @param {Bacon.update5~f1} f1 - * @param {Observable[]} pattern2 - * @param {Bacon.update5~f2} f2 - * @param {Observable[]} pattern3 - * @param {Bacon.update5~f3} f3 - * @param {Observable[]} pattern4 - * @param {Bacon.update5~f4} f4 - * @param {Observable[]} pattern5 - * @param {Bacon.update5~f5} f5 - * @returns {EventStream} - * @example - * { - * // The inputs to `Bacon.update` are defined like this: - * let initial = 0, - * x = Bacon.interval(1e3, 1), - * y = Bacon.interval(2e3, 1), - * z = Bacon.interval(1.5e3, 1); - * // NOTE: had to explicitly specify the typing for `previous:number` - * Bacon.update(initial, - * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, - * [x, y], (previous:number, x, y) => previous + x + y + z - * ); - * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. - * } - * { - * // Here's a simple gaming example: - * let scoreMultiplier = Bacon.constant(1), - * hitUfo = new Bacon.Bus(), - * hitMotherShip = new Bacon.Bus(), - * score = Bacon.update(0, - * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, - * [hitMotherShip], (score, _) => score + 2000 - * ); - * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. - * } - */ - function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => C, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => C, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => C, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => C, pattern5:Observable[], f5:(initial:B, ...args:A5[]) => C):Property; + /** + * @callback Bacon.update5~f1 + * @param {B} initial + * @param {...A1} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f2 + * @param {B} initial + * @param {...A2} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f3 + * @param {B} initial + * @param {...A3} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f4 + * @param {B} initial + * @param {...A4} args + * @returns {B} + */ + /** + * @callback Bacon.update5~f5 + * @param {B} initial + * @param {...A5} args + * @returns {B} + */ + /** + * @method Bacon.update5 + * @description Creates an [Property]{@link Bacon.Property} from an `initial` value and a join-pattern system. + * @param {B} initial + * @param {Observable[]} pattern1 + * @param {Bacon.update5~f1} f1 + * @param {Observable[]} pattern2 + * @param {Bacon.update5~f2} f2 + * @param {Observable[]} pattern3 + * @param {Bacon.update5~f3} f3 + * @param {Observable[]} pattern4 + * @param {Bacon.update5~f4} f4 + * @param {Observable[]} pattern5 + * @param {Bacon.update5~f5} f5 + * @returns {Property} + * @example + * { + * // The inputs to `Bacon.update` are defined like this: + * let initial = 0, + * x = Bacon.interval(1e3, 1), + * y = Bacon.interval(2e3, 1), + * z = Bacon.interval(1.5e3, 1); + * // NOTE: had to explicitly specify the typing for `previous:number` + * Bacon.update(initial, + * [x, y, z], (previous:number, x, y, z) => previous + x + y + z, + * [x, y], (previous:number, x, y) => previous + x + y + z + * ); + * // As input, each function above will get the previous value of the `result` Property, along with values from the listed Observables. The value returned by the function will be used as the next value of `result`. Just like in `Bacon.when`, only EventStreams will trigger an update, while Properties will be just sampled. So, if you list a single EventStream and several Properties, the value will be updated only when an event occurs in the EventStream. + * } + * + * { + * // Here's a simple gaming example: + * let scoreMultiplier = Bacon.constant(1), + * hitUfo = new Bacon.Bus(), + * hitMotherShip = new Bacon.Bus(), + * score = Bacon.update(0, + * [hitUfo, scoreMultiplier], (score, _, multiplier:number) => score + 100 * multiplier, + * [hitMotherShip], (score, _) => score + 2000 + * ); + * // In the example, the `score` property is updated when either `hitUfo` or `hitMotherShip` occur. The `scoreMultiplier` Property is sampled to take multiplier into account when `hitUfo` occurs. + * } + */ + function update(initial:B, pattern1:Observable[], f1:(initial:B, ...args:A1[]) => B, pattern2:Observable[], f2:(initial:B, ...args:A2[]) => B, pattern3:Observable[], f3:(initial:B, ...args:A3[]) => B, pattern4:Observable[], f4:(initial:B, ...args:A4[]) => B, pattern5:Observable[], f5:(initial:B, ...args:A5[]) => B):Property; } declare module "baconjs" { - export = Bacon; + export = Bacon; } From f6c8ca47193fb67947944a3170912672ac3e908e Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Wed, 22 Jul 2015 09:57:53 -0700 Subject: [PATCH 131/881] Update angular2 to alpha32 --- angular2/angular2-2.0.0-alpha.32.d.ts | 6043 +++++++++++++++++++++++++ angular2/angular2-tests.ts | 21 +- angular2/angular2-tests.ts.tscparams | 1 + angular2/angular2.d.ts | 4836 ++++++++++---------- 4 files changed, 8428 insertions(+), 2473 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.32.d.ts create mode 100644 angular2/angular2-tests.ts.tscparams diff --git a/angular2/angular2-2.0.0-alpha.32.d.ts b/angular2/angular2-2.0.0-alpha.32.d.ts new file mode 100644 index 000000000..596db9287 --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.32.d.ts @@ -0,0 +1,6043 @@ +// Type definitions for Angular v2.0.0-alpha.32 +// Project: http://angular.io/ +// Definitions by: angular team +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +// *********************************************************** +// This file is generated by the Angular build process. +// Please do not create manual edits or send pull requests +// modifying this file. +// *********************************************************** + +// Angular depends transitively on these libraries. +// If you don't have them installed you can run +// $ tsd query es6-promise rx rx-lite --action install --save +/// +/// + +interface List extends Array {} +interface Map {} +interface StringMap extends Map {} + +declare module ng { + type SetterFn = typeof Function; + type int = number; + interface Type extends Function { + new (...args: any[]): Type; + } + + // See https://github.com/Microsoft/TypeScript/issues/1168 + class BaseException /* extends Error */ { + message: string; + stack: string; + toString(): string; + } + interface InjectableReference {} +} + + + + +/** + * The `angular2` is the single place to import all of the individual types. + */ +declare module ng { + + /** + * Bootstrapping for Angular applications. + * + * You instantiate an Angular application by explicitly specifying a component to use as the root + * component for your + * application via the `bootstrap()` method. + * + * ## Simple Example + * + * Assuming this `index.html`: + * + * ```html + * + * + * + * loading... + * + * + * ``` + * + * An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike + * Angular 1, Angular 2 + * does not compile/process bindings in `index.html`. This is mainly for security reasons, as well + * as architectural + * changes in Angular 2. This means that `index.html` can safely be processed using server-side + * technologies such as + * bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2 + * component double-curly + * `{{ syntax }}`. + * + * We can use this script code: + * + * ``` + * @Component({ + * selector: 'my-app' + * }) + * @View({ + * template: 'Hello {{ name }}!' + * }) + * class MyApp { + * name:string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * + * main() { + * return bootstrap(MyApp); + * } + * ``` + * + * When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument, + * Angular performs the + * following tasks: + * + * 1. It uses the component's `selector` property to locate the DOM element which needs to be + * upgraded into + * the angular component. + * 2. It creates a new child injector (from the platform injector). Optionally, you can also + * override the injector configuration for an app by + * invoking `bootstrap` with the `componentInjectableBindings` argument. + * 3. It creates a new `Zone` and connects it to the angular application's change detection domain + * instance. + * 4. It creates a shadow DOM on the selected component's host element and loads the template into + * it. + * 5. It instantiates the specified component. + * 6. Finally, Angular performs change detection to apply the initial data bindings for the + * application. + * + * + * ## Instantiating Multiple Applications on a Single Page + * + * There are two ways to do this. + * + * + * ### Isolated Applications + * + * Angular creates a new application each time that the `bootstrap()` method is invoked. When + * multiple applications + * are created for a page, Angular treats each application as independent within an isolated change + * detection and + * `Zone` domain. If you need to share data between applications, use the strategy described in the + * next + * section, "Applications That Share Change Detection." + * + * + * ### Applications That Share Change Detection + * + * If you need to bootstrap multiple applications that share common data, the applications must + * share a common + * change detection and zone. To do that, create a meta-component that lists the application + * components in its template. + * By only invoking the `bootstrap()` method once, with the meta-component as its argument, you + * ensure that only a + * single change detection zone is created and therefore data can be shared across the applications. + * + * + * ## Platform Injector + * + * When working within a browser window, there are many singleton resources: cookies, title, + * location, and others. + * Angular services that represent these resources must likewise be shared across all Angular + * applications that + * occupy the same browser window. For this reason, Angular creates exactly one global platform + * injector which stores + * all shared services, and each angular application injector has the platform injector as its + * parent. + * + * Each application has its own private injector as well. When there are multiple applications on a + * page, Angular treats + * each application injector's services as private to that application. + * + * + * # API + * - `appComponentType`: The root component which should act as the application. This is a reference + * to a `Type` + * which is annotated with `@Component(...)`. + * - `componentInjectableBindings`: An additional set of bindings that can be added to the app + * injector + * to override default injection behavior. + * - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for + * unhandled exceptions. + * + * Returns a `Promise` of {@link ApplicationRef}. + */ + function bootstrap(appComponentType: /*Type*/ any, componentInjectableBindings?: List>) : Promise ; + + class DehydratedException extends BaseException { + } + + class ExpressionChangedAfterItHasBeenChecked extends BaseException { + } + + class ChangeDetectionError extends BaseException { + + location: string; + } + + + /** + * ON_PUSH means that the change detector's mode will be set to CHECK_ONCE during hydration. + */ + const ON_PUSH : string ; + + + /** + * DEFAULT means that the change detector's mode will be set to CHECK_ALWAYS during hydration. + */ + const DEFAULT : string ; + + + /** + * Controls change detection. + * + * {@link ChangeDetectorRef} allows requesting checks for detectors that rely on observables. It + * also allows detaching and + * attaching change detector subtrees. + */ + class ChangeDetectorRef { + + + /** + * Request to check all ON_PUSH ancestors. + */ + requestCheck(): void; + + + /** + * Detaches the change detector from the change detector tree. + * + * The detached change detector will not be checked until it is reattached. + */ + detach(): void; + + + /** + * Reattach the change detector to the change detector tree. + * + * This also requests a check of this change detector. This reattached change detector will be + * checked during the + * next change detection run. + */ + reattach(): void; + } + + class Pipes { + + + /** + * Map of {@link Pipe} names to {@link PipeFactory} lists used to configure the + * {@link Pipes} registry. + * + * #Example + * + * ``` + * var pipesConfig = { + * 'json': [jsonPipeFactory] + * } + * @Component({ + * viewInjector: [ + * bind(Pipes).toValue(new Pipes(pipesConfig)) + * ] + * }) + * ``` + */ + config: StringMap; + + get(type: string, obj: any, cdRef?: ChangeDetectorRef, existingPipe?: Pipe): Pipe; + } + + + /** + * Indicates that the result of a {@link Pipe} transformation has changed even though the reference + * has not changed. + * + * The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored. + */ + class WrappedValue { + + wrapped: any; + } + + + /** + * An interface for extending the list of pipes known to Angular. + * + * If you are writing a custom {@link Pipe}, you must extend this interface. + * + * #Example + * + * ``` + * class DoublePipe implements Pipe { + * supports(obj) { + * return true; + * } + * + * onDestroy() {} + * + * transform(value, args = []) { + * return `${value}${value}`; + * } + * } + * ``` + */ + interface Pipe { + + supports(obj: any): boolean; + + onDestroy(): void; + + transform(value: any, args: List): any; + } + + interface PipeFactory { + + supports(obs: any): boolean; + + create(cdRef: ChangeDetectorRef): Pipe; + } + + class NullPipe extends BasePipe { + + called: boolean; + + supports(obj: any): boolean; + + transform(value: any, args?: List): WrappedValue; + } + + class NullPipeFactory implements PipeFactory { + + supports(obj: any): boolean; + + create(cdRef: ChangeDetectorRef): Pipe; + } + + const defaultPipes : Pipes ; + + + /** + * Provides default implementation of supports and onDestroy. + * + * #Example + * + * ``` + * class DoublePipe extends BasePipe {* + * transform(value) { + * return `${value}${value}`; + * } + * } + * ``` + */ + class BasePipe implements Pipe { + + supports(obj: any): boolean; + + onDestroy(): void; + + transform(value: any, args: List): any; + } + + class Locals { + + parent: Locals; + + current: Map; + + contains(name: string): boolean; + + get(name: string): any; + + set(name: string, value: any): void; + + clearValues(): void; + } + + + /** + * A dispatcher for all events happening in a view. + */ + interface RenderEventDispatcher { + + + /** + * Called when an event was triggered for a on-* attribute on an element. + * @param {Map} locals Locals to be used to evaluate the + * event expressions + */ + dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map): void; + } + + class Renderer { + + + /** + * Creates a root host view that includes the given element. + * Note that the fragmentCount needs to be passed in so that we can create a result + * synchronously even when dealing with webworkers! + * + * @param {RenderProtoViewRef} hostProtoViewRef a RenderProtoViewRef of type + * ProtoViewDto.HOST_VIEW_TYPE + * @param {any} hostElementSelector css selector for the host element (will be queried against the + * main document) + * @return {RenderViewWithFragments} the created view including fragments + */ + createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number, hostElementSelector: string): RenderViewWithFragments; + + + /** + * Creates a regular view out of the given ProtoView. + * Note that the fragmentCount needs to be passed in so that we can create a result + * synchronously even when dealing with webworkers! + */ + createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments; + + + /** + * Destroys the given view after it has been dehydrated and detached + */ + destroyView(viewRef: RenderViewRef): void; + + + /** + * Attaches a fragment after another fragment. + */ + attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef, fragmentRef: RenderFragmentRef): void; + + + /** + * Attaches a fragment after an element. + */ + attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef): void; + + + /** + * Detaches a fragment. + */ + detachFragment(fragmentRef: RenderFragmentRef): void; + + + /** + * Hydrates a view after it has been attached. Hydration/dehydration is used for reusing views + * inside of the view pool. + */ + hydrateView(viewRef: RenderViewRef): void; + + + /** + * Dehydrates a view after it has been attached. Hydration/dehydration is used for reusing views + * inside of the view pool. + */ + dehydrateView(viewRef: RenderViewRef): void; + + + /** + * Returns the native element at the given location. + * Attention: In a WebWorker scenario, this should always return null! + */ + getNativeElementSync(location: RenderElementRef): any; + + + /** + * Sets a property on an element. + */ + setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void; + + + /** + * Sets an attribute on an element. + */ + setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void; + + + /** + * Sets a class on an element. + */ + setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void; + + + /** + * Sets a style on an element. + */ + setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void; + + + /** + * Calls a method on an element. + */ + invokeElementMethod(location: RenderElementRef, methodName: string, args: List): void; + + + /** + * Sets the value of a text node. + */ + setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void; + + + /** + * Sets the dispatcher for all events of the given view + */ + setEventDispatcher(viewRef: RenderViewRef, dispatcher: RenderEventDispatcher): void; + } + + + /** + * Abstract reference to the element which can be marshaled across web-worker boundry. + * + * This interface is used by the Renderer API. + */ + interface RenderElementRef { + + + /** + * Reference to the `RenderViewRef` where the `RenderElementRef` is inside of. + */ + renderView: RenderViewRef; + + + /** + * Index of the element inside the `RenderViewRef`. + * + * This is used internally by the Angular framework to locate elements. + */ + renderBoundElementIndex: number; + } + + class RenderViewRef { + } + + class RenderProtoViewRef { + } + + class RenderFragmentRef { + } + + class RenderViewWithFragments { + + viewRef: RenderViewRef; + + fragmentRefs: RenderFragmentRef[]; + } + + class DomRenderer extends Renderer { + + createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number, hostElementSelector: string): RenderViewWithFragments; + + createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments; + + destroyView(viewRef: RenderViewRef): void; + + getNativeElementSync(location: RenderElementRef): any; + + getRootNodes(fragment: RenderFragmentRef): List; + + attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef, fragmentRef: RenderFragmentRef): void; + + attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef): void; + + detachFragment(fragmentRef: RenderFragmentRef): void; + + hydrateView(viewRef: RenderViewRef): void; + + dehydrateView(viewRef: RenderViewRef): void; + + setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void; + + setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void; + + setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void; + + setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void; + + invokeElementMethod(location: RenderElementRef, methodName: string, args: List): void; + + setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void; + + setEventDispatcher(viewRef: RenderViewRef, dispatcher: any): void; + } + + const DOCUMENT_TOKEN : OpaqueToken ; + + const DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES : OpaqueToken ; + + + /** + * Declare reusable UI building blocks for an application. + * + * Each Angular component requires a single `@Component` and at least one `@View` annotation. The + * `@Component` + * annotation specifies when a component is instantiated, and which properties and hostListeners it + * binds to. + * + * When a component is instantiated, Angular + * - creates a shadow DOM for the component. + * - loads the selected template into the shadow DOM. + * - creates all the injectable objects configured with `hostInjector` and `viewInjector`. + * + * All template expressions and statements are then evaluated against the component instance. + * + * For details on the `@View` annotation, see {@link View}. + * + * ## Example + * + * ``` + * @Component({ + * selector: 'greet' + * }) + * @View({ + * template: 'Hello {{name}}!' + * }) + * class Greet { + * name: string; + * + * constructor() { + * this.name = 'World'; + * } + * } + * ``` + */ + class ComponentAnnotation extends DirectiveAnnotation { + + + /** + * Defines the used change detection strategy. + * + * When a component is instantiated, Angular creates a change detector, which is responsible for + * propagating + * the component's bindings. + * + * The `changeDetection` property defines, whether the change detection will be checked every time + * or only when the component + * tells it to do so. + */ + changeDetection: string; + + + /** + * Defines the set of injectable objects that are visible to its view dom children. + * + * ## Simple Example + * + * Here is an example of a class that can be injected: + * + * ``` + * class Greeter { + * greet(name:string) { + * return 'Hello ' + name + '!'; + * } + * } + * + * @Directive({ + * selector: 'needs-greeter' + * }) + * class NeedsGreeter { + * greeter:Greeter; + * + * constructor(greeter:Greeter) { + * this.greeter = greeter; + * } + * } + * + * @Component({ + * selector: 'greet', + * viewInjector: [ + * Greeter + * ] + * }) + * @View({ + * template: ``, + * directives: [NeedsGreeter] + * }) + * class HelloWorld { + * } + * + * ``` + */ + viewInjector: List; + } + + + /** + * Directives allow you to attach behavior to elements in the DOM. + * + * {@link Directive}s with an embedded view are called {@link Component}s. + * + * A directive consists of a single directive annotation and a controller class. When the + * directive's `selector` matches + * elements in the DOM, the following steps occur: + * + * 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor + * arguments. + * 2. Angular instantiates directives for each matched element using `ElementInjector` in a + * depth-first order, + * as declared in the HTML. + * + * ## Understanding How Injection Works + * + * There are three stages of injection resolution. + * - *Pre-existing Injectors*: + * - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if + * the dependency was + * specified as `@Optional`, returns `null`. + * - The platform injector resolves browser singleton resources, such as: cookies, title, + * location, and others. + * - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow + * the same parent-child hierarchy + * as the component instances in the DOM. + * - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each + * element has an `ElementInjector` + * which follow the same parent-child hierarchy as the DOM elements themselves. + * + * When a template is instantiated, it also must instantiate the corresponding directives in a + * depth-first order. The + * current `ElementInjector` resolves the constructor dependencies for each directive. + * + * Angular then resolves dependencies as follows, according to the order in which they appear in the + * {@link View}: + * + * 1. Dependencies on the current element + * 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary + * 3. Dependencies on component injectors and their parents until it encounters the root component + * 4. Dependencies on pre-existing injectors + * + * + * The `ElementInjector` can inject other directives, element-specific special objects, or it can + * delegate to the parent + * injector. + * + * To inject other directives, declare the constructor parameter as: + * - `directive:DirectiveType`: a directive on the current element only + * - `@Ancestor() directive:DirectiveType`: any directive that matches the type between the current + * element and the + * Shadow DOM root. Current element is not included in the resolution, therefore even if it could + * resolve it, it will + * be ignored. + * - `@Query(DirectiveType) query:QueryList`: A live collection of direct child + * directives. + * - `@QueryDescendants(DirectiveType) query:QueryList`: A live collection of any + * child directives. + * + * To inject element-specific special objects, declare the constructor parameter as: + * - `element: ElementRef` to obtain a reference to logical element in the view. + * - `viewContainer: ViewContainerRef` to control child template instantiation, for + * {@link Directive} directives only + * - `bindingPropagation: BindingPropagation` to control change detection in a more granular way. + * + * ## Example + * + * The following example demonstrates how dependency injection resolves constructor arguments in + * practice. + * + * + * Assume this HTML template: + * + * ``` + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + *
    + * ``` + * + * With the following `dependency` decorator and `SomeService` injectable class. + * + * ``` + * @Injectable() + * class SomeService { + * } + * + * @Directive({ + * selector: '[dependency]', + * properties: [ + * 'id: dependency' + * ] + * }) + * class Dependency { + * id:string; + * } + * ``` + * + * Let's step through the different ways in which `MyDirective` could be declared... + * + * + * ### No injection + * + * Here the constructor is declared with no arguments, therefore nothing is injected into + * `MyDirective`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor() { + * } + * } + * ``` + * + * This directive would be instantiated with no dependencies. + * + * + * ### Component-level injection + * + * Directives can inject any injectable instance from the closest component injector or any of its + * parents. + * + * Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type + * from the parent + * component's injector. + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(someService: SomeService) { + * } + * } + * ``` + * + * This directive would be instantiated with a dependency on `SomeService`. + * + * + * ### Injecting a directive from the current element + * + * Directives can inject other directives declared on the current element. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(dependency: Dependency) { + * expect(dependency.id).toEqual(3); + * } + * } + * ``` + * This directive would be instantiated with `Dependency` declared at the same element, in this case + * `dependency="3"`. + * + * ### Injecting a directive from any ancestor elements + * + * Directives can inject other directives declared on any ancestor element (in the current Shadow + * DOM), i.e. on the + * parent element and its parents. By definition, a directive with an `@Ancestor` annotation does + * not attempt to + * resolve dependencies for the current element, even if this would satisfy the dependency. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Ancestor() dependency: Dependency) { + * expect(dependency.id).toEqual(2); + * } + * } + * ``` + * + * `@Ancestor` checks the parent, as well as its parents recursively. If `dependency="2"` didn't + * exist on the direct parent, this injection would + * have returned + * `dependency="1"`. + * + * + * ### Injecting a live collection of direct child directives + * + * + * A directive can also query for other child directives. Since parent directives are instantiated + * before child directives, a directive can't simply inject the list of child directives. Instead, + * the directive injects a {@link QueryList}, which updates its contents as children are added, + * removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ng-for`, an + * `ng-if`, or an `ng-switch`. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and + * 6. Here, `Dependency` 5 would not be included, because it is not a direct child. + * + * ### Injecting a live collection of descendant directives + * + * By passing the descendant flag to `@Query` above, we can include the children of the child + * elements. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList) { + * } + * } + * ``` + * + * This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6. + * + * ### Optional injection + * + * The normal behavior of directives is to return an error when a specified dependency cannot be + * resolved. If you + * would like to inject `null` on unresolved dependency instead, you can annotate that dependency + * with `@Optional()`. + * This explicitly permits the author of a template to treat some of the surrounding directives as + * optional. + * + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Optional() dependency:Dependency) { + * } + * } + * ``` + * + * This directive would be instantiated with a `Dependency` directive found on the current element. + * If none can be + * found, the injector supplies `null` instead of throwing an error. + * + * ## Example + * + * Here we use a decorator directive to simply define basic tool-tip behavior. + * + * ``` + * @Directive({ + * selector: '[tooltip]', + * properties: [ + * 'text: tooltip' + * ], + * hostListeners: { + * 'onmouseenter': 'onMouseEnter()', + * 'onmouseleave': 'onMouseLeave()' + * } + * }) + * class Tooltip{ + * text:string; + * overlay:Overlay; // NOT YET IMPLEMENTED + * overlayManager:OverlayManager; // NOT YET IMPLEMENTED + * + * constructor(overlayManager:OverlayManager) { + * this.overlay = overlay; + * } + * + * onMouseEnter() { + * // exact signature to be determined + * this.overlay = this.overlayManager.open(text, ...); + * } + * + * onMouseLeave() { + * this.overlay.close(); + * this.overlay = null; + * } + * } + * ``` + * In our HTML template, we can then add this behavior to a `
    ` or any other element with the + * `tooltip` selector, + * like so: + * + * ``` + *
    + * ``` + * + * Directives can also control the instantiation, destruction, and positioning of inline template + * elements: + * + * A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at + * runtime. + * The {@link ViewContainerRef} is created as a result of `