From ee872c633411d2524cafc68d339f016acbfa1fd6 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Sun, 14 Sep 2014 00:08:00 +0300 Subject: [PATCH 001/419] 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/419] 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 52444b5afa70f89d846fa4e0d8671bc90fc169b7 Mon Sep 17 00:00:00 2001 From: Ralf Kruse Date: Sun, 10 May 2015 02:23:43 +0200 Subject: [PATCH 003/419] 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 004/419] 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 005/419] 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 006/419] 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 007/419] 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 008/419] 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 2f1df1f63590f9b97134414eab0ea53eea206c94 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Tue, 2 Jun 2015 12:21:16 -0400 Subject: [PATCH 009/419] 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 010/419] 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 8dd3b27579a67c878e5605b8819718a17c34cf0b Mon Sep 17 00:00:00 2001 From: Laurence Dougal Myers Date: Mon, 22 Jun 2015 17:29:18 +1000 Subject: [PATCH 011/419] 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 012/419] 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 013/419] 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 014/419] 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 015/419] 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 016/419] 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 017/419] 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 018/419] Backported SharePoint.d.ts changes fom master From 31c2a4dc3f9bbb8060ca9d846c03af0aa1a0ac06 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Tue, 14 Jul 2015 00:09:21 +0300 Subject: [PATCH 019/419] 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 9916fab22d48b85591d811a0d8490dc47269a7bf Mon Sep 17 00:00:00 2001 From: lnlwd Date: Tue, 14 Jul 2015 22:53:55 -0300 Subject: [PATCH 020/419] 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 db52e392faaadc8de5e6636d23c3d9c615c61632 Mon Sep 17 00:00:00 2001 From: lnlwd Date: Wed, 15 Jul 2015 11:04:10 -0300 Subject: [PATCH 021/419] 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 022/419] 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 1e5725eeeea816a0411b9f7015bca78b4f1d1252 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 00:57:57 +0300 Subject: [PATCH 023/419] 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 024/419] 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 ae2581f4ce9d1b468089ea3d0652200d17e52af4 Mon Sep 17 00:00:00 2001 From: gandjustas Date: Mon, 20 Jul 2015 19:37:28 +0300 Subject: [PATCH 025/419] 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 f02d001d3d809136f507048113369660ee9876ef Mon Sep 17 00:00:00 2001 From: Daisuke Aoki Date: Tue, 21 Jul 2015 18:37:43 +0900 Subject: [PATCH 026/419] 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 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 027/419] 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 4bfe4cfc5821a779e8ad1393765ffd0d269c5120 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Fri, 24 Jul 2015 23:07:41 +0200 Subject: [PATCH 028/419] initial commit --- vexflow/vexflow.d.ts | 1325 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1325 insertions(+) create mode 100644 vexflow/vexflow.d.ts diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts new file mode 100644 index 000000000..7316987c9 --- /dev/null +++ b/vexflow/vexflow.d.ts @@ -0,0 +1,1325 @@ +// Type definitions for VexFlow v1.2.27 +// Project: http://vexflow.com +// Definitions by: Roman Quiring +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//inconsistent namespace: this is a helper funtion from tables.js and should not pollute the global namespace! +declare function sanitizeDuration(duration : string) : string; + +declare module Vex { + + function L(block : string, args : any[]) : void; + function Merge(destination : T, source : Object) : T; + function Min(a : number, b : number) : number; + function Max(a : number, b : number) : number; + function RoundN(x : number, n : number) : number; + function MidLine(a : number, b : number) : number; + function SortAndUnique(arr : T, cmp : Function, eq : Function) : T; + function Contains(a : any[], obj : any) : boolean; + function getCanvasContext(canvas_sel : string) : CanvasRenderingContext2D; + function drawDot(ctx : IRenderContext, x : number, y : number, color? : string) : void; + function BM(s : number, f : Function) : void; + function Inherit(child : T, parent : Object, object : Object) : T; + + class RuntimeError { + constructor(code : string, message : string); + } + + class RERR { + constructor(code : string, message : string); + } + + /** + * Helper interface for handling the different rendering contexts (i.e. CanvasContext, RaphaelContext, SVGContext). Not part of VexFlow! + */ + interface IRenderContext { + clear() : void; + setFont(family : string, size : number, weight? : number) : IRenderContext; + setRawFont(font : string) : IRenderContext; + setFillStyle(style : string) : IRenderContext; + setBackgroundFillStyle(style : string) : IRenderContext; + setStrokeStyle(style : string) : IRenderContext; + setShadowColor(color : string) : IRenderContext; + setShadowBlur(blur : string) : IRenderContext; + setLineWidth(width : number) : IRenderContext; + setLineCap(cap_type : string) : IRenderContext; + setLineDash(dash : string) : IRenderContext; + scale(x : number, y : number) : IRenderContext; + resize(width : number, height : number) : IRenderContext; + fillRect(x : number, y : number, width : number, height : number) : IRenderContext; + clearRect(x : number, y : number, width : number, height : number) : IRenderContext; + beginPath() : IRenderContext; + moveTo(x : number, y : number) : IRenderContext; + lineTo(x : number, y : number) : IRenderContext; + bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : IRenderContext; + quadraticCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number) : void; + arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : IRenderContext; + glow() : IRenderContext; + fill() : IRenderContext; + stroke() : IRenderContext; + closePath() : IRenderContext; + fillText(text : string, x : number, y : number) : IRenderContext; + save() : IRenderContext; + restore() : IRenderContext; + + /** + * canvas returns TextMetrics, SVG returns SVGRect, Raphael returns {width : number, height : number}. Only width is used throughout VexFlow. + */ + measureText(text : string) : {width : number}; + } + + /** + * Helper interface for handling the Vex.Flow.Font object in Vex.Flow.Glyph. Not part of VexFlow! + */ + interface IFont { + glyphs : {x_min : number, x_max : number, ha : number, o : string[]}[]; + cssFontWeight : string; + ascender : number; + underlinePosition : number; + cssFontStyle : string; + boundingBox : {yMin : number, xMin : number, yMax : number, xMax : number}; + resolution : number; + descender : number; + familyName : string; + lineHeight : number; + underlineThickness : number; + + /** + * This property is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js. + */ + original_font_information? : {postscript_name : string, version_string : string, vendor_url : string, full_font_name : string, font_family_name : string, copyright : string, description : string, trademark : string, designer : string, designer_url : string, unique_font_identifier : string, license_url : string, license_description : string, manufacturer_name : string, font_sub_family_name : string}; + } + + module Flow { + + var RESOLUTION : number; + + // from tables.js: + var STEM_WIDTH : number; + var STEM_HEIGHT : number; + var STAVE_LINE_THICKNESS : number; + var TIME4_4 : {num_beats : number, beat_value : number, resolution : number}; + var unicode : {[name : string] : string}; //inconsistent API: this should be private and have a wrapper function like the other tables + function clefProperties(clef : string) : {line_shift : number}; + function keyProperties(key : string, clef : string, params : {octave_shift? : number}) : {key : string, octave : number, line : number, int_value : number, accidental : string, code : number, stroke : number, shift_right : number, displaced : boolean}; + function integerToNote(integer : number) : string; + function tabToGlyph(fret : string) : {text : string, code : number, width : number, shift_y : number}; + function textWidth(text : string) : number; + function articulationCodes(artic : string) : {code : string, width : number, shift_right : number, shift_up : number, shift_down : number, between_lines : boolean}; + function accidentalCodes(acc : string) : {code : string, width : number, gracenote_width : number, shift_right : number, shift_down : number}; + function ornamentCodes(acc : string) : {code : string, shift_right : number, shift_up : number, shift_down : number, width : number}; + function keySignature(spec : string) : {type: string, line: number}[]; + function parseNoteDurationString(durationString : string) : {duration : string, dots : number, type : string}; + function parseNoteData(noteData : {duration : string, dots : number, type : string}) : {duration : string, type : string, dots : number, ticks : number}; + function durationToFraction(duration : string) : Fraction; + function durationToNumber(duration : string) : number; + function durationToTicks(duration : string) : number; + function durationToGlyph(duration : string, type : string) : {head_width : number, stem : boolean, stem_offset : number, flag : boolean, stem_up_extension : number, stem_down_extension : number, gracenote_stem_up_extension : number, gracenote_stem_down_extension : number, tabnote_stem_up_extension : number, tabnote_stem_down_extension : number, dot_shiftY : number, line_above : number, line_below : number, code_head? : string, rest? : boolean, position? : string}; + + // from glyph.js: + function renderGlyph(ctx : IRenderContext, x_pos : number, y_pos : number, point : number, val : string, nocache : boolean) : void; + + class Accidental extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + setNote(note : Note) : Modifier; + + constructor(type : string); + static CATEGORY : string; + static DEBUG : boolean; + static format(accidentals : Accidental[], state : {left_shift : number, right_shift : number, text_line : number}) : void; + setNote(note : StaveNote) : void; + setAsCautionary() : Accidental; + draw() : void; + static applyAccidentals(voices : Voice[], keySignature? : string) : void; + } + + export module Annotation { + enum Justify {LEFT, CENTER, RIGHT, CENTER_STEM} + enum VerticalJustify {TOP, CENTER, BOTTOM, CENTER_STEM} + } + + class Annotation extends Modifier { + constructor(text : string); + static CATEGORY : string; + static DEBUG : boolean; + static format(annotations : Annotation[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + setTextLine(line : number) : Annotation; + setFont(family : string, size : number, weight : string) : Annotation; + setVerticalJustification(just : Annotation.VerticalJustify) : Annotation; + getJustification() : Annotation.Justify; + setJustification(justification : Annotation.Justify) : Annotation; + draw() : void; + } + + class Articulation extends Modifier { + constructor(type : string); + static CATEGORY : string; + static DEBUG : boolean; + static format(articulations : Articulation[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + draw() : void; + } + + class BarNote extends Note { + static DEBUG : boolean; + getType() : Barline.type; + setType(type : Barline.type) : BarNote; + getBoundingBox() : BoundingBox; + addToModifierContext() : BarNote; + preFormat() : BarNote; + draw() : void; + } + + export module Barline { + enum type {SINGLE, DOUBLE, END, REPEAT_BEGIN, REPEAT_END, REPEAT_BOTH, NONE} + } + + class Barline extends StaveModifier { + constructor(type : Barline.type, x : number); + getCategory() : string; + setX(x : number) : Barline; + draw(stave : Stave, x_shift? : number) : void; + drawVerticalBar(stave : Stave, x : number, double_bar? : boolean) : void; + drawVerticalEndBar(stave : Stave, x : number) : void; + drawRepeatBar(stave : Stave, x : number, begin : boolean) : void; + } + + class Beam { + constructor(notes : StemmableNote[], auto_stem? : boolean); + setContext(context : IRenderContext) : Beam; + getNotes() : StemmableNote[]; + getBeamCount() : number; + breakSecondaryAt(indices : number[]) : Beam; + getSlopeY() : number; + calculateSlope() : void; + applyStemExtensions() : void; + getBeamLines(duration : string) : {start : number, end : number}[]; + drawStems() : void; + drawBeamLines() : void; + preFormat() : Beam; + postFormat() : Beam; + draw() : boolean; + calculateStemDirection(notes : Note) : number; + static getDefaultBeamGroups(time_sig : string) : Fraction[]; + static applyAndGetBeams(voice : Voice, stem_direction : number, groups : Fraction[]) : Beam[]; + static generateBeams(notes : StemmableNote[], config? : {groups? : Fraction[], stem_direction? : number, beam_rests? : boolean, beam_middle_only? : boolean, show_stemlets? : boolean, maintain_stem_directions? : boolean}) : Beam[]; + } + + class Bend { + constructor(text : string, release? : boolean, phrase? : {type : number, text : string, width : number}[]); + static CATEGORY : string; + static UP : number; + static DOWN : number; + static format(bends : Bend[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + setXShift(value : number) : void; + setFont(font : string) : Bend; + getText() : string; + updateWidth() : Bend; + draw() : void; + } + + class BoundingBox { + constructor(x : number, y : number, w : number, h : number); + static copy(that : BoundingBox) : BoundingBox; + getX() : number; + getY() : number; + getW() : number; + getH() : number; + setX(x : number) : BoundingBox; + setY(y : number) : BoundingBox; + setW(w : number) : BoundingBox; + setH(h : number) : BoundingBox; + move(x : number, y : number) : void; + clone() : BoundingBox; + mergeWith(boundingBox : BoundingBox, ctx? : IRenderContext) : BoundingBox; + draw(ctx : IRenderContext, x : number, y : number) : void; + } + + class CanvasContext implements IRenderContext { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setLineDash(dash : string) : CanvasContext; + scale(x : number, y : number) : CanvasContext; + resize(width : number, height : number) : CanvasContext; + fillRect(x : number, y : number, width : number, height : number) : CanvasContext; + clearRect(x : number, y : number, width : number, height : number) : CanvasContext; + beginPath() : CanvasContext; + moveTo(x : number, y : number) : CanvasContext; + lineTo(x : number, y : number) : CanvasContext; + bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : CanvasContext; + quadraticCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number) : CanvasContext; + arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : CanvasContext; + glow() : CanvasContext; + fill() : CanvasContext; + stroke() : CanvasContext; + closePath() : CanvasContext; + fillText(text : string, x : number, y : number) : CanvasContext; + save() : CanvasContext; + restore() : CanvasContext; + + constructor(context : CanvasRenderingContext2D); + static WIDTH : number; + static HEIGHT : number; + clear() : void; + setFont(family : string, size : number, weight? : number) : CanvasContext; + setRawFont(font : string) : CanvasContext; + setFillStyle(style : string) : CanvasContext; + setBackgroundFillStyle(style : string) : CanvasContext; + setStrokeStyle(style : string) : CanvasContext; + setShadowColor(style : string) : CanvasContext; //inconsistent name: style -> color + setShadowBlur(blur : string) : CanvasContext; + setLineWidth(width : number) : CanvasContext; + setLineCap(cap_type : string) : CanvasContext; + + //inconsistent type: void -> CanvasContext + setLineDash(dash : string) : void; + scale(x : number, y : number) : void; + resize(width : number, height : number) : void; + fillRect(x : number, y : number, width : number, height : number) : void; + clearRect(x : number, y : number, width : number, height : number) : void; + beginPath() : void; + moveTo(x : number, y : number) : void; + lineTo(x : number, y : number) : void; + bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : void; + quadraticCurveToTo(x1 : number, y1 : number, x : number, y : number) : void; //inconsistent name: x -> x2, y -> y2 + arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : void; + glow() : void; + fill() : void; + stroke() : void; + closePath() : void; + measureText(text : string) : TextMetrics; + fillText(text : string, x : number, y : number) : void; + save() : void; + restore() : void; + } + + class Clef extends StaveModifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + addModifier() : void; + addEndModifier() : void; + + constructor(clef : string, size? : string, annotation? : string); + static DEBUG : boolean; + addModifier(stave : Stave) : void; + addEndModifier(stave : Stave) : void; + } + + class ClefNote extends Note { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + setStave(stave : Stave) : Note; + + constructor(clef : string, size? : string, annotation? : string); + setClef(clef : string, size? : string, annotation? : string) : ClefNote; + getClef() : string; + setStave(stave : Stave) : void; + getBoundingBox() : BoundingBox; + addToModifierContext() : ClefNote; + getCategory() : string; + preFormat() : ClefNote; + draw() : void; + } + + class Crescendo extends Note { + constructor(note_struct : {duration : number, line? : number}); + static DEBUG : boolean; + setLine(line : number) : Crescendo; + setHeight(height : number) : Crescendo; + setDecrescendo(decresc : boolean) : Crescendo; + preFormat() : Crescendo; + draw() : void; + } + + export module Curve { + enum Position {NEAR_HEAD, NEAR_TOP} + } + + class Curve { + constructor(from : Note, to : Note, options? : {spacing? : number, thickness? : number, x_shift? : number, y_shift : number, position : Curve.Position, invert : boolean, cps? : {x : number, y : number}[]}); + static DEBUG : boolean; + setContext(context : IRenderContext) : Curve; + setNotes(from : Note, to : Note) : Curve; + isPartial() : boolean; + renderCurve(params : {first_x : number, first_y : number, last_x : number, last_y : number, direction : number}) : void; + draw() : boolean; + } + + class Dot extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setNote(note : Note) : Dot; + + static CATEGORY : string; + static format(dots : number, state : {left_shift : number, right_shift : number, text_line : number}) : void; + setNote(note : Note) : void; //inconsistent type: void -> Dot + setDotShiftY(y : number) : Dot; + draw() : void; + } + + var Font : { + glyphs : {x_min : number, x_max : number, ha : number, o : string[]}[]; + cssFontWeight : string; + ascender : number; + underlinePosition : number; + cssFontStyle : string; + boundingBox : {yMin : number, xMin : number, yMax : number, xMax : number}; + resolution : number; + descender : number; + familyName : string; + lineHeight : number; + underlineThickness : number; + + //inconsistent member : this is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js + original_font_information : {postscript_name : string, version_string : string, vendor_url : string, full_font_name : string, font_family_name : string, copyright : string, description : string, trademark : string, designer : string, designer_url : string, unique_font_identifier : string, license_url : string, license_description : string, manufacturer_name : string, font_sub_family_name : string}; + } + + class Formatter { + static DEBUG : boolean; + static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : StaveNote[], params : {auto_beam : boolean, align_rests : boolean}) : BoundingBox; + static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : StaveNote[], params : boolean) : BoundingBox; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : StaveNote[], autobeam : boolean, params : {auto_beam : boolean, align_rests : boolean}) : void; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : StaveNote[], autobeam : boolean, params : boolean) : void; + static AlignRestsToNotes(notes : Note[], align_all_notes? : boolean, align_tuplets? : boolean) : Formatter; + alignRests(voices : Voice[], align_all_notes : boolean) : void; + preCalculateMinTotalWidth(voices : Voice[]) : number; + getMinTotalWidth() : number; + createModifierContexts(voices : Voice[]) : ModifierContext[]; + createTickContexts(voices : Voice[]) : TickContext[]; + preFormat(justifyWidth? : number, rendering_context? : IRenderContext, voices? : Voice[], stave? : Stave) : void; + postFormat() : Formatter; + joinVoices(voices : Voice[]) : Formatter; + format(voices : Voice[], justifyWidth : number, options? : {align_rests? : boolean, context : IRenderContext}) : Formatter; + formatToStave(voices : Voice[], stave : Stave, options? : {align_rests? : boolean, context : IRenderContext}) : Formatter; + } + + class Fraction { + constructor(numerator : number, denominator : number); + static GCD(a : number, b : number) : number; + static LCM(a : number, b : number) : number; + static LCMM(a : number, b : number) : number; + set(numerator : number, denominator : number) : Fraction; + value() : number; + simplify() : Fraction; + add(param1 : Fraction, param2 : Fraction) : Fraction; + add(param1 : number, param2 : number) : Fraction; + subtract(param1 : Fraction, param2 : Fraction) : Fraction; + subtract(param1 : number, param2 : number) : Fraction; + multiply(param1 : Fraction, param2 : Fraction) : Fraction; + multiply(param1 : number, param2 : number) : Fraction; + divide(param1 : Fraction, param2 : Fraction) : Fraction; + divide(param1 : number, param2 : number) : Fraction; + equals(compare : Fraction) : boolean; + greaterThan(compare : Fraction) : boolean; + greaterThanEquals(compare : Fraction) : boolean; + lessThan(compare : Fraction) : boolean; + lessThanEquals(compare : Fraction) : boolean; + clone() : Fraction; + copy(copy : Fraction) : Fraction; + quotient() : number; + fraction() : number; + abs() : Fraction; + toString() : string; + toSimplifiedString() : string; + toMixedString() : string; + parse(str : string) : Fraction; + } + + class FretHandFinger extends Modifier { + constructor(number : number); + static CATEGORY : string; + static format(nums : FretHandFinger[], state : {left_shift : number, right_shift : number, text_line : number}) : void; + getNote() : Note; + setNote(note : Note) : FretHandFinger; + getIndex() : number; + setIndex(index : number) : FretHandFinger; + getPosition() : Modifier.Position; + setPosition(position : Modifier.Position) : FretHandFinger; + setFretHandFinger(number : number) : FretHandFinger; + setOffsetX(x : number) : FretHandFinger; + setOffsetY(y : number) : FretHandFinger; + draw() : void; + } + + class GhostNote extends StemmableNote { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setStave(stave : Stave) : Note; + + constructor(duration : string); + constructor(note_struct : {type? : string, dots? : number, duration : string}); //inconsistent name : init struct is called 'duration', should be 'params'/'options' (may be string or Object) + isRest() : boolean; + setStave(stave : Stave) : void; //inconsistent type: void -> GhostNote + addToModifierContext() : GhostNote; + preFormat() : GhostNote; + draw() : void; + } + + class Glyph { + constructor(code : string, point : number, options? : {cache? : boolean, font? : IFont}); + setOptions(options? : {cache? : boolean, font? : IFont}) : void; + setStave(stave : Stave) : Glyph; + setXShift(x_shift : number) : Glyph; + setYShift(y_shift : number) : Glyph; + setContext(context : IRenderContext) : Glyph; + getContext() : IRenderContext; + reset() : void; + setWidth(width : number) : Glyph; + getMetrics() : {x_min : number, x_max : number, width : number, height : number}; + render(ctx : IRenderContext, x_pos : number, y_pos : number) : void; + renderToStave(x : number) : void; + static loadMetrics(font : IFont, code : string, cache : boolean) : {x_min : number, x_max : number, ha : number, outline : number[]}; + static renderOutline(ctx : IRenderContext, outline : number[], scale : number, x_pos : number, y_pos : number) : void; + } + + class GraceNote extends StaveNote { + getStemExtension() : number; + getCategory() : string; + draw() : void; + } + + class GraceNoteGroup { + constructor(grace_notes : GraceNote[], show_slur? : boolean); //inconsistent name: 'show_slur' is called 'config', suggesting object (is boolean) + static CATEGORY : string; + static DEBUG : boolean; + static format(gracenote_groups : GraceNoteGroup[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + preFormat() : void; + beamNotes() : GraceNoteGroup; + setNote(note : Note) : void; + setWidth(width : number) : void; + getWidth() : number; + setXShift(x_shift : number) : void; + draw() : void; + } + + class KeyManager { + constructor(key : string); + setKey(key : string) : KeyManager; + getKey() : string; + reset() : KeyManager; + getAccidental(key : string) : {note : string, accidental : string}; + selectNote(note : string) : {note : string, accidental : string, change : boolean}; + } + + class KeySignature extends StaveModifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + addModifier() : void; + + constructor(key_spec : string); + addAccToStave(stave : Stave, acc : {type : string, line : number}, next? : {type : string, line : number}) : void; + cancelKey(spec : string) : KeySignature; + addModifier(stave : Stave) : KeySignature; + addToStave(stave : Stave, firstGlyph? : boolean) : KeySignature; + convertAccLines(clef : string, type : string) : void; + } + + export module Modifier { + enum Position {LEFT, RIGHT, ABOVE, BELOW} + } + + class Modifier { + static CATEGORY : string; + static DEBUG : boolean; + getCategory() : string; + getWidth() : number; + setWidth(width : number) : Modifier; + getNote() : Note; + setNote(note : Note) : Modifier; + getIndex() : number; + setIndex(index : number) : Modifier; + getContext() : IRenderContext; + setContext(context : IRenderContext) : Modifier; + getModifierContext() : ModifierContext; + setModifierContext(c : ModifierContext) : Modifier; + getPosition() : Modifier.Position; + setPosition(position : Modifier.Position) : Modifier; + setTextLine(line : number) : Modifier; + setYShift(y : number) : Modifier; + setXShift(x : number) : void; //inconsistent type: void -> Modifier + draw() : void; + } + + class ModifierContext { + static DEBUG : boolean; + addModifier(modifier : Modifier) : ModifierContext; + getModifiers(type : string) : Modifier[]; + getWidth() : number; + getExtraLeftPx() : number; + getExtraRightPx() : number; + getState() : {left_shift : number, right_shift : number, text_line : number}; + getMetrics() : {width : number, spacing : number, extra_left_px : number, extra_right_px : number}; + preFormat() : void; + postFormat() : void; + } + + class Music { + static NUM_TONES : number; + isValidNoteValue(note : number) : boolean; + isValidIntervalValue(interval : number) : boolean; + getNoteParts(noteString : string) : {root : string, accidental : string}; + getKeyParts(noteString : string) : {root : string, accidental : string, type : string}; + getNoteValue(noteString : string) : number; + getIntervalValue(intervalString : string) : number; + getCanonicalNoteName(noteValue : number) : string; + getCanonicalIntervalName(intervalValue : number) : string; + getRelativeNoteValue(noteValue : number, intervalValue : number, direction? : number) : number; + getRelativeNoteName(root : string, noteValue : number) : string; + getScaleTones(key : string, intervals : number[]) : number; + getIntervalBetween(note1 : number, note2 : number, direction? : number) : number; + createScaleMap(keySignature : string) : {[rootName : string] : string}; + } + + class Note extends Tickable { + constructor(note_struct : {type? : string, dots? : number, duration : string}); + static CATEGORY : string; + getPlayNote() : any; + setPlayNote(note : any) : Note; + isRest() : boolean; + addStroke(index : number, stroke : Stroke) : Note; + getStave() : Stave; + setStave(stave : Stave) : Note; + getCategory() : string; + setContext(context : IRenderContext) : Note; + getExtraLeftPx() : number; + getExtraRightPx() : number; + setExtraLeftPx(x : number) : Note; + setExtraRightPx(x : number) : Note; + shouldIgnoreTicks() : boolean; + getLineNumber() : number; + getLineForRest() : number; + getGlyph() : Glyph; + setYs(ys : number[]) : Note; + getYs() : number[]; + getYForTopText(text_line : number) : number; + getBoundingBox() : BoundingBox; + getVoice() : Voice; + setVoice(voice : Voice) : Note; + getTickContext() : TickContext; + setTickContext(tc : TickContext) : Note; + getDuration() : string; + isDotted() : boolean; + hasStem() : boolean; + getDots() : number; + getNoteType() : string; + setBeam() : Note; + setModifierContext(mc : ModifierContext) : Note; + addModifier(modifier : Modifier, index? : number) : Note; + getModifierStartXY() : {x : number, y : number}; + getMetrics() : {width : number, noteWidth : number, left_shift : number, modLeftPx : number, modRightPx : number, extraLeftPx : number, extraRightPx : number}; + setWidth(width : number) : void; + getWidth() : number; + setXShift(x : number) : Note; + getX() : number; + getAbsoluteX() : number; + setPreFormatted(value : boolean) : void; + } + + class NoteHead extends Note { + constructor(head_options : {x? : number, y? : number, note_type? : string, duration : string, displaced? : boolean, stem_direction? : number, x_shift : number, style : string, slashed : boolean, glyph_font_scale? : number}); + static DEBUG : boolean; + getCategory() : string; + setContext(context : IRenderContext) : NoteHead; + getWidth() : number; + isDisplaced() : boolean; + getStyle() : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}; + setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : NoteHead; + getGlyph() : Glyph; + setX(x : number) : NoteHead; + getY() : number; + setY(y : number) : NoteHead; + getLine() : number; + setLine(line : number) : NoteHead; + getAbsoluteX() : number; + getBoundingBox() : BoundingBox; + applyStyle(context : IRenderContext) : NoteHead; + setStave(stave : Stave) : NoteHead; + preFormat() : NoteHead; + draw() : void; + } + + class Ornament extends Modifier { + constructor(type : string); + static CATEGORY : string; + static DEBUG : boolean; + static format(ornaments : Ornament[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + setDelayed(delayed : boolean) : Ornament; + setUpperAccidental(acc : string) : Ornament; + setLowerAccidental(acc : string) : Ornament; + draw() : void; + } + + export module PedalMarking { + enum Styles {TEXT, BRACKET, MIXED} + } + + class PedalMarking { + constructor(notes : Note[]); //inconsistent name: 'notes' is called 'type', suggesting string (is Note[]) + static DEBUG : boolean; + static createSustain(notes : Note[]) : PedalMarking; + static createSostenuto(notes : Note[]) : PedalMarking; + static createUnaCorda(notes : Note[]) : PedalMarking; + setCustomText(depress? : string, release? : string) : PedalMarking; + setStyle(style : PedalMarking.Styles) : PedalMarking; + setLine(line : number) : PedalMarking; + setContext(context : IRenderContext) : PedalMarking; + drawBracketed() : void; + drawText() : void; + draw() : void; + } + + class RaphaelContext implements IRenderContext { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setLineWidth(width : number) : RaphaelContext; + glow() : RaphaelContext; + + constructor(element : HTMLElement); + setFont(family : string, size : number, weight? : number) : RaphaelContext; + setRawFont(font : string) : RaphaelContext; + setFillStyle(style : string) : RaphaelContext; + setBackgroundFillStyle(style : string) : RaphaelContext; + setStrokeStyle(style : string) : RaphaelContext; + setShadowColor(style : string) : RaphaelContext; //inconsistent name: style -> color + setShadowBlur(blur : string) : RaphaelContext; + setLineWidth(width : number) : void; //inconsistent type: void -> RaphaelContext + setLineDash(dash : string) : RaphaelContext; + setLineCap(cap_type : string) : RaphaelContext; + scale(x : number, y : number) : RaphaelContext; + clear() : void; + resize(width : number, height : number) : RaphaelContext; + setViewBox(viewBox : string) : void; + rect(x : number, y : number, width : number, height : number) : void; + fillRect(x : number, y : number, width : number, height : number) : RaphaelContext; + clearRect(x : number, y : number, width : number, height : number) : RaphaelContext; + beginPath() : RaphaelContext; + moveTo(x : number, y : number) : RaphaelContext; + lineTo(x : number, y : number) : RaphaelContext; + bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : RaphaelContext; + quadraticCurveToTo(x1 : number, y1 : number, x : number, y : number) : RaphaelContext; //inconsistent name: x, y -> x2, y2 + arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : RaphaelContext; + glow() : {width : number, fill : boolean, opacity : number, offsetx : number, offsety : number, color : string}; //inconsistent type : Object -> RaphaelContext + fill() : RaphaelContext; + stroke() : RaphaelContext; + closePath() : RaphaelContext; + measureText(text : string) : {width : number, height : number}; + fillText(text : string, x : number, y : number) : RaphaelContext; + save() : RaphaelContext; + restore() : RaphaelContext; + } + + export module Renderer { + enum Backends {CANVAS, RAPHAEL, SVG, VML} + enum LineEndType {NONE, UP, DOWN} + } + + class Renderer { + constructor(sel : HTMLElement, backend : Renderer.Backends) + static USE_CANVAS_PROXY : boolean; + static buildContext(sel : HTMLElement, backend : Renderer.Backends, width? : number, height? : number, background? : string) : IRenderContext; + static getCanvasContext(sel : HTMLElement, backend : Renderer.Backends, width? : number, height? : number, background? : string) : CanvasContext; + static getRaphaelContext(sel : HTMLElement, backend : Renderer.Backends, width? : number, height? : number, background? : string) : RaphaelContext; + static getSVGContext(sel : HTMLElement, backend : Renderer.Backends, width? : number, height? : number, background? : string) : SVGContext; + static bolsterCanvasContext(ctx : CanvasRenderingContext2D) : CanvasContext; + static drawDashedLine(context : IRenderContext, fromX : number, fromY : number, toX : number, toY : number, dashPattern : number[]) : void; + resize(width : number, height : number) : Renderer; + getContext() : IRenderContext; + } + + export module Repetition { + enum type {NONE, CODA_LEFT, CODA_RIGHT, SEGNO_LEFT, SEGNO_RIGHT, DC, DC_AL_CODA, DC_AL_FINE, DS, DS_AL_CODA, DS_AL_FINE, FINE} + } + + class Repetition extends StaveModifier { + constructor(type : Repetition.type, x : number, y_shift : number); + getCategory() : string; + setShiftX(x : number) : Repetition; + setShiftY(y : number) : Repetition; + draw(stave : Stave, x : number) : Repetition; + drawCodaFixed(stave : Stave, x : number) : Repetition; + drawSignoFixed(stave : Stave, x : number) : Repetition; //inconsistent name: drawSignoFixed -> drawSegnoFixed + drawSymbolText(stave : Stave, x : number, text : string, draw_coda : boolean) : Repetition; + } + + class Stave { + constructor(x : number, y : number, width : number, options? : {vertical_bar_width? : number, glyph_spacing_px? : number, num_lines? : number, fill_style? : string, spacing_between_lines_px? : number, space_above_staff_ln? : number, space_below_staff_ln? : number, top_text_position? : number}); + static THICKNESS : number; + resetLines() : void; + setNoteStartX(x : number) : Stave; + getNoteStartX() : number; + getNoteEndX() : number; + getTieStartX() : number; + getTieEndX() : number; + setContext(context : IRenderContext) : Stave; + getContext() : IRenderContext; + getX() : number; + getNumLines() : number; + setY(y : number) : Stave; + setWidth(width : number) : Stave; + getWidth() : number; + setMeasure(measure : number) : Stave; + setBegBarType(type : Barline.type) : Stave; + setEndBarType(type : Barline.type) : Stave; + getModifierXShift(index : number) : number; + setRepetitionTypeLeft(type : Repetition.type, y : number) : Stave; + setRepetitionTypeRight(type : Repetition.type, y : number) : Stave; + setVoltaType(type : Volta.type, number_t : number, y : number) : Stave; + setSection(section : string, y : number) : Stave; + setTempo(tempo : {name? : string, duration : string, dots : number, bpm : number}, y : number) : Stave; + setText(text : string, position : Modifier.Position, options? : {shift_x? : number, shift_y? : number, justification? : TextNote.Justification}) : Stave; + getHeight() : number; + getSpacingBetweenLines() : number; + getBoundingBix() : BoundingBox; + getBottomY() : number; + getBottomLineY() : number; + getYForLine(line : number) : number; + getYForTopText(line? : number) : number; + getYForBottomText(line? : number) : number; + getYForNote(line? : number) : number; + getYForGlyphs() : number; + addGlyph(glypg : Glyph) : Stave; + addEndGlyph(glypg : Glyph) : Stave; + addModifier(modifier : StaveModifier) : Stave; + addEndModifier(modifier : StaveModifier) : Stave; + addKeySignature(keySpec : string) : Stave; + addClef(clef : string, size? : string, annotation? : string) : Stave; + addEndClef(clef : string, size? : string, annotation? : string) : Stave; + addTimeSignature(timeSpec : string, customPadding? : number) : void; //inconsistent type: void -> Stave + addTrebleGlyph() : Stave; + draw() : void; + drawVertical(x : number, isDouble : boolean) : void; + drawVerticalFixed(x : number, isDouble : boolean) : void; + drawVerticalBar(x : number) : void; + drawVerticalBarFixed(x : number) : void; + getConfigForLines() : {visible : boolean}[]; + setConfigForLine(line_number : number, line_config : {visible : boolean}) : Stave; + setConfigForLines(lines_configuration : {visible : boolean}[]) : Stave; + } + + export module StaveConnector { + enum type {SINGLE_RIGHT, SINGLE_LEFT, SINGLE, DOUBLE, BRACE, BRACKET, BOLD_DOUBLE_LEFT, BOLD_DOUBLE_RIGHT, THIN_DOUBLE} + } + + class StaveConnector { + constructor(top_stave : Stave, bottom_stave : Stave); + setContext(ctx : IRenderContext) : StaveConnector; + setType(type : StaveConnector.type) : StaveConnector; + setText(text : string, text_options? : {shift_x? : number, shift_y? : number}) : StaveConnector; + setFont(font : {family? : string, size? : number, weight? : string}) : StaveConnector; + setXShift(x_shift : number) : StaveConnector; + draw() : void; + drawBoldDoubleLine(ctx : Object, type : StaveConnector.type, topX : number, topY : number, botY : number) : void; + } + + export module StaveHairpin { + enum type {CRESC, DECRESC} + } + + class StaveHairpin { + constructor(notes : {first_note : Note, last_note : Note}, type : StaveHairpin.type); + static FormatByTicksAndDraw(ctx : IRenderContext, formatter : Formatter, notes : Note[], type : StaveHairpin.type, position : Modifier.Position, options? : {height? : number, y_shift : number, left_shift_px : number, right_shift_px : number}) : void; + setContext(context : IRenderContext) : StaveHairpin; + setPosition(position : Modifier.Position) : StaveHairpin; + setRenderOptions(options : {height? : number, y_shift : number, left_shift_px : number, right_shift_px : number}) : StaveHairpin; + setNotes(notes : {first_note : Note, last_note : Note}) : StaveHairpin; + draw() : boolean; + } + + export module StaveLine { + enum TextVerticalPosition {TOP, BOTTOM} + enum TextJustification {LEFT, CENTER, RIGHT} + } + + class StaveLine { + constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}); + setContext(context : Object) : StaveLine; + setFont(font : {family : string, size : number, weight : string}) : StaveLine; + setText(text : string) : StaveLine; + setNotes(notes : {first_note: Note, last_note: Note, first_indices? : number[], last_indices? : number[]}) : StaveLine; + applyLineStyle() : void; + applyFontStyle() : void; + draw() : StaveLine; + + //inconsistent API: this should be set via an options object in the constructor + render_options : {padding_left : number, padding_right : number, line_width : number, line_dash : number[], rounded_end : boolean, color : string, draw_start_arrow : boolean, draw_end_arrow : boolean, arrowhead_length : number, arrowhead_angle : number, text_position_vertical : StaveLine.TextVerticalPosition, text_justification : StaveLine.TextJustification}; + } + + class StaveModifier { + getCategory() : string; + makeSpacer(padding : number) : {getContext: Function, setStave: Function, renderToStave: Function, getMetrics: Function}; + placeGlyphOnLine(glyph : Glyph, stave : Stave, line : number) : void; + setPadding(padding : number) : void; + addToStave(stave : Stave, firstGlyph : boolean) : StaveModifier; + addToStaveEnd(stave : Stave, firstGlyph : boolean) : StaveModifier; + addModifier() : void; + addEndModifier() : void; + } + + class StaveNote extends StemmableNote { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes and/or inconsistencies mentioned below are fixed + buildStem() : StemmableNote; + setStave(stave : Stave) : Note; + addModifier(modifier : Modifier, index? : number) : Note; + getModifierStartXY() : {x : number, y : number}; + getDots() : number; + + constructor(note_struct : {type : string, dots? : number, duration : string, clef : string, keys : string[], octave_shift? : number}); + static CATEGORY : string; + static DEBUG : boolean; + static STEM_UP : number; + static STEM_DOWN : number; + static format(notes : StaveNote[] , state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + static formatByY(notes : StaveNote[] , state : {left_shift : number, right_shift : number, text_line : number}) : void; + static postFormat(notes : StaveNote[]) : boolean; + buildStem() : void; //inconsistent type: void -> StaveNote + buildNoteHeads() : void; + autoStem() : void; + calculateKeyProps() : void; + getBoundingBox() : BoundingBox; + getLineNumber() : number; + isRest() : boolean; + isChord() : boolean; + hasStem() : boolean; + getYForTopText(text_line : number) : number; + getYForBottomText(text_line : number) : number; + setStave(stave : Stave) : StaveNote; + getKeys() : string[]; + getKeyProps() : {key : string, octave : number, line : number, int_value : number, accidental : string, code : number, stroke : number, shift_right : number, displaced : boolean}[]; + isDisplaced() : boolean; + setNoteDisplaced(displaced : boolean) : StaveNote; + getTieRightX() : number; + getTieLeftX() : number; + getLineForRest() : number; + getModifierStartXY(position : Modifier.Position, index : number) : {x : number, y : number}; + setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; // inconsistent type: void -> StaveNote + setKeyStyle(index : number, style : string) : StaveNote; + setKeyLine(index : number, line : number) : StaveNote; + getKeyLine(index : number) : number; + addToModifierContext(mContext : ModifierContext) : StaveNote; + addModifier(index : number, modifier : Modifier) : StaveNote; + addAccidental(index : number, accidental : Accidental) : StaveNote; + addArticulation(index : number, articulation : Articulation) : StaveNote; + addAnnotation(index : number, annotation : Annotation) : StaveNote; + addDot(index : number) : StaveNote; + addDotToAll() : StaveNote; + getAccidentals() : Accidental[]; + getDots() : Dot[]; + getVoiceShiftWidth() : number; + calcExtraPx() : void; + preFormat() : void; + getNoteHeadBounds() : {y_top: number, y_bottom: number, highest_line: number, lowest_line: number}; + getNoteHeadBeginX() : number; + getNoteHeadEndX() : number; + drawLedgerLines() : void; + drawModifiers() : void; + drawFlag() : void; + drawNoteHeads() : void; + drawStem(struct : {x_begin? : number, x_end? : number, y_top? : number, y_bottom? : number, y_extend? : number, stem_extension? : number, stem_direction? : number}) : void; + draw() : void; + } + + class StaveSection extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + draw() : void; + + constructor(section : string, x : number, shift_y : number); + getCategory() : string; + setStaveSection(section : string) : StaveSection; + setShiftX(x : number) : StaveSection; + setShiftY(y : number) : StaveSection; + draw(stave : Stave, shift_x : number) : StaveSection; + } + + class StaveTempo extends StaveModifier { + constructor(tempo : {name? : string, duration : string, dots : number, bpm : number}, x : number, shift_y : number); + getCategory() : string; + setTempo(tempo : {name : string, duration : string, dots : number, bpm : number}) : StaveTempo; + setShiftX(x : number) : StaveTempo; + setShiftY(y : number) : StaveTempo; + draw(stave : Stave, shift_x : number) : StaveTempo; + } + + class StaveText extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + draw() : void; + + constructor(text : string, position : Modifier.Position, options? : {shift_x? : number, shift_y? : number, justification? : TextNote.Justification}); + getCategory() : string; + setStaveText(text : string) : StaveText; + setShiftX(x : number) : StaveText; + setShiftY(y : number) : StaveText; + setFont(font : {family? : string, size? : number, weight? : number}) : void; + setText(text : string) : void; + draw(stave : Stave) : StaveText; + } + + class StaveTie { + constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, text : string); + setContext(context : IRenderContext) : StaveTie; + setFont(font : {family : string, size : number, weight : string}) : StaveTie; + setNotes(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}) : StaveTie; + isPartial() : boolean; + renderTie(params : {first_ys : number[], last_ys : number[], last_x_px : number, first_x_px : number, direction : number}) : void; + renderText(first_x_px : number, last_x_px : number) : void; + draw() : boolean; + } + + class Stem { + constructor(options : {x_begin? : number, x_end? : number, y_top? : number, y_bottom? : number, y_extend? : number, stem_extension? : number, stem_direction? : number}); + static DEBUG : boolean; + static UP : number; + static DOWN : number; + static WIDTH : number; + static HEIGHT : number; + setNoteHeadXBounds(x_begin : number, x_end : number) : Stem; + setDirection(direction : number) : void; + setExtension(extension : number) : void; + setYBounds(y_top : number, y_bottom : number) : void; + getCategory() : string; + setContext(context : IRenderContext) : Stem; + getHeight() : number; + getBoundingBox() : BoundingBox; + getExtents() : {topY : number, baseY : number}; + setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; + getStyle() : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}; + applyStyle(context : IRenderContext) : Stem; + draw() : void; + } + + class StemmableNote extends Note { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + setBeam() : Note; + + constructor(note_struct : {type? : string, dots? : number, duration : string}); + static DEBUG : boolean; + getStem() : Stem; + setStem(stem : Stem) : StemmableNote; + buildStem() : StemmableNote; + getStemLength() : number; + getBeamCount() : number; + getStemMinumumLength() : number; //inconsistent name: getStemMinumumLength -> getStemMinimumLength + getStemDirection() : number; + setStemDirection(direction : number) : StemmableNote; + getStemX() : number; + getCenterGlyphX() : number; + getStemExtension() : number; + setStemLength() : number; + getStemExtents() : {topY : number, baseY : number}; + setBeam(beam : Beam) : StemmableNote; + getYForTopText(text_line : number) : number; + getYForBottomText(text_line : number) : number; + postFormat() : StemmableNote; + drawStem(stem_struct : {x_begin? : number, x_end? : number, y_top? : number, y_bottom? : number, y_extend? : number, stem_extension? : number, stem_direction? : number}) : void; + } + + class StringNumber extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + setNote(note : Note) : StringNumber; + + constructor(number : number); + static CATEGORY : string; + static format(nums : StringNumber[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + getNote() : Note; + setNote(note : StaveNote) : StringNumber; + getIndex() : number; + setIndex(index : number) : StringNumber; + setLineEndType(leg : Renderer.LineEndType) : StringNumber; + getPosition() : Modifier.Position; + setPosition(position : Modifier.Position) : StringNumber; + setStringNumber(number : number) : StringNumber; + setOffsetX(x : number) : StringNumber; + setOffsetY(y : number) : StringNumber; + setLastNote(note : StaveNote) : StringNumber; + setDashed(dashed : boolean) : StringNumber; + draw() : void; + } + + export module Stroke { + enum Type {BRUSH_DOWN, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP} + } + + class Stroke extends Modifier { + constructor(type : Stroke.Type, options : {all_voices? : boolean}); + static CATEGORY : string; + static format(strokes : Stroke[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; + getPosition() : Modifier.Position; + addEndNote(note : Note) : Stroke; + draw() : void; + } + + class SVGContext implements IRenderContext { + constructor(element : HTMLElement); + iePolyfill() : boolean; + setFont(family : string, size : number, weight? : number) : SVGContext; + setRawFont(font : string) : SVGContext; + setFillStyle(style : string) : SVGContext; + setBackgroundFillStyle(style : string) : SVGContext; + setStrokeStyle(style : string) : SVGContext; + setShadowColor(style : string) : SVGContext; //inconsistent name: style -> color + setShadowBlur(blur : string) : SVGContext; + setLineWidth(width : number) : SVGContext; + setLineDash(dash : string) : SVGContext; + setLineCap(cap_type : string) : SVGContext; + resize(width : number, height : number) : SVGContext; + scale(x : number, y : number) : SVGContext; + setViewBox(xMin : number, yMin : number, width : number, height : number) : void; + clear() : void; + rect(x : number, y : number, width : number, height : number) : SVGContext; + fillRect(x : number, y : number, width : number, height : number) : SVGContext; + clearRect(x : number, y : number, width : number, height : number) : SVGContext; + beginPath() : SVGContext; + moveTo(x : number, y : number) : SVGContext; + lineTo(x : number, y : number) : SVGContext; + bezierCurveToTo(x1 : number, y1 : number, x2 : number, y2 : number, x : number, y : number) : SVGContext; + quadraticCurveToTo(x1 : number, y1 : number, x : number, y : number) : SVGContext; //inconsistent: x, y -> x2, y2 + arc(x : number, y : number, radius : number, startAngle : number, endAngle : number, antiClockwise : boolean) : SVGContext; + closePath() : SVGContext; + glow() : SVGContext; + fill() : SVGContext; + stroke() : SVGContext; + measureText(text : string) : SVGRect; + ieMeasureTextFix(bbox : SVGRect, text : string) : {x : number, y : number, width : number, height : number}; + fillText(text : string, x : number, y : number) : SVGContext; + save() : SVGContext; + restore() : SVGContext; + } + + class TabNote extends StemmableNote { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + setStave(stave : Stave) : Note; + getModifierStartXY() : {x : number, y : number}; + + constructor(tab_struct : {positions : {str : number, fret : number}[], type : string, dots? : number, duration : string}, draw_stem : boolean); + getCategory() : string; + setGhost(ghost : boolean) : TabNote; + hasStem() : boolean; + getStemExtension() : number; + addDot() : TabNote; + updateWidth() : void; + setStave(stave : Stave) : TabNote; + getPositions() : {str : number, fret : number}[]; + addToModifierContext(mc : ModifierContext) : TabNote; + getTieRightX() : number; + getTieLeftX() : number; + getModifierStartXY(position : Modifier.Position, index : number) : {x : number, y : number}; + getLineForRest() : number; + preFormat() : void; + getStemX() : number; + getStemY() : number; + getStemExtents() : {topY : number, baseY : number}; + drawFlag() : void; + drawModifiers() : void; + drawStemThrough() : void; + draw() : void; + } + + class TabSlide extends TabTie { + constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, direction : number); + static SLIDE_UP : number; + static SLIDE_DOWN : number; + static createSlideUp(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}) : TabSlide; + static createSlideDown(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}) : TabSlide; + renderTie(params : {first_ys : number[], last_ys : number[], last_x_px : number, first_x_px : number, direction : number}) : void; + } + + class TabStave extends Stave { + constructor(x : number, y : number, width : number, options : {vertical_bar_width? : number, glyph_spacing_px? : number, num_lines? : number, fill_style? : string, spacing_between_lines_px? : number, space_above_staff_ln? : number, space_below_staff_ln? : number, top_text_position? : number}); + getYForGlyphs() : number; + addTabGlyph() : TabStave; + } + + class TabTie extends StaveTie { + constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, text : string); + createHammeron(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}) : TabTie; + createPulloff(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}) : TabTie; + draw() : boolean; + } + + export module TextBracket { + enum Position {TOP, BOTTOM} + } + + class TextBracket { + constructor(bracket_data : {start : Note, stop : Note, text? : string, superscript? : string, position : TextBracket.Position}); + static DEBUG : boolean; + applyStyle(context : IRenderContext) : TextBracket; + setDashed(dashed : boolean, dash? : number[]) : TextBracket; + setFont(family : string, size : number, weight? : number) : TextBracket; + setContext(context : IRenderContext) : TextBracket; + setLine(line : number) : TextBracket; + draw() : void; + } + + class TextDynamics extends Note { + constructor(text_struct : {duration : string, text : string, line? : number}); + static DEBUG : boolean; + setLine(line : number) : TextDynamics; + preFormat() : TextDynamics; + draw() : void; + } + + export module TextNote { + enum Justification {LEFT, CENTER, RIGHT} + } + + class TextNote extends Note { + constructor(text_struct : {duration : string, text : string, superscript : boolean, subscript : boolean, glyph : string, font? : {family : string, size : number, weight : string}, line? : number, smooth? : boolean, ignore_ticks? : boolean}); + setJustification(just : TextNote.Justification) : TextNote; + setLine(line : number) : TextNote; + preFormat() : void; + draw() : void; + } + + class Tickable { + setContext(context : IRenderContext) : void; + getBoundingBox() : BoundingBox; + getTicks() : Fraction; + shouldIgnoreTicks() : boolean; + getWidth() : number; + setXShift(x : number) : Tickable; + getCenterXShift() : number; + isCenterAligned() : boolean; + setCenterAlignment(align_center : boolean) : Tickable; + getVoice() : Voice; + setVoice(voice : Voice) : void; + getTuplet() : Tuplet; + setTuplet(tuplet : Tuplet) : Tickable; + addToModifierContext(mc : ModifierContext) : void; + addModifier(mod : Modifier) : Tickable; + setTickContext(tc : TickContext) : void; + preFormat() : void; + postFormat() : Tickable; + getIntrinsicTicks() : Fraction; + setIntrinsicTicks(intrinsicTicks : Fraction) : void; + getTickMultiplier() : Fraction; + applyTickMultiplier(numerator : number, denominator : number) : void; + setDuration(duration : Fraction) : void; + } + + class TickContext { + setContext(context : IRenderContext) : void; + getContext() : IRenderContext; + shouldIgnoreTicks() : boolean; + getWidth() : number; + getX() : number; + setX(x : number) : TickContext; + getPixelsUsed() : number; + setPixelsUsed(pixelsUsed : number) : TickContext; + setPadding(padding : number) : TickContext; + getMaxTicks() : number; + getMinTicks() : number; + getTickables() : Tickable[]; + getCenterAlignedTickables() : Tickable[]; + getMetrics() : {width : number, notePx : number, extraLeftPx : number, extraRightPx : number}; + getCurrentTick() : Fraction; + setCurrentTick(tick : Fraction) : void; + getExtraPx() : {left: number, right: number, extraLeft : number, extraRight : number}; + addTickable(tickable : Tickable) : TickContext; + preFormat() : TickContext; + postFormat() : TickContext; + static getNextContext(tContext : TickContext) : TickContext; + } + + class TimeSignature extends StaveModifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes + addModifier() : void; + addEndModifier() : void; + + constructor(timeSpec : string, customPadding? : number); + parseTimeSpec(timeSpec : string) : {num : number, glyph : Glyph}; + makeTimeSignatureGlyph(topNums : number[], botNums : number[]) : Glyph; + getTimeSig() : {num : number, glyph : Glyph}; + addModifier(stave : Stave) : void; + addEndModifier(stave : Stave) : void; + } + + class TimeSigNote extends Note { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setStave(stave : Stave) : Note; + + constructor(timeSpec : string, customPadding : number); + setStave(stave : Stave) : void; //inconsistent type: void -> TimeSignote + getBoundingBox() : BoundingBox; + addToModifierContext() : TimeSigNote; + preFormat() : TimeSigNote; + draw() : void; + } + + class Tremolo extends Modifier { + constructor(num : number); + getCategory() : string; + draw() : void; + } + + class Tuning { + constructor(tuningString? : string); + noteToInteger(noteString : string) : number; + setTuning(tuningString : string) : void; + getValueForString(stringNum : string) : number; + getValueForFret(fretNum : string, stringNum : string) : number; + getNoteForFret(fretNum : string, stringNum : string) : string; + } + + class Tuplet { + constructor(notes : StaveNote[], options : {num_notes? : number, beats_occupied? : number}); + static LOCATION_TOP : number; + static LOCATION_BOTTOM : number; + attach() : void; + detach() : void; + setContext(context : IRenderContext) : Tuplet; + setBracketed(bracketed : boolean) : Tuplet; + setRatioed(ratioed : boolean) : Tuplet; + setTupletLocation(location : number) : Tuplet; + getNotes() : StaveNote[]; + getNoteCount() : number; + getBeatsOccupied() : number; + setBeatsOccupied(beats : number) : void; + resolveGlyphs() : void; + draw() : void; + } + + class Vibrato extends Modifier { + static CATEGORY : string; + static format(vibratos : Vibrato[], state : {left_shift : number, right_shift : number, text_line : number}, context : ModifierContext) : boolean; + setHarsh(harsh : boolean) : Vibrato; + setVibratoWidth(width : number) : Vibrato; + draw() : void; + } + + export module Voice { + enum Mode {STRICT, SOFT, FULL} + } + + class Voice { + constructor(time : {num_beats : number, beat_value : number, resolution : number}); + getTotalTicks() : Fraction; + getTicksUsed() : Fraction; + getLargestTickWidth() : number; + getSmallestTickCount() : Fraction; + getTickables() : Tickable[]; + getMode() : number; + setMode(mode : number) : Voice; + getResolutionMultiplier() : number; + getActualResolution() : number; + setStave(stave : Stave) : Voice; + getBoundingBox() : BoundingBox; + getVoiceGroup() : VoiceGroup; + setVoiceGroup(g : VoiceGroup) : Voice; + setStrict(strict : boolean) : Voice; + isComplete() : boolean; + addTickable(tickable : Tickable) : Voice; + addTickables(tickables : Tickable[]) : Voice; + preFormat() : Voice; + draw(context : IRenderContext, stave? : Stave) : void; + } + + class VoiceGroup { + getVoices() : Voice[]; + getModifierContexts() : ModifierContext[]; + addVoice(voice : Voice) : void; + } + + export module Volta { + enum type {NONE, BEGIN, MID, END, BEGIN_END} + } + + class Volta extends StaveModifier { + constructor(type : Volta.type, number : number, x : number, y_shift : number); + getCategory() : string; + setShiftY(y : number) : Volta; + draw(stave : Stave, x : number) : Volta; + } + } +} \ No newline at end of file From bcb9de30af34e0c799f74034fdf086501b278d7b Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Fri, 24 Jul 2015 14:30:05 -0700 Subject: [PATCH 029/419] [CodeMirror] add missing `css?` property on TextMarkerOptions --- 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 5fc335ed6..d4e3f4937 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -779,8 +779,8 @@ declare module CodeMirror { /** Like inclusiveLeft , but for the right side. */ inclusiveRight?: boolean; - /** Atomic ranges act as a single unit when cursor movement is concerned � i.e. it is impossible to place the cursor inside of them. - In atomic ranges, inclusiveLeft and inclusiveRight have a different meaning � they will prevent the cursor from being placed + /** Atomic ranges act as a single unit when cursor movement is concerned — i.e. it is impossible to place the cursor inside of them. + In atomic ranges, inclusiveLeft and inclusiveRight have a different meaning — they will prevent the cursor from being placed respectively directly before and directly after the range. */ atomic?: boolean; @@ -813,6 +813,9 @@ declare module CodeMirror { /** When the target document is linked to other documents, you can set shared to true to make the marker appear in all documents. By default, a marker appears only in its target document. */ shared?: boolean; + + /** A string of CSS to be applied to the covered text. For example "color: #fe3". */ + css?: string; } interface StringStream { From 6befcf5e84a99dcee756f5f304c3e003683e7f8e Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:51:07 -0400 Subject: [PATCH 030/419] MediaStream typings --- webrtc/MediaStream.d.ts | 308 +++++++++++++++++++++------------------- 1 file changed, 165 insertions(+), 143 deletions(-) diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 54de34e38..6db34de94 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -5,161 +5,183 @@ // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +/// + +interface ConstrainBooleanParameters { + exact: boolean; + ideal: boolean; +} + +interface NumberRange { + max: number; + min: number; +} + +interface ConstrainNumberRange extends NumberRange { + exact: number; + ideal: number; +} + +interface ConstrainStringParameters { + exact: string | string[]; + ideal: string | string[]; +} + interface MediaStreamConstraints { - audio: any; - video: any; + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; } -declare var MediaStreamConstraints: { - prototype: MediaStreamConstraints; - new (): MediaStreamConstraints; -}; interface MediaTrackConstraints { - mandatory: MediaTrackConstraintSet; - optional: MediaTrackConstraint[]; + advanced: MediaTrackConstraintSet[]; +} + +declare module W3C { + type LongRange = NumberRange; + type DoubleRange = NumberRange; + type ConstrainBoolean = boolean | ConstrainBooleanParameters; + type ConstrainNumber = number | ConstrainNumberRange; + type ConstrainLong = ConstrainNumber; + type ConstrainDouble = ConstrainNumber; + type ConstrainString = string | string[] | ConstrainStringParameters; } -declare var MediaTrackConstraints: { - prototype: MediaTrackConstraints; - new (): MediaTrackConstraints; -}; -// ks - Not defined in the source doc. interface MediaTrackConstraintSet { + width: W3C.ConstrainLong; + height: W3C.ConstrainLong; + aspectRatio: W3C.ConstrainDouble; + frameRate: W3C.ConstrainDouble; + facingMode: W3C.ConstrainString; + volume: W3C.ConstrainDouble; + sampleRate: W3C.ConstrainLong; + sampleSize: W3C.ConstrainLong; + echoCancellation: W3C.ConstrainBoolean; + latency: W3C.ConstrainDouble; + deviceId: W3C.ConstrainString; + groupId: W3C.ConstrainString; } -declare var MediaTrackConstraintSet: { - prototype: MediaTrackConstraintSet; - new (): MediaTrackConstraintSet; -}; -// ks - Not defined in the source doc. -interface MediaTrackConstraint { +interface MediaTrackSupportedConstraints { + width: boolean; + height: boolean; + aspectRatio: boolean; + frameRate: boolean; + facingMode: boolean; + volume: boolean; + sampleRate: boolean; + sampleSize: boolean; + echoCancellation: boolean; + latency: boolean; + deviceId: boolean; + groupId: boolean; +} + +interface MediaStream extends EventTarget { + id: string; + active: boolean; + + onactive: EventListener; + oninactive: EventListener; + onaddtrack: (event: MediaStreamTrackEvent) => any; + onremovetrack: (event: MediaStreamTrackEvent) => any; + + clone(): MediaStream; + stop(): void; + + getAudioTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + getTracks(): MediaStreamTrack[]; + + getTrackById(trackId: string): MediaStreamTrack; + + addTrack(track: MediaStreamTrack): void; + removeTrack(track: MediaStreamTrack): void; +} + +interface MediaStreamTrackEvent extends Event { + track: MediaStreamTrack; +} + +interface MediaStreamTrack extends EventTarget { + id: string; + kind: string; + label: string; + enabled: boolean; + muted: boolean; + remote: boolean; + readyState: string; + + onmute: EventListener; + onunmute: EventListener; + onended: EventListener; + onoverconstrained: EventListener; + + clone(): MediaStreamTrack; + + stop(): void; + + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + applyConstraints(constraints: MediaTrackConstraints): Promise; +} + +interface MediaTrackCapabilities { + width: number | W3C.LongRange; + height: number | W3C.LongRange; + aspectRatio: number | W3C.DoubleRange; + frameRate: number | W3C.DoubleRange; + facingMode: string; + volume: number | W3C.DoubleRange; + sampleRate: number | W3C.LongRange; + sampleSize: number | W3C.LongRange; + echoCancellation: boolean[]; + latency: number | W3C.DoubleRange; + deviceId: string; + groupId: string; +} + +interface MediaTrackSettings { + width: number; + height: number; + aspectRatio: number; + frameRate: number; + facingMode: string; + volume: number; + sampleRate: number; + sampleSize: number; + echoCancellation: boolean; + latency: number; + deviceId: string; + groupId: string; +} + +interface MediaStreamError { + name: string; + message: string; + constraintName: string; +} + +interface NavigatorGetUserMedia { + (constraints: MediaStreamConstraints, + successCallback: (stream: MediaStream) => void, + errorCallback: (error: MediaStreamError) => void): void; } -declare var MediaTrackConstraint: { - prototype: MediaTrackConstraint; - new (): MediaTrackConstraints; -}; interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void) : void; - webkitGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; - mozGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; + getUserMedia: NavigatorGetUserMedia; + + webkitGetUserMedia: NavigatorGetUserMedia; + + mozGetUserMedia: NavigatorGetUserMedia; + + msGetUserMedia: NavigatorGetUserMedia; + + mediaDevices: MediaDevices; } -interface EventHandler { (event: Event): void; } - -interface NavigatorUserMediaSuccessCallback { - (stream: LocalMediaStream): void; +interface MediaDevices { + getSupportedConstraints(): MediaTrackSupportedConstraints; + + getUserMedia(constraints: MediaStreamConstraints): Promise; } - -interface NavigatorUserMediaError { - PERMISSION_DENIED: number; // = 1; - code: number; -} -declare var NavigatorUserMediaError: { - prototype: NavigatorUserMediaError; - new (): NavigatorUserMediaError; - PERMISSION_DENIED: number; // = 1; -}; - -interface NavigatorUserMediaErrorCallback { - (error: NavigatorUserMediaError): void; -} - -interface MediaStreamTrackList { - length: number; - item: MediaStreamTrack; - add(track: MediaStreamTrack): void; - remove(track: MediaStreamTrack): void; - onaddtrack: (event: Event) => void; - onremovetrack: (event: Event) => void; -} -declare var MediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; -declare var webkitMediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; - -interface MediaStream extends EventTarget{ - label: string; - id: string; - getAudioTracks(): MediaStreamTrackList; - getVideoTracks(): MediaStreamTrackList; - ended: boolean; - onended: (event: Event) => void; -} -declare var MediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; -declare var webkitMediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; - -// an - not defined in source doc. -interface SourceInfo { - label: string; - id: string; - kind: string; - facing: string; -} -declare var SourceInfo: { - prototype: SourceInfo; -}; - -interface LocalMediaStream extends MediaStream { - stop(): void; -} - -interface MediaStreamTrack extends EventTarget{ - kind: string; - label: string; - enabled: boolean; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - readyState: number; - onmute: (event: Event) => void; - onunmute: (event: Event) => void; - onended: (event: Event) => void; -} -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new (): MediaStreamTrack; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - getSources: (callback: (sources: SourceInfo[]) => void) => void; -}; - -interface streamURL extends URL { - createObjectURL(stream: MediaStream): string; -} -//declare var URL: { -// prototype: MediaStreamTrack; -// new (): URL; -// createObjectURL(stream: MediaStream): string; -//} - -interface WebkitURL extends streamURL { -} -declare var webkitURL: { - prototype: WebkitURL; - new (): streamURL; - createObjectURL(stream: MediaStream): string; -}; From 35e40c5d8500681f7d05c9aef81ad50f9e043c85 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:52:58 -0400 Subject: [PATCH 031/419] some WebAudio interface missing methods --- webaudioapi/waa.d.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index 3ccc78b78..80823700a 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -171,3 +171,35 @@ declare enum OscillatorType { triangle, custom } + +interface AudioContextConstructor { + new(): AudioContext; +} + +interface Window { + AudioContext: AudioContextConstructor; +} + +interface AudioContext { + createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode; +} + +interface MediaStreamAudioSourceNode extends AudioNode { + +} + +interface AudioBuffer { + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; +} + +interface AudioNode { + disconnect(destination: AudioNode): void; +} + +interface AudioContext { + suspend(): Promise; + resume(): Promise; + close(): Promise; +} From 63e1e0c2b4e7e2555dea4136fc01b5c1568312fb Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Fri, 24 Jul 2015 15:10:00 -0700 Subject: [PATCH 032/419] Add other missing attributes. --- codemirror/codemirror.d.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index d4e3f4937..e20cc59ad 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -791,10 +791,16 @@ declare module CodeMirror { This is mostly useful for text - replacement widgets that need to 'snap open' when the user tries to edit them. The "clear" event fired on the range handle can be used to be notified when this happens. */ clearOnEnter?: boolean; + + /** Determines whether the mark is automatically cleared when it becomes empty. Default is true. */ + clearWhenEmpty: boolean; /** Use a given node to display this range.Implies both collapsed and atomic. The given DOM node must be an inline element(as opposed to a block element). */ replacedWith?: HTMLElement; + + /** When replacedWith is given, this determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture. */ + handleMouseEvents: boolean; /** A read - only span can, as long as it is not cleared, not be modified except by calling setValue to reset the whole document. Note: adding a read - only span currently clears the undo history of the editor, @@ -809,13 +815,16 @@ declare module CodeMirror { /** Equivalent to startStyle, but for the rightmost span. */ endStyle?: string; + + /** A string of CSS to be applied to the covered text. For example "color: #fe3". */ + css?: string; + + /** When given, will give the nodes created for this span a HTML title attribute with the given value. */ + title: string; /** When the target document is linked to other documents, you can set shared to true to make the marker appear in all documents. By default, a marker appears only in its target document. */ shared?: boolean; - - /** A string of CSS to be applied to the covered text. For example "color: #fe3". */ - css?: string; } interface StringStream { From e6764f406becf64bbfccd348653abb75d6c60afb Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Fri, 24 Jul 2015 15:12:41 -0700 Subject: [PATCH 033/419] wrap explanation --- codemirror/codemirror.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index e20cc59ad..cd067fac5 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -799,7 +799,10 @@ declare module CodeMirror { The given DOM node must be an inline element(as opposed to a block element). */ replacedWith?: HTMLElement; - /** When replacedWith is given, this determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture. */ + /** When replacedWith is given, this determines whether the editor will + * capture mouse and drag events occurring in this widget. Default is + * false—the events will be left alone for the default browser handler, + * or specific handlers on the widget, to capture. */ handleMouseEvents: boolean; /** A read - only span can, as long as it is not cleared, not be modified except by calling setValue to reset the whole document. From e5f0425b9782e04534565280a18f7e95d5ad10aa Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Fri, 24 Jul 2015 15:14:02 -0700 Subject: [PATCH 034/419] these are actually optionals --- codemirror/codemirror.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index cd067fac5..babaa57ec 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -793,7 +793,7 @@ declare module CodeMirror { clearOnEnter?: boolean; /** Determines whether the mark is automatically cleared when it becomes empty. Default is true. */ - clearWhenEmpty: boolean; + clearWhenEmpty?: boolean; /** Use a given node to display this range.Implies both collapsed and atomic. The given DOM node must be an inline element(as opposed to a block element). */ @@ -803,7 +803,7 @@ declare module CodeMirror { * capture mouse and drag events occurring in this widget. Default is * false—the events will be left alone for the default browser handler, * or specific handlers on the widget, to capture. */ - handleMouseEvents: boolean; + handleMouseEvents?: boolean; /** A read - only span can, as long as it is not cleared, not be modified except by calling setValue to reset the whole document. Note: adding a read - only span currently clears the undo history of the editor, @@ -823,7 +823,7 @@ declare module CodeMirror { css?: string; /** When given, will give the nodes created for this span a HTML title attribute with the given value. */ - title: string; + title?: string; /** When the target document is linked to other documents, you can set shared to true to make the marker appear in all documents. By default, a marker appears only in its target document. */ From 7f8dfda9a76069741b448ca029d273c68ef98e38 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:34:16 -0400 Subject: [PATCH 035/419] Fix test cases --- webrtc/MediaStream-tests.ts | 28 ++++++++++++-------------- webrtc/MediaStream.d.ts | 40 +++++++++++++++++++++---------------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 0d4e710b8..516abcb02 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -2,16 +2,16 @@ var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true }; var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; -var mediaTrackConstraintArray: MediaTrackConstraint[] = []; +var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } navigator.getUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); @@ -20,12 +20,11 @@ navigator.getUserMedia(mediaStreamConstraints, navigator.webkitGetUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); @@ -35,12 +34,11 @@ navigator.webkitGetUserMedia(mediaStreamConstraints, navigator.mozGetUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 6db34de94..f52551a14 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +// version: W3C Editor's Draft 29 June 2015 /// @@ -32,10 +33,6 @@ interface MediaStreamConstraints { audio?: boolean | MediaTrackConstraints; } -interface MediaTrackConstraints { - advanced: MediaTrackConstraintSet[]; -} - declare module W3C { type LongRange = NumberRange; type DoubleRange = NumberRange; @@ -46,19 +43,23 @@ declare module W3C { type ConstrainString = string | string[] | ConstrainStringParameters; } +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + interface MediaTrackConstraintSet { - width: W3C.ConstrainLong; - height: W3C.ConstrainLong; - aspectRatio: W3C.ConstrainDouble; - frameRate: W3C.ConstrainDouble; - facingMode: W3C.ConstrainString; - volume: W3C.ConstrainDouble; - sampleRate: W3C.ConstrainLong; - sampleSize: W3C.ConstrainLong; - echoCancellation: W3C.ConstrainBoolean; - latency: W3C.ConstrainDouble; - deviceId: W3C.ConstrainString; - groupId: W3C.ConstrainString; + width?: W3C.ConstrainLong; + height?: W3C.ConstrainLong; + aspectRatio?: W3C.ConstrainDouble; + frameRate?: W3C.ConstrainDouble; + facingMode?: W3C.ConstrainString; + volume?: W3C.ConstrainDouble; + sampleRate?: W3C.ConstrainLong; + sampleSize?: W3C.ConstrainLong; + echoCancellation?: W3C.ConstrainBoolean; + latency?: W3C.ConstrainDouble; + deviceId?: W3C.ConstrainString; + groupId?: W3C.ConstrainString; } interface MediaTrackSupportedConstraints { @@ -102,6 +103,11 @@ interface MediaStreamTrackEvent extends Event { track: MediaStreamTrack; } +declare enum MediaStreamTrackState { + "live", + "ended" +} + interface MediaStreamTrack extends EventTarget { id: string; kind: string; @@ -109,7 +115,7 @@ interface MediaStreamTrack extends EventTarget { enabled: boolean; muted: boolean; remote: boolean; - readyState: string; + readyState: MediaStreamTrackState; onmute: EventListener; onunmute: EventListener; From d821276efc1882cb363f783c2071ad5b44ebe781 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:39:59 -0400 Subject: [PATCH 036/419] LocalMediaStream is deprecated --- chrome/chrome.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 1df792b42..a8a48b82e 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -1822,7 +1822,7 @@ declare module chrome.tabCapture { videoConstraints?: MediaTrackConstraints; } - export function capture(options: CaptureOptions, callback: (stream: LocalMediaStream) => void): void; + export function capture(options: CaptureOptions, callback: (stream: MediaStream) => void): void; export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; } From f081c7118745dec548382e0975a803835336cff1 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:44:40 -0400 Subject: [PATCH 037/419] mandatory/optional is deprecated --- webrtc/MediaStream-tests.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 516abcb02..c309a281b 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -3,7 +3,8 @@ var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; -var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } +var mediaTrackConstraints: MediaTrackConstraints = mediaTrackConstraintSet; +var mediaTrackConstraints2: MediaTrackConstraints = { advanced: mediaTrackConstraintArray }; navigator.getUserMedia(mediaStreamConstraints, stream => { From b1dc72bc6e2e247ee96589d433535f6c9cf4efdf Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Sat, 25 Jul 2015 14:15:54 +0200 Subject: [PATCH 038/419] corrected definition for Vex.Flow.StaveNote --- vexflow/vexflow.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 7316987c9..259babf3f 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -855,7 +855,7 @@ declare module Vex { getModifierStartXY() : {x : number, y : number}; getDots() : number; - constructor(note_struct : {type : string, dots? : number, duration : string, clef : string, keys : string[], octave_shift? : number}); + constructor(note_struct : {type? : string, dots? : number, duration : string, clef : string, keys : string[], octave_shift? : number}); static CATEGORY : string; static DEBUG : boolean; static STEM_UP : number; @@ -884,7 +884,7 @@ declare module Vex { getLineForRest() : number; getModifierStartXY(position : Modifier.Position, index : number) : {x : number, y : number}; setStyle(style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : void; // inconsistent type: void -> StaveNote - setKeyStyle(index : number, style : string) : StaveNote; + setKeyStyle(index : number, style : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}) : StaveNote; setKeyLine(index : number, line : number) : StaveNote; getKeyLine(index : number) : number; addToModifierContext(mContext : ModifierContext) : StaveNote; From d2e5432873c2b59db55903430bd2cbe45d41875c Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Sat, 25 Jul 2015 14:28:46 +0200 Subject: [PATCH 039/419] changed constants in Vex.Flow from var to const --- vexflow/vexflow.d.ts | 47 ++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 259babf3f..afdc5f25a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -92,14 +92,14 @@ declare module Vex { module Flow { - var RESOLUTION : number; + const RESOLUTION : number; // from tables.js: - var STEM_WIDTH : number; - var STEM_HEIGHT : number; - var STAVE_LINE_THICKNESS : number; - var TIME4_4 : {num_beats : number, beat_value : number, resolution : number}; - var unicode : {[name : string] : string}; //inconsistent API: this should be private and have a wrapper function like the other tables + const STEM_WIDTH : number; + const STEM_HEIGHT : number; + const STAVE_LINE_THICKNESS : number; + const TIME4_4 : {num_beats : number, beat_value : number, resolution : number}; + const unicode : {[name : string] : string}; //inconsistent API: this should be private and have a wrapper function like the other tables function clefProperties(clef : string) : {line_shift : number}; function keyProperties(key : string, clef : string, params : {octave_shift? : number}) : {key : string, octave : number, line : number, int_value : number, accidental : string, code : number, stroke : number, shift_right : number, displaced : boolean}; function integerToNote(integer : number) : string; @@ -119,6 +119,24 @@ declare module Vex { // from glyph.js: function renderGlyph(ctx : IRenderContext, x_pos : number, y_pos : number, point : number, val : string, nocache : boolean) : void; + // from vexflow_font.js / gonville_original.js / gonville_all.js + var Font : { + glyphs : {x_min : number, x_max : number, ha : number, o : string[]}[]; + cssFontWeight : string; + ascender : number; + underlinePosition : number; + cssFontStyle : string; + boundingBox : {yMin : number, xMin : number, yMax : number, xMax : number}; + resolution : number; + descender : number; + familyName : string; + lineHeight : number; + underlineThickness : number; + + //inconsistent member : this is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js + original_font_information : {postscript_name : string, version_string : string, vendor_url : string, full_font_name : string, font_family_name : string, copyright : string, description : string, trademark : string, designer : string, designer_url : string, unique_font_identifier : string, license_url : string, license_description : string, manufacturer_name : string, font_sub_family_name : string}; + } + class Accidental extends Modifier { //TODO remove the following lines once TypeScript allows subclass overrides with type changes setNote(note : Note) : Modifier; @@ -352,23 +370,6 @@ declare module Vex { draw() : void; } - var Font : { - glyphs : {x_min : number, x_max : number, ha : number, o : string[]}[]; - cssFontWeight : string; - ascender : number; - underlinePosition : number; - cssFontStyle : string; - boundingBox : {yMin : number, xMin : number, yMax : number, xMax : number}; - resolution : number; - descender : number; - familyName : string; - lineHeight : number; - underlineThickness : number; - - //inconsistent member : this is missing in vexflow_font.js, but present in gonville_original.js and gonville_all.js - original_font_information : {postscript_name : string, version_string : string, vendor_url : string, full_font_name : string, font_family_name : string, copyright : string, description : string, trademark : string, designer : string, designer_url : string, unique_font_identifier : string, license_url : string, license_description : string, manufacturer_name : string, font_sub_family_name : string}; - } - class Formatter { static DEBUG : boolean; static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : StaveNote[], params : {auto_beam : boolean, align_rests : boolean}) : BoundingBox; From 826ae11b61ec2f94600a2901af02d82bcb092a57 Mon Sep 17 00:00:00 2001 From: Icereed Date: Sat, 25 Jul 2015 21:51:24 +0200 Subject: [PATCH 040/419] Added typing to the buttons in BootboxDialogOptions. --- bootbox/bootbox.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index bc4f40f0f..d71de8b70 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bootbox 4.4.0 // Project: https://github.com/makeusabrew/bootbox -// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel +// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -28,6 +28,10 @@ interface BootboxButton { callback?: () => any; } +interface BootboxButtonMap { + [key: string]: BootboxButton; +} + interface BootboxDialogOptions { message: string | Element; title?: string | Element; @@ -40,7 +44,7 @@ interface BootboxDialogOptions { animate?: boolean; className?: string; size?: string; - buttons?: Object; // complex object where each key is of type BootboxButton + buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton } interface BootboxDefaultOptions { @@ -69,7 +73,7 @@ interface BootboxStatic { dialog(options: BootboxDialogOptions): JQuery; setDefaults(options: BootboxDefaultOptions): void; hideAll(): void; - + addLocale(name: string, values: BootboxLocaleValues): void; removeLocale(name: string): void; setLocale(name: string): void; From 7518bed77b54c4f2dfc4a1d8254bcdd8c5941729 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Sat, 25 Jul 2015 18:14:47 -0700 Subject: [PATCH 041/419] [CodeMirror] removed is actually a list of string. as is test on the same object. --- codemirror/codemirror.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 5fc335ed6..6574005e3 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -600,7 +600,7 @@ declare module CodeMirror { /** Array of strings representing the text that replaced the changed range (split by line). */ text: string[]; /** Text that used to be between from and to, which is overwritten by this change. */ - removed: string; + removed: string[]; /** String representing the origin of the change event and wether it can be merged with history */ origin: string; } From c703676114bb983ab1812e2505ded6c6e0413c08 Mon Sep 17 00:00:00 2001 From: Andrei Cioara Date: Mon, 27 Jul 2015 12:40:41 -0700 Subject: [PATCH 042/419] d3: correct overloading of interpolate() --- d3/d3.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 50d6fbdaa..9df84276a 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -2193,8 +2193,7 @@ declare module d3 { interpolate(interpolate: "cardinal-open"): Line; interpolate(interpolate: "cardinal-closed"): Line; interpolate(interpolate: "monotone"): Line; - interpolate(interpolate: string): Line; - interpolate(interpolate: (points: Array<[number, number]>) => string): Line; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Line; tension(): number; tension(tension: number): Line; From b0b86846bd466b9ff2cbd60f131be06980e03b0b Mon Sep 17 00:00:00 2001 From: Matt DeKrey Date: Mon, 27 Jul 2015 15:40:53 -0400 Subject: [PATCH 043/419] Partial updates for lodash to 3.10.0 --- lodash/lodash-tests.ts | 20 +++--- lodash/lodash.d.ts | 134 +++++++++++++++++++++++++---------------- 2 files changed, 93 insertions(+), 61 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 627dda565..ca5ad80d1 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -221,19 +221,19 @@ result = _([1, 2, 3]).head(function (num) { result = _(foodsOrganic).head('organic').value(); result = _(foodsType).head({ 'type': 'fruit' }).value(); -result = _.take([1, 2, 3]); +result = _.take([1, 2, 3]); result = _.take([1, 2, 3], 2); -result = _.take([1, 2, 3], (num) => num < 3); -result = _.take(foodsOrganic, 'organic'); -result = _.take(foodsType, { 'type': 'fruit' }); +result = _.takeWhile([1, 2, 3], (num) => num < 3); +result = _.takeWhile(foodsOrganic, 'organic'); +result = _.takeWhile(foodsType, { 'type': 'fruit' }); -result = _([1, 2, 3]).take(); +result = _([1, 2, 3]).take().value(); result = _([1, 2, 3]).take(2).value(); -result = _([1, 2, 3]).take(function (num) { +result = _([1, 2, 3]).takeWhile(function (num) { return num < 3; }).value(); -result = _(foodsOrganic).take('organic').value(); -result = _(foodsType).take({ 'type': 'fruit' }).value(); +result = _(foodsType).takeWhile('organic').value(); +result = _(foodsType).takeWhile({ 'type': 'fruit' }).value(); result = >_.flatten([[1, 2], [3, 4]]); result = >_.flatten([[1, 2], [3, 4], 5, 6]); @@ -310,6 +310,8 @@ result = _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function result = _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); +result = _([1, 2, 3]).union([101, 2, 1, 10], [2, 1]).value(); + result = _.uniq([1, 2, 1, 3, 1]); result = _.uniq([1, 1, 2, 2, 3], true); result = _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function (letter) { @@ -392,6 +394,7 @@ result = _.all([true, 1, null, 'yes'], Boolean); result = _.all(stoogesAges, 'age'); result = _.all(stoogesAges, { 'age': 50 }); +result = _.filter([1, 2, 3, 4, 5, 6]); result = _.filter([1, 2, 3, 4, 5, 6], function (num) { return num % 2 == 0; }); result = _.filter(foodsCombined, 'organic'); result = _.filter(foodsCombined, { 'type': 'fruit' }); @@ -654,6 +657,7 @@ result = _.sortBy(['banana', 'strawberry', 'apple'], 'length'); 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(); +result = _(foodsOrganic).sortByAll('organic', (food) => food.name, { organic: true }).value(); (function (a: number, b: number, c: number, d: number): Array { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); result = _.toArray([1, 2, 3, 4]); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7bc1df648..d49e4104f 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -615,12 +615,12 @@ declare module _ { /** * @see _.first **/ - take(array: Array): T; + take(array: Array): T[]; /** * @see _.first **/ - take(array: List): T; + take(array: List): T[]; /** * @see _.first @@ -637,48 +637,36 @@ declare module _ { n: number): T[]; /** - * @see _.first - **/ - take( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - + * Takes the first items from an array or list based on a predicate + * @param array The array or list of items on which the result set will be based + * @param predicate A predicate function to determine whether a value will be taken. Optional; defaults to identity. + * @param [thisArg] The this binding of predicate. + */ + takeWhile( + array: (Array|List), + predicate?: ListIterator, + thisArg?: any + ): T[]; + /** - * @see _.first - **/ - take( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - + * Takes the first items from an array or list based on a predicate + * @param array The array or list of items on which the result set will be based + * @param pluckValue Uses a _.property style callback to return the property value of the given element + */ + takeWhile( + array: (Array|List), + pluckValue: string + ): any[]; + /** - * @see _.first - **/ - take( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - take( - array: List, - pluckValue: string): T[]; - - /** - * @see _.first - **/ - take( - array: Array, - whereValue: W): T[]; - - /** - * @see _.first - **/ - take( - array: List, - whereValue: W): T[]; + * Takes the first items from an array or list based on a predicate + * @param array The array or list of items on which the result set will be based + * @param whereValue Uses a _.matches style callback to return the first elements that match the given value + */ + takeWhile( + array: (Array|List), + whereValue: W + ): T[]; } interface LoDashArrayWrapper { @@ -749,7 +737,7 @@ declare module _ { /** * @see _.first **/ - take(): T; + take(): LoDashArrayWrapper; /** * @see _.first @@ -758,25 +746,28 @@ declare module _ { take(n: number): LoDashArrayWrapper; /** - * @see _.first - * @param callback The function called per element. + * Takes the first items based on a predicate + * @param predicate The function called per element. * @param [thisArg] The this binding of callback. **/ - take( - callback: ListIterator, + takeWhile( + predicate: ListIterator, thisArg?: any): LoDashArrayWrapper; /** - * @see _.first - * @param pluckValue "_.pluck" style callback value + * Takes the first items based on a predicate + * @param pluckValue Uses a _.property style callback to return the property value of the given element **/ - take(pluckValue: string): LoDashArrayWrapper; + takeWhile( + pluckValue: string): LoDashArrayWrapper; /** - * @see _.first - * @param whereValue "_.where" style callback value + * Takes the first items based on a predicate + * @param whereValue Uses a _.matches style callback to return the first elements that match the given value **/ - take(whereValue: W): LoDashArrayWrapper; + takeWhile( + whereValue: W): LoDashArrayWrapper; + } interface MaybeNestedList extends List> { } @@ -1519,6 +1510,13 @@ declare module _ { **/ union(...arrays: List[]): T[]; } + + interface LoDashArrayWrapper { + /** + * @see _.union + **/ + union(...arrays: (Array|List)[]): LoDashArrayWrapper; + } //_.uniq interface LoDashStatic { @@ -2427,6 +2425,16 @@ declare module _ { //_.filter interface LoDashStatic { + /** + * Iterates over elements of a collection, returning an array of all elements the + * identity function returns truey for. + * + * @param collection The collection to iterate over. + * @return Returns a new array of elements that passed the callback check. + **/ + filter( + collection: (Array|List)): T[]; + /** * Iterates over elements of a collection, returning an array of all elements the * callback returns truey for. The callback is bound to thisArg and invoked with three @@ -2585,6 +2593,11 @@ declare module _ { } interface LoDashArrayWrapper { + /** + * @see _.filter + **/ + filter(): LoDashArrayWrapper; + /** * @see _.filter **/ @@ -4805,6 +4818,15 @@ declare module _ { sortBy( collection: List, whereValue: W): T[]; + + /** + * Sorts by all the given arguments, using either ListIterator, pluckValue, or whereValue foramts + * @param args The rules by which to sort + */ + sortByAll( + collection: (Array|List), + ...args: (ListIterator|Object|string)[] + ): T[]; } interface LoDashArrayWrapper { @@ -4826,6 +4848,12 @@ declare module _ { * @param whereValue _.where style callback **/ sortBy(whereValue: W): LoDashArrayWrapper; + + /** + * Sorts by all the given arguments, using either ListIterator, pluckValue, or whereValue foramts + * @param args The rules by which to sort + */ + sortByAll(...args: (ListIterator|Object|string)[]): LoDashArrayWrapper; } //_.toArray From f444210ac43a53c7e40e3308ff7ad845da6efe38 Mon Sep 17 00:00:00 2001 From: Andrei Cioara Date: Mon, 27 Jul 2015 12:43:47 -0700 Subject: [PATCH 044/419] d3: Implemented all forgotten overloadings --- d3/d3.d.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 9df84276a..3eb48074d 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -2231,8 +2231,7 @@ declare module d3 { interpolate(interpolate: "cardinal-open"): Radial; interpolate(interpolate: "cardinal-closed"): Radial; interpolate(interpolate: "monotone"): Radial; - interpolate(interpolate: string): Radial; - interpolate(interpolate: (points: Array<[number, number]>) => string): Radial; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; tension(): number; tension(tension: number): Radial; @@ -2282,7 +2281,7 @@ declare module d3 { interpolate(interpolate: "cardinal"): Area; interpolate(interpolate: "cardinal-open"): Area; interpolate(interpolate: "monotone"): Area; - interpolate(interpolate: string): Area; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Area; tension(): number; tension(tension: number): Area; @@ -2332,8 +2331,7 @@ declare module d3 { interpolate(interpolate: "cardinal"): Radial; interpolate(interpolate: "cardinal-open"): Radial; interpolate(interpolate: "monotone"): Radial; - interpolate(interpolate: string): Radial; - interpolate(interpolate: (points: Array<[number, number]>) => string): Radial; + interpolate(interpolate: string | ((points: Array<[number, number]>) => string)): Radial; tension(): number; tension(tension: number): Radial; From 4f162bfd4bb19892d621a1ece40ab74838addd2c Mon Sep 17 00:00:00 2001 From: Matt DeKrey Date: Mon, 27 Jul 2015 16:08:33 -0400 Subject: [PATCH 045/419] Add access to $state.$current.locals.globals --- angular-ui-router/angular-ui-router-tests.ts | 4 ++++ angular-ui-router/angular-ui-router.d.ts | 11 +++++++++++ 2 files changed, 15 insertions(+) diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index a43f9e9bc..7ceafacd3 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -148,6 +148,10 @@ class UrlLocatorTestService implements IUrlLocatorTestService { this.$state.get("myState"); this.$state.get(); this.$state.reload(); + + // Accesses the currently resolved values for the current state + // http://stackoverflow.com/questions/28026620/is-there-a-way-to-access-resolved-state-dependencies-besides-injecting-them-into/28027023#28027023 + var resolvedValues = this.$state.$current.locals.globals; } } diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index ed2f36ccf..deaa085e8 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -168,6 +168,17 @@ declare module angular.ui { current: IState; params: IStateParamsService; reload(): void; + + $current: IStateServiceUtilities; + } + + interface IStateServiceUtilities { + locals: { + /** + * Currently resolved "resolve" values from the current state + */ + globals: { [key: string]: any; }; + }; } interface IStateParamsService { From 37f49d9aa9dcde34c137062e796c8ea348710ea8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Sa=C5=82kowski?= Date: Tue, 28 Jul 2015 09:36:18 +0200 Subject: [PATCH 046/419] rename library --- .../bxslider-4-tests.ts => dw-bxslider-4/dw-bxslider-4-tests.ts | 0 bxslider-4/bxslider-4.d.ts => dw-bxslider-4/dw-bxslider-4.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename bxslider-4/bxslider-4-tests.ts => dw-bxslider-4/dw-bxslider-4-tests.ts (100%) rename bxslider-4/bxslider-4.d.ts => dw-bxslider-4/dw-bxslider-4.d.ts (100%) diff --git a/bxslider-4/bxslider-4-tests.ts b/dw-bxslider-4/dw-bxslider-4-tests.ts similarity index 100% rename from bxslider-4/bxslider-4-tests.ts rename to dw-bxslider-4/dw-bxslider-4-tests.ts diff --git a/bxslider-4/bxslider-4.d.ts b/dw-bxslider-4/dw-bxslider-4.d.ts similarity index 100% rename from bxslider-4/bxslider-4.d.ts rename to dw-bxslider-4/dw-bxslider-4.d.ts From 22ade6d066a3a8dc3bdac0f3b1e8a14102605be4 Mon Sep 17 00:00:00 2001 From: Oskar Karlsson Date: Tue, 28 Jul 2015 09:37:47 +0200 Subject: [PATCH 047/419] Add missing method on Response class Added missing method (type) for setting content-type --- hapi/hapi.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index adf166565..ae8090165 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1407,6 +1407,9 @@ declare module "hapi" { options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ state(name: string, value: string, options?: any): void; + /** type(mimeType) - sets the HTTP 'Content-Type' header where: + mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ + type(mimeType: string): void; } From 7661b23edcb008f8af987baf4b4635e3ca58929b Mon Sep 17 00:00:00 2001 From: Oskar Karlsson Date: Tue, 28 Jul 2015 09:49:03 +0200 Subject: [PATCH 048/419] Add test case for chained notation --- hapi/hapi-tests.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/hapi/hapi-tests.ts b/hapi/hapi-tests.ts index ab58fd938..cfe9aa5ee 100644 --- a/hapi/hapi-tests.ts +++ b/hapi/hapi-tests.ts @@ -95,5 +95,18 @@ server.route([{ } }]); +// Should be able to chain reply options +server.route([{ + method: 'GET', + path: '/chained-notation', + handler: function(request: Hapi.Request, reply: Hapi.IReply) { + reply('chained-notation') + .bytes(16) + .code(200) + .type('text/plain') + .header('X-Custom', 'some-value'); + } +}]); + // Start the server server.start(); From 475e8b51dc414b6904d58c1ffdfdd869e0f3c787 Mon Sep 17 00:00:00 2001 From: Oskar Karlsson Date: Tue, 28 Jul 2015 09:50:20 +0200 Subject: [PATCH 049/419] All methods on Response class return itself This makes it possible to chain the methods --- hapi/hapi.d.ts | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index ae8090165..519a0ff27 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1350,19 +1350,19 @@ declare module "hapi" { /** sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: length - the header value. Must match the actual payload size.*/ - bytes(length: number): void; + bytes(length: number): Response; /** sets the 'Content-Type' HTTP header 'charset' property where: charset - the charset property value.*/ - charset(charset: string): void; + charset(charset: string): Response; /** sets the HTTP status code where: statusCode - the HTTP status code.*/ - code(statusCode: number): void; + code(statusCode: number): Response; /** sets the HTTP status code to Created (201) and the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ - created(uri: string): void; + created(uri: string): Response; /** encoding(encoding) - sets the string encoding scheme used to serial data into the HTTP payload where: encoding - the encoding property value (see node Buffer encoding).*/ - encoding(encoding: string): void; + encoding(encoding: string): Response; /** etag(tag, options) - sets the representation entity tag where: tag - the entity tag string without the double-quote. @@ -1371,7 +1371,7 @@ declare module "hapi" { vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true.*/ etag(tag: string, options: { weak: boolean; vary: boolean; - }): void; + }): Response; /**header(name, value, options) - sets an HTTP header where: name - the header name. @@ -1384,32 +1384,32 @@ declare module "hapi" { append: boolean; separator: string; override: boolean; - }): void; + }): Response; /** location(uri) - sets the HTTP 'Location' header where: uri - an absolute or relative URI used as the 'Location' header value.*/ - location(uri: string): void; + location(uri: string): Response; /** redirect(uri) - sets an HTTP redirection response (302) and decorates the response with additional methods listed below, where: uri - an absolute or relative URI used to redirect the client to another resource. */ - redirect(uri: string): void; + redirect(uri: string): Response; /** replacer(method) - sets the JSON.stringify() replacer argument where: method - the replacer function or array. Defaults to none.*/ - replacer(method: Function| Array): void; + replacer(method: Function| Array): Response; /** spaces(count) - sets the JSON.stringify() space argument where: count - the number of spaces to indent nested object keys. Defaults to no indentation. */ - spaces(count: number): void; + spaces(count: number): Response; /**state(name, value, [options]) - sets an HTTP cookie where: name - the cookie name. value - the cookie value. If no encoding is defined, must be a string. options - optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others).*/ - state(name: string, value: string, options?: any): void; + state(name: string, value: string, options?: any): Response; /** type(mimeType) - sets the HTTP 'Content-Type' header where: mimeType - is the mime type. Should only be used to override the built-in default for each response type. */ - type(mimeType: string): void; + type(mimeType: string): Response; } From 5c5b84939028e7e7d517128546bef7c1afd12b1e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Sa=C5=82kowski?= Date: Tue, 28 Jul 2015 12:13:22 +0200 Subject: [PATCH 050/419] fix reference path --- dw-bxslider-4/dw-bxslider-4-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dw-bxslider-4/dw-bxslider-4-tests.ts b/dw-bxslider-4/dw-bxslider-4-tests.ts index 09d48f2a8..8844fcdbe 100644 --- a/dw-bxslider-4/dw-bxslider-4-tests.ts +++ b/dw-bxslider-4/dw-bxslider-4-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// // examples from http://bxslider.com/examples From ac85b43a1cf7e4fe41c7ef48064543c97212e70c Mon Sep 17 00:00:00 2001 From: use-strict Date: Tue, 28 Jul 2015 14:05:20 +0300 Subject: [PATCH 051/419] Type safety for $watch and $watchCollection Added generic constraint to watched values, replacing "any". Using "any" looses type safety. The type should be inferred from the return type of the watching function, or given explicitly when using a watch expression. --- angularjs/angular.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 746fbb0e0..c8caec802 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -617,12 +617,12 @@ declare module angular { $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): Function; $watch(watchExpression: string, listener?: string, objectEquality?: boolean): Function; - $watch(watchExpression: string, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): Function; $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): Function; - $watch(watchExpression: (scope: IScope) => any, listener?: (newValue: any, oldValue: any, scope: IScope) => any, objectEquality?: boolean): Function; + $watch(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): Function; - $watchCollection(watchExpression: string, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; - $watchCollection(watchExpression: (scope: IScope) => any, listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; + $watchCollection(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function; $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; From 35527887e20f7d865aa884ade5af888fd9e88f25 Mon Sep 17 00:00:00 2001 From: use-strict Date: Tue, 28 Jul 2015 14:14:29 +0300 Subject: [PATCH 052/419] Fixed missing generic constraint --- 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 c8caec802..4c4e71190 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -622,7 +622,7 @@ declare module angular { $watch(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): Function; $watchCollection(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function; - $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function; + $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): Function; $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): Function; From c40afe52fbf8575a85f0dd88589d579f64793e9d Mon Sep 17 00:00:00 2001 From: Lokesh Peta Date: Fri, 24 Jul 2015 13:50:41 +0100 Subject: [PATCH 053/419] Definition for postaljs --- postal/postal-tests.ts | 9 ++++++ postal/postal.d.ts | 71 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 postal/postal-tests.ts create mode 100644 postal/postal.d.ts diff --git a/postal/postal-tests.ts b/postal/postal-tests.ts new file mode 100644 index 000000000..e83a3666a --- /dev/null +++ b/postal/postal-tests.ts @@ -0,0 +1,9 @@ + +/// + +var channel = postal.channel("test"); + +channel.subscribe("test", function(data){ }); + +channel.publish("test", {id:1, name:"Test user"}); + diff --git a/postal/postal.d.ts b/postal/postal.d.ts new file mode 100644 index 000000000..0ef40c5d5 --- /dev/null +++ b/postal/postal.d.ts @@ -0,0 +1,71 @@ +// Type definitions for Postal v0.8.9 +// Project: https://github.com/postaljs/postal.js +// Definitions by: Lokesh Peta +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface IConfiguration{ + SYSTEM_CHANNEL: string; + DEFAULT_CHANNEL: string; + resolver: any; +} + +interface ISubscriptionDefinition{ + unsubscribe(): void; + subscribe(callback: (data: any, envelope: IEnvelope)=> void): void; + defer():ISubscriptionDefinition; + disposeAfter(maxCalls: number): ISubscriptionDefinition; + distinctUntilChanged(): ISubscriptionDefinition; + once(): ISubscriptionDefinition; + withConstraint(predicate: Function): ISubscriptionDefinition; + withConstraints(predicates: Array): ISubscriptionDefinition; + + withContext(context: any): ISubscriptionDefinition; + withDebounce(milliseconds: number, immediate: boolean ): ISubscriptionDefinition; + withDelay(milliseconds: number): ISubscriptionDefinition; + withThrottle(milliseconds: number): ISubscriptionDefinition; +} + +interface IEnvelope{ + topic: string; + data?: any; + + /*Uses DEFAULT_CHANNEL if no channel is provided*/ + channel?: string; + + timeStamp?: string; +} + + +interface IChannelDefinition { + subscribe(topic: string): ISubscriptionDefinition; + subscribe(topic: string, callback: (data: any, envelope: IEnvelope)=> void): ISubscriptionDefinition; + + publish(topic: string, data?: any): void; + publish(envelope: IEnvelope): void; + + channel: string; +} + +interface IPostalUtils{ + getSubscribersFor(channel: string, tpc: any): any; + reset(): void; +} + +interface IPostal { + channel(name?:string): IChannelDefinition; + + linkChannels(sources: IEnvelope | IEnvelope[], destinations: IEnvelope | IEnvelope[]): ISubscriptionDefinition[]; + + utils: IPostalUtils; + + configuration: IConfiguration; +} + +declare var postal: IPostal; + +declare module "postal" { + var postal: IPostal; + export = postal; +} \ No newline at end of file From 94d3eee80bd70e9dd63088fedcee696e4eab9773 Mon Sep 17 00:00:00 2001 From: Vasya Aksyonov Date: Tue, 28 Jul 2015 20:28:14 +0500 Subject: [PATCH 054/419] Updating HashMap to latest version + commonjs --- hashmap/hashmap-1.1-tests.ts | 24 +++++++++ hashmap/hashmap-1.1.d.ts | 71 ++++++++++++++++++++++++++ hashmap/hashmap-commonjs-tests.ts | 41 +++++++++++++++ hashmap/hashmap-tests.ts | 37 ++++++++++---- hashmap/hashmap.d.ts | 83 ++++++++++++++++++++++++++----- 5 files changed, 233 insertions(+), 23 deletions(-) create mode 100644 hashmap/hashmap-1.1-tests.ts create mode 100644 hashmap/hashmap-1.1.d.ts create mode 100644 hashmap/hashmap-commonjs-tests.ts diff --git a/hashmap/hashmap-1.1-tests.ts b/hashmap/hashmap-1.1-tests.ts new file mode 100644 index 000000000..a3e7fcced --- /dev/null +++ b/hashmap/hashmap-1.1-tests.ts @@ -0,0 +1,24 @@ +/// + +var map : HashMap = new HashMap(); + +map.set("foo", 123); + +var value : number = map.get("foo"); + +map.has("foo"); + +map.remove("foo"); + +var keys : string[] = map.keys(); + +var values : number[] = map.values(); + +var count : number = map.count(); + +map.forEach(function(value : number, key : string) : void { + console.log(key); + console.log(value); +}); + +map.clear(); diff --git a/hashmap/hashmap-1.1.d.ts b/hashmap/hashmap-1.1.d.ts new file mode 100644 index 000000000..c9f858174 --- /dev/null +++ b/hashmap/hashmap-1.1.d.ts @@ -0,0 +1,71 @@ +// Type definitions for HashMap 1.1.0 +// Project: https://github.com/flesler/hashmap +// Definitions by: Rafał Wrzeszcz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare class HashMap { + /** + * Return value from hashmap. + * + * @param key Key. + * @return Value stored under given key. + */ + get(key : KeyType) : ValueType; + + /** + * Store value in hashmap. + * + * @param key Key. + * @param value Value. + */ + set(key : KeyType, value : ValueType) : void; + + /** + * Checks if given key exists in hashmap. + * + * @param key Key. + * @return Whether given key exists in hashmap. + */ + has(key : KeyType) : boolean; + + /** + * Removes given key from hashmap. + * + * @param key Key. + */ + remove(key : KeyType) : void; + + /** + * Returns all contained keys. + * + * @return List of keys. + */ + keys() : KeyType[]; + + /** + * Returns all container values. + * + * @return List of values. + */ + values() : ValueType[]; + + /** + * Returns size of hashmap (number of entries). + * + * @return Number of entries in hashmap. + */ + count() : number; + + /** + * Clears hashmap. + */ + clear() : void; + + /** + * Iterates over hashmap. + * + * @param callback Function to be invoked for every hashmap entry. + */ + forEach(callback : (value : ValueType, key : KeyType) => void) : void; +} + diff --git a/hashmap/hashmap-commonjs-tests.ts b/hashmap/hashmap-commonjs-tests.ts new file mode 100644 index 000000000..966d62593 --- /dev/null +++ b/hashmap/hashmap-commonjs-tests.ts @@ -0,0 +1,41 @@ +/// + +import HashMap = require("hashmap"); + +var emptyMap:HashMap = new HashMap(); +var filledMap:HashMap = new HashMap("bar", 123, "bar2", 234); +var copiedMap:HashMap = new HashMap(filledMap); + +emptyMap.set("foo", 123); +emptyMap.set("foo", 123).set("foo2", 234); +emptyMap.multi("foo3", 345, "foo4", 456).multi("foo5", 567, "foo6", "678"); +emptyMap.copy(filledMap).copy(copiedMap); + +var value:number = emptyMap.get("foo"); + +var hasFoo:boolean = emptyMap.has("foo"); + +var key:string = emptyMap.search(567); + +emptyMap.remove("foo").remove("foo2"); + +var keys:string[] = emptyMap.keys(); + +var values:number[] = emptyMap.values(); + +var count:number = emptyMap.count(); + +var clonedMap:HashMap = emptyMap.clone(); + +emptyMap + .forEach(function (value:number, key:string):void { + console.log(key); + console.log(value); + }) + .forEach(function (value:number, key:string):void { + console.log("Chained"); + console.log(key); + console.log(value); + }); + +emptyMap.clear().set("foo", 123); diff --git a/hashmap/hashmap-tests.ts b/hashmap/hashmap-tests.ts index 4c3d74ee0..ff9f69529 100644 --- a/hashmap/hashmap-tests.ts +++ b/hashmap/hashmap-tests.ts @@ -1,24 +1,39 @@ /// -var map : HashMap = new HashMap(); +var emptyMap:HashMap = new HashMap(); +var filledMap:HashMap = new HashMap("bar", 123, "bar2", 234); +var copiedMap:HashMap = new HashMap(filledMap); -map.set("foo", 123); +emptyMap.set("foo", 123); +emptyMap.set("foo", 123).set("foo2", 234); +emptyMap.multi("foo3", 345, "foo4", 456).multi("foo5", 567, "foo6", "678"); +emptyMap.copy(filledMap).copy(copiedMap); -var value : number = map.get("foo"); +var value:number = emptyMap.get("foo"); -map.has("foo"); +var hasFoo:boolean = emptyMap.has("foo"); -map.remove("foo"); +var key:string = emptyMap.search(567); -var keys : string[] = map.keys(); +emptyMap.remove("foo").remove("foo2"); -var values : number[] = map.values(); +var keys:string[] = emptyMap.keys(); -var count : number = map.count(); +var values:number[] = emptyMap.values(); -map.forEach(function(value : number, key : string) : void { +var count:number = emptyMap.count(); + +var clonedMap:HashMap = emptyMap.clone(); + +emptyMap + .forEach(function (value:number, key:string):void { console.log(key); console.log(value); -}); + }) + .forEach(function (value:number, key:string):void { + console.log("Chained"); + console.log(key); + console.log(value); + }); -map.clear(); +emptyMap.clear().set("foo", 123); diff --git a/hashmap/hashmap.d.ts b/hashmap/hashmap.d.ts index c9f858174..c20905309 100644 --- a/hashmap/hashmap.d.ts +++ b/hashmap/hashmap.d.ts @@ -1,24 +1,61 @@ -// Type definitions for HashMap 1.1.0 +// Type definitions for HashMap 2.0.3 // Project: https://github.com/flesler/hashmap -// Definitions by: Rafał Wrzeszcz +// Definitions by: Rafał Wrzeszcz , Vasya Aksyonov // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare class HashMap { +declare class HashMap { + + /** + * Creates an empty hashmap. + */ + constructor(); + + /** + * Creates a hashmap with the key-value pairs of map. + * + * @param map + */ + constructor(map:HashMap); + + /** + * Creates a hashmap with several key-value pairs. + * + * @param keysAndValues key1, value1, key2, value2... + */ + constructor(...keysAndValues:(TKey|TValue)[]); + /** * Return value from hashmap. * * @param key Key. * @return Value stored under given key. */ - get(key : KeyType) : ValueType; + get(key:TKey):TValue; /** * Store value in hashmap. * * @param key Key. * @param value Value. + * @return Self. */ - set(key : KeyType, value : ValueType) : void; + set(key:TKey, value:TValue):HashMap; + + /** + * Store several key-value pairs. + * + * @param keysAndValues key1, value1, key2, value2... + * @return Self. + */ + multi(...keysAndValues:(TKey|TValue)[]):HashMap; + + /** + * Copy all key-value pairs from other to this instance. + * + * @param map Other map. + * @return Self. + */ + copy(map:HashMap):HashMap; /** * Checks if given key exists in hashmap. @@ -26,46 +63,68 @@ declare class HashMap { * @param key Key. * @return Whether given key exists in hashmap. */ - has(key : KeyType) : boolean; + has(key:TKey):boolean; + + /** + * Returns key under which given value is stored. + * + * @param value Value. + * @return Key which is assigned to value stored. + */ + search(value:TValue):TKey; /** * Removes given key from hashmap. * * @param key Key. + * @return Self. */ - remove(key : KeyType) : void; + remove(key:TKey):HashMap; /** * Returns all contained keys. * * @return List of keys. */ - keys() : KeyType[]; + keys():TKey[]; /** * Returns all container values. * * @return List of values. */ - values() : ValueType[]; + values():TValue[]; /** * Returns size of hashmap (number of entries). * * @return Number of entries in hashmap. */ - count() : number; + count():number; /** * Clears hashmap. + * + * @return Self. */ - clear() : void; + clear():HashMap; + + /** + * Creates a new hashmap with all the key-value pairs of the original + * + * @return New hashmap. + */ + clone():HashMap; /** * Iterates over hashmap. * * @param callback Function to be invoked for every hashmap entry. + * @return Self. */ - forEach(callback : (value : ValueType, key : KeyType) => void) : void; + forEach(callback:(value:TValue, key:TKey) => void):HashMap; } +declare module "hashmap" { + export = HashMap; +} From ca697533d07c9673a6f574723da34008812da023 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 28 Jul 2015 18:58:36 +0100 Subject: [PATCH 055/419] Type definitions and tests for is-upper-case --- is-upper-case/is-upper-case-tests.ts | 7 +++++++ is-upper-case/is-upper-case.d.ts | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 is-upper-case/is-upper-case-tests.ts create mode 100644 is-upper-case/is-upper-case.d.ts diff --git a/is-upper-case/is-upper-case-tests.ts b/is-upper-case/is-upper-case-tests.ts new file mode 100644 index 000000000..a02db5850 --- /dev/null +++ b/is-upper-case/is-upper-case-tests.ts @@ -0,0 +1,7 @@ +/// + +import isUpperCase = require('is-upper-case') + +console.log(isUpperCase('STRING')); // => true +console.log(isUpperCase('String')); // => false +console.log(isUpperCase('string')); // => false diff --git a/is-upper-case/is-upper-case.d.ts b/is-upper-case/is-upper-case.d.ts new file mode 100644 index 000000000..610b63b28 --- /dev/null +++ b/is-upper-case/is-upper-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for is-upper-case +// Project: https://github.com/blakeembrey/is-upper-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "is-upper-case" { + function isUpperCase(string: string, locale?: string): boolean; + export = isUpperCase; +} \ No newline at end of file From 91eb243dfa4639d6ea6306ae790cf5860d65847d Mon Sep 17 00:00:00 2001 From: Brian Surowiec Date: Sun, 14 Jun 2015 03:56:19 -0400 Subject: [PATCH 056/419] Update to angular ui bootstrap v0.13.0 --- .../angular-ui-bootstrap-tests.ts | 24 +++++- .../angular-ui-bootstrap.d.ts | 74 ++++++++++++++----- 2 files changed, 79 insertions(+), 19 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 5aef97afa..a732d9ac7 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -7,6 +7,7 @@ testApp.config(( $buttonConfig: ng.ui.bootstrap.IButtonConfig, $datepickerConfig: ng.ui.bootstrap.IDatepickerConfig, $datepickerPopupConfig: ng.ui.bootstrap.IDatepickerPopupConfig, + $modalProvider: ng.ui.bootstrap.IModalProvider, $paginationConfig: ng.ui.bootstrap.IPaginationConfig, $pagerConfig: ng.ui.bootstrap.IPagerConfig, $progressConfig: ng.ui.bootstrap.IProgressConfig, @@ -41,6 +42,7 @@ testApp.config(( $datepickerConfig.startingDay = 1; $datepickerConfig.yearFormat = 'y'; $datepickerConfig.yearRange = 10; + $datepickerConfig.shortcutPropagation = true; /** @@ -56,6 +58,12 @@ testApp.config(( $datepickerPopupConfig.toggleWeeksText = 'Show Weeks'; + /** + * $modalProvider tests + */ + $modalProvider.options.animation = false; + + /** * $paginationConfig tests */ @@ -110,7 +118,8 @@ testApp.config(( placement: 'bottom', animation: false, popupDelay: 1000, - appendtoBody: true + appendtoBody: true, + useContentExp: true }); $tooltipProvider.setTriggers({ 'customOpenTrigger': 'customCloseTrigger' @@ -129,7 +138,9 @@ testApp.controller('TestCtrl', ( * test the $modal service */ var modalInstance = $modal.open({ + animation: false, backdrop: 'static', + backdropClass: 'testing', controller: 'ModalTestCtrl', controllerAs: 'vm', keyboard: true, @@ -149,12 +160,23 @@ testApp.controller('TestCtrl', ( $log.log('modal opened'); }); + modalInstance.rendered.then(() => { + $log.log('modal rendered'); + }); + modalInstance.result.then((closeResult:any)=> { $log.log('modal closed', closeResult); }, (dismissResult:any)=> { $log.log('modal dismissed', dismissResult); }); + $modal.open({ + backdrop: 'static' + }); + + $modal.open({ + templateUrl: () => '/templates/modal.html' + }); /** * test the $modalStack service diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 92a7411c9..d725e529c 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular UI Bootstrap 0.11.0 +// Type definitions for Angular UI Bootstrap 0.13.0 // Project: https://github.com/angular-ui/bootstrap // Definitions by: Brian Surowiec // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -107,6 +107,13 @@ declare module angular.ui.bootstrap { * @default null */ maxDate?: any; + + /** + * An option to disable or enable shortcut's event propagation + * + * @default false + */ + shortcutPropagation?: boolean; } interface IDatepickerPopupConfig { @@ -168,6 +175,13 @@ declare module angular.ui.bootstrap { } + interface IModalProvider { + /** + * Default options all modals will use. + */ + options: IModalSettings; + } + interface IModalService { /** * @param {IModalSettings} options @@ -178,47 +192,52 @@ declare module angular.ui.bootstrap { interface IModalServiceInstance { /** - * a method that can be used to close a modal, passing a result + * A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. */ close(result?: any): void; /** - * a method that can be used to dismiss a modal, passing a reason + * A method that can be used to dismiss a modal, passing a reason. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. */ dismiss(reason?: any): void; /** - * a promise that is resolved when a modal is closed and rejected when a modal is dismissed + * A promise that is resolved when a modal is closed and rejected when a modal is dismissed. */ result: angular.IPromise; /** - * a promise that is resolved when a modal gets opened after downloading content's template and resolving all variables + * A promise that is resolved when a modal gets opened after downloading content's template and resolving all variables. */ opened: angular.IPromise; + + /** + * A promise that is resolved when a modal is rendered. + */ + rendered: angular.IPromise; } interface IModalScope extends angular.IScope { /** - * Those methods make it easy to close a modal window without a need to create a dedicated controller + * Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + * + * @returns true if the modal was closed; otherwise false */ + $dismiss(reason?: any): boolean; /** - * Dismiss the dialog without assigning a value to the promise output + * Close the dialog resolving the promise to the given value. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. + * + * @returns true if the modal was closed; otherwise false */ - $dismiss(reason?: any): void; - - /** - * Close the dialog resolving the promise to the given value - */ - $close(result?: any): void; + $close(result?: any): boolean; } interface IModalSettings { /** * a path to a template representing modal's content */ - templateUrl?: string; + templateUrl?: string | (() => string); /** * inline template representing the modal's content @@ -248,6 +267,13 @@ declare module angular.ui.bootstrap { */ resolve?: any; + /** + * Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed. + * + * @default true + */ + animation?: boolean; + /** * controls the presence of a backdrop * Allowed values: @@ -257,10 +283,12 @@ declare module angular.ui.bootstrap { * * @default true */ - backdrop?: any; + backdrop?: boolean | string; /** - * indicates whether the dialog should be closable by hitting the ESC key, defaults to true + * indicates whether the dialog should be closable by hitting the ESC key + * + * @default true */ keyboard?: boolean; @@ -275,7 +303,7 @@ declare module angular.ui.bootstrap { windowClass?: string; /** - * optional size of modal window. Allowed values: 'sm' (small) or 'lg' (large). Requires Bootstrap 3.1.0 or later + * Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`. */ size?: string; @@ -577,7 +605,7 @@ declare module angular.ui.bootstrap { placement?: string; /** - * Should it fade in and out? + * Should the modal fade in and out? * * @default true */ @@ -603,6 +631,13 @@ declare module angular.ui.bootstrap { * @default 'mouseenter' for tooltip, 'click' for popover */ trigger?: string; + + /** + * Should an expression on the scope be used to load the content? + * + * @default false + */ + useContentExp?: boolean; } interface ITooltipProvider { @@ -618,6 +653,9 @@ declare module angular.ui.bootstrap { } + /** + * WARNING: $transition is now deprecated. Use $animate from ngAnimate instead. + */ interface ITransitionService { /** * The browser specific animation event name. From 0c1156706bcc0676502291c90018cfc620ba70d5 Mon Sep 17 00:00:00 2001 From: Brian Surowiec Date: Tue, 28 Jul 2015 14:06:59 -0400 Subject: [PATCH 057/419] Update to angular ui bootstrap v0.13.1 --- .../angular-ui-bootstrap-tests.ts | 6 +++-- .../angular-ui-bootstrap.d.ts | 23 ++++++++++++++++++- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index a732d9ac7..910cf0eff 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -110,6 +110,8 @@ testApp.config(( $timepickerConfig.mousewheel = false; $timepickerConfig.readonlyInput = true; $timepickerConfig.showMeridian = false; + $timepickerConfig.arrowkeys = false; + $timepickerConfig.showSpinners = false; /** * $tooltipProvider tests @@ -140,7 +142,8 @@ testApp.controller('TestCtrl', ( var modalInstance = $modal.open({ animation: false, backdrop: 'static', - backdropClass: 'testing', + backdropClass: 'modal-backdrop-test', + bindToController: true, controller: 'ModalTestCtrl', controllerAs: 'vm', keyboard: true, @@ -152,7 +155,6 @@ testApp.controller('TestCtrl', ( scope: $scope, template: "
    i'm a template!
    ", templateUrl: '/templates/modal.html', - backdropClass: 'modal-backdrop-test', windowClass: 'modal-test' }); diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index d725e529c..95388aada 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular UI Bootstrap 0.13.0 +// Type definitions for Angular UI Bootstrap 0.13.1 // Project: https://github.com/angular-ui/bootstrap // Definitions by: Brian Surowiec // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -262,6 +262,13 @@ declare module angular.ui.bootstrap { */ controllerAs?: string; + /** + * When used with controllerAs and set to true, it will bind the controller properties onto the $scope directly. + * + * @default false + */ + bindToController?: boolean; + /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes */ @@ -593,6 +600,20 @@ declare module angular.ui.bootstrap { * @default true */ mousewheel?: boolean; + + /** + * Whether the user can use up/down arrowkeys inside the hours & minutes input to increase or decrease it's values. + * + * @default true + */ + arrowkeys?: boolean; + + /** + * Shows spinner arrows above and below the inputs. + * + * @default true + */ + showSpinners?: boolean; } From b00355b72732ab296d74066369cce0dd9f54cec6 Mon Sep 17 00:00:00 2001 From: Matt DeKrey Date: Tue, 28 Jul 2015 18:35:57 -0400 Subject: [PATCH 058/419] Update name to match other definitions in library --- angular-ui-router/angular-ui-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index deaa085e8..913655bd4 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -169,10 +169,10 @@ declare module angular.ui { params: IStateParamsService; reload(): void; - $current: IStateServiceUtilities; + $current: IResolvedState; } - interface IStateServiceUtilities { + interface IResolvedState { locals: { /** * Currently resolved "resolve" values from the current state From b6297498638d942a79a76c3e1fe6343134631fc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andy=20Hawkins=20=E2=80=94=20=28=CC=90=CC=85=CC=96=CC=A3?= =?UTF-8?q?=CD=95=CC=A0=CC=AC=CC=AD=CC=9E=CC=AAi=CC=89=CD=AE=CC=AD=CC=A3?= =?UTF-8?q?=CD=88=CC=AA=CC=A0s=CD=91=CD=8C=CD=8B=CD=AA=CC=83=CC=8D=CC=B3?= =?UTF-8?q?=CC=B3=CC=A6=CC=9E=CC=B0=CC=9C=CC=9E=CC=B3=20=CC=81=CD=91=CD=A8?= =?UTF-8?q?=CD=84=CC=8E=CC=8B=CD=AE=CD=8A=CC=80=CC=A9=CC=98n=CC=83=CC=88?= =?UTF-8?q?=CD=AE=CD=A6=CC=81=CD=AB=CD=90=CD=9B=CD=94=CC=A3=CD=85=CD=85?= =?UTF-8?q?=CD=93=CC=ACo=CC=90=CD=86=CC=BD=CC=A9=CC=A6=CC=B3=CC=A0=CC=99?= =?UTF-8?q?=CC=97=CC=AF=CC=BAt=CD=82=CD=A9=CD=8B=CC=85=CD=84=CC=9C=CC=A5?= =?UTF-8?q?=CC=BB=CC=99=CC=9F=CC=BC=CC=9C=20=CD=92=CD=8B=CC=85=CC=81=CD=90?= =?UTF-8?q?=CC=A0=CC=A6=CC=B9=CC=9F=CD=95=CD=95=CC=B1=CD=89a=CC=84=CD=A6?= =?UTF-8?q?=CC=92=CC=8D=CD=8B=CC=9F=CC=BB=CC=B1=20=CD=A8=CD=A9=CD=8A=CD=82?= =?UTF-8?q?=CC=89=CD=85=CC=97=CC=9E=CD=9Ah=CD=A3=CD=94=CC=BC=CD=9A=CC=A9?= =?UTF-8?q?=CD=9A=CC=AA=CC=9D=CC=9Da=CC=92=CC=93=CD=AC=CC=AB=CC=ABc=CC=83?= =?UTF-8?q?=CD=A5=CD=AF=CC=A6=CC=B2=CC=B3=CD=8D=CC=B9k=CC=8A=CC=B2=CD=95?= =?UTF-8?q?=CC=97=CC=96=CC=A4=CC=99=CC=9C=CD=8De=CC=BF=CC=AB=CD=8E=CC=9F?= =?UTF-8?q?=CC=BC=CC=BA=CC=ABr=CC=8A=CC=91=CC=BF=CC=85=CD=AF=CD=99=CD=85?= =?UTF-8?q?=CC=B0=29=CD=86=CC=87=CD=A7=CC=9A=CD=91=CC=AA=CC=96=CD=87=CC=9D?= =?UTF-8?q?=CC=AE=CC=AA=CD=96=CC=A6?= Date: Tue, 28 Jul 2015 21:20:28 -0400 Subject: [PATCH 059/419] Updating autobahn.d.ts to match JQueryStatic Definition and fix AMD require. --- autobahn/autobahn.d.ts | 302 +++++++++++++++++++++-------------------- 1 file changed, 154 insertions(+), 148 deletions(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 7191e9c4f..b08212e5b 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -1,195 +1,201 @@ -// Type definitions for AutobahnJS v0.9.6 +// Type definitions for AutobahnJS v0.9.6 // Project: http://autobahn.ws/js/ // Definitions by: Elad Zelingher +// Updated by: Andy Hawkins [BombSquad Inc](http://www.bmbsqd.com) // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -declare module autobahn { - export class Session { - id: number; - realm: string; - isOpen: boolean; - features: any; - caller_disclose_me: boolean; - publisher_disclose_me: boolean; - subscriptions: ISubscription[][]; - registrations: IRegistration[]; +declare module autobahnModule { - constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler); + export class Session { + id: number; + realm: string; + isOpen: boolean; + features: any; + caller_disclose_me: boolean; + publisher_disclose_me: boolean; + subscriptions: ISubscription[][]; + registrations: IRegistration[]; - join(realm: string, authmethods: string[], authid: string): void; + constructor(transport: ITransport, defer: DeferFactory, challenge: OnChallengeHandler); - leave(reason: string, message: string): void; + join(realm: string, authmethods: string[], authid: string): void; - call(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise; + leave(reason: string, message: string): void; - publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise; + call(procedure: string, args?: any[], kwargs?: any, options?: ICallOptions): When.Promise; - subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise; + publish(topic: string, args?: any[], kwargs?: any, options?: IPublishOptions): When.Promise; - register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise; + subscribe(topic: string, handler: SubscribeHandler, options?: ISubscribeOptions): When.Promise; - unsubscribe(subscription: ISubscription): When.Promise; + register(procedure: string, endpoint: RegisterEndpoint, options?: IRegisterOptions): When.Promise; - unregister(registration: IRegistration): When.Promise; + unsubscribe(subscription: ISubscription): When.Promise; - prefix(prefix: string, uri: string): void; + unregister(registration: IRegistration): When.Promise; - resolve(curie: string): string; + prefix(prefix: string, uri: string): void; - onjoin: (roleFeatures: any) => void; - onleave: (reason: string, details: any) => void; - } + resolve(curie: string): string; - interface IInvocation { - caller?: number; - progress?: boolean; - procedure: string; - } + onjoin: (roleFeatures: any) => void; + onleave: (reason: string, details: any) => void; + } - interface IEvent { - publication: number; - publisher?: number; - topic: string; - } + interface IInvocation { + caller?: number; + progress?: boolean; + procedure: string; + } - interface IResult { - args: any[]; - kwargs: any; - } + interface IEvent { + publication: number; + publisher?: number; + topic: string; + } - interface IError { - error: string; - args: any[]; - kwargs: any; - } + interface IResult { + args: any[]; + kwargs: any; + } - type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void; + interface IError { + error: string; + args: any[]; + kwargs: any; + } - interface ISubscription { - topic: string; - handler: SubscribeHandler; - options: ISubscribeOptions; - session: Session; - id: number; - active: boolean; - unsubscribe(): When.Promise; - } + type SubscribeHandler = (args?: any[], kwargs?: any, details?: IEvent) => void; - type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void; + interface ISubscription { + topic: string; + handler: SubscribeHandler; + options: ISubscribeOptions; + session: Session; + id: number; + active: boolean; + unsubscribe(): When.Promise; + } - interface IRegistration { - procedure: string; - endpoint: RegisterEndpoint; - options: IRegisterOptions; - session: Session; - id: number; - active: boolean; - unregister(): When.Promise; - } + type RegisterEndpoint = (args?: any[], kwargs?: any, details?: IInvocation) => void; - interface IPublication { - id: number; - } + interface IRegistration { + procedure: string; + endpoint: RegisterEndpoint; + options: IRegisterOptions; + session: Session; + id: number; + active: boolean; + unregister(): When.Promise; + } - interface ICallOptions { - timeout?: number; - receive_progress?: boolean; - disclose_me?: boolean; - } + interface IPublication { + id: number; + } - interface IPublishOptions { - exclude?: number[]; - eligible?: number[]; - disclose_me? : Boolean; - } + interface ICallOptions { + timeout?: number; + receive_progress?: boolean; + disclose_me?: boolean; + } - interface ISubscribeOptions { - match? : string; - } + interface IPublishOptions { + exclude?: number[]; + eligible?: number[]; + disclose_me? : Boolean; + } - interface IRegisterOptions { - disclose_caller?: boolean; - } + interface ISubscribeOptions { + match? : string; + } - export class Connection { - constructor(options?: IConnectionOptions); + interface IRegisterOptions { + disclose_caller?: boolean; + } - open(): void; + export class Connection { + constructor(options?: IConnectionOptions); - close(reason: string, message: string): void; + open(): void; - onopen: (session: Session, details: any) => void; - onclose: (reason: string, details: any) => boolean; - } + close(reason: string, message: string): void; - interface ITransportDefinition { - url?: string; - protocols?: string[]; - type: string; - } + onopen: (session: Session, details: any) => void; + onclose: (reason: string, details: any) => boolean; + } - type DeferFactory = () => any; + interface ITransportDefinition { + url?: string; + protocols?: string[]; + type: string; + } - type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; + type DeferFactory = () => any; - interface IConnectionOptions { - use_es6_promises?: boolean; - // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer - use_deferred?: DeferFactory; - transports?: ITransportDefinition[]; - retry_if_unreachable?: boolean; - max_retries?: number; - initial_retry_delay?: number; - max_retry_delay?: number; - retry_delay_growth?: number; - retry_delay_jitter?: number; - url?: string; - protocols?: string[]; - onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; - realm?: string; - authmethods?: string[]; - authid?: string; - } + type OnChallengeHandler = (session: Session, method: string, extra: any) => When.Promise; - interface ICloseEventDetails { - wasClean: boolean; - reason: string; - code: number; - } + interface IConnectionOptions { + use_es6_promises?: boolean; + // use explicit deferred factory, e.g. jQuery.Deferred or Q.defer + use_deferred?: DeferFactory; + transports?: ITransportDefinition[]; + retry_if_unreachable?: boolean; + max_retries?: number; + initial_retry_delay?: number; + max_retry_delay?: number; + retry_delay_growth?: number; + retry_delay_jitter?: number; + url?: string; + protocols?: string[]; + onchallenge?: (session: Session, method: string, extra: any) => OnChallengeHandler; + realm?: string; + authmethods?: string[]; + authid?: string; + } - interface ITransport { - onopen: () => void; - onmessage: (message: any[]) => void; - onclose: (details: ICloseEventDetails) => void; + interface ICloseEventDetails { + wasClean: boolean; + reason: string; + code: number; + } - send(message: any[]): void; - close(errorCode: number, reason?: string): void; - } + interface ITransport { + onopen: () => void; + onmessage: (message: any[]) => void; + onclose: (details: ICloseEventDetails) => void; - interface ITransportFactory { - //constructor(options: any); - type: string; - create(): ITransport; - } + send(message: any[]): void; + close(errorCode: number, reason?: string): void; + } - interface ITransports { - register(name: string, factory: any): void; - isRegistered(name: string): boolean; - get(name: string): any; - list(): any[]; - } + interface ITransportFactory { + //constructor(options: any); + type: string; + create(): ITransport; + } - interface ILog { - debug(...args: any[]): void; - } + interface ITransports { + register(name: string, factory: any): void; + isRegistered(name: string): boolean; + get(name: string): any; + list(): any[]; + } - interface IUtil { - assert(condition: boolean, message: string): void; - } + interface ILog { + debug(...args: any[]): void; + } - var util: IUtil; - var log: ILog; - var transports: ITransports; -} \ No newline at end of file + interface IUtil { + assert(condition: boolean, message: string): void; + } + + var util: IUtil; + var log: ILog; + var transports: ITransports; +} + +declare module "autobahn" { + export = autobahnModule; +} From ac6a769673d6ba7e41593360a8910addd0fab357 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andy=20Hawkins=20=E2=80=94=20=28=CC=90=CC=85=CC=96=CC=A3?= =?UTF-8?q?=CD=95=CC=A0=CC=AC=CC=AD=CC=9E=CC=AAi=CC=89=CD=AE=CC=AD=CC=A3?= =?UTF-8?q?=CD=88=CC=AA=CC=A0s=CD=91=CD=8C=CD=8B=CD=AA=CC=83=CC=8D=CC=B3?= =?UTF-8?q?=CC=B3=CC=A6=CC=9E=CC=B0=CC=9C=CC=9E=CC=B3=20=CC=81=CD=91=CD=A8?= =?UTF-8?q?=CD=84=CC=8E=CC=8B=CD=AE=CD=8A=CC=80=CC=A9=CC=98n=CC=83=CC=88?= =?UTF-8?q?=CD=AE=CD=A6=CC=81=CD=AB=CD=90=CD=9B=CD=94=CC=A3=CD=85=CD=85?= =?UTF-8?q?=CD=93=CC=ACo=CC=90=CD=86=CC=BD=CC=A9=CC=A6=CC=B3=CC=A0=CC=99?= =?UTF-8?q?=CC=97=CC=AF=CC=BAt=CD=82=CD=A9=CD=8B=CC=85=CD=84=CC=9C=CC=A5?= =?UTF-8?q?=CC=BB=CC=99=CC=9F=CC=BC=CC=9C=20=CD=92=CD=8B=CC=85=CC=81=CD=90?= =?UTF-8?q?=CC=A0=CC=A6=CC=B9=CC=9F=CD=95=CD=95=CC=B1=CD=89a=CC=84=CD=A6?= =?UTF-8?q?=CC=92=CC=8D=CD=8B=CC=9F=CC=BB=CC=B1=20=CD=A8=CD=A9=CD=8A=CD=82?= =?UTF-8?q?=CC=89=CD=85=CC=97=CC=9E=CD=9Ah=CD=A3=CD=94=CC=BC=CD=9A=CC=A9?= =?UTF-8?q?=CD=9A=CC=AA=CC=9D=CC=9Da=CC=92=CC=93=CD=AC=CC=AB=CC=ABc=CC=83?= =?UTF-8?q?=CD=A5=CD=AF=CC=A6=CC=B2=CC=B3=CD=8D=CC=B9k=CC=8A=CC=B2=CD=95?= =?UTF-8?q?=CC=97=CC=96=CC=A4=CC=99=CC=9C=CD=8De=CC=BF=CC=AB=CD=8E=CC=9F?= =?UTF-8?q?=CC=BC=CC=BA=CC=ABr=CC=8A=CC=91=CC=BF=CC=85=CD=AF=CD=99=CD=85?= =?UTF-8?q?=CC=B0=29=CD=86=CC=87=CD=A7=CC=9A=CD=91=CC=AA=CC=96=CD=87=CC=9D?= =?UTF-8?q?=CC=AE=CC=AA=CD=96=CC=A6?= Date: Tue, 28 Jul 2015 21:25:12 -0400 Subject: [PATCH 060/419] Updating autobahn.d.ts to JQueryStatic style export and fix AMD require. --- autobahn/autobahn.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index b08212e5b..3f757f721 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -1,7 +1,6 @@ // Type definitions for AutobahnJS v0.9.6 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher -// Updated by: Andy Hawkins [BombSquad Inc](http://www.bmbsqd.com) +// Definitions by: Elad Zelingher , Andy Hawkins [BombSquad Inc](http://www.bmbsqd.com) // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 5f08b28bc03e83fd77306c969f54eb7de1236934 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andy=20Hawkins=20=E2=80=94=20=28=CC=90=CC=85=CC=96=CC=A3?= =?UTF-8?q?=CD=95=CC=A0=CC=AC=CC=AD=CC=9E=CC=AAi=CC=89=CD=AE=CC=AD=CC=A3?= =?UTF-8?q?=CD=88=CC=AA=CC=A0s=CD=91=CD=8C=CD=8B=CD=AA=CC=83=CC=8D=CC=B3?= =?UTF-8?q?=CC=B3=CC=A6=CC=9E=CC=B0=CC=9C=CC=9E=CC=B3=20=CC=81=CD=91=CD=A8?= =?UTF-8?q?=CD=84=CC=8E=CC=8B=CD=AE=CD=8A=CC=80=CC=A9=CC=98n=CC=83=CC=88?= =?UTF-8?q?=CD=AE=CD=A6=CC=81=CD=AB=CD=90=CD=9B=CD=94=CC=A3=CD=85=CD=85?= =?UTF-8?q?=CD=93=CC=ACo=CC=90=CD=86=CC=BD=CC=A9=CC=A6=CC=B3=CC=A0=CC=99?= =?UTF-8?q?=CC=97=CC=AF=CC=BAt=CD=82=CD=A9=CD=8B=CC=85=CD=84=CC=9C=CC=A5?= =?UTF-8?q?=CC=BB=CC=99=CC=9F=CC=BC=CC=9C=20=CD=92=CD=8B=CC=85=CC=81=CD=90?= =?UTF-8?q?=CC=A0=CC=A6=CC=B9=CC=9F=CD=95=CD=95=CC=B1=CD=89a=CC=84=CD=A6?= =?UTF-8?q?=CC=92=CC=8D=CD=8B=CC=9F=CC=BB=CC=B1=20=CD=A8=CD=A9=CD=8A=CD=82?= =?UTF-8?q?=CC=89=CD=85=CC=97=CC=9E=CD=9Ah=CD=A3=CD=94=CC=BC=CD=9A=CC=A9?= =?UTF-8?q?=CD=9A=CC=AA=CC=9D=CC=9Da=CC=92=CC=93=CD=AC=CC=AB=CC=ABc=CC=83?= =?UTF-8?q?=CD=A5=CD=AF=CC=A6=CC=B2=CC=B3=CD=8D=CC=B9k=CC=8A=CC=B2=CD=95?= =?UTF-8?q?=CC=97=CC=96=CC=A4=CC=99=CC=9C=CD=8De=CC=BF=CC=AB=CD=8E=CC=9F?= =?UTF-8?q?=CC=BC=CC=BA=CC=ABr=CC=8A=CC=91=CC=BF=CC=85=CD=AF=CD=99=CD=85?= =?UTF-8?q?=CC=B0=29=CD=86=CC=87=CD=A7=CC=9A=CD=91=CC=AA=CC=96=CD=87=CC=9D?= =?UTF-8?q?=CC=AE=CC=AA=CD=96=CC=A6?= Date: Tue, 28 Jul 2015 21:29:19 -0400 Subject: [PATCH 061/419] Updating autobahn.d.ts to match JQueryStatic Interface, and fix AMD require --- autobahn/autobahn.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 3f757f721..3ef9e7061 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.6 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins [BombSquad Inc](http://www.bmbsqd.com) +// Definitions by: Elad Zelingher , Andy Hawkins // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From ded31eeaeed60bb67213dae6a66531e5d57674e4 Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 29 Jul 2015 15:09:39 +0900 Subject: [PATCH 062/419] Add unref() to child_process.ChildProcess child_process.ChildProcess.unref() isn't described in document. But it actually exist and is described in document for `options.detached`. https://nodejs.org/api/child_process.html#child_process_options_detached --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 75c33c388..dfa8c9665 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -823,6 +823,7 @@ declare module "child_process" { kill(signal?: string): void; send(message: any, sendHandle?: any): void; disconnect(): void; + unref(): void; } export function spawn(command: string, args?: string[], options?: { From 3fc372d45d6a415bf496e9ff121d886f776e7c0e Mon Sep 17 00:00:00 2001 From: Icereed Date: Wed, 29 Jul 2015 08:37:50 +0200 Subject: [PATCH 063/419] Added possibility to add a button as function --- bootbox/bootbox.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index d71de8b70..5ec2a7abd 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -29,7 +29,7 @@ interface BootboxButton { } interface BootboxButtonMap { - [key: string]: BootboxButton; + [key: string]: BootboxButton | Function; } interface BootboxDialogOptions { From b287954ece6b57ee053632ee33c63b8037730e65 Mon Sep 17 00:00:00 2001 From: rhysd Date: Wed, 29 Jul 2015 15:37:39 +0900 Subject: [PATCH 064/419] Add definitions for electron-prebuilt package I added definitions for API of electron-prebuilt package. There is already a directory for GitHub Electron. So I added electron-prebuilt.d.ts to it. If I should add new `electron-prebuilt` directory, please let me know that. --- github-electron/electron-prebuilt-tests.ts | 7 +++++++ github-electron/electron-prebuilt.d.ts | 10 ++++++++++ 2 files changed, 17 insertions(+) create mode 100644 github-electron/electron-prebuilt-tests.ts create mode 100644 github-electron/electron-prebuilt.d.ts diff --git a/github-electron/electron-prebuilt-tests.ts b/github-electron/electron-prebuilt-tests.ts new file mode 100644 index 000000000..771fd0601 --- /dev/null +++ b/github-electron/electron-prebuilt-tests.ts @@ -0,0 +1,7 @@ +/// +/// + +import electron = require('electron-prebuilt'); +import child_process = require('child_process'); + +child_process.spawn(electron); diff --git a/github-electron/electron-prebuilt.d.ts b/github-electron/electron-prebuilt.d.ts new file mode 100644 index 000000000..faaceb46d --- /dev/null +++ b/github-electron/electron-prebuilt.d.ts @@ -0,0 +1,10 @@ +// Type definitions for electron-prebuilt 0.30.1 +// Project: https://github.com/mafintosh/electron-prebuilt +// Definitions by: rhysd +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module 'electron-prebuilt' { + var electron: string; + export = electron; +} + From e4ea80a78330d68e4ed0c5a0d2c41f9d5bcb5a90 Mon Sep 17 00:00:00 2001 From: Lokesh Peta Date: Wed, 29 Jul 2015 09:45:31 +0100 Subject: [PATCH 065/419] added definition for pathjs --- pathjs/path-tests.ts | 33 +++++++++++++++++++++++++++ pathjs/path.d.ts | 53 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 pathjs/path-tests.ts create mode 100644 pathjs/path.d.ts diff --git a/pathjs/path-tests.ts b/pathjs/path-tests.ts new file mode 100644 index 000000000..1a3607a63 --- /dev/null +++ b/pathjs/path-tests.ts @@ -0,0 +1,33 @@ +/// + +Path.map("/test/:id") +.to(()=>{ }); + +Path.listen(); + +//History +Path.history.listen(() =>{ + +}); + +var initial = Path.history.initial; + +//Core +var route = Path.core.route("/test/:id"); + +function test1() { + +} + +route.enter(test1); + +function test2() { + +} + +var funs = new Array(); + +funs.push(test1); +funs.push(test2); + +route.enter(funs); \ No newline at end of file diff --git a/pathjs/path.d.ts b/pathjs/path.d.ts new file mode 100644 index 000000000..133bd5fc0 --- /dev/null +++ b/pathjs/path.d.ts @@ -0,0 +1,53 @@ +// Type definitions for Pathjs v0.8.4 +// Project: https://github.com/mtrpcic/pathjs/blob/master/path.js +// Definitions by: Lokesh Peta +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +interface IPathHistory{ + initial: any; + pushState(state: any, title: string, path: string):void; + popState(event: any): void; + listen(fallback: any): void; +} + +interface IPathRoute{ + to(fn: () => void): IPathRoute; + enter(fns: Function|Function[]): IPathRoute; + exit(fn: () => void): IPathRoute; + partition(): string[]; + run():void; +} + +interface IPathRoutes{ + current: IPathRoute, + root: IPathRoute, + rescue: Function, + previous: IPathRoute, + defined: {} +} + +interface IPathCore{ + route(path: string): IPathRoute; +} + +interface IPath { + map(path: string): IPathRoute; + + root(path: string): void; + + rescure(fn: Function): void; + + history: IPathHistory; + + match(path: string, parameterize: boolean): IPathRoute; + + dispatch(passed_route: string): void; + + listen(): void; + + core: IPathCore; + + routes: IPathRoutes +} + +declare var Path: IPath; \ No newline at end of file From 37231524482452a41c4c1759d6a4e46c14dc610b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Pi=C4=85tkowski?= Date: Wed, 29 Jul 2015 14:50:45 +0200 Subject: [PATCH 066/419] Definitions for OwlCarousel Type definitions for OwlCarousel options and extenstion for jQuery interface. --- owlcarousel/owlCarousel-tests.ts | 12 +++++++ owlcarousel/owlCarousel.d.ts | 62 ++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 owlcarousel/owlCarousel-tests.ts create mode 100644 owlcarousel/owlCarousel.d.ts diff --git a/owlcarousel/owlCarousel-tests.ts b/owlcarousel/owlCarousel-tests.ts new file mode 100644 index 000000000..82190dca6 --- /dev/null +++ b/owlcarousel/owlCarousel-tests.ts @@ -0,0 +1,12 @@ +/// +/// + +$(".className").owlCarousel(); + +$(".className").owlCarousel({ + singleItem: true, + slideSpeed: 300, + paginationSpeed: 400, + lazyLoad: true, + autoPlay: 4000 +}); diff --git a/owlcarousel/owlCarousel.d.ts b/owlcarousel/owlCarousel.d.ts new file mode 100644 index 000000000..14608e39e --- /dev/null +++ b/owlcarousel/owlCarousel.d.ts @@ -0,0 +1,62 @@ +// Type definitions for OwlCarousel v.1.3.3 +// Project: https://github.com/OwlFonk/OwlCarousel +// Definitions by: Damian Piątkowski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface IOwlCarouselOptions { + + // options + items: number; + itemsDesktop: number[]; + itemsDesktopSmall: number[]; + itemsTablet: number[]; + itemsTabletSmall: any; + itemsMobile: number[]; + itemsCustom: any; + singleItem: boolean; + itemsScaleUp: boolean; + slideSpeed: number; + paginationSpeed: number; + rewindSpeed: number; + autoPlay: any; + stopOnHover: boolean; + navigation: boolean; + navigationText: any; + rewindNav: boolean; + scrollPerPage: boolean; + pagination: boolean; + paginationNumbers: boolean; + responsive: boolean; + responsiveRefreshRate: number; + responsiveBaseWidth: JQuery; + baseClass: string; + theme: string; + lazyLoad: boolean; + lazyFollow: boolean; + lazyEffect: any; + autoHeight: boolean; + jsonPath: any; + jsonSuccess: (data: any) => void; + dragBeforeAnimFinish: boolean; + mouseDrag: boolean; + touchDrag: boolean; + addClassActive: boolean; + transitionStyle: any; + + // callbacks + beforeUpdate: (params?: any) => void; + afterUpdate: (params?: any) => void; + beforeInit: (params?: any) => void; + afterInit: (params?: any) => void; + beforeMove: (params?: any) => void; + afterMove: (params?: any) => void; + afterAction: (params?: any) => void; + startDragging: (params?: any) => void; + afterLazyLoad: (params?: any) => void; +} + +interface JQuery { + owlCarousel(options?: any): JQuery; +} From 409a05355918d3ae80fac1c5e3b99024bf5a90e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Pi=C4=85tkowski?= Date: Wed, 29 Jul 2015 15:22:48 +0200 Subject: [PATCH 067/419] Rename owlCarousel-tests.ts to owlcarousel-tests.ts --- owlcarousel/{owlCarousel-tests.ts => owlcarousel-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename owlcarousel/{owlCarousel-tests.ts => owlcarousel-tests.ts} (100%) diff --git a/owlcarousel/owlCarousel-tests.ts b/owlcarousel/owlcarousel-tests.ts similarity index 100% rename from owlcarousel/owlCarousel-tests.ts rename to owlcarousel/owlcarousel-tests.ts From dba1e4eab655c92dbaae71278280d4ea4da0db46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Damian=20Pi=C4=85tkowski?= Date: Wed, 29 Jul 2015 15:23:02 +0200 Subject: [PATCH 068/419] Rename owlCarousel.d.ts to owlcarousel.d.ts --- owlcarousel/{owlCarousel.d.ts => owlcarousel.d.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename owlcarousel/{owlCarousel.d.ts => owlcarousel.d.ts} (100%) diff --git a/owlcarousel/owlCarousel.d.ts b/owlcarousel/owlcarousel.d.ts similarity index 100% rename from owlcarousel/owlCarousel.d.ts rename to owlcarousel/owlcarousel.d.ts From eb5ee58283d278adb624b4832edfde7f61940ef5 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 29 Jul 2015 14:34:47 +0100 Subject: [PATCH 069/419] Type definitions and tests for lower-case --- lower-case/lower-case-tests.ts | 9 +++++++++ lower-case/lower-case.d.ts | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 lower-case/lower-case-tests.ts create mode 100644 lower-case/lower-case.d.ts diff --git a/lower-case/lower-case-tests.ts b/lower-case/lower-case-tests.ts new file mode 100644 index 000000000..70e7a427c --- /dev/null +++ b/lower-case/lower-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import lowerCase = require('lower-case'); + +console.log(lowerCase(null)); // => "" +console.log(lowerCase('STRING')); // => "string" +console.log(lowerCase('string', 'tr')); // => "strıng" + +console.log(lowerCase({ toString: function() { return 'TEST' } })); // => "test" diff --git a/lower-case/lower-case.d.ts b/lower-case/lower-case.d.ts new file mode 100644 index 000000000..ec8aaf1fa --- /dev/null +++ b/lower-case/lower-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for lower-case +// Project: https://github.com/blakeembrey/lower-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "lower-case" { + function lowerCase(string: any, locale?: string): string; + export = lowerCase; +} \ No newline at end of file From eea06e6fe928ef0ca082c2cfef17bd636c53289a Mon Sep 17 00:00:00 2001 From: Chris Wrench Date: Wed, 29 Jul 2015 15:49:16 +0100 Subject: [PATCH 070/419] Fix definition of `google.maps.GeocoderRequest()` Fixes #4364. --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index ed7908df7..8d48758a3 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -820,7 +820,7 @@ declare module google.maps { export interface GeocoderRequest { address?: string; bounds?: LatLngBounds; - componentRestrictions: GeocoderComponentRestrictions; + componentRestrictions?: GeocoderComponentRestrictions; location?: LatLng|LatLngLiteral; region?: string; } From 8c18f7d318940a780470c703d2bd06efd3977839 Mon Sep 17 00:00:00 2001 From: benishouga Date: Thu, 30 Jul 2015 01:03:33 +0900 Subject: [PATCH 071/419] add svg attribute width and height for react element. --- react/react.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/react/react.d.ts b/react/react.d.ts index 5fbad0d22..c27d523f0 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -540,6 +540,7 @@ declare module __React { fy?: number | string; gradientTransform?: string; gradientUnits?: string; + height?: number | string; markerEnd?: string; markerMid?: string; markerStart?: string; @@ -564,6 +565,7 @@ declare module __React { transform?: string; version?: string; viewBox?: string; + width?: number | string; x1?: number | string; x2?: number | string; x?: number | string; From d2101a3f9aab5b791479e8a71b8bee6649acc2a7 Mon Sep 17 00:00:00 2001 From: Felipe Barriga Richards Date: Wed, 29 Jul 2015 13:07:45 -0300 Subject: [PATCH 072/419] lodash: added pullAt --- lodash/lodash-tests.ts | 1 + lodash/lodash.d.ts | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 877364ef0..708908b15 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -283,6 +283,7 @@ result = <_.Dictionary>_.object([['moe', 30], ['larry', 40]]); result = <_.LoDashObjectWrapper<_.Dictionary>>_([['moe', 30], ['larry', 40]]).object(); result = _.pull([1, 2, 3, 1, 2, 3], 2, 3); +result = _.pullAt([1, 2, 3, 1, 2, 3], 2, 3); result = _.range(10); result = _.range(1, 11); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7bbb65a54..97e21f893 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -1123,6 +1123,26 @@ declare module _ { ...values: any[]): any[]; } + interface LoDashStatic { + /** + * Removes all provided values from the given array using strict equality for comparisons, + * i.e. ===. + * @param array The array to modify. + * @param values The values to remove. + * @return array. + **/ + pullAt( + array: Array, + ...values: any[]): any[]; + + /** + * @see _.pull + **/ + pullAt( + array: List, + ...values: any[]): any[]; + } + //_.range interface LoDashStatic { /** From 1f81058cebc7967c01a09c38d131a5d1f6ec0612 Mon Sep 17 00:00:00 2001 From: Arnar Gauti Ingason Date: Wed, 29 Jul 2015 17:23:39 +0000 Subject: [PATCH 073/419] Adding all available options to the BrowserWindowOptions interface --- github-electron/github-electron.d.ts | 45 ++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 4e1e289ca..617f32bd9 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -456,8 +456,53 @@ declare module GitHubElectron { isVisibleOnAllWorkspaces(): boolean; } + // Includes all options BrowserWindow can take as of this writing + // http://electron.atom.io/docs/v0.29.0/api/browser-window/ interface BrowserWindowOptions extends Rectangle { show?: boolean; + 'use-content-size'?: boolean; + center?: boolean; + 'min-width'?: number; + 'min-height'?: number; + 'max-width'?: number; + 'max-height'?: number; + resizable?: boolean; + 'always-on-top'?: boolean; + fullscreen?: boolean; + 'skip-taskbar'?: boolean; + 'zoom-factor'?: number; + kiosk?: boolean; + title?: string; + icon?: NativeImage; + frame?: boolean; + 'node-integration'?: boolean; + 'accept-first-mouse'?: boolean; + 'disable-auto-hide-cursor'?: boolean; + 'auto-hide-menu-bar'?: boolean; + 'enable-larger-than-screen'?: boolean; + 'dark-theme'?: boolean; + preload?: string; + transparent?: boolean; + type?: string; + 'standard-window'?: boolean; + 'web-preferences'?: any; // Object + javascript?: boolean; + 'web-security'?: boolean; + images?: boolean; + java?: boolean; + 'text-areas-are-resizable'?: boolean; + webgl?: boolean; + webaudio?: boolean; + plugins?: boolean; + 'extra-plugin-dirs'?: string[]; + 'experimental-features'?: boolean; + 'experimental-canvas-features'?: boolean; + 'subpixel-font-scaling'?: boolean; + 'overlay-scrollbars'?: boolean; + 'overlay-fullscreen-video'?: boolean; + 'shared-worker'?: boolean; + 'direct-write'?: boolean; + 'page-visibility'?: boolean; } interface Rectangle { From 85ed51e0e3c0a0b31283dc1745194d3925e401e1 Mon Sep 17 00:00:00 2001 From: Arnar Gauti Ingason Date: Wed, 29 Jul 2015 17:38:24 +0000 Subject: [PATCH 074/419] Icon should allow NativeImage or string --- github-electron/github-electron.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 617f32bd9..c184ee7cf 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -473,7 +473,7 @@ declare module GitHubElectron { 'zoom-factor'?: number; kiosk?: boolean; title?: string; - icon?: NativeImage; + icon?: NativeImage|string; frame?: boolean; 'node-integration'?: boolean; 'accept-first-mouse'?: boolean; From 9616e043e67b01f874ec8089a065fdc4964f5857 Mon Sep 17 00:00:00 2001 From: Markus Peloso Date: Wed, 29 Jul 2015 20:26:44 +0200 Subject: [PATCH 075/419] Update sweetalert definitions to 1.1.0 --- sweetalert/sweetalert-tests.ts | 21 ++++++++++++++++++++- sweetalert/sweetalert.d.ts | 20 ++++++++++++++++++-- 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/sweetalert/sweetalert-tests.ts b/sweetalert/sweetalert-tests.ts index ca0faacbf..b6fa2aa1a 100644 --- a/sweetalert/sweetalert-tests.ts +++ b/sweetalert/sweetalert-tests.ts @@ -91,8 +91,27 @@ swal({ } ); +// With a loader (for AJAX request for example) +swal({ + title: "Ajax request example", + text: "Submit to run ajax request", + type: "info", + showCancelButton: true, + closeOnConfirm: false, + showLoaderOnConfirm: true +}, + function () { + setTimeout(function () { + swal("Ajax request finished!"); + }, 2000); + }); + swal.setDefaults({ confirmButtonColor: "#000000" }); swal.close(); -swal.showInputError("Invalid email!"); \ No newline at end of file +swal.showInputError("Invalid email!"); + +swal.disableButtons(); + +swal.enableButtons(); \ No newline at end of file diff --git a/sweetalert/sweetalert.d.ts b/sweetalert/sweetalert.d.ts index 61b643c32..ca48097f4 100644 --- a/sweetalert/sweetalert.d.ts +++ b/sweetalert/sweetalert.d.ts @@ -1,4 +1,4 @@ -// Type definitions for SweetAlert 1.0.1 +// Type definitions for SweetAlert 1.1.0 // Project: https://github.com/t4t5/sweetalert/ // Definitions by: Markus Peloso // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -62,7 +62,7 @@ declare module SweetAlert { /** * Use this to change the background color of the "Confirm"-button (must be a HEX value). - * Default: "#AEDEF4" + * Default: "#8CD4F5" */ confirmButtonColor?: string; @@ -131,6 +131,12 @@ declare module SweetAlert { * Default: null */ inputValue?: string; + + /** + * Set to true to disable the buttons and show that something is loading. + * Default: false + */ + showLoaderOnConfirm?: boolean; } interface Settings extends SettingsBase { @@ -195,5 +201,15 @@ declare module SweetAlert { * Show an error message after validating the input field, if the user's data is bad. */ showInputError(errorMessage: string): void; + + /** + * Enable the user to click on the cancel and confirm buttons. + */ + enableButtons(): void; + + /** + * Disable the user to click on the cancel and confirm buttons. + */ + disableButtons(): void; } } \ No newline at end of file From 6e4441c8d4701ba17e516f7ff87be3787647c175 Mon Sep 17 00:00:00 2001 From: Gitgiddy Date: Fri, 26 Jun 2015 10:51:32 -0400 Subject: [PATCH 076/419] Resolves #5090 --- github-electron/github-electron-main.d.ts | 383 ++++++++++-------- github-electron/github-electron-renderer.d.ts | 127 +++--- github-electron/github-electron.d.ts | 227 ++++++----- 3 files changed, 408 insertions(+), 329 deletions(-) diff --git a/github-electron/github-electron-main.d.ts b/github-electron/github-electron-main.d.ts index 0ecdbf030..a133155a9 100644 --- a/github-electron/github-electron-main.d.ts +++ b/github-electron/github-electron-main.d.ts @@ -1,10 +1,199 @@ -// Type definitions for the Electron 0.25.2 main process +// Type definitions for the Electron 0.25.2 main process // Project: http://electron.atom.io/ // Definitions by: jedmao // Definitions: https://github.com/borisyankov/DefinitelyTyped /// +declare module GitHubElectron { + interface ContentTracing { + /** + * Get a set of category groups. The category groups can change as new code paths are reached. + * @param callback Called once all child processes have acked to the getCategories request. + */ + getCategories(callback: (categoryGroups: any[]) => void): void; + /** + * Start recording on all processes. Recording begins immediately locally, and asynchronously + * on child processes as soon as they receive the EnableRecording request. + * @param categoryFilter A filter to control what category groups should be traced. + * A filter can have an optional "-" prefix to exclude category groups that contain + * a matching category. Having both included and excluded category patterns in the + * same list would not be supported. + * @param options controls what kind of tracing is enabled, it could be a OR-ed + * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING + * and tracing.RECORD_CONTINUOUSLY. + * @param callback Called once all child processes have acked to the startRecording request. + */ + startRecording(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop recording on all processes. Child processes typically are caching trace data and + * only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid + * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all + * child processes to flush any pending trace data. + * @param resultFilePath Trace data will be written into this file if it is not empty, + * or into a temporary file. + * @param callback Called once all child processes have acked to the stopRecording request. + */ + stopRecording(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data. + */ + (filePath: string) => void + ): void; + /** + * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously + * on child processes as soon as they receive the startMonitoring request. + * @param callback Called once all child processes have acked to the startMonitoring request. + */ + startMonitoring(categoryFilter: string, options: number, callback: Function): void; + /** + * Stop monitoring on all processes. + * @param callback Called once all child processes have acked to the stopMonitoring request. + */ + stopMonitoring(callback: Function): void; + /** + * Get the current monitoring traced data. Child processes typically are caching trace data + * and only rarely flush and send trace data back to the main process. That is because it may + * be an expensive operation to send the trace data over IPC, and we would like to avoid much + * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child + * processes to flush any pending trace data. + * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request. + */ + captureMonitoringSnapshot(resultFilePath: string, callback: + /** + * @param filePath A file that contains the traced data + * @returns {} + */ + (filePath: string) => void + ): void; + /** + * Get the maximum across processes of trace buffer percent full state. + * @param callback Called when the TraceBufferUsage value is determined. + */ + getTraceBufferUsage(callback: Function): void; + /** + * @param callback Called every time the given event occurs on any process. + */ + setWatchEvent(categoryName: string, eventName: string, callback: Function): void; + /** + * Cancel the watch event. If tracing is enabled, this may race with the watch event callback. + */ + cancelWatchEvent(): void; + DEFAULT_OPTIONS: number; + ENABLE_SYSTRACE: number; + ENABLE_SAMPLING: number; + RECORD_CONTINUOUSLY: number; + } + + interface Dialog { + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns an array of file paths chosen by the user, + * otherwise returns undefined. + */ + showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog; + /** + * @param callback If supplied, the API call will be asynchronous. + * @returns On success, returns the path of file chosen by the user, otherwise + * returns undefined. + */ + showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog; + /** + * Shows a message box. It will block until the message box is closed. It returns . + * @param callback If supplied, the API call will be asynchronous. + * @returns The index of the clicked button. + */ + showMessageBox: typeof GitHubElectron.Dialog.showMessageBox; + + /** + * Runs a modal dialog that shows an error message. This API can be called safely + * before the ready event of app module emits, it is usually used to report errors + * in early stage of startup. + */ + showErrorBox(title: string, content: string): void; + } + + interface GlobalShortcut { + /** + * Registers a global shortcut of accelerator. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @param callback Called when the registered shortcut is pressed by the user. + * @returns {} + */ + register(accelerator: string, callback: Function): void; + /** + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + * @returns Whether the accelerator is registered. + */ + isRegistered(accelerator: string): boolean; + /** + * Unregisters the global shortcut of keycode. + * @param accelerator Represents a keyboard shortcut. It can contain modifiers + * and key codes, combined by the "+" character. + */ + unregister(accelerator: string): void; + /** + * Unregisters all the global shortcuts. + */ + unregisterAll(): void; + } + + class RequestFileJob { + /** + * Create a request job which would query a file of path and set corresponding mime types. + */ + constructor(path: string); + } + + class RequestStringJob { + /** + * Create a request job which sends a string as response. + */ + constructor(options?: { + /** + * Default is "text/plain". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + charset?: string; + data?: string; + }); + } + + class RequestBufferJob { + /** + * Create a request job which accepts a buffer and sends a string as response. + */ + constructor(options?: { + /** + * Default is "application/octet-stream". + */ + mimeType?: string; + /** + * Default is "UTF-8". + */ + encoding?: string; + data?: Buffer; + }); + } + + interface Protocol { + registerProtocol(scheme: string, handler: (request: any) => void): void; + unregisterProtocol(scheme: string): void; + isHandledProtocol(scheme: string): boolean; + interceptProtocol(scheme: string, handler: (request: any) => void): void; + uninterceptProtocol(scheme: string): void; + RequestFileJob: typeof RequestFileJob; + RequestStringJob: typeof RequestStringJob; + RequestBufferJob: typeof RequestBufferJob; + } +} + declare module 'app' { var _app: GitHubElectron.App; export = _app; @@ -21,138 +210,18 @@ declare module 'browser-window' { } declare module 'content-tracing' { - /** - * Get a set of category groups. The category groups can change as new code paths are reached. - * @param callback Called once all child processes have acked to the getCategories request. - */ - export function getCategories(callback: (categoryGroups: any[]) => void): void; - /** - * Start recording on all processes. Recording begins immediately locally, and asynchronously - * on child processes as soon as they receive the EnableRecording request. - * @param categoryFilter A filter to control what category groups should be traced. - * A filter can have an optional "-" prefix to exclude category groups that contain - * a matching category. Having both included and excluded category patterns in the - * same list would not be supported. - * @param options controls what kind of tracing is enabled, it could be a OR-ed - * combination of tracing.DEFAULT_OPTIONS, tracing.ENABLE_SYSTRACE, tracing.ENABLE_SAMPLING - * and tracing.RECORD_CONTINUOUSLY. - * @param callback Called once all child processes have acked to the startRecording request. - */ - export function startRecording(categoryFilter: string, options: number, callback: Function): void; - /** - * Stop recording on all processes. Child processes typically are caching trace data and - * only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid - * much runtime overhead of tracing. So, to end tracing, we must asynchronously ask all - * child processes to flush any pending trace data. - * @param resultFilePath Trace data will be written into this file if it is not empty, - * or into a temporary file. - * @param callback Called once all child processes have acked to the stopRecording request. - */ - export function stopRecording(resultFilePath: string, callback: - /** - * @param filePath A file that contains the traced data. - */ - (filePath: string) => void - ): void; - /** - * Start monitoring on all processes. Monitoring begins immediately locally, and asynchronously - * on child processes as soon as they receive the startMonitoring request. - * @param callback Called once all child processes have acked to the startMonitoring request. - */ - export function startMonitoring(categoryFilter: string, options: number, callback: Function): void; - /** - * Stop monitoring on all processes. - * @param callback Called once all child processes have acked to the stopMonitoring request. - */ - export function stopMonitoring(callback: Function): void; - /** - * Get the current monitoring traced data. Child processes typically are caching trace data - * and only rarely flush and send trace data back to the main process. That is because it may - * be an expensive operation to send the trace data over IPC, and we would like to avoid much - * runtime overhead of tracing. So, to end tracing, we must asynchronously ask all child - * processes to flush any pending trace data. - * @param callback Called once all child processes have acked to the captureMonitoringSnapshot request. - */ - export function captureMonitoringSnapshot(resultFilePath: string, callback: - /** - * @param filePath A file that contains the traced data - * @returns {} - */ - (filePath: string) => void - ): void; - /** - * Get the maximum across processes of trace buffer percent full state. - * @param callback Called when the TraceBufferUsage value is determined. - */ - export function getTraceBufferUsage(callback: Function): void; - /** - * @param callback Called every time the given event occurs on any process. - */ - export function setWatchEvent(categoryName: string, eventName: string, callback: Function): void; - /** - * Cancel the watch event. If tracing is enabled, this may race with the watch event callback. - */ - export function cancelWatchEvent(): void; - export var DEFAULT_OPTIONS: number; - export var ENABLE_SYSTRACE: number; - export var ENABLE_SAMPLING: number; - export var RECORD_CONTINUOUSLY: number; + var contentTracing: GitHubElectron.ContentTracing + export = contentTracing; } declare module 'dialog' { - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns an array of file paths chosen by the user, - * otherwise returns undefined. - */ - export var showOpenDialog: typeof GitHubElectron.Dialog.showOpenDialog; - /** - * @param callback If supplied, the API call will be asynchronous. - * @returns On success, returns the path of file chosen by the user, otherwise - * returns undefined. - */ - export var showSaveDialog: typeof GitHubElectron.Dialog.showSaveDialog; - /** - * Shows a message box. It will block until the message box is closed. It returns . - * @param callback If supplied, the API call will be asynchronous. - * @returns The index of the clicked button. - */ - export var showMessageBox: typeof GitHubElectron.Dialog.showMessageBox; - - /** - * Runs a modal dialog that shows an error message. This API can be called safely - * before the ready event of app module emits, it is usually used to report errors - * in early stage of startup. - */ - export function showErrorBox(title: string, content: string): void; + var dialog: GitHubElectron.Dialog + export = dialog; } declare module 'global-shortcut' { - /** - * Registers a global shortcut of accelerator. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @param callback Called when the registered shortcut is pressed by the user. - * @returns {} - */ - export function register(accelerator: string, callback: Function): void; - /** - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - * @returns Whether the accelerator is registered. - */ - export function isRegistered(accelerator: string): boolean; - /** - * Unregisters the global shortcut of keycode. - * @param accelerator Represents a keyboard shortcut. It can contain modifiers - * and key codes, combined by the "+" character. - */ - export function unregister(accelerator: string): void; - /** - * Unregisters all the global shortcuts. - */ - export function unregisterAll(): void; + var globalShortcut: GitHubElectron.GlobalShortcut; + export = globalShortcut; } declare module 'ipc' { @@ -176,52 +245,26 @@ declare module 'power-monitor' { } declare module 'protocol' { - export function registerProtocol(scheme: string, handler: (request: any) => void): void; - export function unregisterProtocol(scheme: string): void; - export function isHandledProtocol(scheme: string): boolean; - export function interceptProtocol(scheme: string, handler: (request: any) => void): void; - export function uninterceptProtocol(scheme: string): void; - export class RequestFileJob { - /** - * Create a request job which would query a file of path and set corresponding mime types. - */ - constructor(path: string); - } - export class RequestStringJob { - /** - * Create a request job which sends a string as response. - */ - constructor(options?: { - /** - * Default is "text/plain". - */ - mimeType?: string; - /** - * Default is "UTF-8". - */ - charset?: string; - data?: string; - }); - } - export class RequestBufferJob { - /** - * Create a request job which accepts a buffer and sends a string as response. - */ - constructor(options?: { - /** - * Default is "application/octet-stream". - */ - mimeType?: string; - /** - * Default is "UTF-8". - */ - encoding?: string; - data?: Buffer; - }); - } + var protocol: GitHubElectron.Protocol; + export = protocol; } declare module 'tray' { var Tray: typeof GitHubElectron.Tray; export = Tray; } + +interface NodeRequireFunction { + (id: 'app'): GitHubElectron.App + (id: 'auto-updater'): GitHubElectron.AutoUpdater + (id: 'browser-window'): typeof GitHubElectron.BrowserWindow + (id: 'content-tracing'): GitHubElectron.ContentTracing + (id: 'dialog'): GitHubElectron.Dialog + (id: 'global-shortcut'): GitHubElectron.GlobalShortcut + (id: 'ipc'): NodeJS.EventEmitter + (id: 'menu'): typeof GitHubElectron.Menu + (id: 'menu-item'): typeof GitHubElectron.MenuItem + (id: 'power-monitor'): NodeJS.EventEmitter + (id: 'protocol'): GitHubElectron.Protocol + (id: 'tray'): typeof GitHubElectron.Tray +} diff --git a/github-electron/github-electron-renderer.d.ts b/github-electron/github-electron-renderer.d.ts index e2a310d28..2fff2bb34 100644 --- a/github-electron/github-electron-renderer.d.ts +++ b/github-electron/github-electron-renderer.d.ts @@ -1,4 +1,4 @@ -// Type definitions for the Electron 0.25.2 renderer process (web page) +// Type definitions for the Electron 0.25.2 renderer process (web page) // Project: http://electron.atom.io/ // Definitions by: jedmao // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,8 +6,7 @@ /// declare module GitHubElectron { - - class InProcess implements NodeJS.EventEmitter { + export class InProcess implements NodeJS.EventEmitter { addListener(event: string, listener: Function): InProcess; on(event: string, listener: Function): InProcess; once(event: string, listener: Function): InProcess; @@ -37,69 +36,81 @@ declare module GitHubElectron { sendToHost(channel: string, ...args: any[]): void; } - module Remote { - export function getCurrentWindow(): BrowserWindow; + interface Remote { + /** + * @returns The object returned by require(module) in the main process. + */ + require(module: string): any; + /** + * @returns The BrowserWindow object which this web page belongs to. + */ + getCurrentWindow(): BrowserWindow + /** + * @returns The global variable of name (e.g. global[name]) in the main process. + */ + getGlobal(name: string): any; + /** + * Returns the process object in the main process. This is the same as + * remote.getGlobal('process'), but gets cached. + */ + process: any; + } + + interface WebFrame { + /** + * Changes the zoom factor to the specified factor, zoom factor is + * zoom percent / 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * @returns The current zoom factor. + */ + getZoomFactor(): number; + /** + * Changes the zoom level to the specified level, 0 is "original size", and each + * increment above or below represents zooming 20% larger or smaller to default + * limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; + /** + * @returns The current zoom level. + */ + getZoomLevel(): number; + /** + * Sets a provider for spell checking in input fields and text areas. + */ + setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { + /** + * @returns Whether the word passed is correctly spelled. + */ + spellCheck: (text: string) => boolean; + }): void; + /** + * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content + * warnings. For example, https and data are secure schemes because they cannot be + * corrupted by active network attackers. + */ + registerUrlSchemeAsSecure(scheme: string): void; } } declare module 'ipc' { - var InProcess: GitHubElectron.InProcess; - export = InProcess; + var inProcess: GitHubElectron.InProcess; + export = inProcess; } declare module 'remote' { - /** - * @returns The object returned by require(module) in the main process. - */ - export function require(module: string): any; - /** - * @returns The BrowserWindow object which this web page belongs to. - */ - export var getCurrentWindow: typeof GitHubElectron.Remote.getCurrentWindow; - /** - * @returns The global variable of name (e.g. global[name]) in the main process. - */ - export function getGlobal(name: string): any; - /** - * Returns the process object in the main process. This is the same as - * remote.getGlobal('process'), but gets cached. - */ - export var process: any; + var remote: GitHubElectron.Remote; + export = remote; } declare module 'web-frame' { - /** - * Changes the zoom factor to the specified factor, zoom factor is - * zoom percent / 100, so 300% = 3.0. - */ - export function setZoomFactor(factor: number): void; - /** - * @returns The current zoom factor. - */ - export function getZoomFactor(): number; - /** - * Changes the zoom level to the specified level, 0 is "original size", and each - * increment above or below represents zooming 20% larger or smaller to default - * limits of 300% and 50% of original size, respectively. - */ - export function setZoomLevel(level: number): void; - /** - * @returns The current zoom level. - */ - export function getZoomLevel(): number; - /** - * Sets a provider for spell checking in input fields and text areas. - */ - export function setSpellCheckProvider(language: string, autoCorrectWord: boolean, provider: { - /** - * @returns Whether the word passed is correctly spelled. - */ - spellCheck: (text: string) => boolean; - }): void; - /** - * Sets the scheme as secure scheme. Secure schemes do not trigger mixed content - * warnings. For example, https and data are secure schemes because they cannot be - * corrupted by active network attackers. - */ - export function registerUrlSchemeAsSecure(scheme: string): void; + var webframe: GitHubElectron.WebFrame; + export = webframe; +} + +interface NodeRequireFunction { + (id: 'ipc'): GitHubElectron.InProcess + (id: 'remote'): GitHubElectron.Remote + (id: 'web-frame'): GitHubElectron.WebFrame } diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 4e1e289ca..7b5d7c898 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron 0.25.2 (shared between main and rederer processes) +// Type definitions for Electron 0.25.2 (shared between main and rederer processes) // Project: http://electron.atom.io/ // Definitions by: jedmao // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -1131,123 +1131,159 @@ declare module GitHubElectron { */ setContextMenu(menu: Menu): void; } -} -declare module 'clipboard' { - /** - * @returns The contents of the clipboard as plain text. - */ - export function readText(type?: string): string; - /** - * Writes the text into the clipboard as plain text. - */ - export function writeText(text: string, type?: string): void; - /** - * @returns The contents of the clipboard as a NativeImage. - */ - export var readImage: typeof GitHubElectron.Clipboard.readImage; - /** - * Writes the image into the clipboard. - */ - export var writeImage: typeof GitHubElectron.Clipboard.writeImage; - /** - * Clears everything in clipboard. - */ - export function clear(type?: string): void; - /** - * Note: This API is experimental and could be removed in future. - * @returns Whether the clipboard has data in the specified format. - */ - export function has(format: string, type?: string): boolean; - /** - * Reads the data in the clipboard of the specified format. - * Note: This API is experimental and could be removed in future. - */ - export function read(format: string, type?: string): any; -} - -declare module 'crash-reporter' { - export function start(options?: { + interface Clipboard { /** - * Default: Electron + * @returns The contents of the clipboard as plain text. */ + readText(type?: string): string; + /** + * Writes the text into the clipboard as plain text. + */ + writeText(text: string, type?: string): void; + /** + * @returns The contents of the clipboard as a NativeImage. + */ + readImage: typeof GitHubElectron.Clipboard.readImage; + /** + * Writes the image into the clipboard. + */ + writeImage: typeof GitHubElectron.Clipboard.writeImage; + /** + * Clears everything in clipboard. + */ + clear(type?: string): void; + /** + * Note: This API is experimental and could be removed in future. + * @returns Whether the clipboard has data in the specified format. + */ + has(format: string, type?: string): boolean; + /** + * Reads the data in the clipboard of the specified format. + * Note: This API is experimental and could be removed in future. + */ + read(format: string, type?: string): any; + } + + interface CrashReporterStartOptions { + /** + * Default: Electron + */ productName?: string; /** - * Default: GitHub, Inc. - */ + * Default: GitHub, Inc. + */ companyName?: string; /** - * URL that crash reports would be sent to as POST. - * Default: http://54.249.141.255:1127/post - */ + * URL that crash reports would be sent to as POST. + * Default: http://54.249.141.255:1127/post + */ submitUrl?: string; /** - * Send the crash report without user interaction. - * Default: true. - */ + * Send the crash report without user interaction. + * Default: true. + */ autoSubmit?: boolean; /** - * Default: false. - */ + * Default: false. + */ ignoreSystemCrashHandler?: boolean; /** - * An object you can define which content will be send along with the report. - * Only string properties are send correctly. - * Nested objects are not supported. - */ + * An object you can define which content will be send along with the report. + * Only string properties are send correctly. + * Nested objects are not supported. + */ extra?: {} - }): void; - - /** - * @returns The date and ID of the last crash report. When there was no crash report - * sent or the crash reporter is not started, null will be returned. - */ - export function getLastCrashReport(): CrashReporterPayload; - + } + interface CrashReporterPayload extends Object { /** - * E.g., "electron-crash-service". - */ + * E.g., "electron-crash-service". + */ rept: string; /** - * The version of Electron. - */ + * The version of Electron. + */ ver: string; /** - * E.g., "win32". - */ + * E.g., "win32". + */ platform: string; /** - * E.g., "renderer". - */ + * E.g., "renderer". + */ process_type: string; ptime: number; /** - * The version in package.json. - */ + * The version in package.json. + */ _version: string; /** - * The product name in the crashReporter options object. - */ + * The product name in the crashReporter options object. + */ _productName: string; /** - * Name of the underlying product. In this case, Electron. - */ + * Name of the underlying product. In this case, Electron. + */ prod: string; /** - * The company name in the crashReporter options object. - */ + * The company name in the crashReporter options object. + */ _companyName: string; /** - * The crashreporter as a file. - */ + * The crashreporter as a file. + */ upload_file_minidump: File; } + + interface CrashReporter { + start(options?: CrashReporterStartOptions): void; + + /** + * @returns The date and ID of the last crash report. When there was no crash report + * sent or the crash reporter is not started, null will be returned. + */ + getLastCrashReport(): CrashReporterPayload; + } + + interface Shell{ + /** + * Show the given file in a file manager. If possible, select the file. + */ + showItemInFolder(fullPath: string): void; + /** + * Open the given file in the desktop's default manner. + */ + openItem(fullPath: string): void; + /** + * Open the given external protocol URL in the desktop's default manner + * (e.g., mailto: URLs in the default mail user agent). + */ + openExternal(url: string): void; + /** + * Move the given file to trash and returns boolean status for the operation. + */ + moveItemToTrash(fullPath: string): void; + /** + * Play the beep sound. + */ + beep(): void; + } +} + +declare module 'clipboard' { + var clipboard: GitHubElectron.Clipboard + export = clipboard; +} + +declare module 'crash-reporter' { + var crashReporter: GitHubElectron.CrashReporter + export = crashReporter; } declare module 'native-image' { - var NativeImage: typeof GitHubElectron.NativeImage; - export = NativeImage; + var nativeImage: typeof GitHubElectron.NativeImage; + export = nativeImage; } declare module 'screen' { @@ -1256,27 +1292,8 @@ declare module 'screen' { } declare module 'shell' { - /** - * Show the given file in a file manager. If possible, select the file. - */ - export function showItemInFolder(fullPath: string): void; - /** - * Open the given file in the desktop's default manner. - */ - export function openItem(fullPath: string): void; - /** - * Open the given external protocol URL in the desktop's default manner - * (e.g., mailto: URLs in the default mail user agent). - */ - export function openExternal(url: string): void; - /** - * Move the given file to trash and returns boolean status for the operation. - */ - export function moveItemToTrash(fullPath: string): void; - /** - * Play the beep sound. - */ - export function beep(): void; + var shell: GitHubElectron.Shell; + export = shell; } interface Window { @@ -1293,3 +1310,11 @@ interface File { */ path: string; } + +interface NodeRequireFunction { + (id: 'clipboard'): GitHubElectron.Clipboard + (id: 'crash-reporter'): GitHubElectron.CrashReporter + (id: 'native-image'): typeof GitHubElectron.NativeImage + (id: 'screen'): GitHubElectron.Screen + (id: 'shell'): GitHubElectron.Shell +} From cea9fd521881137df498e929fbd4a22959ad2d28 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Wed, 29 Jul 2015 12:37:41 -0700 Subject: [PATCH 077/419] Couple of fixes and deprecations in ESTree --- estree/estree.d.ts | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/estree/estree.d.ts b/estree/estree.d.ts index 329396b7c..be60f8dbf 100644 --- a/estree/estree.d.ts +++ b/estree/estree.d.ts @@ -22,7 +22,7 @@ declare module ESTree { } interface Program extends Node { - body: Array; + body: Array; sourceType: string; } @@ -72,7 +72,6 @@ declare module ESTree { interface SwitchStatement extends Statement { discriminant: Expression; cases: Array; - lexical: boolean; } interface ReturnStatement extends Statement { @@ -215,7 +214,6 @@ declare module ESTree { interface CatchClause extends Node { param: Pattern; - guard: any; body: BlockStatement; } @@ -227,7 +225,7 @@ declare module ESTree { value?: string | boolean | number | RegExp; } - interface RegexLiteral extends Literal { + interface RegExpLiteral extends Literal { regex: { pattern: string; flags: string; @@ -258,6 +256,7 @@ declare module ESTree { interface YieldExpression extends Expression { argument?: Expression; + delegate: boolean; } interface TemplateLiteral extends Expression { @@ -312,7 +311,7 @@ declare module ESTree { } interface MethodDefinition extends Node { - key: Identifier; + key: Expression; value: FunctionExpression; kind: string; computed: boolean; @@ -330,40 +329,40 @@ declare module ESTree { property: Identifier; } - interface ImportDeclaration extends Node { + interface ModuleDeclaration extends Node {} + + interface ModuleSpecifier extends Node { + local: Identifier; + } + + interface ImportDeclaration extends ModuleDeclaration { specifiers: Array; source: Literal; } - interface ImportSpecifier { + interface ImportSpecifier extends ModuleSpecifier { imported: Identifier; - local: Identifier; } - interface ImportDefaultSpecifier { - local: Identifier; - } + interface ImportDefaultSpecifier extends ModuleSpecifier {} - interface ImportNamespaceSpecifier { - local: Identifier; - } + interface ImportNamespaceSpecifier extends ModuleSpecifier {} - interface ExportNamedDeclaration extends Node { + interface ExportNamedDeclaration extends ModuleDeclaration { declaration?: Declaration; specifiers: Array; source?: Literal; } - interface ExportSpecifier { + interface ExportSpecifier extends ModuleSpecifier { exported: Identifier; - local: Identifier; } - interface ExportDefaultDeclaration extends Node { + interface ExportDefaultDeclaration extends ModuleDeclaration { declaration: Declaration | Expression; } - interface ExportAllDeclaration extends Node { + interface ExportAllDeclaration extends ModuleDeclaration { source: Literal; } -} \ No newline at end of file +} From e4119e7bd75c7177ce076bef4816b1d561aaf3ec Mon Sep 17 00:00:00 2001 From: Roland Hummel Date: Wed, 29 Jul 2015 22:35:39 +0200 Subject: [PATCH 078/419] Making optional parameter optional angular.translate.ITranslateProvider has the method useLoader that can be invoked with just one parameter, too (see http://angular-translate.github.io/docs/#/guide/13_custom-loaders#customer-loaders_make-use-of-a-custom-loader) --- angular-translate/angular-translate.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-translate/angular-translate.d.ts b/angular-translate/angular-translate.d.ts index 1abb13ae8..ab4c1db5f 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -93,7 +93,7 @@ declare module angular.translate { storageKey(key: string): void; // JeroMiya - the library should probably return ITranslateProvider but it doesn't here useUrlLoader(url: string): ITranslateProvider; useStaticFilesLoader(options: IStaticFilesLoaderOptions): ITranslateProvider; - useLoader(loaderFactory: string, options: any): ITranslateProvider; + useLoader(loaderFactory: string, options?: any): ITranslateProvider; useLocalStorage(): ITranslateProvider; useCookieStorage(): ITranslateProvider; useStorage(storageFactory: any): ITranslateProvider; From ee173f2819fed5bd49d06c5d16ffc4922c180c23 Mon Sep 17 00:00:00 2001 From: Roland Hummel Date: Wed, 29 Jul 2015 22:58:58 +0200 Subject: [PATCH 079/419] Updating test so that it also invokes useLoader. --- angular-translate/angular-translate-tests.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/angular-translate/angular-translate-tests.ts b/angular-translate/angular-translate-tests.ts index cc02a85d6..c60247f42 100644 --- a/angular-translate/angular-translate-tests.ts +++ b/angular-translate/angular-translate-tests.ts @@ -2,6 +2,14 @@ var app = angular.module('at', ['pascalprecht.translate']); +app.factory('customLoader', ($q:angular.IQService) => { + return (options:any) => { + var dfd:angular.IDeferred = $q.defer(); + dfd.resolve('whatever you wanted to translate, I simply know nothing about the language with the key ' + options.key); + return dfd.promise; + } +}); + app.config(($translateProvider: angular.translate.ITranslateProvider) => { $translateProvider.translations('en', { TITLE: 'Hello', @@ -16,6 +24,8 @@ app.config(($translateProvider: angular.translate.ITranslateProvider) => { BUTTON_LANG_DE: 'deutsch' }); $translateProvider.preferredLanguage('en'); + + $translateProvider.useLoader('customLoader'); }); interface Scope extends ng.IScope { From 5606d32acba302ec8f60c80b0dc44dc9a5e4f573 Mon Sep 17 00:00:00 2001 From: "stephen.lautier" Date: Wed, 29 Jul 2015 23:09:20 +0200 Subject: [PATCH 080/419] eq.js - fixed issue with tests not pointing to eq.js correctly --- eq.js/eq.js.tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/eq.js/eq.js.tests.ts b/eq.js/eq.js.tests.ts index 1113604f2..4a2192bec 100644 --- a/eq.js/eq.js.tests.ts +++ b/eq.js/eq.js.tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var nodes = document.getElementsByClassName(".test-container"); From a040564265873ef9bb2dad983e477741c7325671 Mon Sep 17 00:00:00 2001 From: Matt Bailey Date: Wed, 29 Jul 2015 15:53:24 -0700 Subject: [PATCH 081/419] Fix compiler warning for Bloodhound constructor Typescript 1.5.3 compiler flags the constructor's lack of a trailing semicolon. --- typeahead/typeahead.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typeahead/typeahead.d.ts b/typeahead/typeahead.d.ts index d377bf75b..159caaacd 100644 --- a/typeahead/typeahead.d.ts +++ b/typeahead/typeahead.d.ts @@ -352,7 +352,7 @@ declare module Bloodhound } declare class Bloodhound { - constructor(options: Bloodhound.BloodhoundOptions) + constructor(options: Bloodhound.BloodhoundOptions); /** * wraps the suggestion engine in an adapter that is compatible with the typeahead jQuery plugin */ From 330c17f6b6d31a224a5d376dd28976f1887b3b7b Mon Sep 17 00:00:00 2001 From: Lee Avital Date: Fri, 24 Jul 2015 11:06:22 -0400 Subject: [PATCH 082/419] Update plottable typings to plottable 1.4 --- plottable/plottable.d.ts | 89 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 87 insertions(+), 2 deletions(-) diff --git a/plottable/plottable.d.ts b/plottable/plottable.d.ts index 683f8397a..bdf968e96 100644 --- a/plottable/plottable.d.ts +++ b/plottable/plottable.d.ts @@ -1,10 +1,9 @@ -// Type definitions for Plottable v1.2.0 +// Type definitions for Plottable v1.4.0 // Project: http://plottablejs.org/ // Definitions by: Plottable Team // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -/// declare module Plottable { module Utils { @@ -601,6 +600,15 @@ declare module Plottable { declare module Plottable { type Formatter = (d: any) => string; + /** + * This field is deprecated and will be removed in v2.0.0. + * + * The number of milliseconds between midnight one day and the next is + * not a fixed quantity. + * + * Use date.setDate(date.getDate() + number_of_days) instead. + * + */ var MILLISECONDS_IN_ONE_DAY: number; module Formatters { /** @@ -1085,6 +1093,7 @@ declare module Plottable { constructor(scaleType?: string); extentOfValues(values: string[]): string[]; protected _getExtent(): string[]; + static invalidateColorCache(): void; /** * Returns the color-string corresponding to a given string. * If there are not enough colors in the range(), a lightened version of an existing color will be used. @@ -1697,6 +1706,8 @@ declare module Plottable { */ formatter(formatter: Formatter): Axis; /** + * @deprecated As of release 1.3, replaced by innerTickLength() + * * Gets the tick mark length in pixels. */ tickLength(): number; @@ -1707,6 +1718,17 @@ declare module Plottable { * @returns {Axis} The calling Axis. */ tickLength(length: number): Axis; + /** + * Gets the tick mark length in pixels. + */ + innerTickLength(): number; + /** + * Sets the tick mark length in pixels. + * + * @param {number} length + * @returns {Axis} The calling Axis. + */ + innerTickLength(length: number): Axis; /** * Gets the end tick mark length in pixels. */ @@ -2557,6 +2579,17 @@ declare module Plottable { * @returns {Pie} The calling Pie Plot. */ labelsEnabled(enabled: boolean): Pie; + /** + * Gets the Formatter for the labels. + */ + labelFormatter(): Formatter; + /** + * Sets the Formatter for the labels. + * + * @param {Formatter} formatter + * @returns {Pie} The calling Pie Plot. + */ + labelFormatter(formatter: Formatter): Pie; entitiesAt(queryPoint: Point): PlotEntity[]; protected _propertyProjectors(): AttributeToProjector; protected _getDataToDraw(): Utils.Map; @@ -2691,6 +2724,8 @@ declare module Plottable { [attr: string]: (datum: any, index: number, dataset: Dataset) => any; }; protected _generateDrawSteps(): Drawers.DrawStep[]; + protected _updateExtentsForProperty(property: string): void; + protected _filterForProperty(property: string): (datum: any, index: number, dataset: Dataset) => boolean; /** * Gets the AccessorScaleBinding for X. */ @@ -3111,6 +3146,8 @@ declare module Plottable { constructor(); protected _createDrawer(dataset: Dataset): Drawers.Segment; protected _generateDrawSteps(): Drawers.DrawStep[]; + protected _updateExtentsForProperty(property: string): void; + protected _filterForProperty(property: string): (datum: any, index: number, dataset: Dataset) => boolean; /** * Gets the AccessorScaleBinding for X */ @@ -3181,6 +3218,46 @@ declare module Plottable { } +declare module Plottable { + module Plots { + class Waterfall extends Bar { + constructor(); + /** + * Gets whether connectors are enabled. + * + * @returns {boolean} Whether connectors should be shown or not. + */ + connectorsEnabled(): boolean; + /** + * Sets whether connectors are enabled. + * + * @param {boolean} enabled + * @returns {Plots.Waterfall} The calling Waterfall Plot. + */ + connectorsEnabled(enabled: boolean): Waterfall; + /** + * Gets the AccessorScaleBinding for whether a bar represents a total or a delta. + */ + total(): Plots.AccessorScaleBinding; + /** + * Sets total to a constant number or the result of an Accessor + * + * @param {Accessor} + * @returns {Plots.Waterfall} The calling Waterfall Plot. + */ + total(total: Accessor): Waterfall; + protected _additionalPaint(time: number): void; + protected _createNodesForDataset(dataset: Dataset): Drawer; + protected _extentsForProperty(attr: string): any[]; + protected _generateAttrToProjector(): { + [attr: string]: (datum: any, index: number, dataset: Dataset) => any; + }; + protected _onDatasetUpdate(): Waterfall; + } + } +} + + declare module Plottable { interface Animator { /** @@ -3993,6 +4070,14 @@ declare module Plottable { * Gets the internal Interactions.Drag of the DragBoxLayer. */ dragInteraction(): Interactions.Drag; + /** + * Enables or disables the interaction and drag box. + */ + enabled(enabled: boolean): DragBoxLayer; + /** + * Gets the enabled state. + */ + enabled(): boolean; } } } From d8dc5313d895cf55d3fec1c6c777163d3f49c50c Mon Sep 17 00:00:00 2001 From: Eric Pelz Date: Mon, 27 Jul 2015 13:51:19 -0700 Subject: [PATCH 083/419] Add definitions for React DnD Adding React DnD type definitions for React DnD v1.1.4, which is the latest version. Paired with @vsiao on parts of this --- react-dnd/react-dnd-test.ts | 260 ++++++++++++++++++++++++++++++++++++ react-dnd/react-dnd.d.ts | 172 ++++++++++++++++++++++++ 2 files changed, 432 insertions(+) create mode 100644 react-dnd/react-dnd-test.ts create mode 100644 react-dnd/react-dnd.d.ts diff --git a/react-dnd/react-dnd-test.ts b/react-dnd/react-dnd-test.ts new file mode 100644 index 000000000..244144029 --- /dev/null +++ b/react-dnd/react-dnd-test.ts @@ -0,0 +1,260 @@ +/// +"use strict"; + +// Test adapted from the ReactDnD chess game tutorial: +// http://gaearon.github.io/react-dnd/docs-tutorial.html + +import React = require("react"); +import ReactDnd = require("react-dnd"); + +var r = React.DOM; + +import DragSource = ReactDnd.DragSource; +import DropTarget = ReactDnd.DropTarget; +import DragDropContext = ReactDnd.DragDropContext; +import HTML5Backend = require('react-dnd/modules/backends/HTML5'); + +// Game Component +// ---------------------------------------------------------------------- + +module Game { + var knightPosition = [0, 0]; + var observer: any = null; + + function emitChange() { + observer(knightPosition); + } + + export function observe(o: any) { + if (observer) { + throw new Error("Multiple observers not implemented."); + } + + observer = o; + emitChange(); + } + + export function moveKnight(toX: number, toY: number) { + knightPosition = [toX, toY]; + emitChange(); + } + + export function canMoveKnight(toX: number, toY: number) { + const x = knightPosition[0]; + const y = knightPosition[1]; + const dx = toX - x; + const dy = toY - y; + + return (Math.abs(dx) === 2 && Math.abs(dy) === 1) || + (Math.abs(dx) === 1 && Math.abs(dy) === 2); + } +} + +var ItemTypes = { + KNIGHT: "knight" +}; + +// Knight Component +// ---------------------------------------------------------------------- + +module Knight { + interface KnightP extends React.Props { + connectDragSource: ReactDnd.ConnectDragSource; + connectDragPreview: ReactDnd.ConnectDragPreview; + isDragging: boolean; + } + + var knightSource: ReactDnd.DragSourceSpec = { + beginDrag: (props) => { + return {}; + } + }; + + function knightCollect(connect: ReactDnd.DragSourceConnector, monitor: ReactDnd.DragSourceMonitor) { + return { + connectDragSource: connect.dragSource(), + connectDragPreview: connect.dragPreview(), + isDragging: monitor.isDragging() + }; + } + + export class Knight extends React.Component { + static create = React.createFactory(Knight); + + componentDidMount() { + var img = HTML5Backend.getEmptyImage(); + img.onload = () => this.props.connectDragPreview(img); + } + + render() { + return this.props.connectDragSource( + r.div({ + style: { + opacity: this.props.isDragging ? 0.5 : 1, + fontSize: 25, + fontWeight: 'bold', + cursor: 'move' + } + }, "♘") + ); + } + } + + export var DndKnight = DragSource(ItemTypes.KNIGHT, knightSource, knightCollect)(Knight); + export var create = React.createFactory(DndKnight); +} + +// Square Component +// ---------------------------------------------------------------------- + +module Square { + interface SquareP extends React.Props { + black: boolean; + } + + export class Square extends React.Component { + render() { + var fill = this.props.black ? 'black' : 'white'; + return r.div({ + style: { + backgroundColor: fill + } + }) + } + } + + export var create = React.createFactory(Square); +} + +// BoardSquare Component +// ---------------------------------------------------------------------- + +module BoardSquare { + interface BoardSquareP extends React.Props { + x: number; + y: number; + connectDropTarget?: ReactDnd.ConnectDropTarget; + isOver?: boolean; + canDrop?: boolean; + } + + var boardSquareTarget: ReactDnd.DropTargetSpec = { + canDrop: (props) => Game.canMoveKnight(props.x, props.y), + drop: (props) => Game.moveKnight(props.x, props.y) + }; + + function boardSquareCollect(connect: ReactDnd.DropTargetConnector, monitor: ReactDnd.DropTargetMonitor) { + return { + connectDropTarget: connect.dropTarget(), + isOver: monitor.isOver(), + canDrop: monitor.canDrop() + }; + } + + export class BoardSquare extends React.Component { + private _renderOverlay = (color: string) => { + return r.div({ + style: { + position: 'absolute', + top: 0, + left: 0, + height: '100%', + width: '100%', + zIndex: 1, + opacity: 0.5, + backgroundColor: color + } + }); + }; + + render() { + var black = (this.props.x + this.props.y) % 2 === 1; + var isOver = this.props.isOver; + var canDrop = this.props.canDrop; + + return this.props.connectDropTarget( + r.div({ + style: { + position: 'relative', + width: '100%', + height: '100%' + }, + children: [ + Square.create({ + black: black + }), + isOver && !canDrop ? this._renderOverlay('red') : null, + !isOver && canDrop ? this._renderOverlay('yellow') : null, + isOver && canDrop ? this._renderOverlay('green') : null + ] + }) + ); + } + } + + export var DndBoardSquare = DropTarget(ItemTypes.KNIGHT, boardSquareTarget, boardSquareCollect)(BoardSquare); + export var create = React.createFactory(DndBoardSquare); +} + +// Board Component +// ---------------------------------------------------------------------- + +module Board { + interface BoardP extends React.Props { + knightPosition: number[]; + } + + export class Board extends React.Component { + private _renderPiece = (x: number, y: number) => { + var knightX = this.props.knightPosition[0]; + var knightY = this.props.knightPosition[1]; + return x === knightX && y === knightY ? + Knight.create() : + null; + }; + + private _renderSquare = (i: number) => { + var x = i % 8; + var y = Math.floor(i / 8); + + return r.div({ + key: i, + style: { + width: '12.5%', + height: '12.5%' + } + }, BoardSquare.create({ + x: x, + y: y + }, this._renderPiece(x, y))); + }; + + render() { + var squares: React.DOMElement[] = []; + for (let i = 0; i < 64; i++) { + squares.push(this._renderSquare(i)); + } + + return r.div({ + style: { + width: '100%', + height: '100%', + display: 'flex', + flexWrap: 'wrap' + }, + children: squares + }); + } + } + + var DndBoard = DragDropContext(HTML5Backend)(Board); + export var create = React.createFactory(DndBoard); +} + + +// Render the Board Component +// ---------------------------------------------------------------------- + +Board.create({ + knightPosition: [0, 0] +}); diff --git a/react-dnd/react-dnd.d.ts b/react-dnd/react-dnd.d.ts new file mode 100644 index 000000000..86eab01cd --- /dev/null +++ b/react-dnd/react-dnd.d.ts @@ -0,0 +1,172 @@ +// Type definitions for React DnD v1.1.4 +// Project: https://github.com/gaearon/react-dnd +// Definitions by: Asana +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module __ReactDnd { + import React = __React; + + // Decorated React Components + // ---------------------------------------------------------------------- + + class ContextComponent extends React.Component { + getDecoratedComponentInstance(): React.Component; + // Note: getManager is not yet documented on the React DnD docs. + getManager(): any; + } + + class DndComponent extends React.Component { + getDecoratedComponentInstance(): React.Component; + getHandlerId(): Identifier; + } + + interface ContextComponentClass

    extends React.ComponentClass

    { + new(props?: P, context?: any): ContextComponent; + DecoratedComponent: React.ComponentClass

    ; + } + + interface DndComponentClass

    extends React.ComponentClass

    { + new(props?: P, context?: any): DndComponent; + DecoratedComponent: React.ComponentClass

    ; + } + + // Top-level API + // ---------------------------------------------------------------------- + + export function DragSource

    ( + type: Identifier | ((props: P) => Identifier), + spec: DragSourceSpec

    , + collect: (connect: DragSourceConnector, monitor: DragSourceMonitor) => Object, + options?: DndOptions

    + ): (componentClass: React.ComponentClass

    ) => DndComponentClass

    ; + + export function DropTarget

    ( + types: Identifier | Identifier[] | ((props: P) => Identifier | Identifier[]), + spec: DropTargetSpec

    , + collect: (connect: DropTargetConnector, monitor: DropTargetMonitor) => Object, + options?: DndOptions

    + ): (componentClass: React.ComponentClass

    ) => DndComponentClass

    ; + + export function DragDropContext

    ( + backend: Backend + ): (componentClass: React.ComponentClass

    ) => ContextComponentClass

    ; + + // TODO: Add exported function for DragLayer. + // The React DnD docs say that this is an advanced feature that is only + // necessary when performing custom rendering or when using a custom + // backend. + + // Shared + // ---------------------------------------------------------------------- + + // The React DnD docs say that this can also be the ES6 Symbol. + type Identifier = string; + + interface ClientOffset { + x: number; + y: number; + } + + interface DndOptions

    { + arePropsEqual?(props: P, otherProps: P): boolean; + } + + // DragSource + // ---------------------------------------------------------------------- + + interface DragSourceSpec

    { + beginDrag(props: P, monitor?: DragSourceMonitor, component?: React.Component): Object; + endDrag?(props: P, monitor?: DragSourceMonitor, component?: React.Component): void; + canDrag?(props: P, monitor?: DragSourceMonitor): boolean; + isDragging?(props: P, monitor?: DragSourceMonitor): boolean; + } + + class DragSourceMonitor { + canDrag(): boolean; + isDragging(): boolean; + getItemType(): Identifier; + getItem(): Object; + getDropResult(): Object; + didDrop(): boolean; + getInitialClientOffset(): ClientOffset; + getInitialSourceClientOffset(): ClientOffset; + getClientOffset(): ClientOffset; + getDifferenceFromInitialOffset(): ClientOffset; + getSourceClientOffset(): ClientOffset; + } + + class DragSourceConnector { + dragSource(): ConnectDragSource; + dragPreview(): ConnectDragPreview; + } + + interface DragElementWrapper { +

    (elementOrNode: React.ReactElement

    , options?: O): React.ReactElement

    ; + } + + interface DragSourceOptions { + dropEffect?: string; + } + + interface DragPreviewOptions { + captureDraggingState?: boolean; + anchorX?: number; + anchorY?: number; + } + + type ConnectDragSource = DragElementWrapper; + type ConnectDragPreview = DragElementWrapper; + + /// DropTarget + // ---------------------------------------------------------------------- + + interface DropTargetSpec

    { + drop?(props: P, monitor?: DropTargetMonitor, component?: React.Component): Object|void; + hover?(props: P, monitor?: DropTargetMonitor, component?: React.Component): void; + canDrop?(props: P, monitor?: DropTargetMonitor): boolean; + } + + class DropTargetMonitor { + canDrop(): boolean; + isOver(options?: { shallow: boolean }): boolean; + getItemType(): Identifier; + getItem(): Object; + getDropResult(): Object; + didDrop(): boolean; + getInitialClientOffset(): ClientOffset; + getInitialSourceClientOffset(): ClientOffset; + getClientOffset(): ClientOffset; + getDifferenceFromInitialOffset(): ClientOffset; + getSourceClientOffset(): ClientOffset; + } + + class DropTargetConnector { + dropTarget(): ConnectDropTarget; + } + + type ConnectDropTarget =

    (elementOrNode: React.ReactElement

    ) => React.ReactElement

    ; + + /// Backend + /// --------------------------------------------------------------------- + + // TODO: Fill in the Backend interface. + // The React DnD docs do not cover this, and this is only needed for + // creating custom backends (i.e. not using the built-in HTML5Backend). + interface Backend {} +} + +declare module "react-dnd" { + export = __ReactDnd; +} + +declare module "react-dnd/modules/backends/HTML5" { + enum _NativeTypes { FILE, URL, TEXT } + class HTML5Backend implements __ReactDnd.Backend { + static getEmptyImage(): any; // Image + static NativeTypes: _NativeTypes; + } + + export = HTML5Backend; +} From f9694258d2d2923c4c185a7c8a64df1ce8b4baa8 Mon Sep 17 00:00:00 2001 From: Lokesh Peta Date: Thu, 30 Jul 2015 09:54:07 +0100 Subject: [PATCH 084/419] rename to pathjs --- pathjs/{path-tests.ts => pathjs-tests.ts} | 2 +- pathjs/{path.d.ts => pathjs.d.ts} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename pathjs/{path-tests.ts => pathjs-tests.ts} (90%) rename pathjs/{path.d.ts => pathjs.d.ts} (93%) diff --git a/pathjs/path-tests.ts b/pathjs/pathjs-tests.ts similarity index 90% rename from pathjs/path-tests.ts rename to pathjs/pathjs-tests.ts index 1a3607a63..5ff4ce5da 100644 --- a/pathjs/path-tests.ts +++ b/pathjs/pathjs-tests.ts @@ -1,4 +1,4 @@ -/// +/// Path.map("/test/:id") .to(()=>{ }); diff --git a/pathjs/path.d.ts b/pathjs/pathjs.d.ts similarity index 93% rename from pathjs/path.d.ts rename to pathjs/pathjs.d.ts index 133bd5fc0..1760b04e6 100644 --- a/pathjs/path.d.ts +++ b/pathjs/pathjs.d.ts @@ -1,5 +1,5 @@ // Type definitions for Pathjs v0.8.4 -// Project: https://github.com/mtrpcic/pathjs/blob/master/path.js +// Project: https://github.com/mtrpcic/pathjs // Definitions by: Lokesh Peta // Definitions: https://github.com/borisyankov/DefinitelyTyped From 524d202369461c3e4b7895e747bd845c02c93a50 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 30 Jul 2015 10:47:52 +0100 Subject: [PATCH 085/419] Type definitions and tests for lower-case-first --- lower-case-first/lower-case-first-tests.ts | 7 +++++++ lower-case-first/lower-case-first.d.ts | 9 +++++++++ 2 files changed, 16 insertions(+) create mode 100644 lower-case-first/lower-case-first-tests.ts create mode 100644 lower-case-first/lower-case-first.d.ts diff --git a/lower-case-first/lower-case-first-tests.ts b/lower-case-first/lower-case-first-tests.ts new file mode 100644 index 000000000..dc21393c3 --- /dev/null +++ b/lower-case-first/lower-case-first-tests.ts @@ -0,0 +1,7 @@ +/// + +import lowerCaseFirst = require('lower-case-first'); + +console.log(lowerCaseFirst(null)); // => "" +console.log(lowerCaseFirst('STRING')); // => "sTRING" + diff --git a/lower-case-first/lower-case-first.d.ts b/lower-case-first/lower-case-first.d.ts new file mode 100644 index 000000000..8dd865bf6 --- /dev/null +++ b/lower-case-first/lower-case-first.d.ts @@ -0,0 +1,9 @@ +// Type definitions for lower-case-first +// Project: https://github.com/blakeembrey/lower-case-first +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "lower-case-first" { + function lowerCaseFirst(string: string, locale?: string): string; + export = lowerCaseFirst; +} From a79c116814eb47881451e79b3da3880ec2c2122b Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Thu, 30 Jul 2015 10:49:11 +0100 Subject: [PATCH 086/419] Type definitions and tests for lower-case-first --- lower-case-first/lower-case-first.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lower-case-first/lower-case-first.d.ts b/lower-case-first/lower-case-first.d.ts index 8dd865bf6..a6abc1bc1 100644 --- a/lower-case-first/lower-case-first.d.ts +++ b/lower-case-first/lower-case-first.d.ts @@ -6,4 +6,4 @@ declare module "lower-case-first" { function lowerCaseFirst(string: string, locale?: string): string; export = lowerCaseFirst; -} +} \ No newline at end of file From b6ec9468136c266c93dd542ddc78dd88f406618f Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 17:16:20 +0100 Subject: [PATCH 087/419] Mark hasListener as returning a boolean --- chrome/chrome.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 1df792b42..660ea64bd 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -869,7 +869,7 @@ declare module chrome.events { addListener(callback: Function): void; getRules(callback: (rules: Rule[]) => void): void; getRules(ruleIdentifiers: string[], callback: (rules: Rule[]) => void): void; - hasListener(callback: Function): void; + hasListener(callback: Function): boolean; removeRules(ruleIdentifiers?: string[], callback?: Function): void; addRules(rules: Rule[], callback?: (rules: Rule[]) => void): void; removeListener(callback: Function): void; From e0438708cfda11de3f112aa892a840cb94dc6488 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 17:30:20 +0100 Subject: [PATCH 088/419] Remove non-existent _.last overloads, add _().last chainable form --- lodash/lodash-tests.ts | 7 +--- lodash/lodash.d.ts | 86 ++++-------------------------------------- 2 files changed, 8 insertions(+), 85 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 877364ef0..d9a27fb2c 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -263,12 +263,7 @@ result = _.initial(foodsType, { 'type': 'vegetable' }); result = _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); result = _.last([1, 2, 3]); -result = _.last([1, 2, 3], 2); -result = _.last([1, 2, 3], function (num) { - return num > 1; -}); -result = _.last(foodsOrganic, 'organic'); -result = _.last(foodsType, { 'type': 'vegetable' }); +result = _([1, 2, 3]).last(); result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); result = _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7bbb65a54..5d658853d 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -991,90 +991,18 @@ declare module _ { //_.last interface LoDashStatic { /** - * Gets the last element or last n elements of an array. If a callback is provided - * elements at the end of the array are returned as long as the callback returns truey. - * The callback is bound to thisArg and invoked with three arguments; (value, index, array). - * - * If a property name is provided for callback the created "_.pluck" style callback will - * return the property value of the given element. - * - * If an object is provided for callback the created "_.where" style callback will return - * true for elements that have the properties of the given object, else false. + * Gets the last element of an array. * @param array The array to query. - * @return Returns the last element(s) of array. + * @return Returns the last element of array. **/ last(array: Array): T; + } + interface LoDashArrayWrapper { /** - * @see _.last - **/ - last(array: List): T; - - /** - * @see _.last - * @param n The number of elements to return - **/ - last( - array: Array, - n: number): T[]; - - /** - * @see _.last - * @param n The number of elements to return - **/ - last( - array: List, - n: number): T[]; - - /** - * @see _.last - * @param callback The function called per element - **/ - last( - array: Array, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.last - * @param callback The function called per element - **/ - last( - array: List, - callback: ListIterator, - thisArg?: any): T[]; - - /** - * @see _.last - * @param pluckValue _.pluck style callback - **/ - last( - array: Array, - pluckValue: string): T[]; - - /** - * @see _.last - * @param pluckValue _.pluck style callback - **/ - last( - array: List, - pluckValue: string): T[]; - - /** - * @see _.last - * @param whereValue _.where style callback - **/ - last( - array: Array, - whereValue: W): T[]; - - /** - * @see _.last - * @param whereValue _.where style callback - **/ - last( - array: List, - whereValue: W): T[]; + * @see _.last + **/ + last(): T; } //_.lastIndexOf From d7637bf1a687afbea36ac198d03d1fd2c66bb53e Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 17:58:20 +0100 Subject: [PATCH 089/419] Add resemble.js types --- resemble/resemble-tests.ts | 32 ++++++++++++++++++ resemble/resemble.d.ts | 66 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+) create mode 100644 resemble/resemble-tests.ts create mode 100644 resemble/resemble.d.ts diff --git a/resemble/resemble-tests.ts b/resemble/resemble-tests.ts new file mode 100644 index 000000000..d79637d47 --- /dev/null +++ b/resemble/resemble-tests.ts @@ -0,0 +1,32 @@ +resemble.outputSettings({ + errorColor: { + red: 255, + green: 0, + blue: 255 + }, + errorType: 'movement', + transparency: 0.3, + largeImageThreshold: 1200 +}); + +resemble("images/image.png").onComplete(function(data) { + var r: number = data.red; + var g: number = data.green; + var b: number = data.blue; + var brightness: number = data.brightness; +}); + +resemble("images/image.png").compareTo("images/image2.png").onComplete(function(data) { + var diffImageDataUrl: string = data.getImageDataUrl(); + var difference: number = data.misMatchPercentage; +}); + +resemble("images/image2.png").compareTo("images/image2.png") + .ignoreAntialiasing() + .ignoreColors() + .repaint() + .onComplete(function(data) { + var diffImageDataUrl: string = data.getImageDataUrl(); + var difference: number = data.misMatchPercentage; +}); + diff --git a/resemble/resemble.d.ts b/resemble/resemble.d.ts new file mode 100644 index 000000000..c10209e07 --- /dev/null +++ b/resemble/resemble.d.ts @@ -0,0 +1,66 @@ +// Type definitions for Resemble.js v1.3.0 +// Project: http://huddle.github.io/Resemble.js/ +// Definitions by: Tim Perry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Resemble { + interface ResembleStatic { + (image: string|ImageData): ResembleAnalysis; + outputSettings(settings: OutputSettings): ResembleStatic; + } + + interface OutputSettings { + errorColor: { + red: number; + green: number; + blue: number; + }; + errorType: string; + transparency: number; + largeImageThreshold: number; + } + + interface ResembleAnalysis { + onComplete(callback: (result: ResembleAnalysisResult) => void): void; + compareTo(fileData: string|ImageData): ResembleComparison; + } + + interface ResembleAnalysisResult { + red: number; + green: number; + blue: number; + brightness: number; + } + + interface ResembleComparison { + onComplete(callback: (result: ResembleComparisonResult) => void): void; + + ignoreNothing(): ResembleComparison; + ignoreAntialiasing(): ResembleComparison; + ignoreColors(): ResembleComparison; + repaint(): ResembleComparison; + + } + + interface ResembleComparisonResult { + isSameDimensions: boolean; + dimensionDifference: { + width: number, + height: number + }; + + getImageDataUrl(): string; + + misMatchPercentage: number; + diffBounds: { + top: number, + left: number, + bottom: number; + right: number; + }; + + analysisTime: number; + } +} + +declare var resemble: Resemble.ResembleStatic; From 17a1e3d27b58493087c2ea5e168b7f470e6d537f Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 18:15:21 +0100 Subject: [PATCH 090/419] Fix resemble tests --- resemble/resemble-tests.ts | 2 ++ resemble/resemble.d.ts | 8 ++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/resemble/resemble-tests.ts b/resemble/resemble-tests.ts index d79637d47..163903fef 100644 --- a/resemble/resemble-tests.ts +++ b/resemble/resemble-tests.ts @@ -1,3 +1,5 @@ +/// + resemble.outputSettings({ errorColor: { red: 255, diff --git a/resemble/resemble.d.ts b/resemble/resemble.d.ts index c10209e07..7d5ad27d1 100644 --- a/resemble/resemble.d.ts +++ b/resemble/resemble.d.ts @@ -45,16 +45,16 @@ declare module Resemble { interface ResembleComparisonResult { isSameDimensions: boolean; dimensionDifference: { - width: number, - height: number + width: number; + height: number; }; getImageDataUrl(): string; misMatchPercentage: number; diffBounds: { - top: number, - left: number, + top: number; + left: number; bottom: number; right: number; }; From 6e3410f0476284ea72e913eb10d2f635dcf77b81 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Thu, 30 Jul 2015 10:26:04 -0700 Subject: [PATCH 091/419] [CodeMirror] Add onchanges that triggers on a per operation basis. cf doc for this event: http://codemirror.net/doc/manual.html#event_changes --- codemirror/codemirror.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 198eaa0a4..2feaab080 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -326,6 +326,16 @@ declare module CodeMirror { /** Fires every time the content of the editor is changed. */ on(eventName: 'change', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList) => void ): void; off(eventName: 'change', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList) => void ): void; + + + /** Like the "change" event, but batched per operation, passing an + * array containing all the changes that happened in the operation. + * This event is fired after the operation finished, and display + * changes it makes will trigger a new operation. */ + on(eventName: 'changes', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList[]) => void ): void; + off(eventName: 'changes', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList[]) => void ): void; + + /** This event is fired before a change is applied, and its handler may choose to modify or cancel the change. The changeObj never has a next property, since this is fired for each individual change, and not batched per operation. From e37796c642232a220e5f063d4b8b9b9c3b3a7904 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Thu, 30 Jul 2015 13:34:47 -0400 Subject: [PATCH 092/419] templateUrl accepts one parameter docs: https://github.com/angular-ui/ui-router/wiki#templates --- angular-ui-router/angular-ui-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index ed2f36ccf..803b414ad 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -16,7 +16,7 @@ declare module angular.ui { /** * String URL path to template file OR Function, returns URL path string */ - templateUrl?: string | {(): string}; + templateUrl?: string | {(IStateParamsService?): string}; /** * Function, returns HTML content string */ From 691392cfca3ea2d419fce9471a0439f7cfb28c51 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Thu, 30 Jul 2015 13:38:12 -0400 Subject: [PATCH 093/419] Spelling fixes --- angular-ui-router/angular-ui-router.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 803b414ad..c82fb51d6 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -53,12 +53,12 @@ declare module angular.ui { abstract?: boolean; /** * Callback function for when a state is entered. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. */ onEnter?: Function|(string|Function)[]; /** * Callback functions for when a state is entered and exited. Good way to trigger an action or dispatch an event, such as opening a dialog. - * If minifying your scripts, make sure to explictly annotate this function, because it won't be automatically annotated by your build tools. + * If minifying your scripts, make sure to explicitly annotate this function, because it won't be automatically annotated by your build tools. */ onExit?: Function|(string|Function)[]; /** @@ -66,7 +66,7 @@ declare module angular.ui { */ data?: any; /** - * Boolean (default true). If false will not retrigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. + * Boolean (default true). If false will not re-trigger the same state just because a search/query parameter has changed. Useful for when you'd like to modify $location.search() without triggering a reload. */ reloadOnSearch?: boolean; } From 90551f00c5bc9a1b2c5a4a112a2db7d17dcb866f Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Thu, 30 Jul 2015 13:44:45 -0400 Subject: [PATCH 094/419] Updating tests --- angular-ui-router/angular-ui-router-tests.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/angular-ui-router/angular-ui-router-tests.ts b/angular-ui-router/angular-ui-router-tests.ts index a43f9e9bc..6dae1c085 100644 --- a/angular-ui-router/angular-ui-router-tests.ts +++ b/angular-ui-router/angular-ui-router-tests.ts @@ -50,7 +50,7 @@ myApp.config(( .state('state1.list', { url: "/list", templateUrl: "partials/state1.list.html", - controller: function ($scope: MyAppScope) { + controller: function ($scope: MyAppScope) { $scope.items = ["A", "List", "Of", "Items"]; } }) @@ -61,7 +61,7 @@ myApp.config(( .state('state2.list', { url: "/list", templateUrl: "partials/state2.list.html", - controller: function ($scope: MyAppScope) { + controller: function ($scope: MyAppScope) { $scope.things = ["A", "Set", "Of", "Things"]; } }) @@ -70,7 +70,14 @@ myApp.config(( url: "/list", templateUrl: "partials/state3.list.html", controller: function ($scope: MyAppScope) { - $scope.things = ["A", "Set", "Of", "Things"]; + $scope.things = ["A", "Set", "Of", "Things"]; + } + }) + .state('state4', { + url: "/state4", + templateUrl: function($stateParams: ng.ui.IStateParamsService){ + //Logic could go here based on $stateParams + return "partials/state4.html"; } }) .state('index', { From 6e43da89b9a2f0b8e4966d2fac4577bba526ea84 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Thu, 30 Jul 2015 13:49:48 -0400 Subject: [PATCH 095/419] Trying to fix CI build - maybe the ? is throwing it off? --- angular-ui-router/angular-ui-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index c82fb51d6..256342ea5 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -16,7 +16,7 @@ declare module angular.ui { /** * String URL path to template file OR Function, returns URL path string */ - templateUrl?: string | {(IStateParamsService?): string}; + templateUrl?: string | {(IStateParamsService): string}; /** * Function, returns HTML content string */ From fb1410b421d11cd7b2b02fccd1ad1069526cbc56 Mon Sep 17 00:00:00 2001 From: Chris Barr Date: Thu, 30 Jul 2015 13:54:38 -0400 Subject: [PATCH 096/419] Oh right, I've gotta name the param and assign it a type! --- angular-ui-router/angular-ui-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts index 256342ea5..85bada50b 100644 --- a/angular-ui-router/angular-ui-router.d.ts +++ b/angular-ui-router/angular-ui-router.d.ts @@ -16,7 +16,7 @@ declare module angular.ui { /** * String URL path to template file OR Function, returns URL path string */ - templateUrl?: string | {(IStateParamsService): string}; + templateUrl?: string | {(params: IStateParamsService): string}; /** * Function, returns HTML content string */ From f37f807a413c2dae116745929ae6cdf70d0bbfbe Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 18:49:19 +0100 Subject: [PATCH 097/419] Add sinon-chrome type definitions --- sinon-chrome/sinon-chrome-tests.ts | 34 ++ sinon-chrome/sinon-chrome.d.ts | 548 +++++++++++++++++++++++++++++ 2 files changed, 582 insertions(+) create mode 100644 sinon-chrome/sinon-chrome-tests.ts create mode 100644 sinon-chrome/sinon-chrome.d.ts diff --git a/sinon-chrome/sinon-chrome-tests.ts b/sinon-chrome/sinon-chrome-tests.ts new file mode 100644 index 000000000..1b714fb4e --- /dev/null +++ b/sinon-chrome/sinon-chrome-tests.ts @@ -0,0 +1,34 @@ +/// + +var chromeStub = window.chrome; + +// Examples taken from https://github.com/vitalets/sinon-chrome: + +chromeStub.tabs.query({}, function(tabs: any) { + chromeStub.browserAction.setBadgeText({text: String(tabs.length)}); +}); + +chromeStub.tabs.query.yields(JSON.parse("[]")); + +sinon.assert.calledOnce(chromeStub.browserAction.setBadgeText); +sinon.assert.calledWithMatch(chromeStub.browserAction.setBadgeText, { + text: "2" +}); + +chromeStub.tabs.onCreated.trigger({url: 'http://google.com'}); + +chromeStub.tabs.onUpdated.applyTrigger([1, {status: "complete"}, {id: 1, url: 'http://google.com'}]); + +// Extended examples: + +var calledOnce: boolean = chromeStub.browserAction.setBadgeText.calledOnce; +var calledWithMatch: boolean = chromeStub.browserAction.setBadgeText.calledWithMatch({text: "2"}); + +chromeStub.storage.local.get.yields({}); +chromeStub.storage.onChanged.trigger(); +chromeStub.alarms.onAlarm.trigger(); + +var id: string = chromeStub.runtime.id; + +chromeStub.proxy.settings.set({value: { }, scope: 'regular'}); +chromeStub.proxy.settings.onChange.trigger(); diff --git a/sinon-chrome/sinon-chrome.d.ts b/sinon-chrome/sinon-chrome.d.ts new file mode 100644 index 000000000..eddb32be4 --- /dev/null +++ b/sinon-chrome/sinon-chrome.d.ts @@ -0,0 +1,548 @@ +// Type definitions for Sinon-Chrome v0.2.1 +// Project: https://github.com/vitalets/sinon-chrome +// Definitions by: Tim Perry +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +/** + * To use sinon-chrome: + * Use chrome.* as normal in your production code + * In tests, forcibly cast window.chrome to typeof SinonChrome to access stub API. + * @example + * var chrome = window.chrome; + * chrome.storage.onChanged.trigger(...); + */ +declare module SinonChrome { + /** + * Flush cache + */ + export function flush(): void; + + /** + * Reset all stubs and remove event listeners + * See https://github.com/cjohansen/Sinon.JS/issues/572 + */ + export function reset(): void; + + export var csi: Sinon.SinonSpy; + export var loadTimes: Sinon.SinonSpy; +} + +declare module SinonChrome.events { + interface Event extends chrome.events.Event { + trigger(...args: any[]): void; + triggerAsync(...args: any[]): void; + + applyTrigger(args: any[]): void; + applyTriggerAsync(args: any[]): void; + + addListener: Sinon.SinonSpy; + removeListener: Sinon.SinonSpy; + removeListeners: Sinon.SinonSpy; + hasListener: Sinon.SinonSpy; + } +} + +declare module SinonChrome.alarms { + export var clear: Sinon.SinonSpy; + export var clearAll: Sinon.SinonSpy; + export var create: Sinon.SinonSpy; + export var get: Sinon.SinonSpy; + export var getAll: Sinon.SinonSpy; + export var onAlarm: SinonChrome.events.Event; +} + +declare module SinonChrome.app { + export var getDetails: Sinon.SinonStub; + export var getDetailsForFrame: Sinon.SinonStub; + export var getDetails: Sinon.SinonStub; + export var getDetailsForFrame: Sinon.SinonStub; + export var getIsInstalled: Sinon.SinonStub; + export var installState: Sinon.SinonStub; + export var runningState: Sinon.SinonStub; +} + +declare module SinonChrome.bookmarks { + export var create: Sinon.SinonStub; + export var get: Sinon.SinonStub; + export var getChildren: Sinon.SinonStub; + export var getRecent: Sinon.SinonStub; + export var getSubTree: Sinon.SinonStub; + export var getTree: Sinon.SinonStub; + export var move: Sinon.SinonStub; + export var remove: Sinon.SinonStub; + export var removeTree: Sinon.SinonStub; + export var search: Sinon.SinonStub; + export var update: Sinon.SinonStub; + + export var onChanged: SinonChrome.events.Event; + export var onChildrenReordered: SinonChrome.events.Event; + export var onCreated: SinonChrome.events.Event; + export var onImportBegan: SinonChrome.events.Event; + export var onImportEnded: SinonChrome.events.Event; + export var onMoved: SinonChrome.events.Event; + export var onRemoved: SinonChrome.events.Event; +} + +declare module SinonChrome.browserAction { + export var disable: Sinon.SinonStub; + export var enable: Sinon.SinonStub; + export var getBadgeBackgroundColor: Sinon.SinonStub; + export var getBadgeText: Sinon.SinonStub; + export var getPopup: Sinon.SinonStub; + export var getTitle: Sinon.SinonStub; + export var setBadgeBackgroundColor: Sinon.SinonStub; + export var setBadgeText: Sinon.SinonStub; + export var setIcon: Sinon.SinonStub; + export var setPopup: Sinon.SinonStub; + export var setTitle: Sinon.SinonStub; + + export var onClicked: SinonChrome.events.Event; +} + +declare module SinonChrome.browsingData { + export var remove: Sinon.SinonStub; + export var removeAppcache: Sinon.SinonStub; + export var removeCache: Sinon.SinonStub; + export var removeCookies: Sinon.SinonStub; + export var removeDownloads: Sinon.SinonStub; + export var removeFileSystems: Sinon.SinonStub; + export var removeFormData: Sinon.SinonStub; + export var removeHistory: Sinon.SinonStub; + export var removeIndexedDB: Sinon.SinonStub; + export var removeLocalStorage: Sinon.SinonStub; + export var removePasswords: Sinon.SinonStub; + export var removePluginData: Sinon.SinonStub; + export var removeWebSQL: Sinon.SinonStub; + export var settings: Sinon.SinonStub; +} + +declare module SinonChrome.contentSettings { + interface StubbedContentSetting { + clear: Sinon.SinonStub; + get: Sinon.SinonStub; + getResourceIdentifiers: Sinon.SinonStub; + set: Sinon.SinonStub; + } + + export var cookies: StubbedContentSetting; + export var images: StubbedContentSetting; + export var javascript: StubbedContentSetting; + export var notifications: StubbedContentSetting; + export var plugins: StubbedContentSetting; + export var popups: StubbedContentSetting; +} + +declare module SinonChrome.contextMenus { + export var create: Sinon.SinonStub; + export var remove: Sinon.SinonStub; + export var removeAll: Sinon.SinonStub; + export var update: Sinon.SinonStub; + + export var onClicked: SinonChrome.events.Event; +} + +declare module SinonChrome.omnibox { + export var setDefaultSuggestion: Sinon.SinonStub; + export var onInputStarted: SinonChrome.events.Event; + export var onInputChanged: SinonChrome.events.Event; + export var onInputEntered: SinonChrome.events.Event; + export var onInputCancelled: SinonChrome.events.Event; +} + +declare module SinonChrome.cookies { + export var get: Sinon.SinonStub; + export var getAll: Sinon.SinonStub; + export var getAllCookieStores: Sinon.SinonStub; + export var onChanged: SinonChrome.events.Event; + export var remove: Sinon.SinonStub; + export var set: Sinon.SinonStub; +} + +declare module "SinonChrome.debugger" { + export var attach: Sinon.SinonStub; + export var detach: Sinon.SinonStub; + export var getTargets: Sinon.SinonStub; + export var sendCommand: Sinon.SinonStub; + + export var onDetach: SinonChrome.events.Event; + export var onEvent: SinonChrome.events.Event; +} + +declare module SinonChrome.declarativeContent { + export var PageStateMatcher: Sinon.SinonStub; + export var RequestContentScript: Sinon.SinonStub; + export var ShowPageAction: Sinon.SinonStub; + + export var onPageChanged: SinonChrome.events.Event; +} + +declare module SinonChrome. desktopCapture { + export var cancelChooseDesktopMedia: Sinon.SinonStub; + export var chooseDesktopMedia: Sinon.SinonStub; +} + +declare module SinonChrome.downloads { + export var acceptDanger: Sinon.SinonStub; + export var cancel: Sinon.SinonStub; + export var download: Sinon.SinonStub; + export var drag: Sinon.SinonStub; + export var erase: Sinon.SinonStub; + export var getFileIcon: Sinon.SinonStub; + export var open: Sinon.SinonStub; + export var pause: Sinon.SinonStub; + export var removeFile: Sinon.SinonStub; + export var resume: Sinon.SinonStub; + export var search: Sinon.SinonStub; + export var setShelfEnabled: Sinon.SinonStub; + export var show: Sinon.SinonStub; + export var showDefaultFolder: Sinon.SinonStub; + + export var onChanged: SinonChrome.events.Event; + export var onCreated: SinonChrome.events.Event; + export var onDeterminingFilename: SinonChrome.events.Event; + export var onErased: SinonChrome.events.Event; +} + +declare module SinonChrome.extension { + export var connect: Sinon.SinonStub; + export var connectNative: Sinon.SinonStub; + export var getBackgroundPage: Sinon.SinonStub; + export var getURL: Sinon.SinonStub; + export var getViews: Sinon.SinonStub; + export var isAllowedFileSchemeAccess: Sinon.SinonStub; + export var isAllowedIncognitoAccess: Sinon.SinonStub; + export var sendMessage: Sinon.SinonStub; + export var sendNativeMessage: Sinon.SinonStub; + export var sendRequest: Sinon.SinonStub; + export var setUpdateUrlData: Sinon.SinonStub; + + export var onConnect: SinonChrome.events.Event; + export var onConnectExternal: SinonChrome.events.Event; + export var onMessage: SinonChrome.events.Event; + export var onMessageExternal: SinonChrome.events.Event; + export var onRequest: SinonChrome.events.Event; + export var onRequestExternal: SinonChrome.events.Event; +} + +declare module SinonChrome.fontSettings { + export var clearDefaultFixedFontSize: Sinon.SinonStub; + export var clearDefaultFontSize: Sinon.SinonStub; + export var clearFont: Sinon.SinonStub; + export var clearMinimumFontSize: Sinon.SinonStub; + export var getDefaultFixedFontSize: Sinon.SinonStub; + export var getDefaultFontSize: Sinon.SinonStub; + export var getFont: Sinon.SinonStub; + export var getFontList: Sinon.SinonStub; + export var getMinimumFontSize: Sinon.SinonStub; + export var setDefaultFixedFontSize: Sinon.SinonStub; + export var setDefaultFontSize: Sinon.SinonStub; + export var setFont: Sinon.SinonStub; + export var setMinimumFontSize: Sinon.SinonStub; + + export var onDefaultFixedFontSizeChanged: SinonChrome.events.Event; + export var onDefaultFontSizeChanged: SinonChrome.events.Event; + export var onFontChanged: SinonChrome.events.Event; + export var onMinimumFontSizeChanged: SinonChrome.events.Event; +} + +declare module SinonChrome.gcm { + export var onMessage: SinonChrome.events.Event; + export var onMessagesDeleted: SinonChrome.events.Event; + export var onSendError: SinonChrome.events.Event; + + export var register: Sinon.SinonStub; + export var send: Sinon.SinonStub; + export var unregister: Sinon.SinonStub; +} + +declare module SinonChrome.history { + export var addUrl: Sinon.SinonStub; + export var deleteAll: Sinon.SinonStub; + export var deleteRange: Sinon.SinonStub; + export var deleteUrl: Sinon.SinonStub; + export var getVisits: Sinon.SinonStub; + export var search: Sinon.SinonStub; + + export var onVisitRemoved: SinonChrome.events.Event; + export var onVisited: SinonChrome.events.Event; +} + +declare module SinonChrome.i18n { + export var getAcceptLanguages: Sinon.SinonStub; + export var getMessage: Sinon.SinonStub; + export var getUILanguage: Sinon.SinonStub; +} + +declare module SinonChrome.identity { + export var getAuthToken: Sinon.SinonStub; + export var getProfileUserInfo: Sinon.SinonStub; + export var getRedirectURL: Sinon.SinonStub; + export var launchWebAuthFlow: Sinon.SinonStub; + export var removeCachedAuthToken: Sinon.SinonStub; + + export var onSignInChanged: SinonChrome.events.Event; +} + +declare module SinonChrome.idle { + export var onStateChanged: SinonChrome.events.Event; + + export var queryState: Sinon.SinonStub; + export var setDetectionInterval: Sinon.SinonStub; +} + +declare module SinonChrome.management { + export var createAppShortcut: Sinon.SinonStub; + export var generateAppForLink: Sinon.SinonStub; + export var get: Sinon.SinonStub; + export var getAll: Sinon.SinonStub; + export var getPermissionWarningsById: Sinon.SinonStub; + export var getPermissionWarningsByManifest: Sinon.SinonStub; + export var launchApp: Sinon.SinonStub; + export var setEnabled: Sinon.SinonStub; + export var setLaunchType: Sinon.SinonStub; + export var uninstall: Sinon.SinonStub; + export var uninstallSelf: Sinon.SinonStub; + + export var onDisabled: SinonChrome.events.Event; + export var onEnabled: SinonChrome.events.Event; + export var onInstalled: SinonChrome.events.Event; + export var onUninstalled: SinonChrome.events.Event; +} + +declare module SinonChrome.notifications { + export var clear: Sinon.SinonStub; + export var create: Sinon.SinonStub; + export var getAll: Sinon.SinonStub; + export var getPermissionLevel: Sinon.SinonStub; + export var update: Sinon.SinonStub; + + export var onButtonClicked: SinonChrome.events.Event; + export var onClicked: SinonChrome.events.Event; + export var onClosed: SinonChrome.events.Event; + export var onPermissionLevelChanged: SinonChrome.events.Event; + export var onShowSettings: SinonChrome.events.Event; +} + +declare module SinonChrome.pageCapture { + export var saveAsMHTML: Sinon.SinonStub; +} + +declare module SinonChrome.permissions { + export var contains: Sinon.SinonStub; + export var getAll: Sinon.SinonStub; + export var onAdded: SinonChrome.events.Event; + export var onRemoved: SinonChrome.events.Event; + export var remove: Sinon.SinonStub; + export var request: Sinon.SinonStub; +} + +declare module SinonChrome.power { + export var releaseKeepAwake: Sinon.SinonStub; + export var requestKeepAwake: Sinon.SinonStub; +} + +declare module SinonChrome.types { + interface StubbedChromeSetting { + clear: Sinon.SinonStub; + get: Sinon.SinonStub; + set: Sinon.SinonStub; + + onChange: SinonChrome.events.Event; + } +} + +declare module SinonChrome.privacy { + export var network: { + networkPredictionEnabled: SinonChrome.types.StubbedChromeSetting; + }; + export var services: { + alternateErrorPagesEnabled: SinonChrome.types.StubbedChromeSetting; + autofillEnabled: SinonChrome.types.StubbedChromeSetting; + passwordSavingEnabled: SinonChrome.types.StubbedChromeSetting; + safeBrowsingEnabled: SinonChrome.types.StubbedChromeSetting; + searchSuggestEnabled: SinonChrome.types.StubbedChromeSetting; + spellingServiceEnabled: SinonChrome.types.StubbedChromeSetting; + translationServiceEnabled: SinonChrome.types.StubbedChromeSetting; + }; + export var website: { + hyperlinkAuditingEnabled: SinonChrome.types.StubbedChromeSetting; + referrersEnabled: SinonChrome.types.StubbedChromeSetting; + thirdPartyCookiesAllowed: SinonChrome.types.StubbedChromeSetting; + }; +} + +declare module SinonChrome.proxy { + export var onProxyError: SinonChrome.events.Event; + export var settings: SinonChrome.types.StubbedChromeSetting; +} + +declare module SinonChrome.pushMessaging { + export var getChannelId: Sinon.SinonStub; + export var onMessage: SinonChrome.events.Event; +} + +declare module SinonChrome.runtime { + export var connect: Sinon.SinonStub; + export var connectNative: Sinon.SinonStub; + export var getBackgroundPage: Sinon.SinonStub; + export var getManifest: Sinon.SinonStub; + export var getPackageDirectoryEntry: Sinon.SinonStub; + export var getPlatformInfo: Sinon.SinonStub; + export var reload: Sinon.SinonStub; + export var requestUpdateCheck: Sinon.SinonStub; + export var restart: Sinon.SinonStub; + export var sendMessage: Sinon.SinonStub; + export var sendNativeMessage: Sinon.SinonStub; + + export var onBrowserUpdateAvailable: SinonChrome.events.Event; + export var onConnect: SinonChrome.events.Event; + export var onConnectExternal: SinonChrome.events.Event; + export var onInstalled: SinonChrome.events.Event; + export var onMessage: SinonChrome.events.Event; + export var onMessageExternal: SinonChrome.events.Event; + export var onRestartRequired: SinonChrome.events.Event; + export var onStartup: SinonChrome.events.Event; + export var onSuspend: SinonChrome.events.Event; + export var onSuspendCanceled: SinonChrome.events.Event; + export var onUpdateAvailable: SinonChrome.events.Event; + + export var id: string; + export var getURL: Sinon.SinonSpy; +} + +declare module SinonChrome.sessions { + export var getDevices: Sinon.SinonStub; + export var getRecentlyClosed: Sinon.SinonStub; + export var restore: Sinon.SinonStub; + + export var onChanged: SinonChrome.events.Event; +} + +declare module SinonChrome.storage { + interface StubbedStorageArea { + clear: Sinon.SinonStub; + get: Sinon.SinonStub; + getBytesInUse: Sinon.SinonStub; + remove: Sinon.SinonStub; + set: Sinon.SinonStub; + } + + export var local: StubbedStorageArea; + export var managed: StubbedStorageArea; + export var sync: StubbedStorageArea; + + export var onChanged: SinonChrome.events.Event; +} + +declare module SinonChrome.tabCapture { + export var capture: Sinon.SinonStub; + export var getCapturedTabs: Sinon.SinonStub; + + export var onStatusChanged: SinonChrome.events.Event; +} + +declare module SinonChrome.tabs { + export var captureVisibleTab: Sinon.SinonStub; + export var connect: Sinon.SinonStub; + export var create: Sinon.SinonStub; + export var detectLanguage: Sinon.SinonStub; + export var duplicate: Sinon.SinonStub; + export var executeScript: Sinon.SinonStub; + export var get: Sinon.SinonStub; + export var getAllInWindow: Sinon.SinonStub; + export var getCurrent: Sinon.SinonStub; + export var getSelected: Sinon.SinonStub; + export var highlight: Sinon.SinonStub; + export var insertCSS: Sinon.SinonStub; + export var move: Sinon.SinonStub; + export var query: Sinon.SinonStub; + export var reload: Sinon.SinonStub; + export var remove: Sinon.SinonStub; + export var sendMessage: Sinon.SinonStub; + export var sendRequest: Sinon.SinonStub; + export var update: Sinon.SinonStub; + + export var onActivated: SinonChrome.events.Event; + export var onActiveChanged: SinonChrome.events.Event; + export var onAttached: SinonChrome.events.Event; + export var onCreated: SinonChrome.events.Event; + export var onDetached: SinonChrome.events.Event; + export var onHighlightChanged: SinonChrome.events.Event; + export var onHighlighted: SinonChrome.events.Event; + export var onMoved: SinonChrome.events.Event; + export var onRemoved: SinonChrome.events.Event; + export var onReplaced: SinonChrome.events.Event; + export var onSelectionChanged: SinonChrome.events.Event; + export var onUpdated: SinonChrome.events.Event; + export var onZoomChange: SinonChrome.events.Event; +} + +declare module SinonChrome.topSites { + export var get: Sinon.SinonStub; +} + +declare module SinonChrome.tts { + export var getVoices: Sinon.SinonStub; + export var isSpeaking: Sinon.SinonStub; + export var pause: Sinon.SinonStub; + export var resume: Sinon.SinonStub; + export var speak: Sinon.SinonStub; + export var stop: Sinon.SinonStub; + + export var onEvent: SinonChrome.events.Event; +} + +declare module SinonChrome.ttsEngine { + export var onPause: SinonChrome.events.Event; + export var onResume: SinonChrome.events.Event; + export var onSpeak: SinonChrome.events.Event; + export var onStop: SinonChrome.events.Event; + + export var sendTtsEvent: Sinon.SinonStub; +} + +declare module SinonChrome.webNavigation { + export var getAllFrames: Sinon.SinonStub; + export var getFrame: Sinon.SinonStub; + + export var onBeforeNavigate: SinonChrome.events.Event; + export var onCommitted: SinonChrome.events.Event; + export var onCompleted: SinonChrome.events.Event; + export var onCreatedNavigationTarget: SinonChrome.events.Event; + export var onDOMContentLoaded: SinonChrome.events.Event; + export var onErrorOccurred: SinonChrome.events.Event; + export var onHistoryStateUpdated: SinonChrome.events.Event; + export var onReferenceFragmentUpdated: SinonChrome.events.Event; + export var onTabReplaced: SinonChrome.events.Event; +} + +declare module SinonChrome.webRequest { + export var handlerBehaviorChanged: Sinon.SinonStub; + + export var onAuthRequired: SinonChrome.events.Event; + export var onBeforeRedirect: SinonChrome.events.Event; + export var onBeforeRequest: SinonChrome.events.Event; + export var onBeforeSendHeaders: SinonChrome.events.Event; + export var onCompleted: SinonChrome.events.Event; + export var onErrorOccurred: SinonChrome.events.Event; + export var onHeadersReceived: SinonChrome.events.Event; + export var onResponseStarted: SinonChrome.events.Event; + export var onSendHeaders: SinonChrome.events.Event; +} + +declare module SinonChrome.windows { + export var create: Sinon.SinonStub; + export var get: Sinon.SinonStub; + export var getAll: Sinon.SinonStub; + export var getCurrent: Sinon.SinonStub; + export var getLastFocused: Sinon.SinonStub; + export var remove: Sinon.SinonStub; + export var update: Sinon.SinonStub; + + export var onCreated: SinonChrome.events.Event; + export var onFocusChanged: SinonChrome.events.Event; + export var onRemoved: SinonChrome.events.Event; +} From 08c6a3c8f6ab8cb9a03fef15d15b12e033e551db Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 11:58:49 -0700 Subject: [PATCH 098/419] Added missing properties to 'AccWizardOptions' for 'acc-wizard'. --- acc-wizard/acc-wizard.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/acc-wizard/acc-wizard.d.ts b/acc-wizard/acc-wizard.d.ts index 5eb81a11c..f6235d2ca 100644 --- a/acc-wizard/acc-wizard.d.ts +++ b/acc-wizard/acc-wizard.d.ts @@ -47,7 +47,19 @@ interface AccWizardOptions { nextText: string; /** - * @summary Text for back button + * @summary Text for back button. + * @type {string} + */ + backText: string; + + /** + * @summary HTML input type for next button. (default: "submit") + * @type {string} + */ + nextType: string; + + /** + * @summary HTML input type for back button. (default: "reset") * @type {string} */ backType: string; From b64570a5a9df55e36d23d57162ae410c83631235 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:00:20 -0700 Subject: [PATCH 099/419] appendtoBody -> appendToBody in 'angular-ui-bootstrap'. --- angular-ui-bootstrap/angular-ui-bootstrap-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 5aef97afa..7f8886496 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -110,7 +110,7 @@ testApp.config(( placement: 'bottom', animation: false, popupDelay: 1000, - appendtoBody: true + appendToBody: true }); $tooltipProvider.setTriggers({ 'customOpenTrigger': 'customCloseTrigger' From ddb28bfd38c94886ce6dae7778dd49f7b9dac653 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:00:56 -0700 Subject: [PATCH 100/419] range -> ranges in 'acorn' tests. --- acorn/acorn-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acorn/acorn-tests.ts b/acorn/acorn-tests.ts index 1c5cf27ba..796ffc3ee 100644 --- a/acorn/acorn-tests.ts +++ b/acorn/acorn-tests.ts @@ -14,7 +14,7 @@ var string: string; // acorn string = acorn.version; program = acorn.parse('code'); -program = acorn.parse('code', {range: true, onToken: tokens, onComment: comments}); +program = acorn.parse('code', {ranges: true, onToken: tokens, onComment: comments}); program = acorn.parse('code', { ranges: true, onToken: (token) => tokens.push(token), From 1c22737dfec0e901a693c212da090d6d848f9f79 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:05:17 -0700 Subject: [PATCH 101/419] callbackOnLoactionHash -> callbackOnLocationHash for 'auth0'. --- auth0/auth0.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 2b200bb37..b2e1149fb 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -33,7 +33,7 @@ interface Auth0Static { interface Auth0ClientOptions { clientID: string; callbackURL: string; - callbackOnLoactionHash?: boolean; + callbackOnLocationHash?: boolean; domain: string; forceJSONP?: boolean; } From 8be8a5707e122817c63bd9ccf1b05c52e7f9de84 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:07:44 -0700 Subject: [PATCH 102/419] Added 'icon' to 'Auth0LockOption' for 'auth0.lcok'. --- auth0.lock/auth0.lock.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index e8ba3cb99..bef269dbc 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -27,6 +27,7 @@ interface Auth0LockOptions { forceJSONP?: boolean; gravatar?: boolean; integratedWindowsLogin?: boolean; + icon?: string; loginAfterSignup?: boolean; popup?: boolean; popupOptions?: Auth0LockPopupOptions; From 46ddfbb037dbe6f28f2cf4c91a686a53ba6359a7 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:40:13 -0700 Subject: [PATCH 103/419] Streams don't have a documented 'name' property in 'bunyan'. --- bunyan/bunyan-test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bunyan/bunyan-test.ts b/bunyan/bunyan-test.ts index 33e2b9cec..b8e51d145 100644 --- a/bunyan/bunyan-test.ts +++ b/bunyan/bunyan-test.ts @@ -57,7 +57,7 @@ var log = bunyan.createLogger(options); log.addSerializers(bunyan.stdSerializers); var child = log.child({name: 'child'}); child.reopenFileStreams(); -log.addStream({path: '/dev/null', name: 'stream1'}); +log.addStream({path: '/dev/null'}); child.level(bunyan.DEBUG); child.level('debug'); child.levels(0, bunyan.ERROR); From 2b83a12c70f2680f207460d78dccdc250bdcdb9e Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:50:29 -0700 Subject: [PATCH 104/419] Add 'cursor' and 'interlacedColor'. to 'canvasjs'. --- canvasjs/canvasjs.d.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/canvasjs/canvasjs.d.ts b/canvasjs/canvasjs.d.ts index 6de602c7e..b6d9febe4 100644 --- a/canvasjs/canvasjs.d.ts +++ b/canvasjs/canvasjs.d.ts @@ -274,6 +274,13 @@ declare module CanvasJS { } interface ChartLegendOptions { + /** + * Sets the cursor type for legend items. + * Default: "default" + * Examples: "pointer", "crosshair" .. + */ + cursor?: string; + /** * Sets the font Size of Legend Text in pixels. * Default: 12 @@ -537,6 +544,16 @@ declare module CanvasJS { * Example: “red”, “#FEFDDF” .. */ gridColor?: string; + + /** + * Sets the Interlacing Color that alternates between the set interval. + * If the interval is not set explicitly, then the auto calculated interval is considered. + * The value of interlacedColor can be an "HTML Color Name" or "hex" code. + * Default: null + * Example: “#F8F1E4″, “#FEFDDF” + */ + interlacedColor?: string; + /** * Strip Lines are vertical or horizontal lines used to highlight/mark a certain region on the plot area. You can choose whether to draw a line at a specific position or shade a region on the plot area. Strip Lines are sometimes referred to as trend lines. * If you want to just mark a certain position on the axis, you can set the value attribute and it’ll draw a line at that position with the set thickness. If you want to shade a region instead, you need to set startValue and endValue attributes. This will fill the area within the specified range. From 25657c644994d986a14843317930409e4fb1b9d3 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:51:55 -0700 Subject: [PATCH 105/419] Normalize double-quotes. --- canvasjs/canvasjs.d.ts | 322 ++++++++++++++++++++--------------------- 1 file changed, 161 insertions(+), 161 deletions(-) diff --git a/canvasjs/canvasjs.d.ts b/canvasjs/canvasjs.d.ts index b6d9febe4..e168371bc 100644 --- a/canvasjs/canvasjs.d.ts +++ b/canvasjs/canvasjs.d.ts @@ -108,7 +108,7 @@ declare module CanvasJS { */ animationEnabled?: boolean; /** - * While exporting any chart, “Chart” is used as the default fine name with corresponding extension “jpg” or “png”. You can override this name using exportFileName property. + * While exporting any chart, "Chart" is used as the default fine name with corresponding extension "jpg" or "png". You can override this name using exportFileName property. * Default: Chart */ exportFileName?: string; @@ -126,25 +126,25 @@ declare module CanvasJS { zoomEnabled?: boolean; /** * Sets the theme of the Chart. Various predefined themes are bundled along with the library. User can easily switch these themes by changing theme property to the below mentioned options. - * Default: “theme1″ - * Options: “theme1″,”theme2″, “theme3″ + * Default: "theme1" + * Options: "theme1","theme2", "theme3" */ theme?: string; /** - * Sets the background color of entire Chart Area. Values can be “HTML Color Name”, “hex code” or “rgba values” - * Default: “white” - * Example: “yellow”, “#F5DEB3″.. + * Sets the background color of entire Chart Area. Values can be "HTML Color Name", "hex code" or "rgba values" + * Default: "white" + * Example: "yellow", "#F5DEB3".. */ backgroundColor?: string; /** * Sets the colorSet of the Chart. Color Set is an array of colors that are used to render data. Various predefined Color Sets are bundled along with the library. You can either choose from the pre-defined Color Sets or define your own Color Set. - * Default: “colorset1″ or as defined in the selected theme - * Example: “colorSet1″, “colorSet2″, “colorSet3″ + * Default: "colorset1" or as defined in the selected theme + * Example: "colorSet1", "colorSet2", "colorSet3" */ colorSet?: string; /** - * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – “en”. - * Default: “en” + * CanvasJS allows you to localize various culture / language / country specific elements in the Chart like number formatting style – where you can choose which character to use as a decimal separator and as a digit group separator (also referred to as a thousand separator). By default CanvasJS is set to Neutral English Culture – "en". + * Default: "en" */ culture?: string; /** @@ -190,19 +190,19 @@ declare module CanvasJS { /** * Sets the Title’s text. * Default: null - * Example: “Chart title” + * Example: "Chart title" */ text?: string; /** * This property lets you align the Chart Title vertically. - * Default: “top” - * Options: “top”, “center”, “bottom” + * Default: "top" + * Options: "top", "center", "bottom" */ verticalAlign?: string; /** * This property lets you align the Chart Title horizontally. - * Default: “center” - * Options: “left”, “right”, “center” + * Default: "center" + * Options: "left", "right", "center" */ horizontalAlign?: string; /** @@ -213,26 +213,26 @@ declare module CanvasJS { fontSize?: number; /** * Sets the Font Family of Chart Title. - * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” - * Example: “arial” , “tahoma”, “verdana” .. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "arial" , "tahoma", "verdana" .. */ fontFamily?: string; /** * Sets the Font Weight used in the Chart Title. - * Default: “bold” - * Options: “lighter”, “normal”, “bold” , “bolder” + * Default: "bold" + * Options: "lighter", "normal", "bold" , "bolder" */ fontWeight?: string; /** - * Sets the font color of Chart Title. The value of fontColor can be a “HTML Color Name” or “hex” code . - * Default: “#3A3A3A” - * Example: “red”, “#FAC003″ .. + * Sets the font color of Chart Title. The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "#3A3A3A" + * Example: "red", "#FAC003" .. */ fontColor?: string; /** * Sets the fontStyle of Chart Title. fontStyle can be set to one of the below options. - * Default: “normal” - * Options: “normal”, “italic” , “oblique” + * Default: "normal" + * Options: "normal", "italic" , "oblique" */ fontStyle?: string; /** @@ -248,15 +248,15 @@ declare module CanvasJS { */ cornerRadius?: number; /** - * Sets the color of border around Chart Title. Values of borderColor can be “HTML Color Name” or “hex” code . - * Default: “black” - * Example: “red”, “#FF0000″ .. + * Sets the color of border around Chart Title. Values of borderColor can be "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FF0000" .. */ borderColor?: string; /** - * Sets the background color of Chart Title. Values can be “HTML Color Name” or “hex” code. + * Sets the background color of Chart Title. Values can be "HTML Color Name" or "hex" code. * Default: null - * Example: “red”, “#FF0000″ .. + * Example: "red", "#FF0000" .. */ backgroundColor?: string; /** @@ -289,38 +289,38 @@ declare module CanvasJS { fontSize?: number; /** * Sets the Font Family of Legend Text. - * Default: “calibri” - * Example: “arial” , “tahoma”, “verdana” .. + * Default: "calibri" + * Example: "arial" , "tahoma", "verdana" .. */ fontFamily?: string; /** - * Sets the font color of Legend Text . The value of fontColor can be a “HTML Color Name” or “hex” code . - * Default: “black” - * Example: “red”, “#FAC003″ .. + * Sets the font color of Legend Text . The value of fontColor can be a "HTML Color Name" or "hex" code . + * Default: "black" + * Example: "red", "#FAC003" .. */ fontColor?: string; /** * Sets the Font Weight of Legend Text. - * Default: “normal” - * Example: “lighter”, “normal”, “bold” , “bolder” + * Default: "normal" + * Example: "lighter", "normal", "bold" , "bolder" */ fontWeight?: string; /** * Sets the fontStyle of Legend Text. fontStyle can be set to one of the below options. - * Default: “normal” - * Example: “normal”, “italic” , “oblique” + * Default: "normal" + * Example: "normal", "italic" , "oblique" */ fontStyle?: string; /** * This property lets you align the Legend Position vertically. - * Default: “bottom” - * Example: “top”, “center”, “bottom” + * Default: "bottom" + * Example: "top", "center", "bottom" */ verticalAlign?: string; /** * This property lets you align the Legend Position horizontally. - * Default: “right” - * Example: “left”, “right”, “center” + * Default: "right" + * Example: "left", "right", "center" */ horizontalAlign?: string; /** @@ -380,13 +380,13 @@ declare module CanvasJS { /** * Sets the Axis Title. * Default: null - * Example: “Axis X Title” + * Example: "Axis X Title" */ title?: string; /** - * Sets the Font Color of Axis Title. The value of titleFontColor can be a “HTML Color Name” or “hex” code . - * Default: “#666666″ - * Example: “red”, “#006400″ . + * Sets the Font Color of Axis Title. The value of titleFontColor can be a "HTML Color Name" or "hex" code . + * Default: "#666666" + * Example: "red", "#006400" . */ titleFontColor?: string; /** @@ -397,20 +397,20 @@ declare module CanvasJS { titleFontSize?: number; /** * Sets the Font Family of Axis Title. - * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” - * Example: “calibri”, “tahoma, “verdana” .. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "calibri", "tahoma, "verdana" .. */ titleFontFamily?: string; /** * Sets the Font Weight used in the Axis Title. It can be set to one of the options below. - * Default: “normal” - * Options: “lighter”, “normal”, “bold” , “bolder” + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" */ titleFontWeight?: string; /** * Sets the Font Style of Axis Title. It can be set to one of the below options. - * Default: “normal” - * Options: “normal”, “italic” , “oblique” + * Default: "normal" + * Options: "normal", "italic" , "oblique" */ titleFontStyle?: string; /** @@ -426,9 +426,9 @@ declare module CanvasJS { */ labelAngle?: number; /** - * Sets the Axis Label color. The value of labelFontColor can be a “HTML Color Name” or “hex” code . - * Default: “grey” - * Example: “red”, “#FAC003″ .. + * Sets the Axis Label color. The value of labelFontColor can be a "HTML Color Name" or "hex" code . + * Default: "grey" + * Example: "red", "#FAC003" .. */ labelFontColor?: string; /** @@ -439,32 +439,32 @@ declare module CanvasJS { labelFontSize?: number; /** * Sets the Font Family of Axis labels. - * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” - * Example: “calibri”, “tahoma”, “verdana” .. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "calibri", "tahoma", "verdana" .. */ labelFontFamily?: string; /** * Set the font Weight used in Axis Labels. It can be set to one of the options below. - * Default: “normal” - * Options: “lighter”, “normal”, “bold” , “bolder” + * Default: "normal" + * Options: "lighter", "normal", "bold" , "bolder" */ labelFontWeight?: string; /** * Sets the Font Style of Axis Labels. It can be set to one of the below options. - * Default: “normal” - * Options: “italic”, “oblique”, “normal” + * Default: "normal" + * Options: "italic", "oblique", "normal" */ labelFontStyle?: string; /** * A string that prepends all the labels on axisX. * Default: null - * Example: “$”,”cat”.. + * Example: "$","cat".. */ prefix?: string; /** * A string that appends all the labels on axisX. * Default: null - * Example: “$”,”cat”.. + * Example: "$","cat".. */ suffix?: string; /** @@ -490,10 +490,10 @@ declare module CanvasJS { */ interval?: number; /** - * intervalType is the unit of interval property. intervalType is by default set to “number” and hence you need to specify the interval type (eg “week”, “month”, etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as “month” - * Default: Automatically handled when interval property is not set. Defaults to “number” when you set the interval. - * Option: “number”,”millisecond” ,”second”,” minute”, “hour”, “day”, “month” ,”year” - * Example: for interval as 15 minutes, set interval as 15, and set intervalType as “minute”, + * intervalType is the unit of interval property. intervalType is by default set to "number" and hence you need to specify the interval type (eg "week", "month", etc) depending on the type of interval you intend to set. If required interval is 3 months, you need to provide interval as 3 and intervalType as "month" + * Default: Automatically handled when interval property is not set. Defaults to "number" when you set the interval. + * Option: "number","millisecond" ,"second"," minute", "hour", "day", "month" ,"year" + * Example: for interval as 15 minutes, set interval as 15, and set intervalType as "minute", */ intervalType?: string; /** @@ -503,9 +503,9 @@ declare module CanvasJS { */ tickLength?: number; /** - * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a “HTML Color Name” or “hex” code . - * Default: “#BBBBBB” - * Example: “red”, “#006400″. + * Sets the color of Tick Marks drawn on the axis. The value of tickColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#006400". */ tickColor?: string; /** @@ -515,9 +515,9 @@ declare module CanvasJS { */ tickThickness?: number; /** - * Sets the color of Axis line. Axis line color can be a “HTML Color Name” or “hex” code . - * Default: “#BBBBBB” - * Example: “blue”,”#21AB13″.. + * Sets the color of Axis line. Axis line color can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "blue","#21AB13".. */ lineColor?: string; /** @@ -527,9 +527,9 @@ declare module CanvasJS { */ lineThickness?: string; /** - * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a “HTML Color Name” or “hex” code . + * Sets the Interlacing Color that alternates between the set interval. If the interval is not set explicitly, then the auto calculated interval is considered. The value of interlacedColor can be a "HTML Color Name" or "hex" code . * Default: null - * Example: “#F8F1E4″, “#FEFDDF” …. + * Example: "#F8F1E4", "#FEFDDF" …. */ interlaceColor?: string; /** @@ -539,9 +539,9 @@ declare module CanvasJS { */ gridThickness?: number; /** - * Sets the Color of Grid Lines. Value of gridColor can be a “HTML Color Name” or “hex” code . - * Default: “#BBBBBB” - * Example: “red”, “#FEFDDF” .. + * Sets the Color of Grid Lines. Value of gridColor can be a "HTML Color Name" or "hex" code . + * Default: "#BBBBBB" + * Example: "red", "#FEFDDF" .. */ gridColor?: string; @@ -550,7 +550,7 @@ declare module CanvasJS { * If the interval is not set explicitly, then the auto calculated interval is considered. * The value of interlacedColor can be an "HTML Color Name" or "hex" code. * Default: null - * Example: “#F8F1E4″, “#FEFDDF” + * Example: "#F8F1E4", "#FEFDDF" */ interlacedColor?: string; @@ -590,32 +590,32 @@ declare module CanvasJS { thickness?: number; /** * Sets the color of the stripLine. - * Default: “orange” - * Example: “green”, “#23EA23″ + * Default: "orange" + * Example: "green", "#23EA23" */ color?: string; /** * Sets the label of the stripLine. These are shown on top of axis labels. - * Default: “” (empty string) - * Example: “Threshold”, “Deaths in 1920″ + * Default: "" (empty string) + * Example: "Threshold", "Deaths in 1920" */ label?: string; /** * Sets the background color of stripLine’s label. - * Default: “#eeeeee” - * Example: “red”,”#fabd76″ + * Default: "#eeeeee" + * Example: "red","#fabd76" */ labelBackgroundColor?: string; /** * Sets the font-family of stripLine’s label. If the first font is not found in the system from the specified font-family list, it tries to use the next font in the list. - * Default: “arial” - * Example: “Arial, Trebuchet MS, Tahoma, sans-serif” + * Default: "arial" + * Example: "Arial, Trebuchet MS, Tahoma, sans-serif" */ labelFontFamily?: string; /** * Sets the font color of label. - * Default: “orange” - * Example: “blue”,”#4135e9″ + * Default: "orange" + * Example: "blue","#4135e9" */ labelFontColor?: string; /** @@ -626,14 +626,14 @@ declare module CanvasJS { labelFontSize?: number; /** * Sets the font weight of stripLine’s label. - * Default: “normal” - * Example: “lighter”,”normal”,”bold”,”bolder” + * Default: "normal" + * Example: "lighter","normal","bold","bolder" */ labelFontWeight?: string; /** * Sets the font style of stripLine’s label. - * Default: “normal” - * Example: “normal”,”italic”,”oblique” + * Default: "normal" + * Example: "normal","italic","oblique" */ labelFontStyle?: string; } @@ -674,7 +674,7 @@ declare module CanvasJS { /** * Sets the border color around Tool Tip. When not set it takes the color of corresponding dataSeries or dataPoint. * Default: dataSeries color/ dataPoint color - * Example: “red”, “#808080″.. + * Example: "red", "#808080".. */ borderColor?: string; } @@ -682,53 +682,53 @@ declare module CanvasJS { interface ChartDataCommon { /** * Sets the dataPoint Name. dataPoint name is shown in various places like toolTip & legend unless overridden. - * Default: Automatically Named (“dataPoint 1″, “dataPoint 2″ .. ) - * Example: “apple”, “mango” .. + * Default: Automatically Named ("dataPoint 1", "dataPoint 2" .. ) + * Example: "apple", "mango" .. */ name?: string; /** - * Sets the color of dataSeries. The value of tickColor can be a “HTML Color Name” or “Hex Code”. + * Sets the color of dataSeries. The value of tickColor can be a "HTML Color Name" or "Hex Code". * Default: Automatically set from Theme. - * Example: “red”, “green” .. + * Example: "red", "green" .. */ color?: string; /** * Instead of setting string values for all indexLabels, you can also use keywords like x, y, etc that will automatically show corresponding properties as indexLabel. This will allow you to define indexLabel at the series level once. While setting indexLabel you specify a keyword by enclosing it in flower brackets like {x}, {y}, {color}, etc. * Range Charts have two indexLabels – one for each y value. This requires the use of a special keyword #index to show index label on either sides of the column/bar/area. - * eg: indexLabel: “{x}: {y[#index]}” + * eg: indexLabel: "{x}: {y[#index]}" * Important keywords to keep in mind are. {x}, {y}, {name}, {label}. * Default: null - * Example: “{label}”, “Win”, “x: {x}, y: {y} ” + * Example: "{label}", "Win", "x: {x}, y: {y} " */ indexLabel?: string; /** - * Using this property you can define whether to render indexLabel “inside” or “outside” the dataPoint. - * Default: “outside” - * Example: “outside”, “inside” + * Using this property you can define whether to render indexLabel "inside" or "outside" the dataPoint. + * Default: "outside" + * Example: "outside", "inside" */ indexLabelPlacement?: string; /** - * Sets the Orientation of indexLabel to “horizontal” or “vertical”. - * Default: “horizontal” - * Options: “horizontal”, “vertical” + * Sets the Orientation of indexLabel to "horizontal" or "vertical". + * Default: "horizontal" + * Options: "horizontal", "vertical" */ indexLabelOrientation?: string; /** - * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a “HTML Color Name” or “Hex Code”. + * Sets the Background color of Index Labels. The value of indexLabelBackgroundColor can be a "HTML Color Name" or "Hex Code". * Default: null - * Example: “red”, “#FAC003″ .. + * Example: "red", "#FAC003" .. */ indexLabelBackgroundColor?: string; /** * Sets the Index Label’s Font Style. It can be set to one of the below options. - * Default: “normal” - * Options: “italic”, “oblique”, “normal” + * Default: "normal" + * Options: "italic", "oblique", "normal" */ indexLabelFontStyle?: string; /** - * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a “HTML Color Name” or “Hex Code”. - * Default: “grey” - * Example: “red”, “#FAC003″ .. + * Sets the Index Label’s Font color. The value of IndexLabelFontColor can be a "HTML Color Name" or "Hex Code". + * Default: "grey" + * Example: "red", "#FAC003" .. */ indexLabelFontColor?: string; /** @@ -739,24 +739,24 @@ declare module CanvasJS { indexLabelFontSize?: number; /** * Sets the Index Label’s Font Family. - * Default: “Calibri, Optima, Candara, Verdana, Geneva, sans-serif” - * Example: “calibri”, “tahoma”, “verdana”.. + * Default: "Calibri, Optima, Candara, Verdana, Geneva, sans-serif" + * Example: "calibri", "tahoma", "verdana".. */ indexLabelFontFamily?: string; /** * Sets the Index Label’s Font Weight. It can be set to one of the below options. - * Default: “normal” - * Example: “lighter”, “normal” ,”bold” , “bolder” + * Default: "normal" + * Example: "lighter", "normal" ,"bold" , "bolder" */ indexLabelFontWeight?: string; /** - * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a “HTML Color Name” or “Hex Code”. - * Default: “lightgrey” - * Example: “red”, “#FAC003″ .. + * Sets the color of line connecting index labels with their dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacment is outside. The value of indexLineColor can be a "HTML Color Name" or "Hex Code". + * Default: "lightgrey" + * Example: "red", "#FAC003" .. */ indexLabelLineColor?: string; /** - * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to “outside”. + * Sets the thickness of line connecting indexLabel with its corresponding dataPoint. It is only applicable for pie and doughnut chart when indexLabelPlacement is set to "outside". * Default: 2 * Example: 4, 6 */ @@ -769,14 +769,14 @@ declare module CanvasJS { /** * Sets marker type to be rendered at each dataPoint. While markers are helpful in highlighting individual dataPoints, they do not help much when the dataPoints are crowded. In case of large number of dataPoints it is recommended to disable markers in order to improve the appearance and performance of chart. * Same marker type is also used in legend unless overridden by legendMarkerType property. - * Default: “circle” - * Options: “none”, “circle”, “square”, “triangle” and “cross” + * Default: "circle" + * Options: "none", "circle", "square", "triangle" and "cross" */ markerType?: string; /** * Sets the color of marker that is displayed on the Chart. Legend Marker for the series uses the same Color as set here unless overridden using legendMarkerColor property. * Default: dataSeries Color - * Example: “red”, “#008000″ .. + * Example: "red", "#008000" .. */ markerColor?: string; /** @@ -786,9 +786,9 @@ declare module CanvasJS { */ markerSize?: number; /** - * Sets the border color around marker. Value of markerBorderColor can be “HTML Color Name” or “hex code”. + * Sets the border color around marker. Value of markerBorderColor can be "HTML Color Name" or "hex code". * Default: dataSeries color. - * Example: “red”, “#008000″ .. + * Example: "red", "#008000" .. */ markerBorderColor?: string; /** @@ -799,14 +799,14 @@ declare module CanvasJS { markerBorderThickness?: number; /** * Sets the text that describes the dataSeries in legend. - * Default: “DataSeries 1″, “DataSeries 2″ ..etc - * Example: “2010″, “2011″.. + * Default: "DataSeries 1", "DataSeries 2" ..etc + * Example: "2010", "2011".. */ legendText?: string; /** * Sets the Legend Marker to one of the options below. This property is used to override the default marker in legend, which is same as dataSeries Marker Type. * Default: same as markerType - * Options: “circle”, “square”, “cross” and “triangle” + * Options: "circle", "square", "cross" and "triangle" */ legendMarkerType?: string; /** @@ -815,9 +815,9 @@ declare module CanvasJS { */ click?: (event: ChartEvent) => void; /** - * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be “HTML Color Name” or “hex code”. + * Sets the color of marker that is displayed on legend. This property overrides default Marker’s Color in Legend, which is same as dataSeries Marker Color. Value of legendMarkerColor can be "HTML Color Name" or "hex code". * Default: dataSeries marker color - * Example: “red”, “#008000″ .. + * Example: "red", "#008000" .. */ legendMarkerColor?: string; /** @@ -846,39 +846,39 @@ declare module CanvasJS { visible?: boolean; /** * Sets the type of chart to be rendered for corresponding dataSeries. One can choose from the following options. - * Default: “column” + * Default: "column" * Options: - * “line” - * “column” - * “bar” - * “area” - * “spline” - * “splineArea” - * “stepLine” - * “scatter” - * “bubble” - * “stackedColumn” - * “stackedBar” - * “stackedArea” - * “stackedColumn100″ - * “stackedBar100″ - * “stackedArea100″ - * “pie” - * “doughnut” + * "line" + * "column" + * "bar" + * "area" + * "spline" + * "splineArea" + * "stepLine" + * "scatter" + * "bubble" + * "stackedColumn" + * "stackedBar" + * "stackedArea" + * "stackedColumn100" + * "stackedBar100" + * "stackedArea100" + * "pie" + * "doughnut" */ type?: string; /** - * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing “secondary” Axis you can plot the series against axisY2. + * Setting axisYType lets you choose between primary and secondary Y Axis for a dataSeries to plot against. By choosing "secondary" Axis you can plot the series against axisY2. * In case of Multi-Series or Combinational Charts, one can assign primary axis to some series and secondary axis to other series. * This is helpful when dataSeries objects use different unit of measurement or range of data. By default, all series are plotted against primary Y axis. - * Default: “primary” - * Options: “primary”, “secondary” + * Default: "primary" + * Options: "primary", "secondary" */ axisYType?: string; /** - * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to “dateTime”. + * This defines the data type of x values. Data Type is normally figured out by default based on the object type that is assigned to x. But if you are providing time stamp (which is integer) values instead of Date objects, you’ll have to explicitly set the xValueType to "dateTime". * Default: Automatically Calculated - * Options: “number”, “dateTime” + * Options: "number", "dateTime" */ xValueType?: string; /** @@ -895,8 +895,8 @@ declare module CanvasJS { zValueFormatString?: string; /** * Sets the bevel property, which creates a chiselled effect at the corners of a Column Charts and Bar Charts. - * Default: “true” - * Example: “true”, “false” + * Default: "true" + * Example: "true", "false" */ bevelEnabled?: boolean; /** @@ -924,8 +924,8 @@ declare module CanvasJS { showInLegend?: boolean; /** * In candle Stick chart, when Closing Price is greater than Opening price, the body is filled with white by default and it can be overridden by risingColor property. - * Default: “white” - * Options: “red”, “#DD7E86″, etc. + * Default: "white" + * Options: "red", "#DD7E86", etc. */ risingColor?: string; /** @@ -957,7 +957,7 @@ declare module CanvasJS { /** * Sets label value of a dataPoint. The value appears next to the dataPoint on axisX Line. If not provided, it takes x value for label. * Default: x value - * Example: “label1″, “label2″.. + * Example: "label1", "label2".. */ label?: string; /** @@ -967,9 +967,9 @@ declare module CanvasJS { */ exploded?: boolean; /** - * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be “HTML Color Name” or “hex” code. + * Sets the color of marker that is displayed on legend. This property works only with Pie and Doughnut charts. Value of legendMarkerColor can be "HTML Color Name" or "hex" code. * Default: dataSeries marker color - * Example: “red”, “#008000″.. + * Example: "red", "#008000".. */ legendMarkerColor?: string; } From 8d58b9e4c7d0f373ed042d7b038eb329ebaf5bdc Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 12:57:02 -0700 Subject: [PATCH 106/419] arguments -> argumentsTest for strict mode-implied modules. --- chai/chai-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chai/chai-tests.ts b/chai/chai-tests.ts index fdd23da16..c34b6cdf1 100644 --- a/chai/chai-tests.ts +++ b/chai/chai-tests.ts @@ -115,7 +115,7 @@ function exist() { should.not.exist(void (0)); } -function arguments() { +function argumentsTest() { var args = arguments; expect(args).to.be.arguments; args.should.be.arguments; From fda5dbc69daeb72cae6c17e2744e703048888519 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 13:10:09 -0700 Subject: [PATCH 107/419] Add 'method' property. --- chocolatechipjs/chocolatechipjs.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts index 269cb6790..d658118a0 100644 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ b/chocolatechipjs/chocolatechipjs.d.ts @@ -671,6 +671,12 @@ interface ChocolateChipAjaxSettings { */ type?: string; + /** + * An property that does not seem to be officially documented, but is used in the documentation. + * Its functionality seems to be identical to that of 'type' which *is* documented. + */ + method?: string; + /** * A pre-request callback function that can be used to modify the XMLHTTPRequest object before it is sent. * Use this to set custom headers, etc. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. From b5f460b1260e3d3f7bb750688e35670897d0a0e4 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 13:14:11 -0700 Subject: [PATCH 108/419] Fixed misspellings. --- chui/chui-tests.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/chui/chui-tests.ts b/chui/chui-tests.ts index 60cbe5afd..ce24f3681 100644 --- a/chui/chui-tests.ts +++ b/chui/chui-tests.ts @@ -41,8 +41,8 @@ $(function() { $.UIBlock(.5); $.UIUnblock(); $.UIPopup({id: "myPopup", message: 'Hello!!!'}); - $.UIPopup({message: 'Hello!!!', title: "Whatever", callback: $.noop}); - $.UIPopup({message: 'Hello!!!', cancleButton: "Forget It!", continueButton: "OK"}); + $.UIPopup({ message: 'Hello!!!', title: "Whatever", callback: $.noop }); + $.UIPopup({ message: 'Hello!!!', cancelButton: "Forget It!", continueButton: "OK" }); $.UIPopover({id: "myPopover"}); $.UIPopover({callback: function() {}}); $.UIPopover({title: "Whatever"}); @@ -57,8 +57,8 @@ $(function() { var myStepper = $('#myStepper'); $.UIResetStepper(myStepper); $.UICreateSwitch({id: "mySwitch", value: 5, checked: "true", callback: $.noop}); - $.UITabbar({tabs: 3, labels: ["one", "two", "three"], selected: 2}); - $.UISearch({articleId: "#main", placehold: "Looking?", results: 10}); + $.UITabbar({ tabs: 3, labels: ["one", "two", "three"], selected: 2 }); + $.UISearch({ articleId: "#main", placeholder: "Looking?", results: 10 }); var carouselPanels = $('li'); $.UISetupCarousel({target: "#carousel", panels: carouselPanels}); $.UIBindData(); @@ -90,7 +90,7 @@ $(function() { $("#panelToggler").UIPanelToggle("#togglePanels", $.noop); $('#editList').UIEditList({callback: $.noop, deletable: false, movable: true}); $('#mySelectList').UISelectList(); - $('#myStepper').UIStepper({start: 1, end: 10, defautValue: 5}); + $('#myStepper').UIStepper({ start: 1, end: 10, defaultValue: 5 }); $('#mySwitch').UISwitch(); $('#myRangeControl').UIRange(); From 5e18c0b64102d1b740af64befc2f268f024bf8c9 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 13:19:16 -0700 Subject: [PATCH 109/419] timezone -> timeZone for 'cron'. --- cron/cron.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cron/cron.d.ts b/cron/cron.d.ts index c956a26fb..f91fedec8 100644 --- a/cron/cron.d.ts +++ b/cron/cron.d.ts @@ -6,9 +6,9 @@ declare module "cron" { interface CronJobStatic { - new(cronTime: string|Date, onTick: () => void, onComplete?: () => void, start?: boolean, timezone?: string, context?: any): CronJob; + new(cronTime: string|Date, onTick: () => void, onComplete?: () => void, start?: boolean, timeZone?: string, context?: any): CronJob; new(options: { - cronTime: string|Date; onTick: () => void; onComplete?: () => void; start?: boolean; timezone?: string; context?: any + cronTime: string|Date; onTick: () => void; onComplete?: () => void; start?: boolean; timeZone?: string; context?: any }): CronJob; } interface CronJob { From dd27aa6a912819ab31bf891711ca9628d12d3fe2 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 30 Jul 2015 13:21:42 -0700 Subject: [PATCH 110/419] An -> A --- chocolatechipjs/chocolatechipjs.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts index d658118a0..9b79934b7 100644 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ b/chocolatechipjs/chocolatechipjs.d.ts @@ -672,7 +672,7 @@ interface ChocolateChipAjaxSettings { type?: string; /** - * An property that does not seem to be officially documented, but is used in the documentation. + * A property that does not seem to be officially documented, but is used in the documentation. * Its functionality seems to be identical to that of 'type' which *is* documented. */ method?: string; From 95821425ff63b39445be29508d7b9881e7ee6cce Mon Sep 17 00:00:00 2001 From: Zach Collins Date: Thu, 30 Jul 2015 15:23:45 -0700 Subject: [PATCH 111/419] Adding evernote and thrift typings. --- evernote/evernote-tests.ts | 5 + evernote/evernote.d.ts | 6322 ++++++++++++++++++++++++++++++++++++ thrift/thrift-tests.ts | 10 + thrift/thrift.d.ts | 281 ++ 4 files changed, 6618 insertions(+) create mode 100644 evernote/evernote-tests.ts create mode 100644 evernote/evernote.d.ts create mode 100644 thrift/thrift-tests.ts create mode 100644 thrift/thrift.d.ts diff --git a/evernote/evernote-tests.ts b/evernote/evernote-tests.ts new file mode 100644 index 000000000..ce84750fa --- /dev/null +++ b/evernote/evernote-tests.ts @@ -0,0 +1,5 @@ +/// + +import { Evernote } from "evernote"; + +var client = new Evernote.Client({ token: "abcdef", sandbox: true }); diff --git a/evernote/evernote.d.ts b/evernote/evernote.d.ts new file mode 100644 index 000000000..75aa724ea --- /dev/null +++ b/evernote/evernote.d.ts @@ -0,0 +1,6322 @@ +// Type definitions for evernote v 1.25.8 +// Project: https://www.npmjs.com/package/evernote +// Definitions by: Zachary Collins +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "evernote" { + import { Thrift } from "thrift"; + + module Evernote { + interface Callback { + (err: EDAMUserException|EDAMSystemException|EDAMNotFoundException, v: T): void + } + + interface ClientConfig { + consumerKey?: string + consumerSecret?: string + sandbox?: boolean + token?: string + serviceHost?: string + additionalHeaders?: { [k: string]: string } + secret?: string + } + + class Client { + static "new": (config: ClientConfig) => Client + constructor(config: ClientConfig); + getNoteStore(): NoteStoreClient; + getUserStore(): UserStoreClient; + } + + + /** + * Numeric codes indicating the type of error that occurred on the + * service. + *

    + *
    UNKNOWN
    + *
    No information available about the error
    + *
    BAD_DATA_FORMAT
    + *
    The format of the request data was incorrect
    + *
    PERMISSION_DENIED
    + *
    Not permitted to perform action
    + *
    INTERNAL_ERROR
    + *
    Unexpected problem with the service
    + *
    DATA_REQUIRED
    + *
    A required parameter/field was absent
    + *
    LIMIT_REACHED
    + *
    Operation denied due to data model limit
    + *
    QUOTA_REACHED
    + *
    Operation denied due to user storage limit
    + *
    INVALID_AUTH
    + *
    Username and/or password incorrect
    + *
    AUTH_EXPIRED
    + *
    Authentication token expired
    + *
    DATA_CONFLICT
    + *
    Change denied due to data model conflict
    + *
    ENML_VALIDATION
    + *
    Content of submitted note was malformed
    + *
    SHARD_UNAVAILABLE
    + *
    Service shard with account data is temporarily down
    + *
    LEN_TOO_SHORT
    + *
    Operation denied due to data model limit, where something such + * as a string length was too short
    + *
    LEN_TOO_LONG
    + *
    Operation denied due to data model limit, where something such + * as a string length was too long
    + *
    TOO_FEW
    + *
    Operation denied due to data model limit, where there were + * too few of something.
    + *
    TOO_MANY
    + *
    Operation denied due to data model limit, where there were + * too many of something.
    + *
    UNSUPPORTED_OPERATION
    + *
    Operation denied because it is currently unsupported.
    + *
    TAKEN_DOWN
    + *
    Operation denied because access to the corresponding object is + * prohibited in response to a take-down notice.
    + *
    RATE_LIMIT_REACHED
    + *
    Operation denied because the calling application has reached + * its hourly API call limit for this user.
    + *
    + */ + enum EDAMErrorCode { + 'UNKNOWN' = 1, + 'BAD_DATA_FORMAT' = 2, + 'PERMISSION_DENIED' = 3, + 'INTERNAL_ERROR' = 4, + 'DATA_REQUIRED' = 5, + 'LIMIT_REACHED' = 6, + 'QUOTA_REACHED' = 7, + 'INVALID_AUTH' = 8, + 'AUTH_EXPIRED' = 9, + 'DATA_CONFLICT' = 10, + 'ENML_VALIDATION' = 11, + 'SHARD_UNAVAILABLE' = 12, + 'LEN_TOO_SHORT' = 13, + 'LEN_TOO_LONG' = 14, + 'TOO_FEW' = 15, + 'TOO_MANY' = 16, + 'UNSUPPORTED_OPERATION' = 17, + 'TAKEN_DOWN' = 18, + 'RATE_LIMIT_REACHED' = 19, + } + + /** + * This exception is thrown by EDAM procedures when a call fails as a result of + * a problem that a caller may be able to resolve. For example, if the user + * attempts to add a note to their account which would exceed their storage + * quota, this type of exception may be thrown to indicate the source of the + * error so that they can choose an alternate action. + * + * This exception would not be used for internal system errors that do not + * reflect user actions, but rather reflect a problem within the service that + * the user cannot resolve. + * + * errorCode: The numeric code indicating the type of error that occurred. + * must be one of the values of EDAMErrorCode. + * + * parameter: If the error applied to a particular input parameter, this will + * indicate which parameter. + */ + class EDAMUserException extends Thrift.TException { + errorCode: EDAMErrorCode; + parameter: string; + + constructor(args?: { errorCode: EDAMErrorCode; parameter?: string; }); + } + + /** + * This exception is thrown by EDAM procedures when a call fails as a result of + * a problem in the service that could not be changed through caller action. + * + * errorCode: The numeric code indicating the type of error that occurred. + * must be one of the values of EDAMErrorCode. + * + * message: This may contain additional information about the error + * + * rateLimitDuration: Indicates the minimum number of seconds that an application should + * expect subsequent API calls for this user to fail. The application should not retry + * API requests for the user until at least this many seconds have passed. Present only + * when errorCode is RATE_LIMIT_REACHED, + */ + class EDAMSystemException extends Thrift.TException { + errorCode: EDAMErrorCode; + message: string; + rateLimitDuration: number; + + constructor(args?: { errorCode: EDAMErrorCode; message?: string; rateLimitDuration?: number; }); + } + + /** + * This exception is thrown by EDAM procedures when a caller asks to perform + * an operation on an object that does not exist. This may be thrown based on an invalid + * primary identifier (e.g. a bad GUID), or when the caller refers to an object + * by another unique identifier (e.g. a User's email address). + * + * identifier: A description of the object that was not found on the server. + * For example, "Note.notebookGuid" when a caller attempts to create a note in a + * notebook that does not exist in the user's account. + * + * key: The value passed from the client in the identifier, which was not + * found. For example, the GUID that was not found. + */ + class EDAMNotFoundException extends Thrift.TException { + identifier: string; + key: string; + + constructor(args?: { identifier?: string; key?: string; }); + } + /** + * Minimum length of any string-based attribute, in Unicode chars + */ + var EDAM_ATTRIBUTE_LEN_MIN: number; + + /** + * Maximum length of any string-based attribute, in Unicode chars + */ + var EDAM_ATTRIBUTE_LEN_MAX: number; + + /** + * Any string-based attribute must match the provided regular expression. + * This excludes all Unicode line endings and control characters. + */ + var EDAM_ATTRIBUTE_REGEX: string; + + /** + * The maximum number of values that can be stored in a list-based attribute + * (e.g. see UserAttributes.recentMailedAddresses) + */ + var EDAM_ATTRIBUTE_LIST_MAX: number; + + /** + * The maximum number of entries that can be stored in a map-based attribute + * such as applicationData fields in Resources and Notes. + */ + var EDAM_ATTRIBUTE_MAP_MAX: number; + + /** + * The minimum length of a GUID generated by the Evernote service + */ + var EDAM_GUID_LEN_MIN: number; + + /** + * The maximum length of a GUID generated by the Evernote service + */ + var EDAM_GUID_LEN_MAX: number; + + /** + * GUIDs generated by the Evernote service will match the provided pattern + */ + var EDAM_GUID_REGEX: string; + + /** + * The minimum length of any email address + */ + var EDAM_EMAIL_LEN_MIN: number; + + /** + * The maximum length of any email address + */ + var EDAM_EMAIL_LEN_MAX: number; + + /** + * A regular expression that matches the part of an email address before + * the '@' symbol. + */ + var EDAM_EMAIL_LOCAL_REGEX: string; + + /** + * A regular expression that matches the part of an email address after + * the '@' symbol. + */ + var EDAM_EMAIL_DOMAIN_REGEX: string; + + /** + * A regular expression that must match any email address given to Evernote. + * Email addresses must comply with RFC 2821 and 2822. + */ + var EDAM_EMAIL_REGEX: string; + + /** + * A regular expression that must match any VAT ID given to Evernote. + * ref http://en.wikipedia.org/wiki/VAT_identification_number + * ref http://my.safaribooksonline.com/book/programming/regular-expressions/9780596802837/4dot-validation-and-formatting/id2995136 + */ + var EDAM_VAT_REGEX: string; + + /** + * The minimum length of a timezone specification string + */ + var EDAM_TIMEZONE_LEN_MIN: number; + + /** + * The maximum length of a timezone specification string + */ + var EDAM_TIMEZONE_LEN_MAX: number; + + /** + * Any timezone string given to Evernote must match the provided pattern. + * This permits either a locale-based standard timezone or a GMT offset. + * E.g.:
      + *
    • America/Los_Angeles
    • + *
    • GMT+08:00
    • + *
    + */ + var EDAM_TIMEZONE_REGEX: string; + + /** + * The minimum length of any MIME type string given to Evernote + */ + var EDAM_MIME_LEN_MIN: number; + + /** + * The maximum length of any MIME type string given to Evernote + */ + var EDAM_MIME_LEN_MAX: number; + + /** + * Any MIME type string given to Evernote must match the provided pattern. + * E.g.: image/gif + */ + var EDAM_MIME_REGEX: string; + + /** + * Canonical MIME type string for GIF image resources + */ + var EDAM_MIME_TYPE_GIF: string; + + /** + * Canonical MIME type string for JPEG image resources + */ + var EDAM_MIME_TYPE_JPEG: string; + + /** + * Canonical MIME type string for PNG image resources + */ + var EDAM_MIME_TYPE_PNG: string; + + /** + * Canonical MIME type string for WAV audio resources + */ + var EDAM_MIME_TYPE_WAV: string; + + /** + * Canonical MIME type string for MP3 audio resources + */ + var EDAM_MIME_TYPE_MP3: string; + + /** + * Canonical MIME type string for AMR audio resources + */ + var EDAM_MIME_TYPE_AMR: string; + + /** + * Canonical MIME type string for AAC audio resources + */ + var EDAM_MIME_TYPE_AAC: string; + + /** + * Canonical MIME type string for MP4 audio resources + */ + var EDAM_MIME_TYPE_M4A: string; + + /** + * Canonical MIME type string for MP4 video resources + */ + var EDAM_MIME_TYPE_MP4_VIDEO: string; + + /** + * Canonical MIME type string for Evernote Ink resources + */ + var EDAM_MIME_TYPE_INK: string; + + /** + * Canonical MIME type string for PDF resources + */ + var EDAM_MIME_TYPE_PDF: string; + + /** + * MIME type used for attachments of an unspecified type + */ + var EDAM_MIME_TYPE_DEFAULT: string; + + /** + * The set of resource MIME types that are expected to be handled + * correctly by all of the major Evernote client applications. + */ + var EDAM_MIME_TYPES: string[]; + + /** + * The set of MIME types that Evernote will parse and index for + * searching. With exception of images, and PDFs, which are + * handled in a different way. + */ + var EDAM_INDEXABLE_RESOURCE_MIME_TYPES: string[]; + + /** + * The minimum length of a user search query string in Unicode chars + */ + var EDAM_SEARCH_QUERY_LEN_MIN: number; + + /** + * The maximum length of a user search query string in Unicode chars + */ + var EDAM_SEARCH_QUERY_LEN_MAX: number; + + /** + * Search queries must match the provided pattern. This is used for + * both ad-hoc queries and SavedSearch.query fields. + * This excludes all control characters and line/paragraph separators. + */ + var EDAM_SEARCH_QUERY_REGEX: string; + + /** + * The exact length of a MD5 hash checksum, in binary bytes. + * This is the exact length that must be matched for any binary hash + * value. + */ + var EDAM_HASH_LEN: number; + + /** + * The minimum length of an Evernote username + */ + var EDAM_USER_USERNAME_LEN_MIN: number; + + /** + * The maximum length of an Evernote username + */ + var EDAM_USER_USERNAME_LEN_MAX: number; + + /** + * Any Evernote User.username field must match this pattern. This + * restricts usernames to a format that could permit use as a domain + * name component. E.g. "username.whatever.evernote.com" + */ + var EDAM_USER_USERNAME_REGEX: string; + + /** + * Minimum length of the User.name field + */ + var EDAM_USER_NAME_LEN_MIN: number; + + /** + * Maximum length of the User.name field + */ + var EDAM_USER_NAME_LEN_MAX: number; + + /** + * The User.name field must match this pattern, which excludes line + * endings and control characters. + */ + var EDAM_USER_NAME_REGEX: string; + + /** + * The minimum length of a Tag.name, in Unicode characters + */ + var EDAM_TAG_NAME_LEN_MIN: number; + + /** + * The maximum length of a Tag.name, in Unicode characters + */ + var EDAM_TAG_NAME_LEN_MAX: number; + + /** + * All Tag.name fields must match this pattern. + * This excludes control chars, commas or line/paragraph separators. + * The string may not begin or end with whitespace. + */ + var EDAM_TAG_NAME_REGEX: string; + + /** + * The minimum length of a Note.title, in Unicode characters + */ + var EDAM_NOTE_TITLE_LEN_MIN: number; + + /** + * The maximum length of a Note.title, in Unicode characters + */ + var EDAM_NOTE_TITLE_LEN_MAX: number; + + /** + * All Note.title fields must match this pattern. + * This excludes control chars or line/paragraph separators. + * The string may not begin or end with whitespace. + */ + var EDAM_NOTE_TITLE_REGEX: string; + + /** + * Minimum length of a Note.content field. + * Note.content fields must comply with the ENML DTD. + */ + var EDAM_NOTE_CONTENT_LEN_MIN: number; + + /** + * Maximum length of a Note.content field + * Note.content fields must comply with the ENML DTD. + */ + var EDAM_NOTE_CONTENT_LEN_MAX: number; + + /** + * Minimum length of an application name, which is the key in an + * applicationData LazyMap found in entities such as Resources and + * Notes. + */ + var EDAM_APPLICATIONDATA_NAME_LEN_MIN: number; + + /** + * Maximum length of an application name, which is the key in an + * applicationData LazyMap found in entities such as Resources and + * Notes. + */ + var EDAM_APPLICATIONDATA_NAME_LEN_MAX: number; + + /** + * Minimum length of an applicationData value in a LazyMap, found + * in entities such as Resources and Notes. + */ + var EDAM_APPLICATIONDATA_VALUE_LEN_MIN: number; + + /** + * Maximum length of an applicationData value in a LazyMap, found + * in entities such as Resources and Notes. Note, however, that + * the sum of the size of hte key and value is constrained by + * EDAM_APPLICATIONDATA_ENTRY_LEN_MAX, so the maximum length, in + * practice, depends upon the key value being used. + */ + var EDAM_APPLICATIONDATA_VALUE_LEN_MAX: number; + + /** + * The total length of an entry in an applicationData LazyMap, which + * is the sum of the length of the key and the value for the entry. + */ + var EDAM_APPLICATIONDATA_ENTRY_LEN_MAX: number; + + /** + * An application name must match this regex. An application + * name is the key portion of an entry in an applicationData + * map as found in entities such as Resources and Notes. + * Note that even if both the name and value regexes match, + * it is still necessary to check the sum of the lengths + * against EDAM_APPLICATIONDATA_ENTRY_LEN_MAX. + */ + var EDAM_APPLICATIONDATA_NAME_REGEX: string; + + /** + * An applicationData map value must match this regex. + * Note that even if both the name and value regexes match, + * it is still necessary to check the sum of the lengths + * against EDAM_APPLICATIONDATA_ENTRY_LEN_MAX. + */ + var EDAM_APPLICATIONDATA_VALUE_REGEX: string; + + /** + * The minimum length of a Notebook.name, in Unicode characters + */ + var EDAM_NOTEBOOK_NAME_LEN_MIN: number; + + /** + * The maximum length of a Notebook.name, in Unicode characters + */ + var EDAM_NOTEBOOK_NAME_LEN_MAX: number; + + /** + * All Notebook.name fields must match this pattern. + * This excludes control chars or line/paragraph separators. + * The string may not begin or end with whitespace. + */ + var EDAM_NOTEBOOK_NAME_REGEX: string; + + /** + * The minimum length of a Notebook.stack, in Unicode characters + */ + var EDAM_NOTEBOOK_STACK_LEN_MIN: number; + + /** + * The maximum length of a Notebook.stack, in Unicode characters + */ + var EDAM_NOTEBOOK_STACK_LEN_MAX: number; + + /** + * All Notebook.stack fields must match this pattern. + * This excludes control chars or line/paragraph separators. + * The string may not begin or end with whitespace. + */ + var EDAM_NOTEBOOK_STACK_REGEX: string; + + /** + * The minimum length of a public notebook URI component + */ + var EDAM_PUBLISHING_URI_LEN_MIN: number; + + /** + * The maximum length of a public notebook URI component + */ + var EDAM_PUBLISHING_URI_LEN_MAX: number; + + /** + * A public notebook URI component must match the provided pattern + */ + var EDAM_PUBLISHING_URI_REGEX: string; + + /** + * The set of strings that may not be used as a publishing URI + */ + var EDAM_PUBLISHING_URI_PROHIBITED: string[]; + + /** + * The minimum length of a Publishing.publicDescription field. + */ + var EDAM_PUBLISHING_DESCRIPTION_LEN_MIN: number; + + /** + * The maximum length of a Publishing.publicDescription field. + */ + var EDAM_PUBLISHING_DESCRIPTION_LEN_MAX: number; + + /** + * Any public notebook's Publishing.publicDescription field must match + * this pattern. + * No control chars or line/paragraph separators, and can't start or + * end with whitespace. + */ + var EDAM_PUBLISHING_DESCRIPTION_REGEX: string; + + /** + * The minimum length of a SavedSearch.name field + */ + var EDAM_SAVED_SEARCH_NAME_LEN_MIN: number; + + /** + * The maximum length of a SavedSearch.name field + */ + var EDAM_SAVED_SEARCH_NAME_LEN_MAX: number; + + /** + * SavedSearch.name fields must match this pattern. + * No control chars or line/paragraph separators, and can't start or + * end with whitespace. + */ + var EDAM_SAVED_SEARCH_NAME_REGEX: string; + + /** + * The minimum length of an Evernote user password + */ + var EDAM_USER_PASSWORD_LEN_MIN: number; + + /** + * The maximum length of an Evernote user password + */ + var EDAM_USER_PASSWORD_LEN_MAX: number; + + /** + * Evernote user passwords must match this regular expression + */ + var EDAM_USER_PASSWORD_REGEX: string; + + /** + * The maximum length of an Evernote Business URI + */ + var EDAM_BUSINESS_URI_LEN_MAX: number; + + /** + * The maximum number of Tags per Note + */ + var EDAM_NOTE_TAGS_MAX: number; + + /** + * The maximum number of Resources per Note + */ + var EDAM_NOTE_RESOURCES_MAX: number; + + /** + * Maximum number of Tags per account + */ + var EDAM_USER_TAGS_MAX: number; + + /** + * Maximum number of Tags per business account. + */ + var EDAM_BUSINESS_TAGS_MAX: number; + + /** + * Maximum number of SavedSearches per account + */ + var EDAM_USER_SAVED_SEARCHES_MAX: number; + + /** + * Maximum number of Notes per user + */ + var EDAM_USER_NOTES_MAX: number; + + /** + * Maximum number of Notes per business account + */ + var EDAM_BUSINESS_NOTES_MAX: number; + + /** + * Maximum number of Notebooks per user + */ + var EDAM_USER_NOTEBOOKS_MAX: number; + + /** + * Maximum number of Notebooks in a business account + */ + var EDAM_BUSINESS_NOTEBOOKS_MAX: number; + + /** + * Maximum number of recent email addresses that are maintained + * (see UserAttributes.recentMailedAddresses) + */ + var EDAM_USER_RECENT_MAILED_ADDRESSES_MAX: number; + + /** + * The number of emails of any type that can be sent by a user with a Free + * account from the service per day. If an email is sent to two different + * recipients, this counts as two emails. + */ + var EDAM_USER_MAIL_LIMIT_DAILY_FREE: number; + + /** + * The number of emails of any type that can be sent by a user with a Premium + * account from the service per day. If an email is sent to two different + * recipients, this counts as two emails. + */ + var EDAM_USER_MAIL_LIMIT_DAILY_PREMIUM: number; + + /** + * The number of bytes of new data that may be uploaded to a Free user's + * account each month. + */ + var EDAM_USER_UPLOAD_LIMIT_FREE: number; + + /** + * The number of bytes of new data that may be uploaded to a Premium user's + * account each month. + */ + var EDAM_USER_UPLOAD_LIMIT_PREMIUM: number; + + /** + * The number of bytes of new data that may be uploaded to a Business user's + * personal account each month. Note that content uploaded into the Business + * notebooks by the user does not count against this limit. + */ + var EDAM_USER_UPLOAD_LIMIT_BUSINESS: number; + + /** + * Maximum total size of a Note that can be added to a Free account. + * The size of a note is calculated as: + * ENML content length (in Unicode characters) plus the sum of all resource + * sizes (in bytes). + */ + var EDAM_NOTE_SIZE_MAX_FREE: number; + + /** + * Maximum total size of a Note that can be added to a Premium account. + * The size of a note is calculated as: + * ENML content length (in Unicode characters) plus the sum of all resource + * sizes (in bytes). + */ + var EDAM_NOTE_SIZE_MAX_PREMIUM: number; + + /** + * Maximum size of a resource, in bytes, for Free accounts + */ + var EDAM_RESOURCE_SIZE_MAX_FREE: number; + + /** + * Maximum size of a resource, in bytes, for Premium accounts + */ + var EDAM_RESOURCE_SIZE_MAX_PREMIUM: number; + + /** + * Maximum number of linked notebooks per account, for a free + * account. + */ + var EDAM_USER_LINKED_NOTEBOOK_MAX: number; + + /** + * Maximum number of linked notebooks per account, for a premium + * account. Users who are part of an active business are also + * covered under "premium". + */ + var EDAM_USER_LINKED_NOTEBOOK_MAX_PREMIUM: number; + + /** + * Maximum number of shared notebooks per notebook + */ + var EDAM_NOTEBOOK_SHARED_NOTEBOOK_MAX: number; + + /** + * The minimum length of the content class attribute of a note. + */ + var EDAM_NOTE_CONTENT_CLASS_LEN_MIN: number; + + /** + * The maximum length of the content class attribute of a note. + */ + var EDAM_NOTE_CONTENT_CLASS_LEN_MAX: number; + + /** + * The regular expression that the content class of a note must match + * to be valid. + */ + var EDAM_NOTE_CONTENT_CLASS_REGEX: string; + + /** + * The content class prefix used for all notes created by Evernote Hello. + * This prefix can be used to assemble individual content class strings, + * or can be used to create a wildcard search to get all notes created by + * Hello. When performing a wildcard search via filtered sync chunks or + * search strings, the * character must be appended to this constant. + */ + var EDAM_HELLO_APP_CONTENT_CLASS_PREFIX: string; + + /** + * The content class prefix used for all notes created by Evernote Food. + * This prefix can be used to assemble individual content class strings, + * or can be used to create a wildcard search to get all notes created by + * Food. When performing a wildcard search via filtered sync chunks or + * search strings, the * character must be appended to this constant. + */ + var EDAM_FOOD_APP_CONTENT_CLASS_PREFIX: string; + + /** + * The content class prefix used for structured notes created by Evernote + * Hello that represents an encounter with a person. When performing a + * wildcard search via filtered sync chunks or search strings, the * + * character must be appended to this constant. + */ + var EDAM_CONTENT_CLASS_HELLO_ENCOUNTER: string; + + /** + * The content class prefix used for structured notes created by Evernote + * Hello that represents the user's profile. When performing a + * wildcard search via filtered sync chunks or search strings, the * + * character must be appended to this constant. + */ + var EDAM_CONTENT_CLASS_HELLO_PROFILE: string; + + /** + * The content class prefix used for structured notes created by + * Evernote Food that captures the experience of a particular meal. + * When performing a wildcard search via filtered sync chunks or search + * strings, the * character must be appended to this constant. + */ + var EDAM_CONTENT_CLASS_FOOD_MEAL: string; + + /** + * The content class prefix used for structured notes created by Evernote + * Skitch. When performing a wildcard search via filtered sync chunks + * or search strings, the * character must be appended to this constant. + */ + var EDAM_CONTENT_CLASS_SKITCH_PREFIX: string; + + /** + * The content class value used for structured image notes created by Evernote + * Skitch. + */ + var EDAM_CONTENT_CLASS_SKITCH: string; + + /** + * The content class value used for structured PDF notes created by Evernote + * Skitch. + */ + var EDAM_CONTENT_CLASS_SKITCH_PDF: string; + + /** + * The content class prefix used for structured notes created by Evernote + * Penultimate. When performing a wildcard search via filtered sync chunks + * or search strings, the * character must be appended to this constant. + */ + var EDAM_CONTENT_CLASS_PENULTIMATE_PREFIX: string; + + /** + * The content class value used for structured notes created by Evernote + * Penultimate that represents a Penultimate notebook. + */ + var EDAM_CONTENT_CLASS_PENULTIMATE_NOTEBOOK: string; + + /** + * The minimum length of the plain text in a findRelated query, assuming that + * plaintext is being provided. + */ + var EDAM_RELATED_PLAINTEXT_LEN_MIN: number; + + /** + * The maximum length of the plain text in a findRelated query, assuming that + * plaintext is being provided. + */ + var EDAM_RELATED_PLAINTEXT_LEN_MAX: number; + + /** + * The maximum number of notes that will be returned from a findRelated() + * query. + */ + var EDAM_RELATED_MAX_NOTES: number; + + /** + * The maximum number of notebooks that will be returned from a findRelated() + * query. + */ + var EDAM_RELATED_MAX_NOTEBOOKS: number; + + /** + * The maximum number of tags that will be returned from a findRelated() query. + */ + var EDAM_RELATED_MAX_TAGS: number; + + /** + * The minimum length, in Unicode characters, of a description for a business + * notebook. + */ + var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MIN: number; + + /** + * The maximum length, in Unicode characters, of a description for a business + * notebook. + */ + var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MAX: number; + + /** + * All business notebook descriptions must match this pattern. + * This excludes control chars or line/paragraph separators. + * The string may not begin or end with whitespace. + */ + var EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_REGEX: string; + + /** + * The maximum length of a business phone number. + */ + var EDAM_BUSINESS_PHONE_NUMBER_LEN_MAX: number; + + /** + * Minimum length of a preference name + */ + var EDAM_PREFERENCE_NAME_LEN_MIN: number; + + /** + * Maximum length of a preference name + */ + var EDAM_PREFERENCE_NAME_LEN_MAX: number; + + /** + * Minimum length of a preference value + */ + var EDAM_PREFERENCE_VALUE_LEN_MIN: number; + + /** + * Maximum length of a preference value + */ + var EDAM_PREFERENCE_VALUE_LEN_MAX: number; + + /** + * Maximum number of name/value pairs allowed + */ + var EDAM_MAX_PREFERENCES: number; + + /** + * Maximum number of values per preference name + */ + var EDAM_MAX_VALUES_PER_PREFERENCE: number; + + /** + * A preference name must match this regex. + */ + var EDAM_PREFERENCE_NAME_REGEX: string; + + /** + * A preference value must match this regex. + */ + var EDAM_PREFERENCE_VALUE_REGEX: string; + + /** + * The name of the preferences entry that contains shortcuts. + */ + var EDAM_PREFERENCE_SHORTCUTS: string; + + /** + * The maximum number of shortcuts that a user may have. + */ + var EDAM_PREFERENCE_SHORTCUTS_MAX_VALUES: number; + + /** + * Maximum length of the device identifier string associated with long sessions. + */ + var EDAM_DEVICE_ID_LEN_MAX: number; + + /** + * Regular expression for device identifier strings associated with long sessions. + */ + var EDAM_DEVICE_ID_REGEX: string; + + /** + * Maximum length of the device description string associated with long sessions. + */ + var EDAM_DEVICE_DESCRIPTION_LEN_MAX: number; + + /** + * Regular expression for device description strings associated with long sessions. + */ + var EDAM_DEVICE_DESCRIPTION_REGEX: string; + + /** + * Maximum number of search suggestions that can be returned + */ + var EDAM_SEARCH_SUGGESTIONS_MAX: number; + + /** + * Maximum length of the search suggestion prefix + */ + var EDAM_SEARCH_SUGGESTIONS_PREFIX_LEN_MAX: number; + + /** + * Minimum length of the search suggestion prefix + */ + var EDAM_SEARCH_SUGGESTIONS_PREFIX_LEN_MIN: number; + class NoteStoreClient { + seqid: number; + + /** + * Asks the NoteStore to provide information about the status of the user + * account corresponding to the provided authentication token. + */ + getSyncState(cb: Callback): void; + + /** + * Asks the NoteStore to provide information about the status of the user + * account corresponding to the provided authentication token. + * This version of 'getSyncState' allows the client to upload coarse- + * grained usage metrics to the service. + * + * @param clientMetrics see the documentation of the ClientUsageMetrics + * structure for an explanation of the fields that clients can pass to + * the service. + */ + getSyncStateWithMetrics(clientMetrics: ClientUsageMetrics, cb: Callback): void; + + /** + * Asks the NoteStore to provide the state of the account in order of + * last modification. This request retrieves one block of the server's + * state so that a client can make several small requests against a large + * account rather than getting the entire state in one big message. + * This call gives fine-grained control of the data that will + * be received by a client by omitting data elements that a client doesn't + * need. This may reduce network traffic and sync times. + * + * @param afterUSN + * The client can pass this value to ask only for objects that + * have been updated after a certain point. This allows the client to + * receive updates after its last checkpoint rather than doing a full + * synchronization on every pass. The default value of "0" indicates + * that the client wants to get objects from the start of the account. + * + * @param maxEntries + * The maximum number of modified objects that should be + * returned in the result SyncChunk. This can be used to limit the size + * of each individual message to be friendly for network transfer. + * + * @param filter + * The caller must set some of the flags in this structure to specify which + * data types should be returned during the synchronization. See + * the SyncChunkFilter structure for information on each flag. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "afterUSN" - if negative + *
    • + *
    • BAD_DATA_FORMAT "maxEntries" - if less than 1 + *
    • + *
    + */ + getFilteredSyncChunk(afterUSN: number, maxEntries: number, filter: SyncChunkFilter, cb: Callback): void; + + /** + * Asks the NoteStore to provide information about the status of a linked + * notebook that has been shared with the caller, or that is public to the + * world. + * This will return a result that is similar to getSyncState, but may omit + * SyncState.uploaded if the caller doesn't have permission to write to + * the linked notebook. + * + * This function must be called on the shard that owns the referenced + * notebook. (I.e. the shardId in /shard/shardId/edam/note must be the + * same as LinkedNotebook.shardId.) + * + * @param authenticationToken + * This should be an authenticationToken for the guest who has received + * the invitation to the share. (I.e. this should not be the result of + * NoteStore.authenticateToSharedNotebook) + * + * @param linkedNotebook + * This structure should contain identifying information and permissions + * to access the notebook in question. + */ + getLinkedNotebookSyncState(linkedNotebook: LinkedNotebook, cb: Callback): void; + + /** + * Asks the NoteStore to provide information about the contents of a linked + * notebook that has been shared with the caller, or that is public to the + * world. + * This will return a result that is similar to getSyncChunk, but will only + * contain entries that are visible to the caller. I.e. only that particular + * Notebook will be visible, along with its Notes, and Tags on those Notes. + * + * This function must be called on the shard that owns the referenced + * notebook. (I.e. the shardId in /shard/shardId/edam/note must be the + * same as LinkedNotebook.shardId.) + * + * @param authenticationToken + * This should be an authenticationToken for the guest who has received + * the invitation to the share. (I.e. this should not be the result of + * NoteStore.authenticateToSharedNotebook) + * + * @param linkedNotebook + * This structure should contain identifying information and permissions + * to access the notebook in question. This must contain the valid fields + * for either a shared notebook (e.g. shareKey) + * or a public notebook (e.g. username, uri) + * + * @param afterUSN + * The client can pass this value to ask only for objects that + * have been updated after a certain point. This allows the client to + * receive updates after its last checkpoint rather than doing a full + * synchronization on every pass. The default value of "0" indicates + * that the client wants to get objects from the start of the account. + * + * @param maxEntries + * The maximum number of modified objects that should be + * returned in the result SyncChunk. This can be used to limit the size + * of each individual message to be friendly for network transfer. + * Applications should not request more than 256 objects at a time, + * and must handle the case where the service returns less than the + * requested number of objects in a given request even though more + * objects are available on the service. + * + * @param fullSyncOnly + * If true, then the client only wants initial data for a full sync. + * In this case, the service will not return any expunged objects, + * and will not return any Resources, since these are also provided + * in their corresponding Notes. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "afterUSN" - if negative + *
    • + *
    • BAD_DATA_FORMAT "maxEntries" - if less than 1 + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "LinkedNotebook" - if the provided information doesn't match any + * valid notebook + *
    • + *
    • "LinkedNotebook.uri" - if the provided public URI doesn't match any + * valid notebook + *
    • + *
    • "SharedNotebook.id" - if the provided information indicates a + * shared notebook that no longer exists + *
    • + *
    + */ + getLinkedNotebookSyncChunk(linkedNotebook: LinkedNotebook, afterUSN: number, maxEntries: number, fullSyncOnly: boolean, cb: Callback): void; + + /** + * Returns a list of all of the notebooks in the account. + */ + listNotebooks(cb: Callback): void; + + /** + * Returns the current state of the notebook with the provided GUID. + * The notebook may be active or deleted (but not expunged). + * + * @param guid + * The GUID of the notebook to be retrieved. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing + *
    • + *
    • PERMISSION_DENIED "Notebook" - private notebook, user doesn't own + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Notebook.guid" - tag not found, by GUID + *
    • + *
    + */ + getNotebook(guid: string, cb: Callback): void; + + /** + * Returns the notebook that should be used to store new notes in the + * user's account when no other notebooks are specified. + */ + getDefaultNotebook(cb: Callback): void; + + /** + * Asks the service to make a notebook with the provided name. + * + * @param notebook + * The desired fields for the notebook must be provided on this + * object. The name of the notebook must be set, and either the 'active' + * or 'defaultNotebook' fields may be set by the client at creation. + * If a notebook exists in the account with the same name (via + * case-insensitive compare), this will throw an EDAMUserException. + * + * @return + * The newly created Notebook. The server-side GUID will be + * saved in this object's 'guid' field. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri + *
    • + *
    • BAD_DATA_FORMAT "Publishing.publicDescription" - if too long + *
    • + *
    • DATA_CONFLICT "Notebook.name" - name already in use + *
    • + *
    • DATA_CONFLICT "Publishing.uri" - if URI already in use + *
    • + *
    • DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing + *
    • + *
    • LIMIT_REACHED "Notebook" - at max number of notebooks + *
    • + *
    + */ + createNotebook(notebook: Notebook, cb: Callback): void; + + /** + * Submits notebook changes to the service. The provided data must include + * the notebook's guid field for identification. + * + * @param notebook + * The notebook object containing the requested changes. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Notebook.name" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Notebook.stack" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Publishing.uri" - if publishing set but bad uri + *
    • + *
    • BAD_DATA_FORMAT "Publishing.publicDescription" - if too long + *
    • + *
    • DATA_CONFLICT "Notebook.name" - name already in use + *
    • + *
    • DATA_CONFLICT "Publishing.uri" - if URI already in use + *
    • + *
    • DATA_REQUIRED "Publishing.uri" - if publishing set but uri missing + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Notebook.guid" - not found, by GUID + *
    • + *
    + */ + updateNotebook(notebook: Notebook, cb: Callback): void; + + /** + * Permanently removes the notebook from the user's account. + * After this action, the notebook is no longer available for undeletion, etc. + * If the notebook contains any Notes, they will be moved to the current + * default notebook and moved into the trash (i.e. Note.active=false). + *

    + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param guid + * The GUID of the notebook to delete. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException

      + *
    • BAD_DATA_FORMAT "Notebook.guid" - if the parameter is missing + *
    • + *
    • LIMIT_REACHED "Notebook" - trying to expunge the last Notebook + *
    • + *
    • PERMISSION_DENIED "Notebook" - private notebook, user doesn't own + *
    • + *
    + */ + expungeNotebook(guid: string, cb: Callback): void; + + /** + * Returns a list of the tags in the account. Evernote does not support + * the undeletion of tags, so this will only include active tags. + */ + listTags(cb: Callback): void; + + /** + * Returns a list of the tags that are applied to at least one note within + * the provided notebook. If the notebook is public, the authenticationToken + * may be ignored. + * + * @param notebookGuid + * the GUID of the notebook to use to find tags + * + * @throws EDAMNotFoundException
      + *
    • "Notebook.guid" - notebook not found by GUID + *
    • + *
    + */ + listTagsByNotebook(notebookGuid: string, cb: Callback): void; + + /** + * Returns the current state of the Tag with the provided GUID. + * + * @param guid + * The GUID of the tag to be retrieved. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Tag.guid" - if the parameter is missing + *
    • + *
    • PERMISSION_DENIED "Tag" - private Tag, user doesn't own + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Tag.guid" - tag not found, by GUID + *
    • + *
    + */ + getTag(guid: string, cb: Callback): void; + + /** + * Asks the service to make a tag with a set of information. + * + * @param tag + * The desired list of fields for the tag are specified in this + * object. The caller must specify the tag name, and may provide + * the parentGUID. + * + * @return + * The newly created Tag. The server-side GUID will be + * saved in this object. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Tag.name" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID + *
    • + *
    • DATA_CONFLICT "Tag.name" - name already in use + *
    • + *
    • LIMIT_REACHED "Tag" - at max number of tags + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Tag.parentGuid" - not found, by GUID + *
    • + *
    + */ + createTag(tag: Tag, cb: Callback): void; + + /** + * Submits tag changes to the service. The provided data must include + * the tag's guid field for identification. The service will apply + * updates to the following tag fields: name, parentGuid + * + * @param tag + * The tag object containing the requested changes. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Tag.name" - invalid length or pattern + *
    • + *
    • BAD_DATA_FORMAT "Tag.parentGuid" - malformed GUID + *
    • + *
    • DATA_CONFLICT "Tag.name" - name already in use + *
    • + *
    • DATA_CONFLICT "Tag.parentGuid" - can't set parent: circular + *
    • + *
    • PERMISSION_DENIED "Tag" - user doesn't own tag + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Tag.guid" - tag not found, by GUID + *
    • + *
    • "Tag.parentGuid" - parent not found, by GUID + *
    • + *
    + */ + updateTag(tag: Tag, cb: Callback): void; + + /** + * Removes the provided tag from every note that is currently tagged with + * this tag. If this operation is successful, the tag will still be in + * the account, but it will not be tagged on any notes. + * + * This function is not indended for use by full synchronizing clients, since + * it does not provide enough result information to the client to reconcile + * the local state without performing a follow-up sync from the service. This + * is intended for "thin clients" that need to efficiently support this as + * a UI operation. + * + * @param guid + * The GUID of the tag to remove from all notes. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing + *
    • + *
    • PERMISSION_DENIED "Tag" - user doesn't own tag + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Tag.guid" - tag not found, by GUID + *
    • + *
    + */ + untagAll(guid: string, cb: Callback): void; + + /** + * Permanently deletes the tag with the provided GUID, if present. + *

    + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param guid + * The GUID of the tag to delete. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException

      + *
    • BAD_DATA_FORMAT "Tag.guid" - if the guid parameter is missing + *
    • + *
    • PERMISSION_DENIED "Tag" - user doesn't own tag + *
    • + *
    + * + * @throws EDAMNotFoundException
      + *
    • "Tag.guid" - tag not found, by GUID + *
    • + *
    + */ + expungeTag(guid: string, cb: Callback): void; + + /** + * Returns a list of the searches in the account. Evernote does not support + * the undeletion of searches, so this will only include active searches. + */ + listSearches(cb: Callback): void; + + /** + * Returns the current state of the search with the provided GUID. + * + * @param guid + * The GUID of the search to be retrieved. + * + * @throws EDAMUserException
      + *
    • BAD_DATA_FORMAT "SavedSearch.guid" - if the parameter is missing + *
    • + *
    • PERMISSION_DENIED "SavedSearch" - private Tag, user doesn't own + *
    • + * + * @throws EDAMNotFoundException
        + *
      • "SavedSearch.guid" - not found, by GUID + *
      • + *
      + */ + getSearch(guid: string, cb: Callback): void; + + /** + * Asks the service to make a saved search with a set of information. + * + * @param search + * The desired list of fields for the search are specified in this + * object. The caller must specify the name and query for the + * search, and may optionally specify a search scope. + * The SavedSearch.format field is ignored by the service. + * + * @return + * The newly created SavedSearch. The server-side GUID will be + * saved in this object. + * + * @throws EDAMUserException
        + *
      • BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern + *
      • + *
      • BAD_DATA_FORMAT "SavedSearch.query" - invalid length + *
      • + *
      • DATA_CONFLICT "SavedSearch.name" - name already in use + *
      • + *
      • LIMIT_REACHED "SavedSearch" - at max number of searches + *
      • + *
      + */ + createSearch(search: SavedSearch, cb: Callback): void; + + /** + * Submits search changes to the service. The provided data must include + * the search's guid field for identification. The service will apply + * updates to the following search fields: name, query, and scope. + * + * @param search + * The search object containing the requested changes. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException
        + *
      • BAD_DATA_FORMAT "SavedSearch.name" - invalid length or pattern + *
      • + *
      • BAD_DATA_FORMAT "SavedSearch.query" - invalid length + *
      • + *
      • DATA_CONFLICT "SavedSearch.name" - name already in use + *
      • + *
      • PERMISSION_DENIED "SavedSearch" - user doesn't own tag + *
      • + *
      + * + * @throws EDAMNotFoundException
        + *
      • "SavedSearch.guid" - not found, by GUID + *
      • + *
      + */ + updateSearch(search: SavedSearch, cb: Callback): number; + + /** + * Permanently deletes the saved search with the provided GUID, if present. + *

      + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param guid + * The GUID of the search to delete. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException

        + *
      • BAD_DATA_FORMAT "SavedSearch.guid" - if the guid parameter is empty + *
      • + *
      • PERMISSION_DENIED "SavedSearch" - user doesn't own + *
      • + *
      + * + * @throws EDAMNotFoundException
        + *
      • "SavedSearch.guid" - not found, by GUID + *
      • + *
      + */ + expungeSearch(guid: string, cb: Callback): void; + + /** + * DEPRECATED. Use findNotesMetadata. + */ + findNotes(filter: NoteFilter, offset: number, maxNotes: number, cb: Callback): void; + + /** + * Finds the position of a note within a sorted subset of all of the user's + * notes. This may be useful for thin clients that are displaying a paginated + * listing of a large account, which need to know where a particular note + * sits in the list without retrieving all notes first. + * + * @param authenticationToken + * Must be a valid token for the user's account unless the NoteFilter + * 'notebookGuid' is the GUID of a public notebook. + * + * @param filter + * The list of criteria that will constrain the notes to be returned. + * + * @param guid + * The GUID of the note to be retrieved. + * + * @return + * If the note with the provided GUID is found within the matching note + * list, this will return the offset of that note within that list (where + * the first offset is 0). If the note is not found within the set of + * notes, this will return -1. + * + * @throws EDAMUserException
        + *
      • BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX + *
      • + *
      • BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX + *
      • + *
      • BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed + *
      • + *
      • BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed + *
      • + *
      • BAD_DATA_FORMAT "NoteFilter.words" - if search string too long + *
      • + * + * @throws EDAMNotFoundException
          + *
        • "Notebook.guid" - not found, by GUID + *
        • + *
        • "Note.guid" - not found, by GUID + *
        • + *
        + */ + findNoteOffset(filter: NoteFilter, guid: string, cb: Callback): void; + + /** + * Used to find the high-level information about a set of the notes from a + * user's account based on various criteria specified via a NoteFilter object. + *

        + * Web applications that wish to periodically check for new content in a user's + * Evernote account should consider using webhooks instead of polling this API. + * See http://dev.evernote.com/documentation/cloud/chapters/polling_notification.php + * for more information. + * + * @param authenticationToken + * Must be a valid token for the user's account unless the NoteFilter + * 'notebookGuid' is the GUID of a public notebook. + * + * @param filter + * The list of criteria that will constrain the notes to be returned. + * + * @param offset + * The numeric index of the first note to show within the sorted + * results. The numbering scheme starts with "0". This can be used for + * pagination. + * + * @param maxNotes + * The mximum notes to return in this query. The service will return a set + * of notes that is no larger than this number, but may return fewer notes + * if needed. The NoteList.totalNotes field in the return value will + * indicate whether there are more values available after the returned set. + * + * @param resultSpec + * This specifies which information should be returned for each matching + * Note. The fields on this structure can be used to eliminate data that + * the client doesn't need, which will reduce the time and bandwidth + * to receive and process the reply. + * + * @return + * The list of notes that match the criteria. + * + * @throws EDAMUserException

          + *
        • BAD_DATA_FORMAT "offset" - not between 0 and EDAM_USER_NOTES_MAX + *
        • + *
        • BAD_DATA_FORMAT "maxNotes" - not between 0 and EDAM_USER_NOTES_MAX + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.words" - if search string too long + *
        • + *
        + * + * @throws EDAMNotFoundException
          + *
        • "Notebook.guid" - not found, by GUID + *
        • + *
        + */ + findNotesMetadata(filter: NoteFilter, offset: number, maxNotes: number, resultSpec: NotesMetadataResultSpec, cb: Callback): void; + + /** + * This function is used to determine how many notes are found for each + * notebook and tag in the user's account, given a current set of filter + * parameters that determine the current selection. This function will + * return a structure that gives the note count for each notebook and tag + * that has at least one note under the requested filter. Any notebook or + * tag that has zero notes in the filtered set will not be listed in the + * reply to this function (so they can be assumed to be 0). + * + * @param authenticationToken + * Must be a valid token for the user's account unless the NoteFilter + * 'notebookGuid' is the GUID of a public notebook. + * + * @param filter + * The note selection filter that is currently being applied. The note + * counts are to be calculated with this filter applied to the total set + * of notes in the user's account. + * + * @param withTrash + * If true, then the NoteCollectionCounts.trashCount will be calculated + * and supplied in the reply. Otherwise, the trash value will be omitted. + * + * @throws EDAMUserException
          + *
        • BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.notebookGuids" - if any are malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.words" - if search string too long + *
        • + * + * @throws EDAMNotFoundException
            + *
          • "Notebook.guid" - not found, by GUID + *
          • + *
          + */ + findNoteCounts(filter: NoteFilter, withTrash: boolean, cb: Callback): void; + + /** + * Returns the current state of the note in the service with the provided + * GUID. The ENML contents of the note will only be provided if the + * 'withContent' parameter is true. The service will include the meta-data + * for each resource in the note, but the binary contents of the resources + * and their recognition data will be omitted. + * If the Note is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). The applicationData + * fields are returned as keysOnly. + * + * @param guid + * The GUID of the note to be retrieved. + * + * @param withContent + * If true, the note will include the ENML contents of its + * 'content' field. + * + * @param withResourcesData + * If true, any Resource elements in this Note will include the binary + * contents of their 'data' field's body. + * + * @param withResourcesRecognition + * If true, any Resource elements will include the binary contents of the + * 'recognition' field's body if recognition data is present. + * + * @param withResourcesAlternateData + * If true, any Resource elements in this Note will include the binary + * contents of their 'alternateData' fields' body, if an alternate form + * is present. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + getNote(guid: string, withContent: boolean, withResourcesData: boolean, withResourcesRecognition: boolean, withResourcesAlternateData: boolean, cb: Callback): void; + + /** + * Get all of the application data for the note identified by GUID, + * with values returned within the LazyMap fullMap field. + * If there are no applicationData entries, then a LazyMap + * with an empty fullMap will be returned. If your application + * only needs to fetch its own applicationData entry, use + * getNoteApplicationDataEntry instead. + */ + getNoteApplicationData(guid: string, cb: Callback): void; + + /** + * Get the value of a single entry in the applicationData map + * for the note identified by GUID. + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - note not found, by GUID
          • + *
          • "NoteAttributes.applicationData.key" - note not found, by key
          • + *
          + */ + getNoteApplicationDataEntry(guid: string, key: string, cb: Callback): void; + + /** + * Update, or create, an entry in the applicationData map for + * the note identified by guid. + */ + setNoteApplicationDataEntry(guid: string, key: string, value: string, cb: Callback): void; + + /** + * Remove an entry identified by 'key' from the applicationData map for + * the note identified by 'guid'. Silently ignores an unset of a + * non-existing key. + */ + unsetNoteApplicationDataEntry(guid: string, key: string, cb: Callback): void; + + /** + * Returns XHTML contents of the note with the provided GUID. + * If the Note is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the note to be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + getNoteContent(guid: string, cb: Callback): void; + + /** + * Returns a block of the extracted plain text contents of the note with the + * provided GUID. This text can be indexed for search purposes by a light + * client that doesn't have capabilities to extract all of the searchable + * text content from the note and its resources. + * + * If the Note is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the note to be retrieved. + * + * @param noteOnly + * If true, this will only return the text extracted from the ENML contents + * of the note itself. If false, this will also include the extracted text + * from any text-bearing resources (PDF, recognized images) + * + * @param tokenizeForIndexing + * If true, this will break the text into cleanly separated and sanitized + * tokens. If false, this will return the more raw text extraction, with + * its original punctuation, capitalization, spacing, etc. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + getNoteSearchText(guid: string, noteOnly: boolean, tokenizeForIndexing: boolean, cb: Callback): void; + + /** + * Returns a block of the extracted plain text contents of the resource with + * the provided GUID. This text can be indexed for search purposes by a light + * client that doesn't have capability to extract all of the searchable + * text content from a resource. + * + * If the Resource is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the resource to be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          + */ + getResourceSearchText(guid: string, cb: Callback): void; + + /** + * Returns a list of the names of the tags for the note with the provided + * guid. This can be used with authentication to get the tags for a + * user's own note, or can be used without valid authentication to retrieve + * the names of the tags for a note in a public notebook. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + getNoteTagNames(guid: string, cb: Callback): void; + + /** + * Asks the service to make a note with the provided set of information. + * + * @param note + * A Note object containing the desired fields to be populated on + * the service. + * + * @return + * The newly created Note from the service. The server-side + * GUIDs for the Note and any Resources will be saved in this object. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.title" - invalid length or pattern + *
          • + *
          • BAD_DATA_FORMAT "Note.content" - invalid length for ENML content + *
          • + *
          • BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type + *
          • + *
          • BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string + *
          • + *
          • BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string + *
          • + *
          • DATA_CONFLICT "Note.deleted" - deleted time set on active note + *
          • + *
          • DATA_REQUIRED "Resource.data" - resource data body missing + *
          • + *
          • ENML_VALIDATION "*" - note content doesn't validate against DTD + *
          • + *
          • LIMIT_REACHED "Note" - at max number per account + *
          • + *
          • LIMIT_REACHED "Note.size" - total note size too large + *
          • + *
          • LIMIT_REACHED "Note.resources" - too many resources on Note + *
          • + *
          • LIMIT_REACHED "Note.tagGuids" - too many Tags on Note + *
          • + *
          • LIMIT_REACHED "Resource.data.size" - resource too large + *
          • + *
          • LIMIT_REACHED "NoteAttribute.*" - attribute string too long + *
          • + *
          • LIMIT_REACHED "ResourceAttribute.*" - attribute string too long + *
          • + *
          • PERMISSION_DENIED "Note.notebookGuid" - NB not owned by user + *
          • + *
          • QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota + *
          • + *
          • BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one + * of the specified tags had an invalid length or pattern + *
          • + *
          • LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required + * new tags would exceed the maximum number per account + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.notebookGuid" - not found, by GUID + *
          • + *
          + */ + createNote(note: Note, cb: Callback): void; + + /** + * Submit a set of changes to a note to the service. The provided data + * must include the note's guid field for identification. The note's + * title must also be set. + * + * @param note + * A Note object containing the desired fields to be populated on + * the service. With the exception of the note's title and guid, fields + * that are not being changed do not need to be set. If the content is not + * being modified, note.content should be left unset. If the list of + * resources is not being modified, note.resources should be left unset. + * + * @return + * The metadata (no contents) for the Note on the server after the update + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.title" - invalid length or pattern + *
          • + *
          • BAD_DATA_FORMAT "Note.content" - invalid length for ENML body + *
          • + *
          • BAD_DATA_FORMAT "NoteAttributes.*" - bad resource string + *
          • + *
          • BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string + *
          • + *
          • BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type + *
          • + *
          • DATA_CONFLICT "Note.deleted" - deleted time set on active note + *
          • + *
          • DATA_REQUIRED "Resource.data" - resource data body missing + *
          • + *
          • ENML_VALIDATION "*" - note content doesn't validate against DTD + *
          • + *
          • LIMIT_REACHED "Note.tagGuids" - too many Tags on Note + *
          • + *
          • LIMIT_REACHED "Note.resources" - too many resources on Note + *
          • + *
          • LIMIT_REACHED "Note.size" - total note size too large + *
          • + *
          • LIMIT_REACHED "Resource.data.size" - resource too large + *
          • + *
          • LIMIT_REACHED "NoteAttribute.*" - attribute string too long + *
          • + *
          • LIMIT_REACHED "ResourceAttribute.*" - attribute string too long + *
          • + *
          • PERMISSION_DENIED "Note" - user doesn't own + *
          • + *
          • PERMISSION_DENIED "Note.notebookGuid" - user doesn't own destination + *
          • + *
          • QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota + *
          • + *
          • BAD_DATA_FORMAT "Tag.name" - Note.tagNames was provided, and one + * of the specified tags had an invalid length or pattern + *
          • + *
          • LIMIT_REACHED "Tag" - Note.tagNames was provided, and the required + * new tags would exceed the maximum number per account + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - note not found, by GUID + *
          • + *
          • "Note.notebookGuid" - if notebookGuid provided, but not found + *
          • + *
          + */ + updateNote(note: Note, cb: Callback): void; + + /** + * Moves the note into the trash. The note may still be undeleted, unless it + * is expunged. This is equivalent to calling updateNote() after setting + * Note.active = false + * + * @param guid + * The GUID of the note to delete. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException
            + *
          • PERMISSION_DENIED "Note" - user doesn't have permission to + * update the note. + *
          • + *
          + * + * @throws EDAMUserException
            + *
          • DATA_CONFLICT "Note.guid" - the note is already deleted + *
          • + *
          + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + deleteNote(guid: string, cb: Callback): void; + + /** + * Permanently removes a Note, and all of its Resources, + * from the service. + *

          + * NOTE: This function is not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param guid + * The GUID of the note to delete. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException

            + *
          • PERMISSION_DENIED "Note" - user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + expungeNote(guid: string, cb: Callback): void; + + /** + * Permanently removes a list of Notes, and all of their Resources, from + * the service. This should be invoked with a small number of Note GUIDs + * (e.g. 100 or less) on each call. To expunge a larger number of notes, + * call this method multiple times. This should also be used to reduce the + * number of Notes in a notebook before calling expungeNotebook() or + * in the trash before calling expungeInactiveNotes(), since these calls may + * be prohibitively slow if there are more than a few hundred notes. + * If an exception is thrown for any of the GUIDs, then none of the notes + * will be deleted. I.e. this call can be treated as an atomic transaction. + *

          + * NOTE: This function is not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param noteGuids + * The list of GUIDs for the Notes to remove. + * + * @return + * The account's updateCount at the end of this operation + * + * @throws EDAMUserException

            + *
          • PERMISSION_DENIED "Note" - user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + expungeNotes(noteGuids: string[], cb: Callback): void; + + /** + * Permanently removes all of the Notes that are currently marked as + * inactive. This is equivalent to "emptying the trash", and these Notes + * will be gone permanently. + *

          + * This operation may be relatively slow if the account contains a large + * number of inactive Notes. + *

          + * NOTE: This function is not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @return + * The number of notes that were expunged. + */ + expungeInactiveNotes(cb: Callback): void; + + /** + * Performs a deep copy of the Note with the provided GUID 'noteGuid' into + * the Notebook with the provided GUID 'toNotebookGuid'. + * The caller must be the owner of both the Note and the Notebook. + * This creates a new Note in the destination Notebook with new content and + * Resources that match all of the content and Resources from the original + * Note, but with new GUID identifiers. + * The original Note is not modified by this operation. + * The copied note is considered as an "upload" for the purpose of upload + * transfer limit calculation, so its size is added to the upload count for + * the owner. + * + * @param noteGuid + * The GUID of the Note to copy. + * + * @param toNotebookGuid + * The GUID of the Notebook that should receive the new Note. + * + * @return + * The metadata for the new Note that was created. This will include the + * new GUID for this Note (and any copied Resources), but will not include + * the content body or the binary bodies of any Resources. + * + * @throws EDAMUserException

            + *
          • LIMIT_REACHED "Note" - at max number per account + *
          • + *
          • PERMISSION_DENIED "Notebook.guid" - destination not owned by user + *
          • + *
          • PERMISSION_DENIED "Note" - user doesn't own + *
          • + *
          • QUOTA_REACHED "Accounting.uploadLimit" - note exceeds upload quota + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Notebook.guid" - not found, by GUID + *
          • + *
          + */ + copyNote(noteGuid: string, toNotebookGuid: string, cb: Callback): void; + + /** + * Returns a list of the prior versions of a particular note that are + * saved within the service. These prior versions are stored to provide a + * recovery from unintentional removal of content from a note. The identifiers + * that are returned by this call can be used with getNoteVersion to retrieve + * the previous note. + * The identifiers will be listed from the most recent versions to the oldest. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + listNoteVersions(noteGuid: string, cb: Callback): void; + + /** + * This can be used to retrieve a previous version of a Note after it has been + * updated within the service. The caller must identify the note (via its + * guid) and the version (via the updateSequenceNumber of that version). + * to find a listing of the stored version USNs for a note, call + * listNoteVersions. + * This call is only available for notes in Premium accounts. (I.e. access + * to past versions of Notes is a Premium-only feature.) + * + * @param noteGuid + * The GUID of the note to be retrieved. + * + * @param updateSequenceNum + * The USN of the version of the note that is being retrieved + * + * @param withResourcesData + * If true, any Resource elements in this Note will include the binary + * contents of their 'data' field's body. + * + * @param withResourcesRecognition + * If true, any Resource elements will include the binary contents of the + * 'recognition' field's body if recognition data is present. + * + * @param withResourcesAlternateData + * If true, any Resource elements in this Note will include the binary + * contents of their 'alternateData' fields' body, if an alternate form + * is present. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          • PERMISSION_DENIED "updateSequenceNum" - + * The account isn't permitted to access previous versions of notes. + * (i.e. this is a Free account.) + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          • "Note.updateSequenceNumber" - the Note doesn't have a version with + * the corresponding USN. + *
          • + *
          + */ + getNoteVersion(noteGuid: string, updateSequenceNum: number, withResourcesData: boolean, withResourcesRecognition: boolean, withResourcesAlternateData: boolean, cb: Callback): void; + + /** + * Returns the current state of the resource in the service with the + * provided GUID. + * If the Resource is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). Only the + * keys for the applicationData will be returned. + * + * @param guid + * The GUID of the resource to be retrieved. + * + * @param withData + * If true, the Resource will include the binary contents of the + * 'data' field's body. + * + * @param withRecognition + * If true, the Resource will include the binary contents of the + * 'recognition' field's body if recognition data is present. + * + * @param withAttributes + * If true, the Resource will include the attributes + * + * @param withAlternateData + * If true, the Resource will include the binary contents of the + * 'alternateData' field's body, if an alternate form is present. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          + */ + getResource(guid: string, withData: boolean, withRecognition: boolean, withAttributes: boolean, withAlternateData: boolean, cb: Callback): void; + + /** + * Get all of the application data for the Resource identified by GUID, + * with values returned within the LazyMap fullMap field. + * If there are no applicationData entries, then a LazyMap + * with an empty fullMap will be returned. If your application + * only needs to fetch its own applicationData entry, use + * getResourceApplicationDataEntry instead. + */ + getResourceApplicationData(guid: string, cb: Callback): void; + + /** + * Get the value of a single entry in the applicationData map + * for the Resource identified by GUID. + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - Resource not found, by GUID
          • + *
          • "ResourceAttributes.applicationData.key" - Resource not found, by key
          • + *
          + */ + getResourceApplicationDataEntry(guid: string, key: string, cb: Callback): void; + + /** + * Update, or create, an entry in the applicationData map for + * the Resource identified by guid. + */ + setResourceApplicationDataEntry(guid: string, key: string, value: string, cb: Callback): void; + + /** + * Remove an entry identified by 'key' from the applicationData map for + * the Resource identified by 'guid'. + */ + unsetResourceApplicationDataEntry(guid: string, key: string, cb: Callback): void; + + /** + * Submit a set of changes to a resource to the service. This can be used + * to update the meta-data about the resource, but cannot be used to change + * the binary contents of the resource (including the length and hash). These + * cannot be changed directly without creating a new resource and removing the + * old one via updateNote. + * + * @param resource + * A Resource object containing the desired fields to be populated on + * the service. The service will attempt to update the resource with the + * following fields from the client: + *
            + *
          • guid: must be provided to identify the resource + *
          • + *
          • mime + *
          • + *
          • width + *
          • + *
          • height + *
          • + *
          • duration + *
          • + *
          • attributes: optional. if present, the set of attributes will + * be replaced. + *
          • + *
          + * + * @return + * The Update Sequence Number of the resource after the changes have been + * applied. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • BAD_DATA_FORMAT "Resource.mime" - invalid resource MIME type + *
          • + *
          • BAD_DATA_FORMAT "ResourceAttributes.*" - bad resource string + *
          • + *
          • LIMIT_REACHED "ResourceAttribute.*" - attribute string too long + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          + */ + updateResource(resource: Resource, cb: Callback): void; + + /** + * Returns binary data of the resource with the provided GUID. For + * example, if this were an image resource, this would contain the + * raw bits of the image. + * If the Resource is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the resource to be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          + */ + getResourceData(guid: string, cb: Callback): void; + + /** + * Returns the current state of a resource, referenced by containing + * note GUID and resource content hash. + * + * @param noteGuid + * The GUID of the note that holds the resource to be retrieved. + * + * @param contentHash + * The MD5 checksum of the resource within that note. Note that + * this is the binary checksum, for example from Resource.data.bodyHash, + * and not the hex-encoded checksum that is used within an en-media + * tag in a note body. + * + * @param withData + * If true, the Resource will include the binary contents of the + * 'data' field's body. + * + * @param withRecognition + * If true, the Resource will include the binary contents of the + * 'recognition' field's body. + * + * @param withAlternateData + * If true, the Resource will include the binary contents of the + * 'alternateData' field's body, if an alternate form is present. + * + * @throws EDAMUserException
            + *
          • DATA_REQUIRED "Note.guid" - noteGuid param missing + *
          • + *
          • DATA_REQUIRED "Note.contentHash" - contentHash param missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note" - not found, by guid + *
          • + *
          • "Resource" - not found, by hash + *
          • + *
          + */ + getResourceByHash(noteGuid: string, contentHash: string, withData: boolean, withRecognition: boolean, withAlternateData: boolean, cb: Callback): void; + + /** + * Returns the binary contents of the recognition index for the resource + * with the provided GUID. If the caller asks about a resource that has + * no recognition data, this will throw EDAMNotFoundException. + * If the Resource is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the resource whose recognition data should be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          • "Resource.recognition" - resource has no recognition + *
          • + *
          + */ + getResourceRecognition(guid: string, cb: Callback): void; + + /** + * If the Resource with the provided GUID has an alternate data representation + * (indicated via the Resource.alternateData field), then this request can + * be used to retrieve the binary contents of that alternate data file. + * If the caller asks about a resource that has no alternate data form, this + * will throw EDAMNotFoundException. + * + * @param guid + * The GUID of the resource whose recognition data should be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          • "Resource.alternateData" - resource has no recognition + *
          • + *
          + */ + getResourceAlternateData(guid: string, cb: Callback): void; + + /** + * Returns the set of attributes for the Resource with the provided GUID. + * If the Resource is found in a public notebook, the authenticationToken + * will be ignored (so it could be an empty string). + * + * @param guid + * The GUID of the resource whose attributes should be retrieved. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Resource.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Resource" - private resource, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Resource.guid" - not found, by GUID + *
          • + *
          + */ + getResourceAttributes(guid: string, cb: Callback): void; + + /** + *

          + * Looks for a user account with the provided userId on this NoteStore + * shard and determines whether that account contains a public notebook + * with the given URI. If the account is not found, or no public notebook + * exists with this URI, this will throw an EDAMNotFoundException, + * otherwise this will return the information for that Notebook. + *

          + *

          + * If a notebook is visible on the web with a full URL like + * http://www.evernote.com/pub/sethdemo/api + * Then 'sethdemo' is the username that can be used to look up the userId, + * and 'api' is the publicUri. + *

          + * + * @param userId + * The numeric identifier for the user who owns the public notebook. + * To find this value based on a username string, you can invoke + * UserStore.getPublicUserInfo + * + * @param publicUri + * The uri string for the public notebook, from Notebook.publishing.uri. + * + * @throws EDAMNotFoundException
            + *
          • "Publishing.uri" - not found, by URI
          • + *
          + * + * @throws EDAMSystemException
            + *
          • TAKEN_DOWN "PublicNotebook" - The specified public notebook is + * taken down (for all requesters).
          • + *
          • TAKEN_DOWN "Country" - The specified public notebook is taken + * down for the requester because of an IP-based country lookup.
          • + *
          + */ + getPublicNotebook(userId: number, publicUri: string, cb: Callback): void; + + /** + * Used to construct a shared notebook object. The constructed notebook will + * contain a "share key" which serve as a unique identifer and access token + * for a user to access the notebook of the shared notebook owner. + * + * @param sharedNotebook + * A shared notebook object populated with the email address of the share + * recipient, the notebook guid and the access permissions. All other + * attributes of the shared object are ignored. The SharedNotebook.allowPreview + * field must be explicitly set with either a true or false value. + * + * @return + * The fully populated SharedNotebook object including the server assigned + * share id and shareKey which can both be used to uniquely identify the + * SharedNotebook. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid
          • + *
          • BAD_DATA_FORMAT "requireLogin" - if the SharedNotebook.allowPreview field was + * not set, and the SharedNotebook.requireLogin was also not set or was set to + * false.
          • + *
          • PERMISSION_DENIED "SharedNotebook.recipientSettings" - if + * recipientSettings is set in the sharedNotebook. Only the recipient + * can set these values via the setSharedNotebookRecipientSettings + * method. + *
          • + *
          + * @throws EDAMNotFoundException
            + *
          • Notebook.guid - if the notebookGuid is not a valid GUID for the user. + *
          • + *
          + */ + createSharedNotebook(sharedNotebook: SharedNotebook, cb: Callback): void; + + /** + * Update a SharedNotebook object. + * + * @param authenticationToken + * Must be an authentication token from the owner or a shared notebook + * authentication token or business authentication token with sufficient + * permissions to change invitations for a notebook. + * + * @param sharedNotebook + * The SharedNotebook object containing the requested changes. + * The "id" of the shared notebook must be set to allow the service + * to identify the SharedNotebook to be updated. In addition, you MUST set + * the email, permission, and allowPreview fields to the desired values. + * All other fields will be ignored if set. + * + * @return + * The Update Serial Number for this change within the account. + * + * @throws EDAMUserException
            + *
          • UNSUPPORTED_OPERATION "updateSharedNotebook" - if this service instance does not support shared notebooks.
          • + *
          • BAD_DATA_FORMAT "SharedNotebook.email" - if the email was not valid.
          • + *
          • DATA_REQUIRED "SharedNotebook.id" - if the id field was not set.
          • + *
          • DATA_REQUIRED "SharedNotebook.privilege" - if the privilege field was not set.
          • + *
          • DATA_REQUIRED "SharedNotebook.allowPreview" - if the allowPreview field was not set.
          • + *
          + * @throws EDAMNotFoundException
            + *
          • SharedNotebook.id - if no shared notebook with the specified ID was found. + *
          + */ + updateSharedNotebook(sharedNotebook: SharedNotebook, cb: Callback): void; + + /** + * Set values for the recipient settings associated with a shared notebook. Having + * update rights to the shared notebook record itself has no effect on this call; + * only the recipient of the shared notebook can can the recipient settings. + * + * If you do not wish to, or cannot, change one of the reminderNotifyEmail or + * reminderNotifyInApp fields, you must leave that field unset in recipientSettings. + * This method will skip that field for updates and leave the existing state as + * it is. + * + * @return The update sequence number of the account to which the shared notebook + * belongs, which is the account from which we are sharing a notebook. + * + * @throws EDAMNotFoundException "sharedNotebookId" - Thrown if the service does not + * have a shared notebook record for the sharedNotebookId on the given shard. If you + * receive this exception, it is probable that the shared notebook record has + * been revoked or expired, or that you accessed the wrong shard. + * + * @throws EDAMUserException
            + *
          • PEMISSION_DENIED "authenticationToken" - If you do not have permission to set + * the recipient settings for the shared notebook. Only the recipient has + * permission to do this. + *
          • DATA_CONFLICT "recipientSettings.reminderNotifyEmail" - Setting whether + * or not you want to receive reminder e-mail notifications is possible on + * a business notebook in the business to which the user belongs. All + * others can safely unset the reminderNotifyEmail field from the + * recipientSettings parameter. + *
          + */ + setSharedNotebookRecipientSettings(sharedNotebookId: number, recipientSettings: SharedNotebookRecipientSettings, cb: Callback): void; + + /** + * Send a reminder message to some or all of the email addresses that a notebook has been + * shared with. The message includes the current link to view the notebook. + * @param authenticationToken + * The auth token of the user with permissions to share the notebook + * @param notebookGuid + * The guid of the shared notebook + * @param messageText + * User provided text to include in the email + * @param recipients + * The email addresses of the recipients. If this list is empty then all of the + * users that the notebook has been shared with are emailed. + * If an email address doesn't correspond to share invite members then that address + * is ignored. + * @return + * The number of messages sent + * @throws EDAMUserException
            + *
          • LIMIT_REACHED "(recipients)" - + * The email can't be sent because this would exceed the user's daily + * email limit. + *
          • + *
          • PERMISSION_DENIED "Notebook.guid" - The user doesn't have permission to + * send a message for the specified notebook. + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Notebook.guid" - not found, by GUID + *
          • + *
          + */ + sendMessageToSharedNotebookMembers(notebookGuid: string, messageText: string, recipients: string[], cb: Callback): void; + + /** + * Lists the collection of shared notebooks for all notebooks in the + * users account. + * + * @return + * The list of all SharedNotebooks for the user + */ + listSharedNotebooks(cb: Callback): void; + + /** + * Expunges the SharedNotebooks in the user's account using the + * SharedNotebook.id as the identifier. + *

          + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param + * sharedNotebookIds - a list of ShardNotebook.id longs identifying the + * objects to delete permanently. + * + * @return + * The account's update sequence number. + */ + expungeSharedNotebooks(sharedNotebookIds: number[], cb: Callback): void; + + /** + * Asks the service to make a linked notebook with the provided name, username + * of the owner and identifiers provided. A linked notebook can be either a + * link to a public notebook or to a private shared notebook. + * + * @param linkedNotebook + * The desired fields for the linked notebook must be provided on this + * object. The name of the linked notebook must be set. Either a username + * uri or a shard id and share key must be provided otherwise a + * EDAMUserException is thrown. + * + * @return + * The newly created LinkedNotebook. The server-side id will be + * saved in this object's 'id' field. + * + * @throws EDAMUserException

            + *
          • BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern + *
          • + *
          • BAD_DATA_FORMAT "LinkedNotebook.username" - bad username format + *
          • + *
          • BAD_DATA_FORMAT "LinkedNotebook.uri" - + * if public notebook set but bad uri + *
          • + *
          • BAD_DATA_FORMAT "LinkedNotebook.shareKey" - + * if private notebook set but bad shareKey + *
          • + *
          • DATA_REQUIRED "LinkedNotebook.shardId" - + * if private notebook but shard id not provided + *
          • + *
          + */ + createLinkedNotebook(linkedNotebook: LinkedNotebook, cb: Callback): void; + + /** + * @param linkedNotebook + * Updates the name of a linked notebook. + * + * @return + * The Update Sequence Number for this change within the account. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "LinkedNotebook.name" - invalid length or pattern + *
          • + *
          + */ + updateLinkedNotebook(linkedNotebook: LinkedNotebook, cb: Callback): void; + + /** + * Returns a list of linked notebooks + */ + listLinkedNotebooks(cb: Callback): void; + + /** + * Permanently expunges the linked notebook from the account. + *

          + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param guid + * The LinkedNotebook.guid field of the LinkedNotebook to permanently remove + * from the account. + */ + expungeLinkedNotebook(guid: string, cb: Callback): void; + + /** + * Asks the service to produce an authentication token that can be used to + * access the contents of a shared notebook from someone else's account. + * This authenticationToken can be used with the various other NoteStore + * calls to find and retrieve notes, and if the permissions in the shared + * notebook are sufficient, to make changes to the contents of the notebook. + * + * @param shareKey + * The 'shareKey' identifier from the SharedNotebook that was granted to + * some recipient. This string internally encodes the notebook identifier + * and a security signature. + * + * @param authenticationToken + * If a non-empty string is provided, this is the full user-based + * authentication token that identifies the user who is currently logged in + * and trying to access the shared notebook. This may be required if the + * notebook was created with 'requireLogin'. + * If this string is empty, the service will attempt to authenticate to the + * shared notebook without any logged in user. + * + * @throws EDAMSystemException

            + *
          • BAD_DATA_FORMAT "shareKey" - invalid shareKey string + *
          • + *
          • INVALID_AUTH "shareKey" - bad signature on shareKey string + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "SharedNotebook.id" - the shared notebook no longer exists + *
          • + *
          + * + * @throws EDAMUserException
            + *
          • DATA_REQUIRED "authenticationToken" - the share requires login, and + * no valid authentication token was provided. + *
          • + *
          • PERMISSION_DENIED "SharedNotebook.username" - share requires login, + * and another username has already been bound to this notebook. + *
          • + *
          + */ + authenticateToSharedNotebook(shareKey: string, cb: Callback): void; + + /** + * This function is used to retrieve extended information about a shared + * notebook by a guest who has already authenticated to access that notebook. + * This requires an 'authenticationToken' parameter which should be the + * resut of a call to authenticateToSharedNotebook(...). + * I.e. this is the token that gives access to the particular shared notebook + * in someone else's account -- it's not the authenticationToken for the + * owner of the notebook itself. + * + * @param authenticationToken + * Should be the authentication token retrieved from the reply of + * authenticateToSharedNotebook(), proving access to a particular shared + * notebook. + * + * @throws EDAMUserException
            + *
          • PERMISSION_DENIED "authenticationToken" - + * authentication token doesn't correspond to a valid shared notebook + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "SharedNotebook.id" - the shared notebook no longer exists + *
          • + *
          + */ + getSharedNotebookByAuth(cb: Callback): void; + + /** + * Attempts to send a single note to one or more email recipients. + *

          + * NOTE: This function is generally not available to third party applications. + * Calls will result in an EDAMUserException with the error code + * PERMISSION_DENIED. + * + * @param authenticationToken + * The note will be sent as the user logged in via this token, using that + * user's registered email address. If the authenticated user doesn't + * have permission to read that note, the emailing will fail. + * + * @param parameters + * The note must be specified either by GUID (in which case it will be + * sent using the existing data in the service), or else the full Note + * must be passed to this call. This also specifies the additional + * email fields that will be used in the email. + * + * @throws EDAMUserException

            + *
          • LIMIT_REACHED "NoteEmailParameters.toAddresses" - + * The email can't be sent because this would exceed the user's daily + * email limit. + *
          • + *
          • BAD_DATA_FORMAT "(email address)" - + * email address malformed + *
          • + *
          • DATA_REQUIRED "NoteEmailParameters.toAddresses" - + * if there are no To: or Cc: addresses provided. + *
          • + *
          • DATA_REQUIRED "Note.title" - + * if the caller provides a Note parameter with no title + *
          • + *
          • DATA_REQUIRED "Note.content" - + * if the caller provides a Note parameter with no content + *
          • + *
          • ENML_VALIDATION "*" - note content doesn't validate against DTD + *
          • + *
          • DATA_REQUIRED "NoteEmailParameters.note" - + * if no guid or note provided + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + emailNote(parameters: NoteEmailParameters, cb: Callback): void; + + /** + * If this note is not already shared (via its own direct URL), then this + * will start sharing that note. + * This will return the secret "Note Key" for this note that + * can currently be used in conjunction with the Note's GUID to gain direct + * read-only access to the Note. + * If the note is already shared, then this won't make any changes to the + * note, and the existing "Note Key" will be returned. The only way to change + * the Note Key for an existing note is to stopSharingNote first, and then + * call this function. + * + * @param guid + * The GUID of the note to be shared. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + shareNote(guid: string, cb: Callback): void; + + /** + * If this note is not already shared then this will stop sharing that note + * and invalidate its "Note Key", so any existing URLs to access that Note + * will stop working. + * If the Note is not shared, then this function will do nothing. + * + * @param guid + * The GUID of the note to be un-shared. + * + * @throws EDAMUserException
            + *
          • BAD_DATA_FORMAT "Note.guid" - if the parameter is missing + *
          • + *
          • PERMISSION_DENIED "Note" - private note, user doesn't own + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "Note.guid" - not found, by GUID + *
          • + *
          + */ + stopSharingNote(guid: string, cb: Callback): void; + + /** + * Asks the service to produce an authentication token that can be used to + * access the contents of a single Note which was individually shared + * from someone's account. + * This authenticationToken can be used with the various other NoteStore + * calls to find and retrieve the Note and its directly-referenced children. + * + * @param guid + * The GUID identifying this Note on this shard. + * + * @param noteKey + * The 'noteKey' identifier from the Note that was originally created via + * a call to shareNote() and then given to a recipient to access. + * + * @param authenticationToken + * An optional authenticationToken that identifies the user accessing the + * shared note. This parameter may be required to access some shared notes. + * + * @throws EDAMUserException
            + *
          • PERMISSION_DENIED "Note" - the Note with that GUID is either not + * shared, or the noteKey doesn't match the current key for this note + *
          • + *
          • PERMISSION_DENIED "authenticationToken" - an authentication token is + * required to access this Note, but either no authentication token or a + * "non-owner" authentication token was provided. + *
          • + *
          + * + * @throws EDAMNotFoundException
            + *
          • "guid" - the note with that GUID is not found + *
          • + *
          + * + * @throws EDAMSystemException
            + *
          • TAKEN_DOWN "Note" - The specified shared note is taken down (for + * all requesters). + *
          • + *
          • TAKEN_DOWN "Country" - The specified shared note is taken down + * for the requester because of an IP-based country lookup. + *
          + *
        + */ + authenticateToSharedNote(guid: string, noteKey: string, cb: Callback): void; + + /** + * Identify related entities on the service, such as notes, + * notebooks, and tags related to notes or content. + * + * @param query + * The information about which we are finding related entities. + * + * @param resultSpec + * Allows the client to indicate the type and quantity of + * information to be returned, allowing a saving of time and + * bandwidth. + * + * @return + * The result of the query, with information considered + * to likely be relevantly related to the information + * described by the query. + * + * @throws EDAMUserException
          + *
        • BAD_DATA_FORMAT "RelatedQuery.plainText" - If you provided a + * a zero-length plain text value. + *
        • + *
        • BAD_DATA_FORMAT "RelatedQuery.noteGuid" - If you provided an + * invalid Note GUID, that is, one that does not match the constraints + * defined by EDAM_GUID_LEN_MIN, EDAM_GUID_LEN_MAX, EDAM_GUID_REGEX. + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.notebookGuid" - if malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.tagGuids" - if any are malformed + *
        • + *
        • BAD_DATA_FORMAT "NoteFilter.words" - if search string too long + *
        • + *
        • PERMISSION_DENIED "Note" - If the caller does not have access to + * the note identified by RelatedQuery.noteGuid. + *
        • + *
        • DATA_REQUIRED "RelatedResultSpec" - If you did not not set any values + * in the result spec. + *
        • + *
        + * + * @throws EDAMNotFoundException
          + *
        • "RelatedQuery.noteGuid" - the note with that GUID is not + * found, if that field has been set in the query. + *
        • + *
        + */ + findRelated(query: RelatedQuery, resultSpec: RelatedResultSpec, cb: Callback): void; + } + /** + * This structure encapsulates the information about the state of the + * user's account for the purpose of "state based" synchronization. + *
        + *
        currentTime
        + *
        + * The server's current date and time. + *
        + * + *
        fullSyncBefore
        + *
        + * The cutoff date and time for client caches to be + * updated via incremental synchronization. Any clients that were last + * synched with the server before this date/time must do a full resync of all + * objects. This cutoff point will change over time as archival data is + * deleted or special circumstances on the service require resynchronization. + *
        + * + *
        updateCount
        + *
        + * Indicates the total number of transactions that have + * been committed within the account. This reflects (for example) the + * number of discrete additions or modifications that have been made to + * the data in this account (tags, notes, resources, etc.). + * This number is the "high water mark" for Update Sequence Numbers (USN) + * within the account. + *
        + * + *
        uploaded
        + *
        + * The total number of bytes that have been uploaded to + * this account in the current monthly period. This can be compared against + * Accounting.uploadLimit (from the UserStore) to determine how close the user + * is to their monthly upload limit. + * This value may not be present if the SyncState has been retrieved by + * a caller that only has read access to the account. + *
        + *
        + */ + class SyncState { + currentTime: number; + fullSyncBefore: number; + updateCount: number; + uploaded: number; + + constructor(args?: { currentTime: number; fullSyncBefore: number; updateCount: number; uploaded?: number; }); + } + + /** + * This structure is given out by the NoteStore when a client asks to + * receive the current state of an account. The client asks for the server's + * state one chunk at a time in order to allow clients to retrieve the state + * of a large account without needing to transfer the entire account in + * a single message. + * + * The server always gives SyncChunks using an ascending series of Update + * Sequence Numbers (USNs). + * + *
        + *
        currentTime
        + *
        + * The server's current date and time. + *
        + * + *
        chunkHighUSN
        + *
        + * The highest USN for any of the data objects represented + * in this sync chunk. If there are no objects in the chunk, this will not be + * set. + *
        + * + *
        updateCount
        + *
        + * The total number of updates that have been performed in + * the service for this account. This is equal to the highest USN within the + * account at the point that this SyncChunk was generated. If updateCount + * and chunkHighUSN are identical, that means that this is the last chunk + * in the account ... there is no more recent information. + *
        + * + *
        notes
        + *
        + * If present, this is a list of non-expunged notes that + * have a USN in this chunk. This will include notes that are "deleted" + * but not expunged (i.e. in the trash). The notes will include their list + * of tags and resources, but the note content, resource content, resource + * recognition data and resource alternate data will not be supplied. + *
        + * + *
        notebooks
        + *
        + * If present, this is a list of non-expunged notebooks that + * have a USN in this chunk. This will include notebooks that are "deleted" + * but not expunged (i.e. in the trash). + *
        + * + *
        tags
        + *
        + * If present, this is a list of the non-expunged tags that have a + * USN in this chunk. + *
        + * + *
        searches
        + *
        + * If present, this is a list of non-expunged searches that + * have a USN in this chunk. + *
        + * + *
        resources
        + *
        + * If present, this is a list of the non-expunged resources + * that have a USN in this chunk. This will include the metadata for each + * resource, but not its binary contents or recognition data, which must be + * retrieved separately. + *
        + * + *
        expungedNotes
        + *
        + * If present, the GUIDs of all of the notes that were + * permanently expunged in this chunk. + *
        + * + *
        expungedNotebooks
        + *
        + * If present, the GUIDs of all of the notebooks that + * were permanently expunged in this chunk. When a notebook is expunged, + * this implies that all of its child notes (and their resources) were + * also expunged. + *
        + * + *
        expungedTags
        + *
        + * If present, the GUIDs of all of the tags that were + * permanently expunged in this chunk. + *
        + * + *
        expungedSearches
        + *
        + * If present, the GUIDs of all of the saved searches + * that were permanently expunged in this chunk. + *
        + * + *
        linkedNotebooks
        + *
        + * If present, this is a list of non-expunged LinkedNotebooks that + * have a USN in this chunk. + *
        + * + *
        expungedLinkedNotebooks
        + *
        + * If present, the GUIDs of all of the LinkedNotebooks + * that were permanently expunged in this chunk. + *
        + *
        + */ + class SyncChunk { + currentTime: number; + chunkHighUSN: number; + updateCount: number; + notes: Note[]; + notebooks: Notebook[]; + tags: Tag[]; + searches: SavedSearch[]; + resources: Resource[]; + expungedNotes: string[]; + expungedNotebooks: string[]; + expungedTags: string[]; + expungedSearches: string[]; + linkedNotebooks: LinkedNotebook[]; + expungedLinkedNotebooks: string[]; + + constructor(args?: { currentTime: number; chunkHighUSN?: number; updateCount: number; notes?: Note[]; notebooks?: Notebook[]; tags?: Tag[]; searches?: SavedSearch[]; resources?: Resource[]; expungedNotes?: string[]; expungedNotebooks?: string[]; expungedTags?: string[]; expungedSearches?: string[]; linkedNotebooks?: LinkedNotebook[]; expungedLinkedNotebooks?: string[]; }); + } + + /** + * This structure is used with the 'getFilteredSyncChunk' call to provide + * fine-grained control over the data that's returned when a client needs + * to synchronize with the service. Each flag in this structure specifies + * whether to include one class of data in the results of that call. + * + *
        + *
        includeNotes
        + *
        + * If true, then the server will include the SyncChunks.notes field + *
        + * + *
        includeNoteResources
        + *
        + * If true, then the server will include the 'resources' field on all of + * the Notes that are in SyncChunk.notes. + * If 'includeNotes' is false, then this will have no effect. + *
        + * + *
        includeNoteAttributes
        + *
        + * If true, then the server will include the 'attributes' field on all of + * the Notes that are in SyncChunks.notes. + * If 'includeNotes' is false, then this will have no effect. + *
        + * + *
        includeNotebooks
        + *
        + * If true, then the server will include the SyncChunks.notebooks field + *
        + * + *
        includeTags
        + *
        + * If true, then the server will include the SyncChunks.tags field + *
        + * + *
        includeSearches
        + *
        + * If true, then the server will include the SyncChunks.searches field + *
        + * + *
        includeResources
        + *
        + * If true, then the server will include the SyncChunks.resources field. + * Since the Resources are also provided with their Note + * (in the Notes.resources list), this is primarily useful for clients that + * want to watch for changes to individual Resources due to recognition data + * being added. + *
        + * + *
        includeLinkedNotebooks
        + *
        + * If true, then the server will include the SyncChunks.linkedNotebooks field. + *
        + * + *
        includeExpunged
        + *
        + * If true, then the server will include the 'expunged' data for any type + * of included data. For example, if 'includeTags' and 'includeExpunged' + * are both true, then the SyncChunks.expungedTags field will be set with + * the GUIDs of tags that have been expunged from the server. + *
        + * + *
        includeNoteApplicationDataFullMap
        + *
        + * If true, then the values for the applicationData map will be filled + * in, assuming notes and note attributes are being returned. Otherwise, + * only the keysOnly field will be filled in. + *
        + * + *
        includeResourceApplicationDataFullMap
        + *
        + * If true, then the fullMap values for the applicationData map will be + * filled in, assuming resources and resource attributes are being returned + * (includeResources is true). Otherwise, only the keysOnly field will be + * filled in. + *
        + * + *
        includeNoteResourceApplicationDataFullMap
        + *
        + * If true, then the fullMap values for the applicationData map will be + * filled in for resources found inside of notes, assuming resources are + * being returned in notes (includeNoteResources is true). Otherwise, + * only the keysOnly field will be filled in. + *
        + * + *
        requireNoteContentClass
        + *
        + * If set, then only send notes whose content class matches this value. + * The value can be a literal match or, if the last character is an + * asterisk, a prefix match. + *
        + *
        + */ + class SyncChunkFilter { + includeNotes: boolean; + includeNoteResources: boolean; + includeNoteAttributes: boolean; + includeNotebooks: boolean; + includeTags: boolean; + includeSearches: boolean; + includeResources: boolean; + includeLinkedNotebooks: boolean; + includeExpunged: boolean; + includeNoteApplicationDataFullMap: boolean; + includeResourceApplicationDataFullMap: boolean; + includeNoteResourceApplicationDataFullMap: boolean; + requireNoteContentClass: string; + + constructor(args?: { includeNotes?: boolean; includeNoteResources?: boolean; includeNoteAttributes?: boolean; includeNotebooks?: boolean; includeTags?: boolean; includeSearches?: boolean; includeResources?: boolean; includeLinkedNotebooks?: boolean; includeExpunged?: boolean; includeNoteApplicationDataFullMap?: boolean; includeResourceApplicationDataFullMap?: boolean; includeNoteResourceApplicationDataFullMap?: boolean; requireNoteContentClass?: string; }); + } + + /** + * A list of criteria that are used to indicate which notes are desired from + * the account. This is used in queries to the NoteStore to determine + * which notes should be retrieved. + * + *
        + *
        order
        + *
        + * The NoteSortOrder value indicating what criterion should be + * used to sort the results of the filter. + *
        + * + *
        ascending
        + *
        + * If true, the results will be ascending in the requested + * sort order. If false, the results will be descending. + *
        + * + *
        words
        + *
        + * If present, a search query string that will filter the set of notes to be returned. + * Accepts the full search grammar documented in the Evernote API Overview. + *
        + * + *
        notebookGuid
        + *
        + * If present, the Guid of the notebook that must contain + * the notes. + *
        + * + *
        tagGuids
        + *
        + * If present, the list of tags (by GUID) that must be present + * on the notes. + *
        + * + *
        timeZone
        + *
        + * The zone ID for the user, which will be used to interpret + * any dates or times in the queries that do not include their desired zone + * information. + * For example, if a query requests notes created "yesterday", this + * will be evaluated from the provided time zone, if provided. + * The format must be encoded as a standard zone ID such as + * "America/Los_Angeles". + *
        + * + *
        inactive
        + *
        + * If true, then only notes that are not active (i.e. notes in + * the Trash) will be returned. Otherwise, only active notes will be returned. + * There is no way to find both active and inactive notes in a single query. + *
        + * + *
        emphasized
        + *
        + * If present, a search query string that may or may not influence the notes + * to be returned, both in terms of coverage as well as of order. Think of it + * as a wish list, not a requirement. + * Accepts the full search grammar documented in the Evernote API Overview. + *
        + *
        + */ + class NoteFilter { + order: number; + ascending: boolean; + words: string; + notebookGuid: string; + tagGuids: string[]; + timeZone: string; + inactive: boolean; + emphasized: string; + + constructor(args?: { order?: number; ascending?: boolean; words?: string; notebookGuid?: string; tagGuids?: string[]; timeZone?: string; inactive?: boolean; emphasized?: string; }); + } + + /** + * A small structure for returning a list of notes out of a larger set. + * + *
        + *
        startIndex
        + *
        + * The starting index within the overall set of notes. This + * is also the number of notes that are "before" this list in the set. + *
        + * + *
        totalNotes
        + *
        + * The number of notes in the larger set. This can be used + * to calculate how many notes are "after" this note in the set. + * (I.e. remaining = totalNotes - (startIndex + notes.length) ) + *
        + * + *
        notes
        + *
        + * The list of notes from this range. The Notes will include all + * metadata (attributes, resources, etc.), but will not include the ENML + * content of the note or the binary contents of any resources. + *
        + * + *
        stoppedWords
        + *
        + * If the NoteList was produced using a text based search + * query that included words that are not indexed or searched by the service, + * this will include a list of those ignored words. + *
        + * + *
        searchedWords
        + *
        + * If the NoteList was produced using a text based search + * query that included viable search words or quoted expressions, this will + * include a list of those words. Any stopped words will not be included + * in this list. + *
        + * + *
        updateCount
        + *
        + * Indicates the total number of transactions that have + * been committed within the account. This reflects (for example) the + * number of discrete additions or modifications that have been made to + * the data in this account (tags, notes, resources, etc.). + * This number is the "high water mark" for Update Sequence Numbers (USN) + * within the account. + *
        + *
        + */ + class NoteList { + startIndex: number; + totalNotes: number; + notes: Note[]; + stoppedWords: string[]; + searchedWords: string[]; + updateCount: number; + + constructor(args?: { startIndex: number; totalNotes: number; notes: Note[]; stoppedWords?: string[]; searchedWords?: string[]; updateCount?: number; }); + } + + /** + * This structure is used in the set of results returned by the + * findNotesMetadata function. It represents the high-level information about + * a single Note, without some of the larger deep structure. This allows + * for the information about a list of Notes to be returned relatively quickly + * with less marshalling and data transfer to remote clients. + * Most fields in this structure are identical to the corresponding field in + * the Note structure, with the exception of: + * + *
        + *
        largestResourceMime
        + *
        If set, then this will contain the MIME type of the largest Resource + * (in bytes) within the Note. This may be useful, for example, to choose + * an appropriate icon or thumbnail to represent the Note. + *
        + * + *
        largestResourceSize
        + *
        If set, this will contain the size of the largest Resource file, in + * bytes, within the Note. This may be useful, for example, to decide whether + * to ask the server for a thumbnail to represent the Note. + *
        + *
        + */ + class NoteMetadata { + guid: string; + title: string; + contentLength: number; + created: number; + updated: number; + deleted: number; + updateSequenceNum: number; + notebookGuid: string; + tagGuids: string[]; + attributes: NoteAttributes; + largestResourceMime: string; + largestResourceSize: number; + + constructor(args?: { guid: string; title?: string; contentLength?: number; created?: number; updated?: number; deleted?: number; updateSequenceNum?: number; notebookGuid?: string; tagGuids?: string[]; attributes?: NoteAttributes; largestResourceMime?: string; largestResourceSize?: number; }); + } + + /** + * This structure is returned from calls to the findNotesMetadata function to + * give the high-level metadata about a subset of Notes that are found to + * match a specified NoteFilter in a search. + * + *
        + *
        startIndex
        + *
        + * The starting index within the overall set of notes. This + * is also the number of notes that are "before" this list in the set. + *
        + * + *
        totalNotes
        + *
        + * The number of notes in the larger set. This can be used + * to calculate how many notes are "after" this note in the set. + * (I.e. remaining = totalNotes - (startIndex + notes.length) ) + *
        + * + *
        notes
        + *
        + * The list of metadata for Notes in this range. The set of optional fields + * that are set in each metadata structure will depend on the + * NotesMetadataResultSpec provided by the caller when the search was + * performed. Only the 'guid' field will be guaranteed to be set in each + * Note. + *
        + * + *
        stoppedWords
        + *
        + * If the NoteList was produced using a text based search + * query that included words that are not indexed or searched by the service, + * this will include a list of those ignored words. + *
        + * + *
        searchedWords
        + *
        + * If the NoteList was produced using a text based search + * query that included viable search words or quoted expressions, this will + * include a list of those words. Any stopped words will not be included + * in this list. + *
        + * + *
        updateCount
        + *
        + * Indicates the total number of transactions that have + * been committed within the account. This reflects (for example) the + * number of discrete additions or modifications that have been made to + * the data in this account (tags, notes, resources, etc.). + * This number is the "high water mark" for Update Sequence Numbers (USN) + * within the account. + *
        + *
        + */ + class NotesMetadataList { + startIndex: number; + totalNotes: number; + notes: NoteMetadata[]; + stoppedWords: string[]; + searchedWords: string[]; + updateCount: number; + + constructor(args?: { startIndex: number; totalNotes: number; notes: NoteMetadata[]; stoppedWords?: string[]; searchedWords?: string[]; updateCount?: number; }); + } + + /** + * This structure is provided to the findNotesMetadata function to specify + * the subset of fields that should be included in each NoteMetadata element + * that is returned in the NotesMetadataList. + * Each field on this structure is a boolean flag that indicates whether the + * corresponding field should be included in the NoteMetadata structure when + * it is returned. For example, if the 'includeTitle' field is set on this + * structure when calling findNotesMetadata, then each NoteMetadata in the + * list should have its 'title' field set. + * If one of the fields in this spec is not set, then it will be treated as + * 'false' by the server, so the default behavior is to include nothing in + * replies (but the mandatory GUID) + */ + class NotesMetadataResultSpec { + includeTitle: boolean; + includeContentLength: boolean; + includeCreated: boolean; + includeUpdated: boolean; + includeDeleted: boolean; + includeUpdateSequenceNum: boolean; + includeNotebookGuid: boolean; + includeTagGuids: boolean; + includeAttributes: boolean; + includeLargestResourceMime: boolean; + includeLargestResourceSize: boolean; + + constructor(args?: { includeTitle?: boolean; includeContentLength?: boolean; includeCreated?: boolean; includeUpdated?: boolean; includeDeleted?: boolean; includeUpdateSequenceNum?: boolean; includeNotebookGuid?: boolean; includeTagGuids?: boolean; includeAttributes?: boolean; includeLargestResourceMime?: boolean; includeLargestResourceSize?: boolean; }); + } + + /** + * A data structure representing the number of notes for each notebook + * and tag with a non-zero set of applicable notes. + * + *
        + *
        notebookCounts
        + *
        + * A mapping from the Notebook GUID to the number of + * notes (from some selection) that are in the corresponding notebook. + *
        + * + *
        tagCounts
        + *
        + * A mapping from the Tag GUID to the number of notes (from some + * selection) that have the corresponding tag. + *
        + * + *
        trashCount
        + *
        + * If this is set, then this is the number of notes that are in the trash. + * If this is not set, then the number of notes in the trash hasn't been + * reported. (I.e. if there are no notes in the trash, this will be set + * to 0.) + *
        + *
        + */ + class NoteCollectionCounts { + notebookCounts: { [k: string]: number; }; + tagCounts: { [k: string]: number; }; + trashCount: number; + + constructor(args?: { notebookCounts?: { [k: string]: number; }; tagCounts?: { [k: string]: number; }; trashCount?: number; }); + } + + /** + * Parameters that must be given to the NoteStore emailNote call. These allow + * the caller to specify the note to send, the recipient addresses, etc. + * + *
        + *
        guid
        + *
        + * If set, this must be the GUID of a note within the user's account that + * should be retrieved from the service and sent as email. If not set, + * the 'note' field must be provided instead. + *
        + * + *
        note
        + *
        + * If the 'guid' field is not set, this field must be provided, including + * the full contents of the note note (and all of its Resources) to send. + * This can be used for a Note that as not been created in the service, + * for example by a local client with local notes. + *
        + * + *
        toAddresses
        + *
        + * If provided, this should contain a list of the SMTP email addresses + * that should be included in the "To:" line of the email. + * Callers must specify at least one "to" or "cc" email address. + *
        + * + *
        ccAddresses
        + *
        + * If provided, this should contain a list of the SMTP email addresses + * that should be included in the "Cc:" line of the email. + * Callers must specify at least one "to" or "cc" email address. + *
        + * + *
        subject
        + *
        + * If provided, this should contain the subject line of the email that + * will be sent. If not provided, the title of the note will be used + * as the subject of the email. + *
        + * + *
        message
        + *
        + * If provided, this is additional personal text that should be included + * into the email as a message from the owner to the recipient(s). + *
        + *
        + */ + class NoteEmailParameters { + guid: string; + note: Note; + toAddresses: string[]; + ccAddresses: string[]; + subject: string; + message: string; + + constructor(args?: { guid?: string; note?: Note; toAddresses?: string[]; ccAddresses?: string[]; subject?: string; message?: string; }); + } + + /** + * Identifying information about previous versions of a note that are backed up + * within Evernote's servers. Used in the return value of the listNoteVersions + * call. + * + *
        + *
        updateSequenceNum
        + *
        + * The update sequence number for the Note when it last had this content. + * This serves to uniquely identify each version of the note, since USN + * values are unique within an account for each update. + *
        + *
        updated
        + *
        + * The 'updated' time that was set on the Note when it had this version + * of the content. This is the user-modifiable modification time on the + * note, so it's not reliable for guaranteeing the order of various + * versions. (E.g. if someone modifies the note, then changes this time + * manually into the past and then updates the note again.) + *
        + *
        saved
        + *
        + * A timestamp that holds the date and time when this version of the note + * was backed up by Evernote's servers. This + *
        + *
        title
        + *
        + * The title of the note when this particular version was saved. (The + * current title of the note may differ from this value.) + *
        + *
        + */ + class NoteVersionId { + updateSequenceNum: number; + updated: number; + saved: number; + title: string; + + constructor(args?: { updateSequenceNum: number; updated: number; saved: number; title: string; }); + } + + /** + * This structure is passed from clients to the Evernote service when they wish + * to relay coarse-grained usage metrics to the service to help improve + * products. + * + *
        + *
        sessions
        + *
        + * This field contains a count of the number of usage "sessions" that have + * occurred with this client which have not previously been reported to + * the service. + * A "session" is defined as one of the 96 fifteen-minute intervals of the + * day when someone used Evernote's interface at least once. + * So if a user interacts with an Evernote client at 12:18, 12:24, and 12:36, + * and then the client synchronizes at 12:39, it would report that there were + * two previously-unreported sessions (one session for the 12:15-12:30 time + * period, and one for the 12:30-12:45 period). + * If the user used Evernote again at 12:41 and synchronized at 12:43, it + * would not report any new sessions, because the 12:30-12:45 session had + * already been reported. + *
        + *
        + */ + class ClientUsageMetrics { + sessions: number; + + constructor(args?: { sessions?: number; }); + } + + /** + * A description of the thing for which we are searching for related + * entities. + * + * You must specify either noteGuid or plainText, but + * not both. filter and referenceUri are optional. + * + *
        + *
        noteGuid
        + *
        The GUID of an existing note in your account for which related + * entities will be found.
        + * + *
        plainText
        + *
        A string of plain text for which to find related entities. + * You should provide a text block with a number of characters between + * EDAM_RELATED_PLAINTEXT_LEN_MIN and EDAM_RELATED_PLAINTEXT_LEN_MAX. + *
        + * + *
        filter
        + *
        The list of criteria that will constrain the notes being considered + * related. + * Please note that some of the parameters may be ignored, such as + * order and ascending. + *
        + * + *
        referenceUri
        + *
        A URI string specifying a reference entity, around which "relatedness" + * should be based. This can be an URL pointing to a web page, for example. + *
        + *
        + */ + class RelatedQuery { + noteGuid: string; + plainText: string; + filter: NoteFilter; + referenceUri: string; + + constructor(args?: { noteGuid?: string; plainText?: string; filter?: NoteFilter; referenceUri?: string; }); + } + + /** + * The result of calling findRelated(). The contents of the notes, + * notebooks, and tags fields will be in decreasing order of expected + * relevance. It is possible that fewer results than requested will be + * returned even if there are enough distinct entities in the account + * in cases where the relevance is estimated to be low. + * + *
        + *
        notes
        + *
        If notes have been requested to be included, this will be the + * list of notes.
        + * + *
        notebooks
        + *
        If notebooks have been requested to be included, this will be the + * list of notebooks.
        + * + *
        tags
        + *
        If tags have been requested to be included, this will be the list + * of tags.
        + *
        + * + *
        containingNotebooks
        + *
        If includeContainingNotebooks is set to true + * in the RelatedResultSpec, return the list of notebooks to + * to which the returned related notes belong. The notebooks in this + * list will occur once per notebook GUID and are represented as + * NotebookDescriptor objects.
        + * + * + */ + class RelatedResult { + notes: Note[]; + notebooks: Notebook[]; + tags: Tag[]; + containingNotebooks: NotebookDescriptor[]; + + constructor(args?: { notes?: Note[]; notebooks?: Notebook[]; tags?: Tag[]; containingNotebooks?: NotebookDescriptor[]; }); + } + + /** + * A description of the thing for which the service will find related + * entities, via findRelated(), together with a description of what + * type of entities and how many you are seeking in the + * RelatedResult. + * + *
        + *
        maxNotes
        + *
        Return notes that are related to the query, but no more than + * this many. Any value greater than EDAM_RELATED_MAX_NOTES + * will be silently capped. If you do not set this field, then + * no notes will be returned.
        + * + *
        maxNotebooks
        + *
        Return notebooks that are related to the query, but no more than + * this many. Any value greater than EDAM_RELATED_MAX_NOTEBOOKS + * will be silently capped. If you do not set this field, then + * no notebooks will be returned.
        + * + *
        maxTags
        + *
        Return tags that are related to the query, but no more than + * this many. Any value greater than EDAM_RELATED_MAX_TAGS + * will be silently capped. If you do not set this field, then + * no tags will be returned.
        + *
        + * + *
        writableNotebooksOnly
        + *
        Require that all returned related notebooks are writable. + * The user will be able to create notes in all returned notebooks. + * However, individual notes returned may still belong to notebooks + * in which the user lacks the ability to create notes.
        + * + * + *
        includeContainingNotebooks
        + *
        If set to true, return the containingNotebooks field + * in the RelatedResult, which will contain the list of notebooks to + * to which the returned related notes belong.
        + * + * + */ + class RelatedResultSpec { + maxNotes: number; + maxNotebooks: number; + maxTags: number; + writableNotebooksOnly: boolean; + includeContainingNotebooks: boolean; + + constructor(args?: { maxNotes?: number; maxNotebooks?: number; maxTags?: number; writableNotebooksOnly?: boolean; includeContainingNotebooks?: boolean; }); + } + /** + * This enumeration defines the possible permission levels for a user. + * Free accounts will have a level of NORMAL and paid Premium accounts + * will have a level of PREMIUM. + */ + enum PrivilegeLevel { + 'NORMAL' = 1, + 'PREMIUM' = 3, + 'VIP' = 5, + 'MANAGER' = 7, + 'SUPPORT' = 8, + 'ADMIN' = 9, + } + + /** + * Every search query is specified as a sequence of characters. + * Currently, only the USER query format is supported. + */ + enum QueryFormat { + 'USER' = 1, + 'SEXP' = 2, + } + + /** + * This enumeration defines the possible sort ordering for notes when + * they are returned from a search result. + */ + enum NoteSortOrder { + 'CREATED' = 1, + 'UPDATED' = 2, + 'RELEVANCE' = 3, + 'UPDATE_SEQUENCE_NUMBER' = 4, + 'TITLE' = 5, + } + + /** + * This enumeration defines the possible states of a premium account + * + * NONE: the user has never attempted to become a premium subscriber + * + * PENDING: the user has requested a premium account but their charge has not + * been confirmed + * + * ACTIVE: the user has been charged and their premium account is in good + * standing + * + * FAILED: the system attempted to charge the was denied. Their premium + * privileges have been revoked. We will periodically attempt to re-validate + * their order. + * + * CANCELLATION_PENDING: the user has requested that no further charges be made + * but the current account is still active. + * + * CANCELED: the premium account was canceled either because of failure to pay + * or user cancelation. No more attempts will be made to activate the account. + */ + enum PremiumOrderStatus { + 'NONE' = 0, + 'PENDING' = 1, + 'ACTIVE' = 2, + 'FAILED' = 3, + 'CANCELLATION_PENDING' = 4, + 'CANCELED' = 5, + } + + /** + * Privilege levels for accessing shared notebooks. + * + * READ_NOTEBOOK: Recipient is able to read the contents of the shared notebook + * but does to have access to information about other recipients of the + * notebook or the activity stream information. + * + * MODIFY_NOTEBOOK_PLUS_ACTIVITY: Recipient has rights to read and modify the contents + * of the shared notebook, including the right to move notes to the trash and to create + * notes in the notebook. The recipient can also access information about other + * recipients and the activity stream. + * + * READ_NOTEBOOK_PLUS_ACTIVITY: Recipient has READ_NOTEBOOK rights and can also + * access information about other recipients and the activity stream. + * + * GROUP: If the user belongs to a group, such as a Business, that has a defined + * privilege level, use the privilege level of the group as the privilege for + * the individual. + * + * FULL_ACCESS: Recipient has full rights to the shared notebook and recipient lists, + * including privilege to revoke and create invitations and to change privilege + * levels on invitations for individuals. This privilege level is primarily intended + * for use by individual shares. + * + * BUSINESS_FULL_ACCESS: Intended for use with Business Notebooks, a + * BUSINESS_FULL_ACCESS level is FULL_ACCESS with the additional rights to + * change how the notebook will appear in the business library, including the + * rights to publish and unpublish the notebook from the library. + */ + enum SharedNotebookPrivilegeLevel { + 'READ_NOTEBOOK' = 0, + 'MODIFY_NOTEBOOK_PLUS_ACTIVITY' = 1, + 'READ_NOTEBOOK_PLUS_ACTIVITY' = 2, + 'GROUP' = 3, + 'FULL_ACCESS' = 4, + 'BUSINESS_FULL_ACCESS' = 5, + } + + /** + * Enumeration of the roles that a User can have within a sponsored group. + * + * GROUP_MEMBER: The user is a member of the group with no special privileges. + * + * GROUP_ADMIN: The user is an administrator within the group. + * + * GROUP_OWNER: The user is the owner of the group. + */ + enum SponsoredGroupRole { + 'GROUP_MEMBER' = 1, + 'GROUP_ADMIN' = 2, + 'GROUP_OWNER' = 3, + } + + /** + * Enumeration of the roles that a User can have within an Evernote Business account. + * + * ADMIN: The user is an administrator of the Evernote Business account. + * + * NORMAL: The user is a regular user within the Evernote Business account. + */ + enum BusinessUserRole { + 'ADMIN' = 1, + 'NORMAL' = 2, + } + + /** + * An enumeration describing restrictions on the domain of shared notebook + * instances that are valid for a given operation, as used, for example, in + * NotebookRestrictions. + * + * ONLY_JOINED_OR_PREVIEW: The domain consists of shared notebooks that + * "belong" to the recipient or still available for preview by any recipient. + * Shared notebooks that the recipient has joined (the username has already been + * assigned to our user) are in the domain. Additionally, shared notebooks + * that allow preview and have not yet been joined are in the domain. + * + * NO_SHARED_NOTEBOOKS: No shared notebooks are applicable to the operation. + */ + enum SharedNotebookInstanceRestrictions { + 'ONLY_JOINED_OR_PREVIEW' = 1, + 'NO_SHARED_NOTEBOOKS' = 2, + } + + /** + * An enumeration describing the configuration state related to receiving + * reminder e-mails from the service. Reminder e-mails summarize notes + * based on their Note.attributes.reminderTime values. + * + * DO_NOT_SEND: The user has selected to not receive reminder e-mail. + * + * SEND_DAILY_EMAIL: The user has selected to receive reminder e-mail for those + * days when there is a reminder. + */ + enum ReminderEmailConfig { + 'DO_NOT_SEND' = 1, + 'SEND_DAILY_EMAIL' = 2, + } + + /** + * In several places, EDAM exchanges blocks of bytes of data for a component + * which may be relatively large. For example: the contents of a clipped + * HTML note, the bytes of an embedded image, or the recognition XML for + * a large image. This structure is used in the protocol to represent + * any of those large blocks of data when they are transmitted or when + * they are only referenced their metadata. + * + *
        + *
        bodyHash
        + *
        This field carries a one-way hash of the contents of the + * data body, in binary form. The hash function is MD5
        + * Length: EDAM_HASH_LEN (exactly) + *
        + * + *
        size
        + *
        The length, in bytes, of the data body. + *
        + * + *
        body
        + *
        This field is set to contain the binary contents of the data + * whenever the resource is being transferred. If only metadata is + * being exchanged, this field will be empty. For example, a client could + * notify the service about the change to an attribute for a resource + * without transmitting the binary resource contents. + *
        + *
        + */ + class Data { + bodyHash: string; + size: number; + body: string; + + constructor(args?: { bodyHash?: string; size?: number; body?: string; }); + } + + /** + * A structure holding the optional attributes that can be stored + * on a User. These are generally less critical than the core User fields. + * + *
        + *
        defaultLocationName
        + *
        the location string that should be associated + * with the user in order to determine where notes are taken if not otherwise + * specified.
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        defaultLatitude
        + *
        if set, this is the latitude that should be + * assigned to any notes that have no other latitude information. + *
        + * + *
        defaultLongitude
        + *
        if set, this is the longitude that should be + * assigned to any notes that have no other longitude information. + *
        + * + *
        preactivation
        + *
        if set, the user account is not yet confirmed for + * login. I.e. the account has been created, but we are still waiting for + * the user to complete the activation step. + *
        + * + *
        viewedPromotions
        + *
        a list of promotions the user has seen. + * This list may occasionally be modified by the system when promotions are + * no longer available.
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        incomingEmailAddress
        + *
        if set, this is the email address that the + * user may send email to in order to add an email note directly into the + * account via the SMTP email gateway. This is the part of the email + * address before the '@' symbol ... our domain is not included. + * If this is not set, the user may not add notes via the gateway.
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        recentMailedAddresses
        + *
        if set, this will contain a list of email + * addresses that have recently been used as recipients + * of outbound emails by the user. This can be used to pre-populate a + * list of possible destinations when a user wishes to send a note via + * email.
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX each
        + * Max: EDAM_USER_RECENT_MAILED_ADDRESSES_MAX entries + *
        + * + *
        comments
        + *
        Free-form text field that may hold general support + * information, etc.
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        dateAgreedToTermsOfService
        + *
        The date/time when the user agreed to + * the terms of service. This can be used as the effective "start date" + * for the account. + *
        + * + *
        maxReferrals
        + *
        The number of referrals that the user is permitted + * to make. + *
        + * + *
        referralCount
        + *
        The number of referrals sent from this account. + *
        + * + *
        refererCode
        + *
        A code indicating where the user was sent from. AKA + * promotion code + *
        + * + *
        sentEmailDate
        + *
        The most recent date when the user sent outbound + * emails from the service. Used with sentEmailCount to limit the number + * of emails that can be sent per day. + *
        + * + *
        sentEmailCount
        + *
        The number of emails that were sent from the user + * via the service on sentEmailDate. Used to enforce a limit on the number + * of emails per user per day to prevent spamming. + *
        + * + *
        dailyEmailLimit
        + *
        If set, this is the maximum number of emails that + * may be sent in a given day from this account. If unset, the server will + * use the configured default limit. + *
        + * + *
        emailOptOutDate
        + *
        If set, this is the date when the user asked + * to be excluded from offers and promotions sent by Evernote. If not set, + * then the user currently agrees to receive these messages. + *
        + * + *
        partnerEmailOptInDate
        + *
        If set, this is the date when the user asked + * to be included in offers and promotions sent by Evernote's partners. + * If not sent, then the user currently does not agree to receive these + * emails. + *
        + * + *
        preferredLanguage
        + *
        a 2 character language codes based on: + * http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt used for + * localization purposes to determine what language to use for the web + * interface and for other direct communication (e.g. emails). + *
        + * + *
        preferredCountry
        + *
        Preferred country code based on ISO 3166-1-alpha-2 indicating the + * users preferred country
        + * + *
        clipFullPage
        + *
        Boolean flag set to true if the user wants to clip full pages by + * default when they use the web clipper without a selection.
        + * + *
        twitterUserName
        + *
        The username of the account of someone who has chosen to enable + * Twittering into Evernote. This value is subject to change, since users + * may change their Twitter user name.
        + * + *
        twitterId
        + *
        The unique identifier of the user's Twitter account if that user + * has chosen to enable Twittering into Evernote.
        + * + *
        groupName
        + *
        A name identifier used to identify a particular set of branding and + * light customization.
        + * + *
        recognitionLanguage
        + *
        a 2 character language codes based on: + * http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt + * If set, this is used to determine the language that should be used + * when processing images and PDF files to find text. + * If not set, then the 'preferredLanguage' will be used. + *
        + * + *
        educationalInstitution
        + *
        a flag indicating that the user is part of an educational institution which + * makes them eligible for discounts on bulk purchases + *
        + * + *
        businessAddress
        + *
        A string recording the business address of a Sponsored Account user who has requested invoicing. + *
        + * + *
        hideSponsorBilling
        + *
        A flag indicating whether to hide the billing information on a sponsored + * account owner's settings page + *
        + * + *
        taxExempt
        + *
        A flag indicating the user's sponsored group is exempt from sale tax + *
        + * + *
        useEmailAutoFiling
        + *
        A flag indicating whether the user chooses to allow Evernote to automatically + * file and tag emailed notes + *
        + * + *
        reminderEmailConfig
        + *
        Configuration state for whether or not the user wishes to receive + * reminder e-mail. This setting applies to both the reminder e-mail sent + * for personal reminder notes and for the reminder e-mail sent for reminder + * notes in the user's business notebooks that the user has configured for + * e-mail notifications. + *
        + *
        + */ + class UserAttributes { + defaultLocationName: string; + defaultLatitude: number; + defaultLongitude: number; + preactivation: boolean; + viewedPromotions: string[]; + incomingEmailAddress: string; + recentMailedAddresses: string[]; + comments: string; + dateAgreedToTermsOfService: number; + maxReferrals: number; + referralCount: number; + refererCode: string; + sentEmailDate: number; + sentEmailCount: number; + dailyEmailLimit: number; + emailOptOutDate: number; + partnerEmailOptInDate: number; + preferredLanguage: string; + preferredCountry: string; + clipFullPage: boolean; + twitterUserName: string; + twitterId: string; + groupName: string; + recognitionLanguage: string; + referralProof: string; + educationalDiscount: boolean; + businessAddress: string; + hideSponsorBilling: boolean; + taxExempt: boolean; + useEmailAutoFiling: boolean; + reminderEmailConfig: ReminderEmailConfig; + + constructor(args?: { defaultLocationName?: string; defaultLatitude?: number; defaultLongitude?: number; preactivation?: boolean; viewedPromotions?: string[]; incomingEmailAddress?: string; recentMailedAddresses?: string[]; comments?: string; dateAgreedToTermsOfService?: number; maxReferrals?: number; referralCount?: number; refererCode?: string; sentEmailDate?: number; sentEmailCount?: number; dailyEmailLimit?: number; emailOptOutDate?: number; partnerEmailOptInDate?: number; preferredLanguage?: string; preferredCountry?: string; clipFullPage?: boolean; twitterUserName?: string; twitterId?: string; groupName?: string; recognitionLanguage?: string; referralProof?: string; educationalDiscount?: boolean; businessAddress?: string; hideSponsorBilling?: boolean; taxExempt?: boolean; useEmailAutoFiling?: boolean; reminderEmailConfig?: ReminderEmailConfig; }); + } + + /** + * This represents the bookkeeping information for the user's subscription. + * + *
        + *
        uploadLimit
        + *
        The number of bytes that can be uploaded to the account + * in the current month. For new notes that are created, this is the length + * of the note content (in Unicode characters) plus the size of each resource + * (in bytes). For edited notes, this is the the difference between the old + * length and the new length (if this is greater than 0) plus the size of + * each new resource. + *
        + *
        uploadLimitEnd
        + *
        The date and time when the current upload limit + * expires. At this time, the monthly upload count reverts to 0 and a new + * limit is imposed. This date and time is exclusive, so this is effectively + * the start of the new month. + *
        + *
        uploadLimitNextMonth
        + *
        When uploadLimitEnd is reached, the service + * will change uploadLimit to uploadLimitNextMonth. If a premium account is + * canceled, this mechanism will reset the quota appropriately. + *
        + *
        premiumServiceStatus
        + *
        Indicates the phases of a premium account + * during the billing process. + *
        + *
        premiumOrderNumber
        + *
        The order number used by the commerce system to + * process recurring payments + *
        + *
        premiumServiceStart
        + *
        The start date when this premium promotion + * began (this number will get overwritten if a premium service is canceled + * and then re-activated). + *
        + *
        premiumCommerceService
        + *
        The commerce system used (paypal, Google + * checkout, etc) + *
        + *
        premiumServiceSKU
        + *
        The code associated with the purchase eg. monthly + * or annual purchase. Clients should interpret this value and localize it. + *
        + *
        lastSuccessfulCharge
        + *
        Date the last time the user was charged. + * Null if never charged. + *
        + *
        lastFailedCharge
        + *
        Date the last time a charge was attempted and + * failed. + *
        + *
        lastFailedChargeReason
        + *
        Reason provided for the charge failure + *
        + *
        nextPaymentDue
        + *
        The end of the billing cycle. This could be in the + * past if there are failed charges. + *
        + *
        premiumLockUntil
        + *
        An internal variable to manage locking operations + * on the commerce variables. + *
        + *
        updated
        + *
        The date any modification where made to this record. + *
        + *
        premiumSubscriptionNumber
        + *
        The number number identifying the + * recurring subscription used to make the recurring charges. + *
        + *
        lastRequestedCharge
        + *
        Date charge last attempted
        + *
        currency
        + *
        ISO 4217 currency code
        + *
        unitPrice
        + *
        charge in the smallest unit of the currency (e.g. cents for USD)
        + *
        businessId
        + *
        DEPRECATED:See BusinessUserInfo.
        + *
        businessName
        + *
        DEPRECATED:See BusinessUserInfo.
        + *
        businessRole
        + *
        DEPRECATED:See BusinessUserInfo.
        + *
        unitDiscount
        + *
        discount per seat in negative amount and smallest unit of the currency (e.g. cents for USD)
        + *
        nextChargeDate
        + *
        The next time the user will be charged, may or may not be the same as nextPaymentDue
        + *
        + */ + class Accounting { + uploadLimit: number; + uploadLimitEnd: number; + uploadLimitNextMonth: number; + premiumServiceStatus: PremiumOrderStatus; + premiumOrderNumber: string; + premiumCommerceService: string; + premiumServiceStart: number; + premiumServiceSKU: string; + lastSuccessfulCharge: number; + lastFailedCharge: number; + lastFailedChargeReason: string; + nextPaymentDue: number; + premiumLockUntil: number; + updated: number; + premiumSubscriptionNumber: string; + lastRequestedCharge: number; + currency: string; + unitPrice: number; + businessId: number; + businessName: string; + businessRole: BusinessUserRole; + unitDiscount: number; + nextChargeDate: number; + + constructor(args?: { uploadLimit?: number; uploadLimitEnd?: number; uploadLimitNextMonth?: number; premiumServiceStatus?: PremiumOrderStatus; premiumOrderNumber?: string; premiumCommerceService?: string; premiumServiceStart?: number; premiumServiceSKU?: string; lastSuccessfulCharge?: number; lastFailedCharge?: number; lastFailedChargeReason?: string; nextPaymentDue?: number; premiumLockUntil?: number; updated?: number; premiumSubscriptionNumber?: string; lastRequestedCharge?: number; currency?: string; unitPrice?: number; businessId?: number; businessName?: string; businessRole?: BusinessUserRole; unitDiscount?: number; nextChargeDate?: number; }); + } + + /** + * This structure is used to provide information about an Evernote Business + * membership, for members who are part of a business. + * + *
        + *
        businessId
        + *
        The ID of the Evernote Business account that the user is a member of. + *
        businessName
        + *
        The human-readable name of the Evernote Business account that the user + * is a member of.
        + *
        role
        + *
        The role of the user within the Evernote Business account that + * they are a member of.
        + *
        email
        + *
        An e-mail address that will be used by the service in the context of your + * Evernote Business activities. For example, this e-mail address will be used + * when you e-mail a business note, when you update notes in the account of + * your business, etc. The business e-mail cannot be used for identification + * purposes such as for logging into the service. + *
        + *
        + */ + class BusinessUserInfo { + businessId: number; + businessName: string; + role: BusinessUserRole; + email: string; + + constructor(args?: { businessId?: number; businessName?: string; role?: BusinessUserRole; email?: string; }); + } + + /** + * This structure is used to provide information about a user's Premium account. + *
        + *
        currentTime
        + *
        + * The server-side date and time when this data was generated. + *
        + *
        premium
        + *
        + * True if the user's account is Premium. + *
        + *
        premiumRecurring
        + *
        + * True if the user's account is Premium and has a recurring payment method. + *
        + *
        premiumExpirationDate
        + *
        + * The date when the user's Premium account expires, or the date when the + * user's account is due for payment if it has a recurring payment method. + *
        + *
        premiumExtendable
        + *
        + * True if the user is eligible for purchasing Premium account extensions. + *
        + *
        premiumPending
        + *
        + * True if the user's Premium account is pending payment confirmation + *
        + *
        premiumCancellationPending
        + *
        + * True if the user has requested that no further charges to be made; the + * Premium account will remain active until it expires. + *
        + *
        canPurchaseUploadAllowance
        + *
        + * True if the user is eligible for purchasing additional upload allowance. + *
        + *
        sponsoredGroupName
        + *
        + * The name of the sponsored group that the user is part of. + *
        + *
        sponsoredGroupRole
        + *
        + * DEPRECATED - will be removed in a future update. + *
        + *
        premiumUpgradable
        + *
        + * True if the user is eligible for purchasing Premium account upgrade. + *
        + *
        + */ + class PremiumInfo { + currentTime: number; + premium: boolean; + premiumRecurring: boolean; + premiumExpirationDate: number; + premiumExtendable: boolean; + premiumPending: boolean; + premiumCancellationPending: boolean; + canPurchaseUploadAllowance: boolean; + sponsoredGroupName: string; + sponsoredGroupRole: SponsoredGroupRole; + premiumUpgradable: boolean; + + constructor(args?: { currentTime: number; premium: boolean; premiumRecurring: boolean; premiumExpirationDate?: number; premiumExtendable: boolean; premiumPending: boolean; premiumCancellationPending: boolean; canPurchaseUploadAllowance: boolean; sponsoredGroupName?: string; sponsoredGroupRole?: SponsoredGroupRole; premiumUpgradable?: boolean; }); + } + + /** + * This represents the information about a single user account. + *
        + *
        id
        + *
        The unique numeric identifier for the account, which will not + * change for the lifetime of the account. + *
        + * + *
        username
        + *
        The name that uniquely identifies a single user account. This name + * may be presented by the user, along with their password, to log into + * their account. + * May only contain a-z, 0-9, or '-', and may not start or end with the '-' + *
        + * Length: EDAM_USER_USERNAME_LEN_MIN - EDAM_USER_USERNAME_LEN_MAX + *
        + * Regex: EDAM_USER_USERNAME_REGEX + *
        + * + *
        email
        + *
        The email address registered for the user. Must comply with + * RFC 2821 and RFC 2822.
        + * Third party applications that authenticate using OAuth do not have + * access to this field. + * Length: EDAM_EMAIL_LEN_MIN - EDAM_EMAIL_LEN_MAX + *
        + * Regex: EDAM_EMAIL_REGEX + *
        + * + *
        name
        + *
        The printable name of the user, which may be a combination + * of given and family names. This is used instead of separate "first" + * and "last" names due to variations in international name format/order. + * May not start or end with a whitespace character. May contain any + * character but carriage return or newline (Unicode classes Zl and Zp). + *
        + * Length: EDAM_USER_NAME_LEN_MIN - EDAM_USER_NAME_LEN_MAX + *
        + * Regex: EDAM_USER_NAME_REGEX + *
        + * + *
        timezone
        + *
        The zone ID for the user's default location. If present, + * this may be used to localize the display of any timestamp for which no + * other timezone is available. + * The format must be encoded as a standard zone ID such as + * "America/Los_Angeles" or "GMT+08:00" + *
        + * Length: EDAM_TIMEZONE_LEN_MIN - EDAM_TIMEZONE_LEN_MAX + *
        + * Regex: EDAM_TIMEZONE_REGEX + *
        + * + *
        privilege
        + *
        The level of access permitted for the user. + *
        + * + *
        created
        + *
        The date and time when this user account was created in the + * service. + *
        + * + *
        updated
        + *
        The date and time when this user account was last modified + * in the service. + *
        + * + *
        deleted
        + *
        If the account has been deleted from the system (e.g. as + * the result of a legal request by the user), the date and time of the + * deletion will be represented here. If not, this value will not be set. + *
        + * + *
        active
        + *
        If the user account is available for login and + * synchronization, this flag will be set to true. + *
        + * + *
        shardId
        + *
        DEPRECATED - Client applications should have no need to use this field. + *
        + * + *
        attributes
        + *
        If present, this will contain a list of the attributes + * for this user account. + *
        + * + *
        accounting
        + *
        Bookkeeping information for the user's subscription. + *
        + * + *
        premiumInfo
        + *
        If present, this will contain a set of commerce information + * relating to the user's premium service level. + *
        + * + *
        businessUserInfo
        + *
        If present, this will contain a set of business information + * relating to the user's business membership. If not present, the + * user is not currently part of a business. + *
        + *
        + */ + class User { + id: number; + username: string; + email: string; + name: string; + timezone: string; + privilege: PrivilegeLevel; + created: number; + updated: number; + deleted: number; + active: boolean; + shardId: string; + attributes: UserAttributes; + accounting: Accounting; + premiumInfo: PremiumInfo; + businessUserInfo: BusinessUserInfo; + + constructor(args?: { id?: number; username?: string; email?: string; name?: string; timezone?: string; privilege?: PrivilegeLevel; created?: number; updated?: number; deleted?: number; active?: boolean; shardId?: string; attributes?: UserAttributes; accounting?: Accounting; premiumInfo?: PremiumInfo; businessUserInfo?: BusinessUserInfo; }); + } + + /** + * A tag within a user's account is a unique name which may be organized + * a simple hierarchy. + *
        + *
        guid
        + *
        The unique identifier of this tag. Will be set by the service, + * so may be omitted by the client when creating the Tag. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        name
        + *
        A sequence of characters representing the tag's identifier. + * Case is preserved, but is ignored for comparisons. + * This means that an account may only have one tag with a given name, via + * case-insensitive comparison, so an account may not have both "food" and + * "Food" tags. + * May not contain a comma (','), and may not begin or end with a space. + *
        + * Length: EDAM_TAG_NAME_LEN_MIN - EDAM_TAG_NAME_LEN_MAX + *
        + * Regex: EDAM_TAG_NAME_REGEX + *
        + * + *
        parentGuid
        + *
        If this is set, then this is the GUID of the tag that + * holds this tag within the tag organizational hierarchy. If this is + * not set, then the tag has no parent and it is a "top level" tag. + * Cycles are not allowed (e.g. a->parent->parent == a) and will be + * rejected by the service. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this object. The USN values are sequential within an + * account, and can be used to compare the order of modifications within the + * service. + *
        + *
        + */ + class Tag { + guid: string; + name: string; + parentGuid: string; + updateSequenceNum: number; + + constructor(args?: { guid?: string; name?: string; parentGuid?: string; updateSequenceNum?: number; }); + } + + /** + * A structure that wraps a map of name/value pairs whose values are not + * always present in the structure in order to reduce space when obtaining + * batches of entities that contain the map. + * + * When the server provides the client with a LazyMap, it will fill in either + * the keysOnly field or the fullMap field, but never both, based on the API + * and parameters. + * + * When a client provides a LazyMap to the server as part of an update to + * an object, the server will only update the LazyMap if the fullMap field is + * set. If the fullMap field is not set, the server will not make any changes + * to the map. + * + * Check the API documentation of the individual calls involving the LazyMap + * for full details including the constraints of the names and values of the + * map. + * + *
        + *
        keysOnly
        + *
        The set of keys for the map. This field is ignored by the + * server when set. + *
        + * + *
        fullMap
        + *
        The complete map, including all keys and values. + *
        + *
        + */ + class LazyMap { + keysOnly: string[]; + fullMap: { [k: string]: string; }; + + constructor(args?: { keysOnly?: string[]; fullMap?: { [k: string]: string; }; }); + } + + /** + * Structure holding the optional attributes of a Resource + *
        + *
        sourceURL
        + *
        the original location where the resource was hosted + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        timestamp
        + *
        the date and time that is associated with this resource + * (e.g. the time embedded in an image from a digital camera with a clock) + *
        + * + *
        latitude
        + *
        the latitude where the resource was captured + *
        + * + *
        longitude
        + *
        the longitude where the resource was captured + *
        + * + *
        altitude
        + *
        the altitude where the resource was captured + *
        + * + *
        cameraMake
        + *
        information about an image's camera, e.g. as embedded in + * the image's EXIF data + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        cameraModel
        + *
        information about an image's camera, e.g. as embedded + * in the image's EXIF data + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        clientWillIndex
        + *
        if true, then the original client that submitted + * the resource plans to submit the recognition index for this resource at a + * later time. + *
        + * + *
        recoType
        + *
        DEPRECATED - this field is no longer set by the service, so should + * be ignored. + *
        + * + *
        fileName
        + *
        if the resource came from a source that provided an + * explicit file name, the original name will be stored here. Many resources + * come from unnamed sources, so this will not always be set. + *
        + * + *
        attachment
        + *
        this will be true if the resource should be displayed as an attachment, + * or false if the resource should be displayed inline (if possible). + *
        + * + *
        applicationData
        + *
        Provides a location for applications to store a relatively small + * (4kb) blob of data associated with a Resource that is not visible to the user + * and that is opaque to the Evernote service. A single application may use at most + * one entry in this map, using its API consumer key as the map key. See the + * documentation for LazyMap for a description of when the actual map values + * are returned by the service. + *

        To safely add or modify your application's entry in the map, use + * NoteStore.setResourceApplicationDataEntry. To safely remove your application's + * entry from the map, use NoteStore.unsetResourceApplicationDataEntry.

        + * Minimum length of a name (key): EDAM_APPLICATIONDATA_NAME_LEN_MIN + *
        + * Sum max size of key and value: EDAM_APPLICATIONDATA_ENTRY_LEN_MAX + *
        + * Syntax regex for name (key): EDAM_APPLICATIONDATA_NAME_REGEX + *
        + * + *
        + */ + class ResourceAttributes { + sourceURL: string; + timestamp: number; + latitude: number; + longitude: number; + altitude: number; + cameraMake: string; + cameraModel: string; + clientWillIndex: boolean; + recoType: string; + fileName: string; + attachment: boolean; + applicationData: LazyMap; + + constructor(args?: { sourceURL?: string; timestamp?: number; latitude?: number; longitude?: number; altitude?: number; cameraMake?: string; cameraModel?: string; clientWillIndex?: boolean; recoType?: string; fileName?: string; attachment?: boolean; applicationData?: LazyMap; }); + } + + /** + * Every media file that is embedded or attached to a note is represented + * through a Resource entry. + *
        + *
        guid
        + *
        The unique identifier of this resource. Will be set whenever + * a resource is retrieved from the service, but may be null when a client + * is creating a resource. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        noteGuid
        + *
        The unique identifier of the Note that holds this + * Resource. Will be set whenever the resource is retrieved from the service, + * but may be null when a client is creating a resource. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        data
        + *
        The contents of the resource. + * Maximum length: The data.body is limited to EDAM_RESOURCE_SIZE_MAX_FREE + * for free accounts and EDAM_RESOURCE_SIZE_MAX_PREMIUM for premium accounts. + *
        + * + *
        mime
        + *
        The MIME type for the embedded resource. E.g. "image/gif" + *
        + * Length: EDAM_MIME_LEN_MIN - EDAM_MIME_LEN_MAX + *
        + * Regex: EDAM_MIME_REGEX + *
        + * + *
        width
        + *
        If set, this contains the display width of this resource, in + * pixels. + *
        + * + *
        height
        + *
        If set, this contains the display height of this resource, + * in pixels. + *
        + * + *
        duration
        + *
        DEPRECATED: ignored. + *
        + * + *
        active
        + *
        DEPRECATED: ignored. + *
        + * + *
        recognition
        + *
        If set, this will hold the encoded data that provides + * information on search and recognition within this resource. + *
        + * + *
        attributes
        + *
        A list of the attributes for this resource. + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this object. The USN values are sequential within an + * account, and can be used to compare the order of modifications within the + * service. + *
        + * + *
        alternateData
        + *
        Some Resources may be assigned an alternate data format by the service + * which may be more appropriate for indexing or rendering than the original + * data provided by the user. In these cases, the alternate data form will + * be available via this Data element. If a Resource has no alternate form, + * this field will be unset.
        + *
        + */ + class Resource { + guid: string; + noteGuid: string; + data: Data; + mime: string; + width: number; + height: number; + duration: number; + active: boolean; + recognition: Data; + attributes: ResourceAttributes; + updateSequenceNum: number; + alternateData: Data; + + constructor(args?: { guid?: string; noteGuid?: string; data?: Data; mime?: string; width?: number; height?: number; duration?: number; active?: boolean; recognition?: Data; attributes?: ResourceAttributes; updateSequenceNum?: number; alternateData?: Data; }); + } + + /** + * The list of optional attributes that can be stored on a note. + *
        + *
        subjectDate
        + *
        time that the note refers to + *
        + * + *
        latitude
        + *
        the latitude where the note was taken + *
        + * + *
        longitude
        + *
        the longitude where the note was taken + *
        + * + *
        altitude
        + *
        the altitude where the note was taken + *
        + * + *
        author
        + *
        the author of the content of the note + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        source
        + *
        the method that the note was added to the account, if the + * note wasn't directly authored in an Evernote desktop client. + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        sourceURL
        + *
        the original location where the resource was hosted. For web clips, + * this will be the URL of the page that was clipped. + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        sourceApplication
        + *
        an identifying string for the application that + * created this note. This string does not have a guaranteed syntax or + * structure -- it is intended for human inspection and tracking. + *
        + * Length: EDAM_ATTRIBUTE_LEN_MIN - EDAM_ATTRIBUTE_LEN_MAX + *
        + * + *
        shareDate
        + *
        The date and time when this note was directly shared via its own URL. + * This is only set on notes that were individually shared - it is independent + * of any notebook-level sharing of the containing notebook. This field + * is treated as "read-only" for clients; the server will ignore changes + * to this field from an external client. + *
        + * + *
        reminderOrder
        + *
        The set of notes with this parameter set are considered + * "reminders" and are to be treated specially by clients to give them + * higher UI prominence within a notebook. The value is used to sort + * the reminder notes within the notebook with higher values + * representing greater prominence. Outside of the context of a + * notebook, the value of this parameter is undefined. The value is + * not intended to be compared to the values of reminder notes in + * other notebooks. In order to allow clients to place a note at a + * higher precedence than other notes, you should never set a value + * greater than the current time (as defined for a Timetstamp). To + * place a note at higher precedence than existing notes, set the + * value to the current time as defined for a timestamp (milliseconds + * since the epoch). Synchronizing clients must remember the time when + * the update was performed, using the local clock on the client, + * and use that value when they later upload the note to the service. + * Clients must not set the reminderOrder to the reminderTime as the + * reminderTime could be in the future. Those two fields are never + * intended to be related. The correct value for reminderOrder field + * for new notes is the "current" time when the user indicated that + * the note is a reminder. Clients may implement a separate + * "sort by date" feature to show notes ordered by reminderTime. + * Whenever a reminderDoneTime or reminderTime is set but a + * reminderOrder is not set, the server will fill in the current + * server time for the reminderOrder field.
        + * + *
        reminderDoneTime
        + *
        The date and time when a user dismissed/"marked done" the reminder + * on the note. Users typically do not manually set this value directly + * as it is set to the time when the user dismissed/"marked done" the + * reminder.
        + * + *
        reminderTime
        + *
        The date and time a user has selected to be reminded of the note. + * A note with this value set is known as a "reminder" and the user can + * be reminded, via e-mail or client-specific notifications, of the note + * when the time is reached or about to be reached. When a user sets + * a reminder time on a note that has a reminder done time, and that + * reminder time is in the future, then the reminder done time should be + * cleared. This should happen regardless of any existing reminder time + * that may have previously existed on the note.
        + * + *
        placeName
        + *
        Allows the user to assign a human-readable location name associated + * with a note. Users may assign values like 'Home' and 'Work'. Place + * names may also be populated with values from geonames database + * (e.g., a restaurant name). Applications are encouraged to normalize values + * so that grouping values by place name provides a useful result. Applications + * MUST NOT automatically add place name values based on geolocation without + * confirmation from the user; that is, the value in this field should be + * more useful than a simple automated lookup based on the note's latitude + * and longitude.
        + * + *
        contentClass
        + *
        The class (or type) of note. This field is used to indicate to + * clients that special structured information is represented within + * the note such that special rules apply when making + * modifications. If contentClass is set and the client + * application does not specifically support the specified class, + * the client MUST treat the note as read-only. In this case, the + * client MAY modify the note's notebook and tags via the + * Note.notebookGuid and Note.tagGuids fields. The client MAY also + * modify the reminderOrder field as well as the reminderTime and + * reminderDoneTime fields. + *

        Applications should set contentClass only when they are creating notes + * that contain structured information that needs to be maintained in order + * for the user to be able to use the note within that application. + * Setting contentClass makes a note read-only in other applications, so + * there is a trade-off when an application chooses to use contentClass. + * Applications that set contentClass when creating notes must use a contentClass + * string of the form CompanyName.ApplicationName to ensure uniqueness.

        + * Length restrictions: EDAM_NOTE_CONTENT_CLASS_LEN_MIN, EDAM_NOTE_CONTENT_CLASS_LEN_MAX + *
        + * Regex: EDAM_NOTE_CONTENT_CLASS_REGEX + *
        + * + *
        applicationData
        + *
        Provides a location for applications to store a relatively small + * (4kb) blob of data that is not meant to be visible to the user and + * that is opaque to the Evernote service. A single application may use at most + * one entry in this map, using its API consumer key as the map key. See the + * documentation for LazyMap for a description of when the actual map values + * are returned by the service. + *

        To safely add or modify your application's entry in the map, use + * NoteStore.setNoteApplicationDataEntry. To safely remove your application's + * entry from the map, use NoteStore.unsetNoteApplicationDataEntry.

        + * Minimum length of a name (key): EDAM_APPLICATIONDATA_NAME_LEN_MIN + *
        + * Sum max size of key and value: EDAM_APPLICATIONDATA_ENTRY_LEN_MAX + *
        + * Syntax regex for name (key): EDAM_APPLICATIONDATA_NAME_REGEX + *
        + * + *
        creatorId
        + *
        The numeric user ID of the user who originally created the note.
        + * + *
        lastEditedBy
        + *
        An indication of who made the last change to the note. If you are + * accessing the note via a shared notebook to which you have modification + * rights, or if you are the owner of the notebook to which the note belongs, + * then you have access to the value. In this case, the value will be + * unset if the owner of the notebook containing the note was the last to + * make the modification, else it will be a string describing the + * guest who made the last edit. If you do not have access to this value, + * it will be left unset. This field is read-only by clients. The server + * will ignore all values set by clients into this field.
        + * + *
        lastEditorId
        + *
        The numeric user ID of the user described in lastEditedBy.
        + * + *
        classifications
        + *
        A map of classifications applied to the note by clients or by the + * Evernote service. The key is the string name of the classification type, + * and the value is a constant that begins with CLASSIFICATION_.
        + * + *
        + */ + class NoteAttributes { + subjectDate: number; + latitude: number; + longitude: number; + altitude: number; + author: string; + source: string; + sourceURL: string; + sourceApplication: string; + shareDate: number; + reminderOrder: number; + reminderDoneTime: number; + reminderTime: number; + placeName: string; + contentClass: string; + applicationData: LazyMap; + lastEditedBy: string; + classifications: { [k: string]: string; }; + creatorId: number; + lastEditorId: number; + + constructor(args?: { subjectDate?: number; latitude?: number; longitude?: number; altitude?: number; author?: string; source?: string; sourceURL?: string; sourceApplication?: string; shareDate?: number; reminderOrder?: number; reminderDoneTime?: number; reminderTime?: number; placeName?: string; contentClass?: string; applicationData?: LazyMap; lastEditedBy?: string; classifications?: { [k: string]: string; }; creatorId?: number; lastEditorId?: number; }); + } + + /** + * Represents a single note in the user's account. + * + *
        + *
        guid
        + *
        The unique identifier of this note. Will be set by the + * server, but will be omitted by clients calling NoteStore.createNote() + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        title
        + *
        The subject of the note. Can't begin or end with a space. + *
        + * Length: EDAM_NOTE_TITLE_LEN_MIN - EDAM_NOTE_TITLE_LEN_MAX + *
        + * Regex: EDAM_NOTE_TITLE_REGEX + *
        + * + *
        content
        + *
        The XHTML block that makes up the note. This is + * the canonical form of the note's contents, so will include abstract + * Evernote tags for internal resource references. A client may create + * a separate transformed version of this content for internal presentation, + * but the same canonical bytes should be used for transmission and + * comparison unless the user chooses to modify their content. + *
        + * Length: EDAM_NOTE_CONTENT_LEN_MIN - EDAM_NOTE_CONTENT_LEN_MAX + *
        + * + *
        contentHash
        + *
        The binary MD5 checksum of the UTF-8 encoded content + * body. This will always be set by the server, but clients may choose to omit + * this when they submit a note with content. + *
        + * Length: EDAM_HASH_LEN (exactly) + *
        + * + *
        contentLength
        + *
        The number of Unicode characters in the content of + * the note. This will always be set by the service, but clients may choose + * to omit this value when they submit a Note. + *
        + * + *
        created
        + *
        The date and time when the note was created in one of the + * clients. In most cases, this will match the user's sense of when + * the note was created, and ordering between notes will be based on + * ordering of this field. However, this is not a "reliable" timestamp + * if a client has an incorrect clock, so it cannot provide a true absolute + * ordering between notes. Notes created directly through the service + * (e.g. via the web GUI) will have an absolutely ordered "created" value. + *
        + * + *
        updated
        + *
        The date and time when the note was last modified in one of + * the clients. In most cases, this will match the user's sense of when + * the note was modified, but this field may not be absolutely reliable + * due to the possibility of client clock errors. + *
        + * + *
        deleted
        + *
        If present, the note is considered "deleted", and this + * stores the date and time when the note was deleted by one of the clients. + * In most cases, this will match the user's sense of when the note was + * deleted, but this field may be unreliable due to the possibility of + * client clock errors. + *
        + * + *
        active
        + *
        If the note is available for normal actions and viewing, + * this flag will be set to true. + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this note (including changes to the note's attributes + * or resources). The USN values are sequential within an account, + * and can be used to compare the order of modifications within the service. + *
        + * + *
        notebookGuid
        + *
        The unique identifier of the notebook that contains + * this note. If no notebookGuid is provided on a call to createNote(), the + * default notebook will be used instead. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        tagGuids
        + *
        A list of the GUID identifiers for tags that are applied to this note. + * This may be provided in a call to createNote() to unambiguously + * the tags that should be assigned to the new note. Alternately, clients + * may pass the names of desired tags via the 'tagNames' field during + * note creation. + * If the list of tags are omitted on a call to createNote(), then + * the server will assume that no changes have been made to the resources. + * Maximum: EDAM_NOTE_TAGS_MAX tags per note + *
        + * + *
        resources
        + *
        The list of resources that are embedded within this note. + * If the list of resources are omitted on a call to updateNote(), then + * the server will assume that no changes have been made to the resources. + * The binary contents of the resources must be provided when the resource + * is first sent to the service, but it will be omitted by the service when + * the Note is returned in the future. + * Maximum: EDAM_NOTE_RESOURCES_MAX resources per note + *
        + * + *
        attributes
        + *
        A list of the attributes for this note. + * If the list of attributes are omitted on a call to updateNote(), then + * the server will assume that no changes have been made to the resources. + *
        + * + *
        tagNames
        + *
        May be provided by clients during calls to createNote() as an + * alternative to providing the tagGuids of existing tags. If any tagNames + * are provided during createNote(), these will be found, or created if they + * don't already exist. Created tags will have no parent (they will be at + * the top level of the tag panel). + *
        + *
        + */ + class Note { + guid: string; + title: string; + content: string; + contentHash: string; + contentLength: number; + created: number; + updated: number; + deleted: number; + active: boolean; + updateSequenceNum: number; + notebookGuid: string; + tagGuids: string[]; + resources: Resource[]; + attributes: NoteAttributes; + tagNames: string[]; + + constructor(args?: { guid?: string; title?: string; content?: string; contentHash?: string; contentLength?: number; created?: number; updated?: number; deleted?: number; active?: boolean; updateSequenceNum?: number; notebookGuid?: string; tagGuids?: string[]; resources?: Resource[]; attributes?: NoteAttributes; tagNames?: string[]; }); + } + + /** + * If a Notebook has been opened to the public, the Notebook will have a + * reference to one of these structures, which gives the location and optional + * description of the externally-visible public Notebook. + *
        + *
        uri
        + *
        If this field is present, then the notebook is published for + * mass consumption on the Internet under the provided URI, which is + * relative to a defined base publishing URI defined by the service. + * This field can only be modified via the web service GUI ... publishing + * cannot be modified via an offline client. + *
        + * Length: EDAM_PUBLISHING_URI_LEN_MIN - EDAM_PUBLISHING_URI_LEN_MAX + *
        + * Regex: EDAM_PUBLISHING_URI_REGEX + *
        + * + *
        order
        + *
        When the notes are publicly displayed, they will be sorted + * based on the requested criteria. + *
        + * + *
        ascending
        + *
        If this is set to true, then the public notes will be + * displayed in ascending order (e.g. from oldest to newest). Otherwise, + * the notes will be displayed in descending order (e.g. newest to oldest). + *
        + * + *
        publicDescription
        + *
        This field may be used to provide a short + * description of the notebook, which may be displayed when (e.g.) the + * notebook is shown in a public view. Can't begin or end with a space. + *
        + * Length: EDAM_PUBLISHING_DESCRIPTION_LEN_MIN - + * EDAM_PUBLISHING_DESCRIPTION_LEN_MAX + *
        + * Regex: EDAM_PUBLISHING_DESCRIPTION_REGEX + *
        + * + *
        + */ + class Publishing { + uri: string; + order: NoteSortOrder; + ascending: boolean; + publicDescription: string; + + constructor(args?: { uri?: string; order?: NoteSortOrder; ascending?: boolean; publicDescription?: string; }); + } + + /** + * If a Notebook contained in an Evernote Business account has been published + * the to business library, the Notebook will have a reference to one of these + * structures, which specifies how the Notebook will be represented in the + * library. + * + *
        + *
        notebookDescription
        + *
        A short description of the notebook's content that will be displayed + * in the business library user interface. The description may not begin + * or end with whitespace. + *
        + * Length: EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MIN - + * EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_LEN_MAX + *
        + * Regex: EDAM_BUSINESS_NOTEBOOK_DESCRIPTION_REGEX + *
        + * + *
        privilege
        + *
        The privileges that will be granted to users who join the notebook through + * the business library. + *
        + * + *
        recommended
        + *
        Whether the notebook should be "recommended" when displayed in the business + * library user interface. + *
        + *
        + */ + class BusinessNotebook { + notebookDescription: string; + privilege: SharedNotebookPrivilegeLevel; + recommended: boolean; + + constructor(args?: { notebookDescription?: string; privilege?: SharedNotebookPrivilegeLevel; recommended?: boolean; }); + } + + /** + * A structure defining the scope of a SavedSearch. + * + *
        + *
        includeAccount
        + *
        The search should include notes from the account that contains the SavedSearch.
        + * + *
        includePersonalLinkedNotebooks
        + *
        The search should include notes within those shared notebooks + * that the user has joined that are NOT business notebooks.
        + * + *
        includeBusinessLinkedNotebooks
        + *
        The search should include notes within those shared notebooks + * that the user has joined that are business notebooks in the business that + * the user is currently a member of.
        + *
        + */ + class SavedSearchScope { + includeAccount: boolean; + includePersonalLinkedNotebooks: boolean; + includeBusinessLinkedNotebooks: boolean; + + constructor(args?: { includeAccount?: boolean; includePersonalLinkedNotebooks?: boolean; includeBusinessLinkedNotebooks?: boolean; }); + } + + /** + * A named search associated with the account that can be quickly re-used. + *
        + *
        guid
        + *
        The unique identifier of this search. Will be set by the + * service, so may be omitted by the client when creating. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        name
        + *
        The name of the saved search to display in the GUI. The + * account may only contain one search with a given name (case-insensitive + * compare). Can't begin or end with a space. + *
        + * Length: EDAM_SAVED_SEARCH_NAME_LEN_MIN - EDAM_SAVED_SEARCH_NAME_LEN_MAX + *
        + * Regex: EDAM_SAVED_SEARCH_NAME_REGEX + *
        + * + *
        query
        + *
        A string expressing the search to be performed. + *
        + * Length: EDAM_SAVED_SEARCH_QUERY_LEN_MIN - EDAM_SAVED_SEARCH_QUERY_LEN_MAX + *
        + * + *
        format
        + *
        The format of the query string, to determine how to parse + * and process it. + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this object. The USN values are sequential within an + * account, and can be used to compare the order of modifications within the + * service. + *
        + * + *
        scope
        + *

        Specifies the set of notes that should be included in the search, if + * possible.

        + *

        Clients are expected to search as much of the desired scope as possible, + * with the understanding that a given client may not be able to cover the full + * specified scope. For example, when executing a search that includes notes in both + * the owner's account and business notebooks, a mobile client may choose to only + * search within the user's account because it is not capable of searching both + * scopes simultaneously. When a search across multiple scopes is not possible, + * a client may choose which scope to search based on the current application + * context. If a client cannot search any of the desired scopes, it should refuse + * to execute the search.

        + *
        + *
        + */ + class SavedSearch { + guid: string; + name: string; + query: string; + format: QueryFormat; + updateSequenceNum: number; + scope: SavedSearchScope; + + constructor(args?: { guid?: string; name?: string; query?: string; format?: QueryFormat; updateSequenceNum?: number; scope?: SavedSearchScope; }); + } + + /** + * Settings meant for the recipient of a shared notebook, such as + * for indicating which types of notifications the recipient wishes + * for reminders, etc. + * + * The reminderNotifyEmail and reminderNotifyInApp fields have a + * 3-state read value but a 2-state write value. On read, it is + * possible to observe "unset", true, or false. The initial state is + * "unset". When you choose to set a value, you may set it to either + * true or false, but you cannot unset the value. Once one of these + * members has a true/false value, it will always have a true/false + * value. + * + *
        + *
        reminderNotifyEmail
        + *
        Indicates that the user wishes to receive daily e-mail notifications + * for reminders associated with the shared notebook. This may be + * true only for business notebooks that belong to the business of + * which the user is a member. You may only set this value on a + * notebook in your business.
        + *
        reminderNotifyInApp
        + *
        Indicates that the user wishes to receive notifications for + * reminders by applications that support providing such + * notifications. The exact nature of the notification is defined + * by the individual applications.
        + *
        + * + */ + class SharedNotebookRecipientSettings { + reminderNotifyEmail: boolean; + reminderNotifyInApp: boolean; + + constructor(args?: { reminderNotifyEmail?: boolean; reminderNotifyInApp?: boolean; }); + } + + /** + * Shared notebooks represent a relationship between a notebook and a single + * share invitation recipient. + *
        + *
        id
        + *
        the primary identifier of the share
        + * + *
        userId
        + *
        the user id of the owner of the notebook
        + * + *
        notebookGuid
        + *
        the GUID of the associated notebook shared.
        + * + *
        email
        + *
        the email address of the recipient - used by the notebook + * owner to identify who they shared with.
        + * + *
        notebookModifiable
        + *
        (DEPRECATED) a flag indicating the share is read/write -otherwise it's read + * only. This field is deprecated in favor of the new "privilege" field.
        + * + *
        requireLogin
        + *
        (DEPRECATED) indicates that a user must login to access the share. This + * field is deprecated and will be "true" for all new shared notebooks. It + * is read-only and ignored when creating or modifying a shared notebook, + * except that a shared notebook can be modified to require login. + * See "allowPreview" for information on privileges and shared notebooks.
        + * + *
        serviceCreated
        + *
        the date the owner first created the share with the specific email + * address
        + * + *
        serviceUpdated
        + *
        the date the shared notebook was last updated on the service. This + * will be updated when authenticateToSharedNotebook is called the first + * time with a shared notebook requiring login (i.e. when the username is + * bound to that shared notebook).
        + * + *
        username
        + *
        the username of the user who can access this share. + * Once it's assigned it cannot be changed.
        + * + *
        privilege
        + *
        The privilege level granted to the notebook, activity stream, and + * invitations. See the corresponding enumeration for details.
        + * + *
        allowPreview
        + *
        Whether or not to grant "READ_NOTEBOOK" privilege without an + * authentication token, for authenticateToSharedNotebook(...). With + * the change to "requireLogin" always being true for new shared + * notebooks, this is the only way to access a shared notebook without + * an authorization token. This setting expires after the first use + * of authenticateToSharedNotebook(...) with a valid authentication + * token.
        + * + *
        recipientSettings
        + *
        Settings intended for use only by the recipient of this shared + * notebook. You should skip setting this value unless you want + * to change the value contained inside the structure, and only if + * you are the recipient.
        + *
        + */ + class SharedNotebook { + id: number; + userId: number; + notebookGuid: string; + email: string; + notebookModifiable: boolean; + requireLogin: boolean; + serviceCreated: number; + serviceUpdated: number; + shareKey: string; + username: string; + privilege: SharedNotebookPrivilegeLevel; + allowPreview: boolean; + recipientSettings: SharedNotebookRecipientSettings; + + constructor(args?: { id?: number; userId?: number; notebookGuid?: string; email?: string; notebookModifiable?: boolean; requireLogin?: boolean; serviceCreated?: number; serviceUpdated?: number; shareKey?: string; username?: string; privilege?: SharedNotebookPrivilegeLevel; allowPreview?: boolean; recipientSettings?: SharedNotebookRecipientSettings; }); + } + + /** + * This structure captures information about the types of operations + * that cannot be performed on a given notebook with a type of + * authenticated access and credentials. The values filled into this + * structure are based on then-current values in the server database + * for shared notebooks and notebook publishing records, as well as + * information related to the authentication token. Information from + * the authentication token includes the application that is accessing + * the server, as defined by the permissions granted by consumer (api) + * key, and the method used to obtain the token, for example via + * authenticateToSharedNotebook, authenticateToBusiness, etc. Note + * that changes to values in this structure that are the result of + * shared notebook or publishing record changes are communicated to + * the client via a change in the notebook USN during sync. It is + * important to use the same access method, parameters, and consumer + * key in order obtain correct results from the sync engine. + * + * The server has the final say on what is allowed as values may + * change between calls to obtain NotebookRestrictions instances + * and to operate on data on the service. + * + * If the following are set and true, then the given restriction is + * in effect, as accessed by the same authentication token from which + * the values were obtained. + * + *
        noReadNotes
        + *
        The client is not able to read notes from the service and + * the notebook is write-only. + *
        + *
        noCreateNotes
        + *
        The client may not create new notes in the notebook. + *
        + *
        noUpdateNotes
        + *
        The client may not update notes currently in the notebook. + *
        + *
        noExpungeNotes
        + *
        The client may not expunge notes currently in the notebook. + *
        + *
        noShareNotes
        + *
        The client may not share notes in the notebook via the + * shareNote method. + *
        + *
        noEmailNotes
        + *
        The client may not e-mail notes via the Evernote service by + * using the emailNote method. + *
        + *
        noSendMessageToRecipients
        + *
        The client may not send messages to the share recipients of + * the notebook. + *
        + *
        noUpdateNotebook
        + *
        The client may not update the Notebook object itself, for + * example, via the updateNotebook method. + *
        + *
        noExpungeNotebook
        + *
        The client may not expunge the Notebook object itself, for + * example, via the expungeNotebook method. + *
        + *
        noSetDefaultNotebook
        + *
        The client may not set this notebook to be the default notebook. + * The caller should leave Notebook.defaultNotebook unset. + *
        + *
        noSetNotebookStack
        + *
        If the client is able to update the Notebook, the Notebook.stack + * value may not be set. + *
        + *
        noPublishToPublic
        + *
        The client may not change the publish the notebook to the public. + * For example, business notebooks may not be shared publicly. + *
        + *
        noPublishToBusinessLibrary
        + *
        The client may not publish the notebook to the business library. + *
        + *
        noCreateTags
        + *
        The client may not complete an operation that results in a new tag + * being created in the owner's account. + *
        + *
        noUpdateTags
        + *
        The client may not update tags in the owner's account. + *
        + *
        noExpungeTags
        + *
        The client may not expunge tags in the owner's account. + *
        + *
        noSetParentTag
        + *
        If the client is able to create or update tags in the owner's account, + * then they will not be able to set the parent tag. Leave the value unset. + *
        + *
        noCreateSharedNotebooks
        + *
        The client is unable to create shared notebooks for the notebook. + *
        + *
        updateWhichSharedNotebookRestrictions
        + *
        Restrictions on which shared notebook instances can be updated. If the + * value is not set or null, then the client can update any of the shared notebooks + * associated with the notebook on which the NotebookRestrictions are defined. + * See the enumeration for further details. + *
        + *
        expungeWhichSharedNotebookRestrictions
        + *
        Restrictions on which shared notebook instances can be expunged. If the + * value is not set or null, then the client can expunge any of the shared notebooks + * associated with the notebook on which the NotebookRestrictions are defined. + * See the enumeration for further details. + *
        + */ + class NotebookRestrictions { + noReadNotes: boolean; + noCreateNotes: boolean; + noUpdateNotes: boolean; + noExpungeNotes: boolean; + noShareNotes: boolean; + noEmailNotes: boolean; + noSendMessageToRecipients: boolean; + noUpdateNotebook: boolean; + noExpungeNotebook: boolean; + noSetDefaultNotebook: boolean; + noSetNotebookStack: boolean; + noPublishToPublic: boolean; + noPublishToBusinessLibrary: boolean; + noCreateTags: boolean; + noUpdateTags: boolean; + noExpungeTags: boolean; + noSetParentTag: boolean; + noCreateSharedNotebooks: boolean; + updateWhichSharedNotebookRestrictions: SharedNotebookInstanceRestrictions; + expungeWhichSharedNotebookRestrictions: SharedNotebookInstanceRestrictions; + + constructor(args?: { noReadNotes?: boolean; noCreateNotes?: boolean; noUpdateNotes?: boolean; noExpungeNotes?: boolean; noShareNotes?: boolean; noEmailNotes?: boolean; noSendMessageToRecipients?: boolean; noUpdateNotebook?: boolean; noExpungeNotebook?: boolean; noSetDefaultNotebook?: boolean; noSetNotebookStack?: boolean; noPublishToPublic?: boolean; noPublishToBusinessLibrary?: boolean; noCreateTags?: boolean; noUpdateTags?: boolean; noExpungeTags?: boolean; noSetParentTag?: boolean; noCreateSharedNotebooks?: boolean; updateWhichSharedNotebookRestrictions?: SharedNotebookInstanceRestrictions; expungeWhichSharedNotebookRestrictions?: SharedNotebookInstanceRestrictions; }); + } + + /** + * A unique container for a set of notes. + *
        + *
        guid
        + *
        The unique identifier of this notebook. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        name
        + *
        A sequence of characters representing the name of the + * notebook. May be changed by clients, but the account may not contain two + * notebooks with names that are equal via a case-insensitive comparison. + * Can't begin or end with a space. + *
        + * Length: EDAM_NOTEBOOK_NAME_LEN_MIN - EDAM_NOTEBOOK_NAME_LEN_MAX + *
        + * Regex: EDAM_NOTEBOOK_NAME_REGEX + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this object. The USN values are sequential within an + * account, and can be used to compare the order of modifications within the + * service. + *
        + * + *
        defaultNotebook
        + *
        If true, this notebook should be used for new notes + * whenever the user has not (or cannot) specify a desired target notebook. + * For example, if a note is submitted via SMTP email. + * The service will maintain at most one defaultNotebook per account. + * If a second notebook is created or updated with defaultNotebook set to + * true, the service will automatically update the prior notebook's + * defaultNotebook field to false. If the default notebook is deleted + * (i.e. "active" set to false), the "defaultNotebook" field will be + * set to false by the service. If the account has no default notebook + * set, the service will use the most recent notebook as the default. + *
        + * + *
        serviceCreated
        + *
        The time when this notebook was created on the + * service. This will be set on the service during creation, and the service + * will provide this value when it returns a Notebook to a client. + * The service will ignore this value if it is sent by clients. + *
        + * + *
        serviceUpdated
        + *
        The time when this notebook was last modified on the + * service. This will be set on the service during creation, and the service + * will provide this value when it returns a Notebook to a client. + * The service will ignore this value if it is sent by clients. + *
        + * + *
        publishing
        + *
        If the Notebook has been opened for public access, or + * business users shared with their business (i.e. if 'published' is + * set to true), then this will point to the set of publishing + * information for the Notebook (URI, description, etc.). A + * Notebook cannot be published without providing this information, + * but it will persist for later use if publishing is ever disabled + * on the Notebook. Clients that do not wish to change the + * publishing behavior of a Notebook should not set this value when + * calling NoteStore.updateNotebook(). + *
        + * + *
        published
        + *
        If this is set to true, then the Notebook will be + * accessible either to the public, or for business users to their business, + * via the 'publishing' specification, which must also be set. If this is set + * to false, the Notebook will not be available to the public (or business). + * Clients that do not wish to change the publishing behavior of a Notebook + * should not set this value when calling NoteStore.updateNotebook(). + *
        + * + *
        stack
        + *
        If this is set, then the notebook is visually contained within a stack + * of notebooks with this name. All notebooks in the same account with the + * same 'stack' field are considered to be in the same stack. + * Notebooks with no stack set are "top level" and not contained within a + * stack. + *
        + * + *
        sharedNotebookIds
        + *
        DEPRECATED - replaced by sharedNotebooks.
        + * + *
        sharedNotebooks
        + *
        The list of recipients to whom this notebook has been shared + * (one SharedNotebook object per recipient email address). This field will + * be unset if you do not have permission to access this data. If you are + * accessing the notebook as the owner or via a shared notebook that is + * modifiable, then you have access to this data and the value will be set. + * This field is read-only. Clients may not make changes to shared notebooks + * via this field. + *
        + * + *
        businessNotebook
        + *
        If the notebook is part of a business account and has been published to the + * business library, this will contain information for the library listing. + * The presence or absence of this field is not a reliable test of whether a given + * notebook is in fact a business notebook - the field is only used when a notebook is or + * has been published to the business library. + *
        + * + *
        contact
        + *
        Intended for use with Business accounts, this field identifies the user who + * has been designated as the "contact". For notebooks created in business + * accounts, the server will automatically set this value to the user who created + * the notebook unless Notebook.contact.username has been set, in which that value + * will be used. When updating a notebook, it is common to leave Notebook.contact + * field unset, indicating that no change to the value is being requested and that + * the existing value, if any, should be preserved. + *
        + * + *
        + */ + class Notebook { + guid: string; + name: string; + updateSequenceNum: number; + defaultNotebook: boolean; + serviceCreated: number; + serviceUpdated: number; + publishing: Publishing; + published: boolean; + stack: string; + sharedNotebookIds: number[]; + sharedNotebooks: SharedNotebook[]; + businessNotebook: BusinessNotebook; + contact: User; + restrictions: NotebookRestrictions; + + constructor(args?: { guid?: string; name?: string; updateSequenceNum?: number; defaultNotebook?: boolean; serviceCreated?: number; serviceUpdated?: number; publishing?: Publishing; published?: boolean; stack?: string; sharedNotebookIds?: number[]; sharedNotebooks?: SharedNotebook[]; businessNotebook?: BusinessNotebook; contact?: User; restrictions?: NotebookRestrictions; }); + } + + /** + * A link in an users account that refers them to a public or individual share in + * another user's account. + * + *
        + *
        shareName
        + *
        the display name of the shared notebook. + * The link owner can change this.
        + * + *
        username
        + *
        the username of the user who owns the shared or public notebook
        + * + *
        shardId
        + *
        the shard ID of the notebook if the notebook is not public + * + *
        shareKey
        + *
        the secret key that provides access to the shared notebook
        + * + *
        uri
        + *
        the identifier of the public notebook
        + * + *
        guid
        + *
        The unique identifier of this linked notebook. Will be set whenever + * a linked notebook is retrieved from the service, but may be null when a client + * is creating a linked notebook. + *
        + * Length: EDAM_GUID_LEN_MIN - EDAM_GUID_LEN_MAX + *
        + * Regex: EDAM_GUID_REGEX + *
        + * + *
        updateSequenceNum
        + *
        A number identifying the last transaction to + * modify the state of this object. The USN values are sequential within an + * account, and can be used to compare the order of modifications within the + * service. + *
        + * + *
        noteStoreUrl
        + *
        + * This field will contain the full URL that clients should use to make + * NoteStore requests to the server shard that contains that notebook's data. + * I.e. this is the URL that should be used to create the Thrift HTTP client + * transport to send messages to the NoteStore service for the account. + *
        + * + *
        webApiUrlPrefix:
        + *
        + * This field will contain the initial part of the URLs that should be used + * to make requests to Evernote's thin client "web API", which provide + * optimized operations for clients that aren't capable of manipulating + * the full contents of accounts via the full Thrift data model. Clients + * should concatenate the relative path for the various servlets onto the + * end of this string to construct the full URL, as documented on our + * developer web site. + *
        + * + *
        stack
        + *
        If this is set, then the notebook is visually contained within a stack + * of notebooks with this name. All notebooks in the same account with the + * same 'stack' field are considered to be in the same stack. + * Notebooks with no stack set are "top level" and not contained within a + * stack. The link owner can change this and this field is for the benefit + * of the link owner. + *
        + * + *
        businessId
        + *
        If set, this will be the unique identifier for the business that owns + * the notebook to which the linked notebook refers. + * + *
        + */ + class LinkedNotebook { + shareName: string; + username: string; + shardId: string; + shareKey: string; + uri: string; + guid: string; + updateSequenceNum: number; + noteStoreUrl: string; + webApiUrlPrefix: string; + stack: string; + businessId: number; + + constructor(args?: { shareName?: string; username?: string; shardId?: string; shareKey?: string; uri?: string; guid?: string; updateSequenceNum?: number; noteStoreUrl?: string; webApiUrlPrefix?: string; stack?: string; businessId?: number; }); + } + + /** + * A structure that describes a notebook or a user's relationship with + * a notebook. NotebookDescriptor is expected to remain a lighter-weight + * structure when compared to Notebook. + *
        + *
        guid
        + *
        The unique identifier of the notebook. + *
        + * + *
        notebookDisplayName
        + *
        A sequence of characters representing the name of the + * notebook. + *
        + * + *
        contactName
        + *
        The User.name value of the notebook's "contact". + *
        + * + *
        hasSharedNotebook
        + *
        Whether a SharedNotebook record exists between the calling user and this + * notebook. + *
        + * + *
        joinedUserCount
        + *
        The number of users who have joined this notebook. + *
        + * + *
        + */ + class NotebookDescriptor { + guid: string; + notebookDisplayName: string; + contactName: string; + hasSharedNotebook: boolean; + joinedUserCount: number; + + constructor(args?: { guid?: string; notebookDisplayName?: string; contactName?: string; hasSharedNotebook?: boolean; joinedUserCount?: number; }); + } + + /** + * A value for the "recipe" key in the "classifications" map in NoteAttributes + * that indicates the user has classified a note as being a non-recipe. + */ + var CLASSIFICATION_RECIPE_USER_NON_RECIPE: string; + + /** + * A value for the "recipe" key in the "classifications" map in NoteAttributes + * that indicates the user has classified a note as being a recipe. + */ + var CLASSIFICATION_RECIPE_USER_RECIPE: string; + + /** + * A value for the "recipe" key in the "classifications" map in NoteAttributes + * that indicates the Evernote service has classified a note as being a recipe. + */ + var CLASSIFICATION_RECIPE_SERVICE_RECIPE: string; + + /** + * Standardized value for the 'source' NoteAttribute for notes that + * were clipped from the web in some manner. + */ + var EDAM_NOTE_SOURCE_WEB_CLIP: string; + + /** + * Standardized value for the 'source' NoteAttribute for notes that + * were clipped from an email message. + */ + var EDAM_NOTE_SOURCE_MAIL_CLIP: string; + + /** + * Standardized value for the 'source' NoteAttribute for notes that + * were created via email sent to Evernote's email interface. + */ + var EDAM_NOTE_SOURCE_MAIL_SMTP_GATEWAY: string; + /** + * Service: UserStore + *

        + * The UserStore service is primarily used by EDAM clients to establish + * authentication via username and password over a trusted connection (e.g. + * SSL). A client's first call to this interface should be checkVersion() to + * ensure that the client's software is up to date. + *

        + * All calls which require an authenticationToken may throw an + * EDAMUserException for the following reasons: + *
          + *
        • AUTH_EXPIRED "authenticationToken" - token has expired + *
        • BAD_DATA_FORMAT "authenticationToken" - token is malformed + *
        • DATA_REQUIRED "authenticationToken" - token is empty + *
        • INVALID_AUTH "authenticationToken" - token signature is invalid + *
        + */ + class UserStoreClient { + seqid: number; + + /** + * This should be the first call made by a client to the EDAM service. It + * tells the service what protocol version is used by the client. The + * service will then return true if the client is capable of talking to + * the service, and false if the client's protocol version is incompatible + * with the service, so the client must upgrade. If a client receives a + * false value, it should report the incompatibility to the user and not + * continue with any more EDAM requests (UserStore or NoteStore). + * + * @param clientName + * This string provides some information about the client for + * tracking/logging on the service. It should provide information about + * the client's software and platform. The structure should be: + * application/version; platform/version; [ device/version ] + * E.g. "Evernote Windows/3.0.1; Windows/XP SP3". + * + * @param edamVersionMajor + * This should be the major protocol version that was compiled by the + * client. This should be the current value of the EDAM_VERSION_MAJOR + * constant for the client. + * + * @param edamVersionMinor + * This should be the major protocol version that was compiled by the + * client. This should be the current value of the EDAM_VERSION_MINOR + * constant for the client. + */ + checkVersion(clientName: string, edamVersionMajor: number, edamVersionMinor: number, cb: Callback): void; + + /** + * This provides bootstrap information to the client. Various bootstrap + * profiles and settings may be used by the client to configure itself. + * + * @param locale + * The client's current locale, expressed in language[_country] + * format. E.g., "en_US". See ISO-639 and ISO-3166 for valid + * language and country codes. + * + * @return + * The bootstrap information suitable for this client. + */ + getBootstrapInfo(locale: string, cb: Callback): void; + + /** + * Revoke an existing long lived authentication token. This can be used to + * revoke OAuth tokens or tokens created by calling authenticateLongSession, + * and allows a user to effectively log out of Evernote from the perspective + * of the application that holds the token. The authentication token that is + * passed is immediately revoked and may not be used to call any authenticated + * EDAM function. + * + * @param authenticationToken the authentication token to revoke. + * + * @throws EDAMUserException
          + *
        • DATA_REQUIRED "authenticationToken" - no authentication token provided + *
        • BAD_DATA_FORMAT "authenticationToken" - the authentication token is not well formed + *
        • INVALID_AUTH "authenticationToken" - the authentication token is invalid + *
        • AUTH_EXPIRED "authenticationToken" - the authentication token is expired or + * is already revoked. + *
        + */ + revokeLongSession(cb: Callback): void; + + /** + * This is used to take an existing authentication token that grants access + * to an individual user account (returned from 'authenticate', + * 'authenticateLongSession' or an OAuth authorization) and obtain an additional + * authentication token that may be used to access business notebooks if the user + * is a member of an Evernote Business account. + * + * The resulting authentication token may be used to make NoteStore API calls + * against the business using the NoteStore URL returned in the result. + * + * @param authenticationToken + * The authentication token for the user. This may not be a shared authentication + * token (returned by NoteStore.authenticateToSharedNotebook or + * NoteStore.authenticateToSharedNote) or a business authentication token. + * + * @return + * The result of the authentication, with the token granting access to the + * business in the result's 'authenticationToken' field. The URL that must + * be used to access the business account NoteStore will be returned in the + * result's 'noteStoreUrl' field. The 'User' field will + * not be set in the result. + * + * @throws EDAMUserException
          + *
        • PERMISSION_DENIED "authenticationToken" - the provided authentication token + * is a shared or business authentication token.
        • + *
        • PERMISSION_DENIED "Business" - the user identified by the provided + * authentication token is not currently a member of a business.
        • + *
        • PERMISSION_DENIED "Business.status" - the business that the user is a + * member of is not currently in an active status.
        • + *
        + */ + authenticateToBusiness(cb: Callback): void; + + /** + * Returns the User corresponding to the provided authentication token, + * or throws an exception if this token is not valid. + * The level of detail provided in the returned User structure depends on + * the access level granted by the token, so a web service client may receive + * fewer fields than an integrated desktop client. + */ + getUser(cb: Callback): void; + + /** + * Asks the UserStore about the publicly available location information for + * a particular username. + * + * @throws EDAMUserException
          + *
        • DATA_REQUIRED "username" - username is empty + *
        + */ + getPublicUserInfo(username: string, cb: Callback): void; + + + /** + * Returns the URL that should be used to talk to the NoteStore for the + * account represented by the provided authenticationToken. + * This method isn't needed by most clients, who can retrieve the correct + * NoteStore URL from the AuthenticationResult returned from the authenticate + * or refreshAuthentication calls. This method is typically only needed + * to look up the correct URL for a long-lived session token (e.g. for an + * OAuth web service). + */ + getNoteStoreUrl(cb: Callback): void; + } + /** + * This structure is used to provide publicly-available user information + * about a particular account. + *
        + *
        userId:
        + *
        + * The unique numeric user identifier for the user account. + *
        + *
        shardId:
        + *
        + * DEPRECATED - Client applications should have no need to use this field. + *
        + *
        privilege:
        + *
        + * The privilege level of the account, to determine whether + * this is a Premium or Free account. + *
        + *
        noteStoreUrl:
        + *
        + * This field will contain the full URL that clients should use to make + * NoteStore requests to the server shard that contains that user's data. + * I.e. this is the URL that should be used to create the Thrift HTTP client + * transport to send messages to the NoteStore service for the account. + *
        + *
        webApiUrlPrefix:
        + *
        + * This field will contain the initial part of the URLs that should be used + * to make requests to Evernote's thin client "web API", which provide + * optimized operations for clients that aren't capable of manipulating + * the full contents of accounts via the full Thrift data model. Clients + * should concatenate the relative path for the various servlets onto the + * end of this string to construct the full URL, as documented on our + * developer web site. + *
        + *
        + */ + class PublicUserInfo { + userId: number; + shardId: string; + privilege: PrivilegeLevel; + username: string; + noteStoreUrl: string; + webApiUrlPrefix: string; + + constructor(args?: { userId: number; shardId: string; privilege?: PrivilegeLevel; username?: string; noteStoreUrl?: string; webApiUrlPrefix?: string; }); + } + + /** + * When an authentication (or re-authentication) is performed, this structure + * provides the result to the client. + *
        + *
        currentTime:
        + *
        + * The server-side date and time when this result was + * generated. + *
        + *
        authenticationToken:
        + *
        + * Holds an opaque, ASCII-encoded token that can be + * used by the client to perform actions on a NoteStore. + *
        + *
        expiration:
        + *
        + * Holds the server-side date and time when the + * authentication token will expire. + * This time can be compared to "currentTime" to produce an expiration + * time that can be reconciled with the client's local clock. + *
        + *
        user:
        + *
        + * Holds the information about the account which was + * authenticated if this was a full authentication. May be absent if this + * particular authentication did not require user information. + *
        + *
        publicUserInfo:
        + *
        + * If this authentication result was achieved without full permissions to + * access the full User structure, this field may be set to give back + * a more limited public set of data. + *
        + *
        noteStoreUrl:
        + *
        + * This field will contain the full URL that clients should use to make + * NoteStore requests to the server shard that contains that user's data. + * I.e. this is the URL that should be used to create the Thrift HTTP client + * transport to send messages to the NoteStore service for the account. + *
        + *
        webApiUrlPrefix:
        + *
        + * This field will contain the initial part of the URLs that should be used + * to make requests to Evernote's thin client "web API", which provide + * optimized operations for clients that aren't capable of manipulating + * the full contents of accounts via the full Thrift data model. Clients + * should concatenate the relative path for the various servlets onto the + * end of this string to construct the full URL, as documented on our + * developer web site. + *
        + *
        secondFactorRequired:
        + *
        + * If set to true, this field indicates that the user has enabled two-factor + * authentication and must enter their second factor in order to complete + * authentication. In this case the value of authenticationResult will be + * a short-lived authentication token that may only be used to make a + * subsequent call to completeTwoFactorAuthentication. + *
        + *
        secondFactorDeliveryHint:
        + *
        + * When secondFactorRequired is set to true, this field may contain a string + * describing the second factor delivery method that the user has configured. + * This will typically be an obfuscated mobile device number, such as + * "(xxx) xxx-x095". This string can be displayed to the user to remind them + * how to obtain the required second factor. + * TODO do we need to differentiate between SMS and voice delivery? + *
        + *
        + */ + class AuthenticationResult { + currentTime: number; + authenticationToken: string; + expiration: number; + user: User; + publicUserInfo: PublicUserInfo; + noteStoreUrl: string; + webApiUrlPrefix: string; + secondFactorRequired: boolean; + secondFactorDeliveryHint: string; + + constructor(args?: { currentTime: number; authenticationToken: string; expiration: number; user?: User; publicUserInfo?: PublicUserInfo; noteStoreUrl?: string; webApiUrlPrefix?: string; secondFactorRequired?: boolean; secondFactorDeliveryHint?: string; }); + } + + /** + * This structure describes a collection of bootstrap settings. + *
        + *
        serviceHost:
        + *
        + * The hostname and optional port for composing Evernote web service URLs. + * This URL can be used to access the UserStore and related services, + * but must not be used to compose the NoteStore URL. Client applications + * must handle serviceHost values that include only the hostname + * (e.g. www.evernote.com) or both the hostname and port (e.g. www.evernote.com:8080). + * If no port is specified, or if port 443 is specified, client applications must + * use the scheme "https" when composing URLs. Otherwise, a client must use the + * scheme "http". + *
        + *
        marketingUrl:
        + *
        + * The URL stem for the Evernote corporate marketing website, e.g. http://www.evernote.com. + * This stem can be used to compose website URLs. For example, the URL of the Evernote + * Trunk is composed by appending "/about/trunk/" to the value of marketingUrl. + *
        + *
        supportUrl:
        + *
        + * The full URL for the Evernote customer support website, e.g. https://support.evernote.com. + *
        + *
        accountEmailDomain:
        + *
        + * The domain used for an Evernote user's incoming email address, which allows notes to + * be emailed into an account. E.g. m.evernote.com. + *
        + *
        enableFacebookSharing:
        + *
        + * Whether the client application should enable sharing of notes on Facebook. + *
        + *
        enableGiftSubscriptions:
        + *
        + * Whether the client application should enable gift subscriptions. + *
        + *
        enableSupportTickets:
        + *
        + * Whether the client application should enable in-client creation of support tickets. + *
        + *
        enableSharedNotebooks:
        + *
        + * Whether the client application should enable shared notebooks. + *
        + *
        enableSingleNoteSharing:
        + *
        + * Whether the client application should enable single note sharing. + *
        + *
        enableSponsoredAccounts:
        + *
        + * Whether the client application should enable sponsored accounts. + *
        + *
        enableTwitterSharing:
        + *
        + * Whether the client application should enable sharing of notes on Twitter. + *
        + *
        + */ + class BootstrapSettings { + serviceHost: string; + marketingUrl: string; + supportUrl: string; + accountEmailDomain: string; + enableFacebookSharing: boolean; + enableGiftSubscriptions: boolean; + enableSupportTickets: boolean; + enableSharedNotebooks: boolean; + enableSingleNoteSharing: boolean; + enableSponsoredAccounts: boolean; + enableTwitterSharing: boolean; + enableLinkedInSharing: boolean; + enablePublicNotebooks: boolean; + + constructor(args?: { serviceHost: string; marketingUrl: string; supportUrl: string; accountEmailDomain: string; enableFacebookSharing?: boolean; enableGiftSubscriptions?: boolean; enableSupportTickets?: boolean; enableSharedNotebooks?: boolean; enableSingleNoteSharing?: boolean; enableSponsoredAccounts?: boolean; enableTwitterSharing?: boolean; enableLinkedInSharing?: boolean; enablePublicNotebooks?: boolean; }); + } + + /** + * This structure describes a collection of bootstrap settings. + *
        + *
        name:
        + *
        + * The unique name of the profile, which is guaranteed to remain consistent across + * calls to getBootstrapInfo. + *
        + *
        settings:
        + *
        + * The settings for this profile. + *
        + *
        + */ + class BootstrapProfile { + name: string; + settings: BootstrapSettings; + + constructor(args?: { name: string; settings: BootstrapSettings; }); + } + + /** + * This structure describes a collection of bootstrap profiles. + *
        + *
        profiles:
        + *
        + * List of one or more bootstrap profiles, in descending + * preference order. + *
        + *
        + */ + class BootstrapInfo { + profiles: BootstrapProfile[]; + + constructor(args?: { profiles: BootstrapProfile[]; }); + } + + /** + * The major version number for the current revision of the EDAM protocol. + * Clients pass this to the service using UserStore.checkVersion at the + * beginning of a session to confirm that they are not out of date. + */ + var EDAM_VERSION_MAJOR: number; + + /** + * The minor version number for the current revision of the EDAM protocol. + * Clients pass this to the service using UserStore.checkVersion at the + * beginning of a session to confirm that they are not out of date. + */ + var EDAM_VERSION_MINOR: number; + + } +} diff --git a/thrift/thrift-tests.ts b/thrift/thrift-tests.ts new file mode 100644 index 000000000..abe39678a --- /dev/null +++ b/thrift/thrift-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +// Currently, the thrift bindings are minimal just to support the thrift generated +// evernote bindings. Add more tests if you flesh out and plan to use the thrift +// bindings more deeply. + +import evernote = require("evernote"); + +1 + 1; diff --git a/thrift/thrift.d.ts b/thrift/thrift.d.ts new file mode 100644 index 000000000..d0232b40d --- /dev/null +++ b/thrift/thrift.d.ts @@ -0,0 +1,281 @@ +// Type definitions for thrift 0.9.2 +// Project: https://www.npmjs.com/package/thrift +// Definitions by: Zachary Collins +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +declare module "thrift" { + export module Thrift { + /** + * Thrift IDL type string to Id mapping. + * @property {number} STOP - End of a set of fields. + * @property {number} VOID - No value (only legal for return types). + * @property {number} BOOL - True/False integer. + * @property {number} BYTE - Signed 8 bit integer. + * @property {number} I08 - Signed 8 bit integer. + * @property {number} DOUBLE - 64 bit IEEE 854 floating point. + * @property {number} I16 - Signed 16 bit integer. + * @property {number} I32 - Signed 32 bit integer. + * @property {number} I64 - Signed 64 bit integer. + * @property {number} STRING - Array of bytes representing a string of characters. + * @property {number} UTF7 - Array of bytes representing a string of UTF7 encoded characters. + * @property {number} STRUCT - A multifield type. + * @property {number} MAP - A collection type (map/associative-array/dictionary). + * @property {number} SET - A collection type (unordered and without repeated values). + * @property {number} LIST - A collection type (unordered). + * @property {number} UTF8 - Array of bytes representing a string of UTF8 encoded characters. + * @property {number} UTF16 - Array of bytes representing a string of UTF16 encoded characters. + */ + interface Type { + 'STOP': number; + 'VOID': number; + 'BOOL': number; + 'BYTE': number; + 'I08': number; + 'DOUBLE': number; + 'I16': number; + 'I32': number; + 'I64': number; + 'STRING': number; + 'UTF7': number; + 'STRUCT': number; + 'MAP': number; + 'SET': number; + 'LIST': number; + 'UTF8': number; + 'UTF16': number; + } + var Type: Type; + + /** + * Thrift RPC message type string to Id mapping. + * @property {number} CALL - RPC call sent from client to server. + * @property {number} REPLY - RPC call normal response from server to client. + * @property {number} EXCEPTION - RPC call exception response from server to client. + * @property {number} ONEWAY - Oneway RPC call from client to server with no response. + */ + interface MessageType { + 'CALL': number; + 'REPLY': number; + 'EXCEPTION': number; + 'ONEWAY': number; + } + var MessageType: MessageType; + + /** + * Utility function returning the count of an object's own properties. + * @param {object} obj - Object to test. + * @returns {number} number of object's own properties + */ + function objectLength(obj: Object): number; + + /** + * Utility function to establish prototype inheritance. + * @param {function} constructor - Contstructor function to set as derived. + * @param {function} superConstructor - Contstructor function to set as base. + * @param {string} [name] - Type name to set as name property in derived prototype. + */ + function inherits(constructor: Function, superConstructor: Function, name?: string): void; + + /** + * TException is the base class for all Thrift exceptions types. + */ + class TException implements Error { + name: string; + message: string; + + /** + * Initializes a Thrift TException instance. + * @param {string} message - The TException message (distinct from the Error message). + */ + constructor(message: string); + + /** + * Returns the message set on the exception. + * @returns {string} exception message + */ + getMessage(): string; + } + + /** + * Thrift Application Exception type string to Id mapping. + * @property {number} UNKNOWN - Unknown/undefined. + * @property {number} UNKNOWN_METHOD - Client attempted to call a method unknown to the server. + * @property {number} INVALID_MESSAGE_TYPE - Client passed an unknown/unsupported MessageType. + * @property {number} WRONG_METHOD_NAME - Unused. + * @property {number} BAD_SEQUENCE_ID - Unused in Thrift RPC, used to flag proprietary sequence number errors. + * @property {number} MISSING_RESULT - Raised by a server processor if a handler fails to supply the required return result. + * @property {number} INTERNAL_ERROR - Something bad happened. + * @property {number} PROTOCOL_ERROR - The protocol layer failed to serialize or deserialize data. + * @property {number} INVALID_TRANSFORM - Unused. + * @property {number} INVALID_PROTOCOL - The protocol (or version) is not supported. + * @property {number} UNSUPPORTED_CLIENT_TYPE - Unused. + */ + interface TApplicationExceptionType { + 'UNKNOWN': number; + 'UNKNOWN_METHOD': number; + 'INVALID_MESSAGE_TYPE': number; + 'WRONG_METHOD_NAME': number; + 'BAD_SEQUENCE_ID': number; + 'MISSING_RESULT': number; + 'INTERNAL_ERROR': number; + 'PROTOCOL_ERROR': number; + 'INVALID_TRANSFORM': number; + 'INVALID_PROTOCOL': number; + 'UNSUPPORTED_CLIENT_TYPE': number; + } + var TApplicationExceptionType: TApplicationExceptionType; + + /** + * TApplicationException is the exception class used to propagate exceptions from an RPC server back to a calling client. + */ + class TApplicationException extends TException { + message: string; + code: number; + + /** + * Initializes a Thrift TApplicationException instance. + * @param {string} message - The TApplicationException message (distinct from the Error message). + * @param {Thrift.TApplicationExceptionType} [code] - The TApplicationExceptionType code. + */ + constructor(message: string, code?: number); + + /** + * Read a TApplicationException from the supplied protocol. + * @param {object} input - The input protocol to read from. + */ + read(input: Object): void; + + /** + * Write a TApplicationException to the supplied protocol. + * @param {object} output - The output protocol to write to. + */ + write(output: Object): void; + + /** + * Returns the application exception code set on the exception. + * @returns {Thrift.TApplicationExceptionType} exception code + */ + getCode(): number; + } + + /** + * The Apache Thrift Transport layer performs byte level I/O between RPC + * clients and servers. The JavaScript Transport object type uses Http[s]/XHR and is + * the sole browser based Thrift transport. Target servers must implement the http[s] + * transport (see: node.js example server). + */ + class TXHRTransport { + url: string; + wpos: number; + rpos: number; + useCORS: any; + send_buf: string; + recv_buf: string; + + /** + * If you do not specify a url then you must handle XHR operations on + * your own. This type can also be constructed using the Transport alias + * for backward compatibility. + * @param {string} [url] - The URL to connect to. + * @param {object} [options] - Options. + */ + constructor(url?: string, options?: Object); + + /** + * Gets the browser specific XmlHttpRequest Object. + * @returns {object} the browser XHR interface object + */ + getXmlHttpRequestObject(): Object; + + /** + * Sends the current XRH request if the transport was created with a URL and + * the async parameter if false. If the transport was not created with a URL + * or the async parameter is True or the URL is an empty string, the current + * send buffer is returned. + * @param {object} async - If true the current send buffer is returned. + * @param {function} callback - Optional async completion callback. + * @returns {undefined|string} Nothing or the current send buffer. + */ + flush(async: any, callback?: Function): string; + + /** + * Creates a jQuery XHR object to be used for a Thrift server call. + * @param {object} client - The Thrift Service client object generated by the IDL compiler. + * @param {object} postData - The message to send to the server. + * @param {function} args - The function to call if the request succeeds. + * @param {function} recv_method - The Thrift Service Client receive method for the call. + * @returns {object} A new jQuery XHR object. + */ + jqRequest(client: Object, postData: any, args: Function, recv_method: Function): Object; + + /** + * Sets the buffer to use when receiving server responses. + * @param {string} buf - The buffer to receive server responses. + */ + setRecvBuffer(buf: string): void; + + /** + * Returns true if the transport is open, in browser based JavaScript + * this function always returns true. + * @returns {boolean} Always True. + */ + isOpen(): boolean; + + /** + * Opens the transport connection, in browser based JavaScript + * this function is a nop. + */ + open(): void; + + /** + * Closes the transport connection, in browser based JavaScript + * this function is a nop. + */ + close(): void; + + /** + * Returns the specified number of characters from the response + * buffer. + * @param {number} len - The number of characters to return. + * @returns {string} Characters sent by the server. + */ + read(len: number): string; + + /** + * Returns the entire response buffer. + * @returns {string} Characters sent by the server. + */ + readAll(): string; + + /** + * Sets the send buffer to buf. + * @param {string} buf - The buffer to send. + */ + write(buf: string): void; + + /** + * Returns the send buffer. + * @returns {string} The send buffer. + */ + getSendBuffer(): string; + } + } +} From 5e11cf3c90ae085c78b4d11e6b952a2ad3dedce0 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 30 Jul 2015 23:41:54 -0700 Subject: [PATCH 112/419] Update estree-tests.ts --- estree/estree-tests.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/estree/estree-tests.ts b/estree/estree-tests.ts index bbf16586d..d119f6ac0 100644 --- a/estree/estree-tests.ts +++ b/estree/estree-tests.ts @@ -59,7 +59,6 @@ expression = withStatement.object; var switchStatement: ESTree.SwitchStatement; expression = switchStatement.discriminant; switchCase = switchStatement.cases[0]; -boolean = switchStatement.lexical; // ReturnStatement var returnStatement: ESTree.ReturnStatement; @@ -164,7 +163,6 @@ statement = switchCase.consequent[0]; // CatchClause string = catchClause.type; pattern = catchClause.param; -expression = catchClause.guard; blockStatement = catchClause.body; // Misc From 702708845497a9e65430518b4ad8222e2800911f Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 30 Jul 2015 23:46:34 -0700 Subject: [PATCH 113/419] Add definitions for Facebook Flow AST extensions --- estree/flow.d.ts | 174 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) create mode 100644 estree/flow.d.ts diff --git a/estree/flow.d.ts b/estree/flow.d.ts new file mode 100644 index 000000000..43281c6c8 --- /dev/null +++ b/estree/flow.d.ts @@ -0,0 +1,174 @@ +// Type definitions for ESTree AST extensions for Facebook Flow +// Project: https://github.com/estree/estree +// Definitions by: RReverser +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module ESTree { + interface FlowTypeAnnotation extends Node { + _flowTypeAnnotationBrand: any; + } + + interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} + + interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} + + interface FlowDeclaration extends Declaration {} + + interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ArrayTypeAnnotation extends FlowTypeAnnotation { + elementType: FlowTypeAnnotation; + } + + interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface ClassImplements extends Node { + id: Identifier; + typeParameters?: TypeParameterInstantiation; + } + + interface ClassProperty { + key: Expression; + value?: Expression; + typeAnnotation?: TypeAnnotation; + computed: boolean; + static: boolean; + } + + interface DeclareClass extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration; + body: ObjectTypeAnnotation; + extends: Array; + } + + interface DeclareFunction extends FlowDeclaration { + id: Identifier; + } + + interface DeclareModule extends FlowDeclaration { + id: Literal | Identifier; + body: BlockStatement; + } + + interface DeclareVariable extends FlowDeclaration { + id: Identifier; + } + + interface FunctionTypeAnnotation extends FlowTypeAnnotation { + params: Array; + returnType: FlowTypeAnnotation; + rest?: FunctionTypeParam; + typeParameters?: TypeParameterDeclaration; + } + + interface FunctionTypeParam { + name: Identifier; + typeAnnotation: FlowTypeAnnotation; + optional: boolean; + } + + interface GenericTypeAnnotation extends FlowTypeAnnotation { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation; + } + + interface InterfaceExtends extends Node { + id: Identifier | QualifiedTypeIdentifier; + typeParameters?: TypeParameterInstantiation; + } + + interface InterfaceDeclaration extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration; + extends: Array; + body: ObjectTypeAnnotation; + } + + interface IntersectionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface NullableTypeAnnotation extends FlowTypeAnnotation { + typeAnnotation: TypeAnnotation; + } + + interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} + + interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} + + interface TupleTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface TypeofTypeAnnotation extends FlowTypeAnnotation { + argument: FlowTypeAnnotation; + } + + interface TypeAlias extends FlowDeclaration { + id: Identifier; + typeParameters?: TypeParameterDeclaration; + right: FlowTypeAnnotation; + } + + interface TypeAnnotation extends Node { + typeAnnotation: FlowTypeAnnotation; + } + + interface TypeCastExpression extends Expression { + expression: Expression; + typeAnnotation: TypeAnnotation; + } + + interface TypeParameterDeclaration extends Node { + params: Array; + } + + interface TypeParameterInstantiation extends Node { + params: Array; + } + + interface ObjectTypeAnnotation extends FlowTypeAnnotation { + properties: Array; + indexers: Array; + callProperties: Array; + } + + interface ObjectTypeCallProperty extends Node { + value: FunctionTypeAnnotation; + static: boolean; + } + + interface ObjectTypeIndexer extends Node { + id: Identifier; + key: FlowTypeAnnotation; + value: FlowTypeAnnotation; + static: boolean; + } + + interface ObjectTypeProperty extends Node { + key: Expression; + value: FlowTypeAnnotation; + optional: boolean; + static: boolean; + } + + interface QualifiedTypeIdentifier extends Node { + qualification: Identifier | QualifiedTypeIdentifier; + id: Identifier; + } + + interface UnionTypeAnnotation extends FlowTypeAnnotation { + types: Array; + } + + interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} +} From f6aec8b1c50cc6d1b12b1c3a8d89de227c0d3721 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 30 Jul 2015 23:49:13 -0700 Subject: [PATCH 114/419] Fix TemplateElement.value.value -> .value.raw Issue: https://github.com/estree/estree/issues/97 --- estree/estree.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/estree/estree.d.ts b/estree/estree.d.ts index be60f8dbf..76bc94279 100644 --- a/estree/estree.d.ts +++ b/estree/estree.d.ts @@ -273,7 +273,7 @@ declare module ESTree { tail: boolean; value: { cooked: string; - value: string; + raw: string; }; } From 7bcd3629afaaf7ee3092cf40c4adb54641c0d541 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 30 Jul 2015 23:51:34 -0700 Subject: [PATCH 115/419] Remove brand property as it's not used in other ESTree defs --- estree/flow.d.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/estree/flow.d.ts b/estree/flow.d.ts index 43281c6c8..7ebb56e50 100644 --- a/estree/flow.d.ts +++ b/estree/flow.d.ts @@ -4,9 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module ESTree { - interface FlowTypeAnnotation extends Node { - _flowTypeAnnotationBrand: any; - } + interface FlowTypeAnnotation extends Node {} interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} From b8b75340b71b8de2b16e0bec47c36567c12e4faa Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Thu, 30 Jul 2015 23:53:32 -0700 Subject: [PATCH 116/419] Add reference to estree.d.ts as dependency --- estree/flow.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/estree/flow.d.ts b/estree/flow.d.ts index 7ebb56e50..b34e56fb9 100644 --- a/estree/flow.d.ts +++ b/estree/flow.d.ts @@ -3,6 +3,8 @@ // Definitions by: RReverser // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module ESTree { interface FlowTypeAnnotation extends Node {} From 4889743ea8f8f06266de73e8da2430f02aed82b2 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 31 Jul 2015 09:27:34 +0200 Subject: [PATCH 117/419] new types for angular-notifications (angular plugin) --- .../angular-notifications-tests.ts | 12 +++ .../angular-notifications.d.ts | 82 +++++++++++++++++++ 2 files changed, 94 insertions(+) create mode 100644 angular-notifications/angular-notifications-tests.ts create mode 100644 angular-notifications/angular-notifications.d.ts diff --git a/angular-notifications/angular-notifications-tests.ts b/angular-notifications/angular-notifications-tests.ts new file mode 100644 index 000000000..bbfc3e90e --- /dev/null +++ b/angular-notifications/angular-notifications-tests.ts @@ -0,0 +1,12 @@ +/// + +var myapp = angular.module("myapp", ["notifications"]); + +myapp.controller("MyController", ["$scope", "notifications", + function ($scope:ng.IScope, $notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications + + var userData = {'some': 'data', 'optional': true}; + $notification.info("Something happened", "here is the content of what happened", userData); + + } +]); \ No newline at end of file diff --git a/angular-notifications/angular-notifications.d.ts b/angular-notifications/angular-notifications.d.ts new file mode 100644 index 000000000..e4f3d852c --- /dev/null +++ b/angular-notifications/angular-notifications.d.ts @@ -0,0 +1,82 @@ +// Type definitions for angular-notifications +// Project: https://github.com/DerekRies/angular-notifications +// Definitions by: Tomasz Ducin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module angular.notifications { + + interface IAnimation { + duration: number; + enabled: boolean; + } + + interface ISettings { + info: IAnimation; + warning: IAnimation; + error: IAnimation; + success: IAnimation; + progress: IAnimation; + custom: IAnimation; + details: boolean; + localStorage: boolean; + html5Mode: boolean; + html5DefaultIcon: string; + } + + interface INotification { + type: string; + image: string; + icon: string; + title: string; + content: string; + timestamp: string; + userData: string; + } + + interface INotificationFactory extends angular.IModule { + + /* ========== SETTINGS RELATED METHODS =============*/ + + disableHtml5Mode(): void; + disableType(notificationType: string): void; + enableHtml5Mode(): void; + enableType(notificationType: string): void; + getSettings(): ISettings; + toggleType(notificationType: string): void; + toggleHtml5Mode(): void; + requestHtml5ModePermissions(): boolean; + + /* ============ QUERYING RELATED METHODS ============*/ + + getAll(): Array; + getQueue(): Array; + + /* ============== NOTIFICATION METHODS ==============*/ + + info(title): INotification; + info(title, content): INotification; + info(title, content, userData): INotification; + error(title): INotification; + error(title, content): INotification; + error(title, content, userData): INotification; + success(title): INotification; + success(title, content): INotification; + success(title, content, userData): INotification; + warning(title): INotification; + warning(title, content): INotification; + warning(title, content, userData): INotification; + awesomeNotify(type, icon, title, content, userData): INotification; + notify(image, title, content, userData): INotification; + makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: string): INotification; + + /* ============ PERSISTENCE METHODS ============ */ + + save(): void; + restore(): void; + clear(): void; + } + +} + From efc6bfe2ec4d7d55236001c44d3858b4b91a9edf Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 31 Jul 2015 09:40:07 +0200 Subject: [PATCH 118/419] typo fix --- angular-notifications/angular-notifications-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angular-notifications/angular-notifications-tests.ts b/angular-notifications/angular-notifications-tests.ts index bbfc3e90e..f71a2e689 100644 --- a/angular-notifications/angular-notifications-tests.ts +++ b/angular-notifications/angular-notifications-tests.ts @@ -3,10 +3,10 @@ var myapp = angular.module("myapp", ["notifications"]); myapp.controller("MyController", ["$scope", "notifications", - function ($scope:ng.IScope, $notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications + function ($scope:ng.IScope, notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications var userData = {'some': 'data', 'optional': true}; $notification.info("Something happened", "here is the content of what happened", userData); } -]); \ No newline at end of file +]); From 2d6ebeb1a906ac8c7ee960f9c0f1d2857ab40006 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 31 Jul 2015 09:43:34 +0200 Subject: [PATCH 119/419] method parameter types --- .../angular-notifications.d.ts | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/angular-notifications/angular-notifications.d.ts b/angular-notifications/angular-notifications.d.ts index e4f3d852c..49883efb3 100644 --- a/angular-notifications/angular-notifications.d.ts +++ b/angular-notifications/angular-notifications.d.ts @@ -55,21 +55,21 @@ declare module angular.notifications { /* ============== NOTIFICATION METHODS ==============*/ - info(title): INotification; - info(title, content): INotification; - info(title, content, userData): INotification; - error(title): INotification; - error(title, content): INotification; - error(title, content, userData): INotification; - success(title): INotification; - success(title, content): INotification; - success(title, content, userData): INotification; - warning(title): INotification; - warning(title, content): INotification; - warning(title, content, userData): INotification; - awesomeNotify(type, icon, title, content, userData): INotification; - notify(image, title, content, userData): INotification; - makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: string): INotification; + info(title: string): INotification; + info(title: string, content: string): INotification; + info(title: string, content: string, userData: any): INotification; + error(title: string): INotification; + error(title: string, content: string): INotification; + error(title: string, content: string, userData: any): INotification; + success(title: string): INotification; + success(title: string, content: string): INotification; + success(title: string, content: string, userData: any): INotification; + warning(title: string): INotification; + warning(title: string, content: string): INotification; + warning(title: string, content: string, userData: any): INotification; + awesomeNotify(type: string, icon: string, title: string, content: string, userData: any): INotification; + notify(image: string, title: string, content: string, userData: any): INotification; + makeNotification(type: string, image: string, icon: string, title: string, content: string, userData: any): INotification; /* ============ PERSISTENCE METHODS ============ */ From a315ac7f88d1dc754a21cf5511818216cbae67a5 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 31 Jul 2015 09:47:12 +0200 Subject: [PATCH 120/419] typo fix --- angular-notifications/angular-notifications-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-notifications/angular-notifications-tests.ts b/angular-notifications/angular-notifications-tests.ts index f71a2e689..b6aaf99cf 100644 --- a/angular-notifications/angular-notifications-tests.ts +++ b/angular-notifications/angular-notifications-tests.ts @@ -6,7 +6,7 @@ myapp.controller("MyController", ["$scope", "notifications", function ($scope:ng.IScope, notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications var userData = {'some': 'data', 'optional': true}; - $notification.info("Something happened", "here is the content of what happened", userData); + notification.info("Something happened", "here is the content of what happened", userData); } ]); From 25dd3de39c4f6f508cf775836707df8f3c920859 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 31 Jul 2015 09:49:57 +0200 Subject: [PATCH 121/419] typo fix --- angular-notifications/angular-notifications-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angular-notifications/angular-notifications-tests.ts b/angular-notifications/angular-notifications-tests.ts index b6aaf99cf..1632ff1e7 100644 --- a/angular-notifications/angular-notifications-tests.ts +++ b/angular-notifications/angular-notifications-tests.ts @@ -6,7 +6,7 @@ myapp.controller("MyController", ["$scope", "notifications", function ($scope:ng.IScope, notifications:angular.notifications.INotificationFactory) { // <-- Inject notifications var userData = {'some': 'data', 'optional': true}; - notification.info("Something happened", "here is the content of what happened", userData); + notifications.info("Something happened", "here is the content of what happened", userData); } ]); From b8130a65bc3284dd1ac1cde827370771b35dc6ee Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 11:52:32 +0200 Subject: [PATCH 122/419] Moved pixi to pixi.js https://www.npmjs.com/package/pixi has been deprecated in favor of the official https://www.npmjs.com/package/pixi.js --- pixi/pixi-tests.ts => pixi.js/pixi.js-tests.ts | 2 +- .../pixi.js-tests.ts.tscparams | 0 pixi/pixi.d.ts => pixi.js/pixi.js.d.ts | 0 pixi/pixi.d.ts.tscparams => pixi.js/pixi.js.d.ts.tscparams | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename pixi/pixi-tests.ts => pixi.js/pixi.js-tests.ts (99%) rename pixi/pixi-tests.ts.tscparams => pixi.js/pixi.js-tests.ts.tscparams (100%) rename pixi/pixi.d.ts => pixi.js/pixi.js.d.ts (100%) rename pixi/pixi.d.ts.tscparams => pixi.js/pixi.js.d.ts.tscparams (100%) diff --git a/pixi/pixi-tests.ts b/pixi.js/pixi.js-tests.ts similarity index 99% rename from pixi/pixi-tests.ts rename to pixi.js/pixi.js-tests.ts index 6600bb121..65fb7458a 100644 --- a/pixi/pixi-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,4 +1,4 @@ -/// +/// function PixiTests() { diff --git a/pixi/pixi-tests.ts.tscparams b/pixi.js/pixi.js-tests.ts.tscparams similarity index 100% rename from pixi/pixi-tests.ts.tscparams rename to pixi.js/pixi.js-tests.ts.tscparams diff --git a/pixi/pixi.d.ts b/pixi.js/pixi.js.d.ts similarity index 100% rename from pixi/pixi.d.ts rename to pixi.js/pixi.js.d.ts diff --git a/pixi/pixi.d.ts.tscparams b/pixi.js/pixi.js.d.ts.tscparams similarity index 100% rename from pixi/pixi.d.ts.tscparams rename to pixi.js/pixi.js.d.ts.tscparams From d2fc6f24c572f34949ffc3fbd25c773d3eebf706 Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:13:35 +0200 Subject: [PATCH 123/419] Updated pixi.js definitions to v2 --- pixi.js/pixi.js-tests.ts | 34 +- pixi.js/pixi.js.d.ts | 2000 +++++++++++++++++++++++++++++++++----- 2 files changed, 1741 insertions(+), 293 deletions(-) diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 65fb7458a..309f7f66a 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -3,7 +3,7 @@ function PixiTests() { -var stage = new PIXI.Stage(0xFFFFFF, true); +var stage = new PIXI.Stage(0xFFFFFF); stage.interactive = true; @@ -70,15 +70,7 @@ var count = 0; stage.click = stage.tap = function() { - if(!container.filter) - { - container.mask = thing; - PIXI.runList(stage); - } - else - { - container.mask = null; - } + container.mask = null; } /* @@ -136,15 +128,13 @@ function animate() { /* 13 */ // create an new instance of a pixi stage -var stage = new PIXI.Stage(0xFFFFFF, true); - -stage.setInteractive(true); +var stage = new PIXI.Stage(0xFFFFFF); var sprite= PIXI.Sprite.fromImage("spinObj_02.png"); //stage.addChild(sprite); // create a renderer instance // the 5the parameter is the anti aliasing -var renderer = PIXI.autoDetectRenderer(620, 380, null, false, true); +var renderer = PIXI.autoDetectRenderer(620, 380); // set the canvas width and height to fill the screen //renderer.view.style.width = window.innerWidth + "px"; @@ -352,10 +342,7 @@ function init() var assetsToLoader = ["desyrel.fnt"]; // create a new loader - var loader = new PIXI.AssetLoader(assetsToLoader); - - // use callback - loader.onComplete = onAssetsLoaded; + var loader = new PIXI.AssetLoader(assetsToLoader, false); //begin load @@ -369,7 +356,6 @@ function init() bitmapFontText.position.x = 620 - bitmapFontText.width - 20; bitmapFontText.position.y = 20; - PIXI.runList(bitmapFontText) stage.addChild(bitmapFontText); @@ -439,7 +425,7 @@ function init() // create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e, true); +var stage = new PIXI.Stage(0x97c56e); // create a renderer instance var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); @@ -487,7 +473,7 @@ function animate33() { // create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e, true); +var stage = new PIXI.Stage(0x97c56e); // create a renderer instance var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); @@ -586,7 +572,7 @@ function animate44() { var stage = new PIXI.Stage(0x66FF99); // create a renderer instance -var renderer = PIXI.autoDetectRenderer(400, 300, null, true); +var renderer = PIXI.autoDetectRenderer(400, 300, null); // add the renderer view element to the DOM document.body.appendChild(renderer.view); @@ -630,7 +616,7 @@ function animate55() { // create an new instance of a pixi stage // the second parameter is interactivity... var interactive = true; -var stage = new PIXI.Stage(0x000000, interactive); +var stage = new PIXI.Stage(0x000000); // create a renderer instance. var renderer = PIXI.autoDetectRenderer(620, 400); @@ -765,8 +751,6 @@ stage.addChild(pixiLogo); pixiLogo.position.x = 620 - 56; pixiLogo.position.y = 400- 32; -pixiLogo.setInteractive(true); - pixiLogo.click = pixiLogo.tap = function(){ var win=window.open("https://github.com/GoodBoyDigital/pixi.js", '_blank'); diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index c86c1bd47..0452e7432 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1,448 +1,1912 @@ -// Type definitions for PIXI 1.3 +// Type definitions for PIXI 2.2.8 2015-03-24 // Project: https://github.com/GoodBoyDigital/pixi.js/ -// Definitions by: xperiments +// Definitions by: clark-stevenson // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module PIXI -{ +declare module PIXI { - /* STATICS */ - export var gl:WebGLRenderingContext; - export var BaseTextureCache: {}; - export var texturesToUpdate: BaseTexture[]; - export var texturesToDestroy: BaseTexture[]; - export var TextureCache: {}; - export var FrameCache: {}; - export var blendModes:{ NORMAL:number; SCREEN:number; }; + export var WEBGL_RENDERER: number; + export var CANVAS_RENDERER: number; + export var VERSION: string; + export enum blendModes { - /* MODULE FUNCTIONS */ - export function autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?: boolean): IPixiRenderer; - export function FilterBlock( mask:Graphics ):void; - export function MaskFilter( graphics:Graphics ):void; + NORMAL, + ADD, + MULTIPLY, + SCREEN, + OVERLAY, + DARKEN, + LIGHTEN, + COLOR_DODGE, + COLOR_BURN, + HARD_LIGHT, + SOFT_LIGHT, + DIFFERENCE, + EXCLUSION, + HUE, + SATURATION, + COLOR, + LUMINOSITY - - /* DEBUG METHODS */ - - export function runList( x ):void; - - /*INTERFACES*/ - - export interface IBasicCallback - { - ():void } - export interface IEvent - { + export enum scaleModes { + + DEFAULT, + LINEAR, + NEAREST + + } + + export var defaultRenderOptions: PixiRendererOptions; + + export var INTERACTION_REQUENCY: number; + export var AUTO_PREVENT_DEFAULT: boolean; + + export var PI_2: number; + export var RAD_TO_DEG: number; + export var DEG_TO_RAD: number; + + export var RETINA_PREFIX: string; + export var identityMatrix: Matrix; + export var glContexts: WebGLRenderingContext[]; + export var instances: any[]; + + export var BaseTextureCache: { [key: string]: BaseTexture } + export var TextureCache: { [key: string]: Texture } + + export function isPowerOfTwo(width: number, height: number): boolean; + + export function rgb2hex(rgb: number[]): string; + export function hex2rgb(hex: string): number[]; + + export function autoDetectRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; + export function autoDetectRecommendedRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; + + export function canUseNewCanvasBlendModes(): boolean; + export function getNextPowerOfTwo(number: number): number; + + export function AjaxRequest(): XMLHttpRequest; + + export function CompileFragmentShader(gl: WebGLRenderingContext, shaderSrc: string[]): any; + export function CompileProgram(gl: WebGLRenderingContext, vertexSrc: string[], fragmentSrc: string[]): any; + + + export interface IEventCallback { + (e?: IEvent): void + } + + export interface IEvent { type: string; content: any; } - export interface IHitArea - { - contains(x: number, y: number):boolean; + export interface HitArea { + contains(x: number, y: number): boolean; } - export interface IInteractionDataCallback - { - (interactionData: InteractionData):void + export interface IInteractionDataCallback { + (interactionData: InteractionData): void } - export interface IPixiRenderer - { + export interface PixiRenderer { + + autoResize: boolean; + clearBeforeRender: boolean; + height: number; + resolution: number; + transparent: boolean; + type: number; view: HTMLCanvasElement; + width: number; + + destroy(): void; render(stage: Stage): void; + resize(width: number, height: number): void; + } - export interface IBitmapTextStyle - { + export interface PixiRendererOptions { + + autoResize?: boolean; + antialias?: boolean; + clearBeforeRender?: boolean; + preserveDrawingBuffer?: boolean; + resolution?: number; + transparent?: boolean; + view?: HTMLCanvasElement; + + } + + export interface BitmapTextStyle { + font?: string; align?: string; + tint?: string; + } - export interface ITextStyle - { - font?: string; - stroke?: string; + export interface TextStyle { + + align?: string; + dropShadow?: boolean; + dropShadowColor?: string; + dropShadowAngle?: number; + dropShadowDistance?: number; fill?: string; - align?: string; + font?: string; + lineJoin?: string; + stroke?: string; strokeThickness?: number; wordWrap?: boolean; - wordWrapWidth?:number; + wordWrapWidth?: number; + } + export interface Loader { - - /* CLASES */ - - export class AssetLoader extends EventTarget - { - assetURLs: string[]; - onComplete: IBasicCallback; - onProgress: IBasicCallback; - constructor(assetURLs: string[], crossorigin?:boolean ); load(): void; + } - export class BaseTexture extends EventTarget - { + export interface MaskData { + + alpha: number; + worldTransform: number[]; + + } + + export interface RenderSession { + + context: CanvasRenderingContext2D; + maskManager: CanvasMaskManager; + scaleMode: scaleModes; + smoothProperty: string; + roundPixels: boolean; + + } + + export interface ShaderAttribute { + // TODO: Find signature of shader attributes + } + + export interface FilterBlock { + + visible: boolean; + renderable: boolean; + + } + + export class AbstractFilter { + + constructor(fragmentSrc: string[], uniforms: any); + + dirty: boolean; + padding: number; + uniforms: any; + fragmentSrc: string[]; + + apply(frameBuffer: WebGLFramebuffer): void; + syncUniforms(): void; + + } + + export class AlphaMaskFilter extends AbstractFilter { + + constructor(texture: Texture); + + map: Texture; + + onTextureLoaded(): void; + + } + + export class AsciiFilter extends AbstractFilter { + + size: number; + + } + + export class AssetLoader implements Mixin { + + assetURLs: string[]; + crossorigin: boolean; + loadersByType: { [key: string]: Loader }; + + constructor(assetURLs: string[], crossorigin?: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + + } + + export class AtlasLoader implements Mixin { + + url: string; + baseUrl: string; + crossorigin: boolean; + loaded: boolean; + + constructor(url: string, crossorigin: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class BaseTexture implements Mixin { + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): BaseTexture; + + constructor(source: HTMLImageElement, scaleMode: scaleModes); + constructor(source: HTMLCanvasElement, scaleMode: scaleModes); + height: number; + hasLoaded: boolean; + mipmap: boolean; + premultipliedAlpha: boolean; + resolution: number; + scaleMode: scaleModes; + source: HTMLImageElement; width: number; - source: string; - constructor(source: HTMLImageElement); - constructor(source: HTMLCanvasElement); - destroy():void; + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + destroy(): void; + dirty(): void; + updateSourceImage(newSrc: string): void; + unloadFromGPU(): void; - static fromImage(imageUrl: string, crossorigin?:boolean ): BaseTexture; } - export class BitmapFontLoader extends EventTarget - { - baseUrl:string; - crossorigin:boolean; - texture:Texture; - url:string; - constructor(url: string, crossorigin?: boolean); - load():void; + export class BitmapFontLoader implements Mixin { + + constructor(url: string, crossorigin: boolean); + + baseUrl: string; + crossorigin: boolean; + texture: Texture; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + } - export class BitmapText extends DisplayObjectContainer - { - width:number; - height:number; - constructor(text: string, style: IBitmapTextStyle); - setStyle(style: IBitmapTextStyle): void; + export class BitmapText extends DisplayObjectContainer { + + static fonts: any; + + constructor(text: string, style: BitmapTextStyle); + + dirty: boolean; + fontName: string; + fontSize: number; + maxWidth: number; + textWidth: number; + textHeight: number; + tint: number; + style: BitmapTextStyle; + setText(text: string): void; + setStyle(style: BitmapTextStyle): void; + } - export class CanvasRenderer implements IPixiRenderer - { + export class BlurFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + + } + + export class BlurXFilter extends AbstractFilter { + + blur: number; + + } + + export class BlurYFilter extends AbstractFilter { + + blur: number; + + } + + export class CanvasBuffer { + + constructor(width: number, height: number); + + canvas: HTMLCanvasElement; context: CanvasRenderingContext2D; height: number; - view: HTMLCanvasElement; width: number; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean); - render(stage: Stage): void; - resize(width: number, height: number):void; + + clear(): void; + resize(width: number, height: number): void; + } - export class Circle implements IHitArea - { + export class CanvasMaskManager { + + pushMask(maskData: MaskData, renderSession: RenderSession): void; + popMask(renderSession: RenderSession): void; + + } + + export class CanvasRenderer implements PixiRenderer { + + constructor(width?: number, height?: number, options?: PixiRendererOptions); + + autoResize: boolean; + clearBeforeRender: boolean; + context: CanvasRenderingContext2D; + count: number; + height: number; + maskManager: CanvasMaskManager; + refresh: boolean; + renderSession: RenderSession; + resolution: number; + transparent: boolean; + type: number; + view: HTMLCanvasElement; + width: number; + + destroy(removeView?: boolean): void; + render(stage: Stage): void; + resize(width: number, height: number): void; + + } + + export class CanvasTinter { + + static getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; + static tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static roundColor(color: number): void; + + static cacheStepsPerColorChannel: number; + static convertTintToImage: boolean; + static canUseMultiply: boolean; + static tintMethod: any; + + } + + export class Circle implements HitArea { + + constructor(x: number, y: number, radius: number); + x: number; y: number; radius: number; - constructor(x: number, y: number, radius: number); + clone(): Circle; - contains(x: number, y: number):boolean; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + } - // TODO what is renderGroup - export class CustomRenderable extends DisplayObject - { - constructor(); - renderCanvas(renderer: CanvasRenderer): void; - initWebGL(renderer: WebGLRenderer): void; - renderWebGL(renderGroup: any, projectionMatrix: any): void; + export class ColorMatrixFilter extends AbstractFilter { + + matrix: Matrix; + } - export class DisplayObject - { - x: number; - y: number; + export class ColorStepFilter extends AbstractFilter { + + step: number; + + } + + export class ConvolutionFilter extends AbstractFilter { + + constructor(matrix: number[], width: number, height: number); + + matrix: Matrix; + width: number; + height: number; + + } + + export class CrossHatchFilter extends AbstractFilter { + + blur: number; + + } + + export class DisplacementFilter extends AbstractFilter { + + constructor(texture: Texture); + + map: Texture; + offset: Point; + scale: Point; + + } + + export class DotScreenFilter extends AbstractFilter { + + angle: number; + scale: Point; + + } + + export class DisplayObject { + alpha: number; buttonMode: boolean; - filter:boolean; - hitArea: IHitArea; + cacheAsBitmap: boolean; + defaultCursor: string; + filterArea: Rectangle; + filters: AbstractFilter[]; + hitArea: HitArea; + interactive: boolean; + mask: Graphics; parent: DisplayObjectContainer; pivot: Point; position: Point; - rotation: number; renderable: boolean; + rotation: number; scale: Point; stage: Stage; visible: boolean; worldAlpha: number; - constructor(); - static autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean): IPixiRenderer; - click: IInteractionDataCallback; - mousedown: IInteractionDataCallback; - mouseout: IInteractionDataCallback; - mouseover: IInteractionDataCallback; - mouseup: IInteractionDataCallback; - mouseupoutside: IInteractionDataCallback; - mousemove: IInteractionDataCallback; - tap: IInteractionDataCallback; - touchend: IInteractionDataCallback; - touchendoutside: IInteractionDataCallback; - touchstart: IInteractionDataCallback; - touchmove: IInteractionDataCallback; + worldVisible: boolean; + x: number; + y: number; - //deprecated - setInteractive(interactive: boolean): void; + click(e: InteractionData): void; + displayObjectUpdateTransform(): void; + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + generateTexture(resolution: number, scaleMode: scaleModes, renderer: PixiRenderer): RenderTexture; + mousedown(e: InteractionData): void; + mouseout(e: InteractionData): void; + mouseover(e: InteractionData): void; + mouseup(e: InteractionData): void; + mousemove(e: InteractionData): void; + mouseupoutside(e: InteractionData): void; + rightclick(e: InteractionData): void; + rightdown(e: InteractionData): void; + rightup(e: InteractionData): void; + rightupoutside(e: InteractionData): void; + setStageReference(stage: Stage): void; + tap(e: InteractionData): void; + toGlobal(position: Point): Point; + toLocal(position: Point, from: DisplayObject): Point; + touchend(e: InteractionData): void; + touchendoutside(e: InteractionData): void; + touchstart(e: InteractionData): void; + touchmove(e: InteractionData): void; + updateTransform(): void; - // getters setters - interactive:boolean; - mask:Graphics; } - export class DisplayObjectContainer extends DisplayObject - { + export class DisplayObjectContainer extends DisplayObject { + + constructor(); + children: DisplayObject[]; - constructor(); + height: number; + width: number; - addChild(child: DisplayObject): void; - addChildAt(child: DisplayObject, index: number): void; - getChildAt(index:number):DisplayObject; - removeChild(child: DisplayObject): void; + addChild(child: DisplayObject): DisplayObject; + addChildAt(child: DisplayObject, index: number): DisplayObject; + getBounds(): Rectangle; + getChildAt(index: number): DisplayObject; + getChildIndex(child: DisplayObject): number; + getLocalBounds(): Rectangle; + removeChild(child: DisplayObject): DisplayObject; + removeChildAt(index: number): DisplayObject; + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; + removeStageReference(): void; + setChildIndex(child: DisplayObject, index: number): void; swapChildren(child: DisplayObject, child2: DisplayObject): void; + } - export class Ellipse implements IHitArea - { + export class Ellipse implements HitArea { + + constructor(x: number, y: number, width: number, height: number); + x: number; y: number; width: number; height: number; - constructor(x: number, y: number, width: number, height: number); clone(): Ellipse; - contains(x: number, y: number):boolean; - getBounds():Rectangle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + } - export class EventTarget - { - addEventListener(type: string, listener: (event: IEvent) => void ); - removeEventListener(type: string, listener: (event: IEvent) => void ); - dispatchEvent(event: IEvent); + export class Event { + + constructor(target: any, name: string, data: any); + + target: any; + type: string; + data: any; + timeStamp: number; + + stopPropagation(): void; + preventDefault(): void; + stopImmediatePropagation(): void; + } - export class Graphics extends DisplayObjectContainer - { - lineWidth:number; - lineColor:string; - constructor(); + export class EventTarget { + + static mixin(obj: any): void; + + } + + export class FilterTexture { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: scaleModes); + + fragmentSrc: string[]; + frameBuffer: WebGLFramebuffer; + gl: WebGLRenderingContext; + program: WebGLProgram; + scaleMode: number; + texture: WebGLTexture; - beginFill(color?: number, alpha?: number): void; clear(): void; - drawCircle(x: number, y: number, radius: number): void; - drawElipse(x: number, y: number, width: number, height: number): void; - drawRect(x: number, y: number, width: number, height: number): void; - endFill(): void; - lineStyle(lineWidth?: number, color?: number, alpha?: number ): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; + resize(width: number, height: number): void; + destroy(): void; - static POLY:number; - static RECT:number; - static CIRC:number; - static ELIP:number; } - export class ImageLoader extends EventTarget - { - texture:Texture; + export class GraphicsData { + + constructor(lineWidth?: number, lineColor?: number, lineAlpha?: number, fillColor?: number, fillAlpha?: number, fill?: boolean, shape?: any); + + lineWidth: number; + lineColor: number; + lineAlpha: number; + fillColor: number; + fillAlpha: number; + fill: boolean; + shape: any; + type: number; + + } + + export class Graphics extends DisplayObjectContainer { + + static POLY: number; + static RECT: number; + static CIRC: number; + static ELIP: number; + static RREC: number; + + blendMode: number; + boundsPadding: number; + fillAlpha: number; + isMask: boolean; + lineWidth: number; + lineColor: number; + tint: number; + worldAlpha: number; + + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + beginFill(color?: number, alpha?: number): Graphics; + bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; + clear(): Graphics; + destroyCachedSprite(): void; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(...path: any[]): Graphics; + drawRect(x: number, y: number, width: number, height: number): Graphics; + drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; + drawShape(shape: Circle): GraphicsData; + drawShape(shape: Rectangle): GraphicsData; + drawShape(shape: Ellipse): GraphicsData; + drawShape(shape: Polygon): GraphicsData; + endFill(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + lineTo(x: number, y: number): Graphics; + moveTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + + } + + export class GrayFilter extends AbstractFilter { + + gray: number; + + } + + export class ImageLoader implements Mixin { + constructor(url: string, crossorigin?: boolean); + + texture: Texture; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + load(): void; + loadFramedSpriteSheet(frameWidth: number, frameHeight: number, textureName: string): void; + } - /* TODO determine type of originalEvent*/ - export class InteractionData - { + export class InteractionData { + global: Point; target: Sprite; - constructor(); - originalEvent:any; - getLocalPosition(displayObject: DisplayObject): Point; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + } - export class InteractionManager - { + export class InteractionManager { + + currentCursorStyle: string; + last: number; mouse: InteractionData; + mouseOut: boolean; + mouseoverEnabled: boolean; + onMouseMove: Function; + onMouseDown: Function; + onMouseOut: Function; + onMouseUp: Function; + onTouchStart: Function; + onTouchEnd: Function; + onTouchMove: Function; + pool: InteractionData[]; + resolution: number; stage: Stage; - touchs:{ [id:string]:InteractionData }; + touches: { [id: string]: InteractionData }; + constructor(stage: Stage); } - export class JsonLoader extends EventTarget - { - url:string; - crossorigin: boolean; - baseUrl:string; - loaded:boolean; - constructor(url: string, crossorigin?: boolean); - load(): void; + export class InvertFilter extends AbstractFilter { + + invert: number; + } - export class MovieClip extends Sprite - { + export class JsonLoader implements Mixin { + + constructor(url: string, crossorigin?: boolean); + + baseUrl: string; + crossorigin: boolean; + loaded: boolean; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class Matrix { + + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; + + append(matrix: Matrix): Matrix; + apply(pos: Point, newPos: Point): Point; + applyInverse(pos: Point, newPos: Point): Point; + determineMatrixArrayType(): number[]; + identity(): Matrix; + rotate(angle: number): Matrix; + fromArray(array: number[]): void; + translate(x: number, y: number): Matrix; + toArray(transpose: boolean): number[]; + scale(x: number, y: number): Matrix; + + } + + export interface Mixin { + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + } + + export class MovieClip extends Sprite { + + static fromFrames(frames: string[]): MovieClip; + static fromImages(images: HTMLImageElement[]): HTMLImageElement; + + constructor(textures: Texture[]); + animationSpeed: number; - currentFrame:number; + currentFrame: number; loop: boolean; playing: boolean; textures: Texture[]; - constructor(textures: Texture[]); - onComplete:IBasicCallback; + totalFrames: number; + gotoAndPlay(frameNumber: number): void; gotoAndStop(frameNumber: number): void; + onComplete(): void; play(): void; stop(): void; + } - export class Point - { + export class NoiseFilter extends AbstractFilter { + + noise: number; + + } + + export class NormalMapFilter extends AbstractFilter { + + map: Texture; + offset: Point; + scale: Point; + + } + + export class PixelateFilter extends AbstractFilter { + + size: number; + + } + + export interface IPixiShader { + + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class PixiShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + + attributes: ShaderAttribute[]; + defaultVertexSrc: string[]; + dirty: boolean; + firstRun: boolean; + textureCount: number; + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + initSampler2D(): void; + initUniforms(): void; + syncUniforms(): void; + + destroy(): void; + init(): void; + + } + + export class PixiFastShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + + textureCount: number; + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class PrimitiveShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class ComplexPrimitiveShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class StripShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class Point { + + constructor(x?: number, y?: number); + x: number; y: number; - constructor(x: number, y: number); + clone(): Point; + set(x: number, y: number): void; + } - export class Polygon implements IHitArea - { - points: Point[]; + export class Polygon implements HitArea { constructor(points: Point[]); constructor(points: number[]); constructor(...points: Point[]); constructor(...points: number[]); + points: any[]; //number[] Point[] + clone(): Polygon; - contains( x:number, y:number ):boolean; + contains(x: number, y: number): boolean; + } - export class Rectangle implements IHitArea - { + export class Rectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number); + x: number; y: number; width: number; height: number; - constructor(x: number, y: number, width: number, height: number); + clone(): Rectangle; - contains(x: number, y: number):boolean; + contains(x: number, y: number): boolean; + } - export class RenderTexture extends Texture - { - constructor(width: number, height: number); - resize(width: number, height: number): void; + export class RGBSplitFilter extends AbstractFilter { + + red: Point; + green: Point; + blue: Point; + } - export class Sprite extends DisplayObjectContainer - { - anchor: Point; - blendMode: number; - texture: Texture; + export class Rope extends Strip { - //getters setters - height: number; + points: Point[]; + vertices: number[]; + + constructor(texture: Texture, points: Point[]); + + refresh(): void; + setTexture(texture: Texture): void; + + } + + export class RoundedRectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); + + x: number; + y: number; width: number; + height: number; + radius: number; + + clone(): RoundedRectangle; + contains(x: number, y: number): boolean; + + } + + export class SepiaFilter extends AbstractFilter { + + sepia: number; + + } + + export class SmartBlurFilter extends AbstractFilter { + + blur: number; + + } + + export class SpineLoader implements Mixin { + + url: string; + crossorigin: boolean; + loaded: boolean; + + constructor(url: string, crossOrigin: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class SpineTextureLoader { + + constructor(basePath: string, crossorigin: boolean); + + load(page: AtlasPage, file: string): void; + unload(texture: BaseTexture): void; + + } + + export class Sprite extends DisplayObjectContainer { + + static fromFrame(frameId: string): Sprite; + static fromImage(url: string, crossorigin?: boolean, scaleMode?: scaleModes): Sprite; constructor(texture: Texture); - static fromFrame(frameId: string): Sprite; - static fromImage(url: string): Sprite; + anchor: Point; + blendMode: blendModes; + shader: IPixiShader; + texture: Texture; + tint: number; + setTexture(texture: Texture): void; + } - /* TODO determine type of frames */ - export class SpriteSheetLoader extends EventTarget - { - url:string; - crossorigin:boolean; - baseUrl:string; - texture:Texture; - frames:Object; + export class SpriteBatch extends DisplayObjectContainer { + + constructor(texture?: Texture); + + ready: boolean; + textureThing: Texture; + + initWebGL(gl: WebGLRenderingContext): void; + + } + + export class SpriteSheetLoader implements Mixin { + constructor(url: string, crossorigin?: boolean); - load(); + + baseUrl: string; + crossorigin: boolean; + frames: any; + texture: Texture; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + } - export class Stage extends DisplayObjectContainer - { - interactive:boolean; - interactionManager:InteractionManager; - constructor(backgroundColor: number, interactive?: boolean); + export class Stage extends DisplayObjectContainer { + + constructor(backgroundColor: number); + + interactionManager: InteractionManager; + getMousePosition(): Point; setBackgroundColor(backgroundColor: number): void; + setInteractionDelegate(domElement: HTMLElement): void; + } - export class Text extends Sprite - { - constructor(text: string, style: ITextStyle); - destroy(destroyTexture:boolean):void; + export class Strip extends DisplayObjectContainer { + + static DrawModes: { + + TRIANGLE_STRIP: number; + TRIANGLES: number; + + } + + constructor(texture: Texture); + + blendMode: number; + colors: number[]; + dirty: boolean; + indices: number[]; + canvasPadding: number; + texture: Texture; + uvs: number[]; + vertices: number[]; + + getBounds(matrix?: Matrix): Rectangle; + + } + + export class Text extends Sprite { + + constructor(text: string, style?: TextStyle); + + static fontPropertiesCanvas: any; + static fontPropertiesContext: any; + static fontPropertiesCache: any; + + context: CanvasRenderingContext2D; + resolution: number; + + destroy(destroyTexture: boolean): void; + setStyle(style: TextStyle): void; setText(text: string): void; - setStyle(style: ITextStyle): void; + } - export class Texture extends EventTarget - { + export class Texture implements Mixin { + + static emptyTexture: Texture; + + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): Texture; + static fromFrame(frameId: string): Texture; + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle); + baseTexture: BaseTexture; + crop: Rectangle; frame: Rectangle; - trim:Point; - render( displayObject:DisplayObject, position:Point, clear:boolean ):void; - constructor(baseTexture: BaseTexture, frame?: Rectangle); - destroy(destroyBase:boolean):void; + height: number; + noFrame: boolean; + requiresUpdate: boolean; + trim: Point; + width: number; + scope: any; + valid: boolean; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + destroy(destroyBase: boolean): void; setFrame(frame: Rectangle): void; - static addTextureToCache(texture: Texture, id: string): void; - static fromCanvas(canvas: HTMLCanvasElement): Texture; - static fromFrame(frameId: string): Texture; - static fromImage(imageUrl: string, crossorigin?: boolean): Texture; - static removeTextureFromCache(id: any): Texture; } - export class TilingSprite extends DisplayObjectContainer - { - width:number; - height:number; - texture:Texture; + export class TilingSprite extends Sprite { + + constructor(texture: Texture, width: number, height: number); + + blendMode: number; + texture: Texture; + tint: number; tilePosition: Point; tileScale: Point; - constructor(texture: Texture, width: number, height: number); - setTexture( texture: Texture ):void; + tileScaleOffset: Point; + + destroy(): void; + generateTilingTexture(forcePowerOfTwo?: boolean): void; + setTexture(texture: Texture): void; + } - export class WebGLBatch - { - constructor(webGLContext: WebGLRenderingContext); - clean():void; - restoreLostContext(gl:WebGLRenderingContext); - init(sprite: Sprite): void; - insertAfter(sprite: Sprite, previousSprite: Sprite): void; - insertBefore(sprite: Sprite, nextSprite: Sprite): void; - growBatch(): void; - merge(batch: WebGLBatch): void; - refresh(): void; - remove(sprite: Sprite): void; - render(): void; - split(sprite: Sprite): WebGLBatch; - update(): void; + export class TiltShiftFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + } - /* Determine type of Object */ - export class WebGLRenderGroup - { - render(projection:Object):void; + export class TiltShiftXFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + } - export class WebGLRenderer implements IPixiRenderer - { + export class TiltShiftYFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + + } + + export class TwistFilter extends AbstractFilter { + + angle: number; + offset: Point; + radius: number; + + } + + export class VideoTexture extends BaseTexture { + + static baseTextureFromVideo(video: HTMLVideoElement, scaleMode: number): BaseTexture; + static textureFromVideo(video: HTMLVideoElement, scaleMode: number): Texture; + static fromUrl(videoSrc: string, scaleMode: number): Texture; + + autoUpdate: boolean; + + destroy(): void; + updateBound(): void; + onPlayStart(): void; + onPlayStop(): void; + onCanPlay(): void; + + } + + export class WebGLBlendModeManager { + + currentBlendMode: number; + + destroy(): void; + setBlendMode(blendMode: number): boolean; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLFastSpriteBatch { + + constructor(gl: CanvasRenderingContext2D); + + currentBatchSize: number; + currentBaseTexture: BaseTexture; + currentBlendMode: number; + renderSession: RenderSession; + drawing: boolean; + indexBuffer: any; + indices: number[]; + lastIndexCount: number; + matrix: Matrix; + maxSize: number; + shader: IPixiShader; + size: number; + vertexBuffer: any; + vertices: number[]; + vertSize: number; + + end(): void; + begin(spriteBatch: SpriteBatch, renderSession: RenderSession): void; + destroy(removeView?: boolean): void; + flush(): void; + render(spriteBatch: SpriteBatch): void; + renderSprite(sprite: Sprite): void; + setContext(gl: WebGLRenderingContext): void; + start(): void; + stop(): void; + + } + + export class WebGLFilterManager { + + filterStack: AbstractFilter[]; + transparent: boolean; + offsetX: number; + offsetY: number; + + applyFilterPass(filter: AbstractFilter, filterArea: Texture, width: number, height: number): void; + begin(renderSession: RenderSession, buffer: ArrayBuffer): void; + destroy(): void; + initShaderBuffers(): void; + popFilter(): void; + pushFilter(filterBlock: FilterBlock): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLGraphics { + + static graphicsDataPool: any[]; + + static renderGraphics(graphics: Graphics, renderRession: RenderSession): void; + static updateGraphics(graphics: Graphics, gl: WebGLRenderingContext): void; + static switchMode(webGL: WebGLRenderingContext, type: number): any; //WebGLData + static buildRectangle(graphicsData: GraphicsData, webGLData: any): void; + static buildRoundedRectangle(graphicsData: GraphicsData, webGLData: any): void; + static quadraticBezierCurve(fromX: number, fromY: number, cpX: number, cpY: number, toX: number, toY: number): number[]; + static buildCircle(graphicsData: GraphicsData, webGLData: any): void; + static buildLine(graphicsData: GraphicsData, webGLData: any): void; + static buildComplexPoly(graphicsData: GraphicsData, webGLData: any): void; + static buildPoly(graphicsData: GraphicsData, webGLData: any): boolean; + + reset(): void; + upload(): void; + + } + + export class WebGLGraphicsData { + + constructor(gl: WebGLRenderingContext); + + gl: WebGLRenderingContext; + glPoints: any[]; + color: number[]; + points: any[]; + indices: any[]; + buffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + mode: number; + alpha: number; + dirty: boolean; + + reset(): void; + upload(): void; + + } + + export class WebGLMaskManager { + + destroy(): void; + popMask(renderSession: RenderSession): void; + pushMask(maskData: any[], renderSession: RenderSession): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLRenderer implements PixiRenderer { + + static createWebGLTexture(texture: Texture, gl: WebGLRenderingContext): void; + + constructor(width?: number, height?: number, options?: PixiRendererOptions); + + autoResize: boolean; + clearBeforeRender: boolean; + contextLost: boolean; + contextLostBound: Function; + contextRestoreLost: boolean; + contextRestoredBound: Function; + height: number; + gl: WebGLRenderingContext; + offset: Point; + preserveDrawingBuffer: boolean; + projection: Point; + resolution: number; + renderSession: RenderSession; + shaderManager: WebGLShaderManager; + spriteBatch: WebGLSpriteBatch; + maskManager: WebGLMaskManager; + filterManager: WebGLFilterManager; + stencilManager: WebGLStencilManager; + blendModeManager: WebGLBlendModeManager; + transparent: boolean; + type: number; view: HTMLCanvasElement; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?:boolean ); + width: number; + + destroy(): void; + initContext(): void; + mapBlendModes(): void; render(stage: Stage): void; + renderDisplayObject(displayObject: DisplayObject, projection: Point, buffer: WebGLBuffer): void; resize(width: number, height: number): void; + updateTexture(texture: Texture): void; + + } + + export class WebGLShaderManager { + + maxAttibs: number; + attribState: any[]; + stack: any[]; + tempAttribState: any[]; + + destroy(): void; + setAttribs(attribs: ShaderAttribute[]): void; + setContext(gl: WebGLRenderingContext): void; + setShader(shader: IPixiShader): boolean; + + } + + export class WebGLStencilManager { + + stencilStack: any[]; + reverse: boolean; + count: number; + + bindGraphics(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + destroy(): void; + popStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + pushStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLSpriteBatch { + + blendModes: number[]; + colors: number[]; + currentBatchSize: number; + currentBaseTexture: Texture; + defaultShader: AbstractFilter; + dirty: boolean; + drawing: boolean; + indices: number[]; + lastIndexCount: number; + positions: number[]; + textures: Texture[]; + shaders: IPixiShader[]; + size: number; + sprites: any[]; //todo Sprite[]? + vertices: number[]; + vertSize: number; + + begin(renderSession: RenderSession): void; + destroy(): void; + end(): void; + flush(shader?: IPixiShader): void; + render(sprite: Sprite): void; + renderBatch(texture: Texture, size: number, startIndex: number): void; + renderTilingSprite(sprite: TilingSprite): void; + setBlendMode(blendMode: blendModes): void; + setContext(gl: WebGLRenderingContext): void; + start(): void; + stop(): void; + + } + + export class RenderTexture extends Texture { + + constructor(width?: number, height?: number, renderer?: PixiRenderer, scaleMode?: scaleModes, resolution?: number); + + frame: Rectangle; + baseTexture: BaseTexture; + renderer: PixiRenderer; + resolution: number; + valid: boolean; + + clear(): void; + getBase64(): string; + getCanvas(): HTMLCanvasElement; + getImage(): HTMLImageElement; + resize(width: number, height: number, updateBase: boolean): void; + render(displayObject: DisplayObject, position?: Point, clear?: boolean): void; + + } + + //SPINE + + export class BoneData { + + constructor(name: string, parent?: any); + + name: string; + parent: any; + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + + } + + export class SlotData { + + constructor(name: string, boneData: BoneData); + + name: string; + boneData: BoneData; + r: number; + g: number; + b: number; + a: number; + attachmentName: string; + + } + + export class Bone { + + constructor(boneData: BoneData, parent?: any); + + data: BoneData; + parent: any; + yDown: boolean; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + worldRotation: number; + worldScaleX: number; + worldScaleY: number; + + updateWorldTransform(flipX: boolean, flip: boolean): void; + setToSetupPose(): void; + + } + + export class Slot { + + constructor(slotData: SlotData, skeleton: Skeleton, bone: Bone); + + data: SlotData; + skeleton: Skeleton; + bone: Bone; + r: number; + g: number; + b: number; + a: number; + attachment: RegionAttachment; + setAttachment(attachment: RegionAttachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + + } + + export class Skin { + + constructor(name: string); + + name: string; + attachments: any; + + addAttachment(slotIndex: number, name: string, attachment: RegionAttachment): void; + getAttachment(slotIndex: number, name: string): void; + + } + + export class Animation { + + constructor(name: string, timelines: ISpineTimeline[], duration: number); + + name: string; + timelines: ISpineTimeline[]; + duration: number; + apply(skeleton: Skeleton, time: number, loop: boolean): void; + min(skeleton: Skeleton, time: number, loop: boolean, alpha: number): void; + + } + + export class Curves { + + constructor(frameCount: number); + + curves: number[]; + + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + + } + + export interface ISpineTimeline { + + curves: Curves; + frames: number[]; + + getFrameCount(): number; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class RotateTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, angle: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class TranslateTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class ScaleTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class ColorTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class AttachmentTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + attachmentNames: string[]; + slotIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class SkeletonData { + + bones: Bone[]; + slots: Slot[]; + skins: Skin[]; + animations: Animation[]; + defaultSkin: Skin; + + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findAnimation(animationName: string): Animation; + + } + + export class Skeleton { + + constructor(skeletonData: SkeletonData); + + data: SkeletonData; + bones: Bone[]; + slots: Slot[]; + drawOrder: any[]; + x: number; + y: number; + skin: Skin; + r: number; + g: number; + b: number; + a: number; + time: number; + flipX: boolean; + flipY: boolean; + + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + fineBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): void; + setSkin(newSkin: Skin): void; + getAttachmentBySlotName(slotName: string, attachmentName: string): RegionAttachment; + getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): RegionAttachment; + setAttachment(slotName: string, attachmentName: string): void; + update(data: number): void; + + } + + export class RegionAttachment { + + offset: number[]; + uvs: number[]; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + width: number; + height: number; + rendererObject: any; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + + setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; + updateOffset(): void; + computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; + + } + + export class AnimationStateData { + + constructor(skeletonData: SkeletonData); + + skeletonData: SkeletonData; + animationToMixTime: any; + defaultMix: number; + + setMixByName(fromName: string, toName: string, duration: number): void; + setMix(from: string, to: string): number; + + } + + export class AnimationState { + + constructor(stateData: any); + + animationSpeed: number; + current: any; + previous: any; + currentTime: number; + previousTime: number; + currentLoop: boolean; + previousLoop: boolean; + mixTime: number; + mixDuration: number; + queue: Animation[]; + + update(delta: number): void; + apply(skeleton: any): void; + clearAnimation(): void; + setAnimation(animation: any, loop: boolean): void; + setAnimationByName(animationName: string, loop: boolean): void; + addAnimationByName(animationName: string, loop: boolean, delay: number): void; + addAnimation(animation: any, loop: boolean, delay: number): void; + isComplete(): number; + + } + + export class SkeletonJson { + + constructor(attachmentLoader: AtlasAttachmentLoader); + + attachmentLoader: AtlasAttachmentLoader; + scale: number; + + readSkeletonData(root: any): SkeletonData; + readAttachment(skin: Skin, name: string, map: any): RegionAttachment; + readAnimation(name: string, map: any, skeletonData: SkeletonData): void; + readCurve(timeline: ISpineTimeline, frameIndex: number, valueMap: any): void; + toColor(hexString: string, colorIndex: number): number; + + } + + export class Atlas { + + static FORMAT: { + + alpha: number; + intensity: number; + luminanceAlpha: number; + rgb565: number; + rgba4444: number; + rgb888: number; + rgba8888: number; + + } + + static TextureFilter: { + + nearest: number; + linear: number; + mipMap: number; + mipMapNearestNearest: number; + mipMapLinearNearest: number; + mipMapNearestLinear: number; + mipMapLinearLinear: number; + + } + + static textureWrap: { + + mirroredRepeat: number; + clampToEdge: number; + repeat: number; + + } + + constructor(atlasText: string, textureLoader: AtlasLoader); + + textureLoader: AtlasLoader; + pages: AtlasPage[]; + regions: AtlasRegion[]; + + findRegion(name: string): AtlasRegion; + dispose(): void; + updateUVs(page: AtlasPage): void; + + } + + export class AtlasPage { + + name: string; + format: number; + minFilter: number; + magFilter: number; + uWrap: number; + vWrap: number; + rendererObject: any; + width: number; + height: number; + + } + + export class AtlasRegion { + + page: AtlasPage; + name: string; + x: number; + y: number; + width: number; + height: number; + u: number; + v: number; + u2: number; + v2: number; + offsetX: number; + offsetY: number; + originalWidth: number; + originalHeight: number; + index: number; + rotate: boolean; + splits: any[]; + pads: any[]; + + } + + export class AtlasReader { + + constructor(text: string); + + lines: string[]; + index: number; + + trim(value: string): string; + readLine(): string; + readValue(): string; + readTuple(tuple: number): number; + + } + + export class AtlasAttachmentLoader { + + constructor(atlas: Atlas); + + atlas: Atlas; + + newAttachment(skin: Skin, type: number, name: string): RegionAttachment; + + } + + export class Spine extends DisplayObjectContainer { + + constructor(url: string); + + autoUpdate: boolean; + spineData: any; + skeleton: Skeleton; + stateData: AnimationStateData; + state: AnimationState; + slotContainers: DisplayObjectContainer[]; + + createSprite(slot: Slot, descriptor: { name: string }): Sprite[]; + update(dt: number): void; + } } -declare function requestAnimFrame( animate: PIXI.IBasicCallback ); - - -declare module PIXI.PolyK -{ - export function Triangulate( p:number[]):number[]; -} - - +declare function requestAnimFrame(callback: Function): void; +declare module PIXI.PolyK { + export function Triangulate(p: number[]): number[]; +} \ No newline at end of file From d5557c6a5a666883277e0df2d2e3dfacefd5b39c Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:34:26 +0200 Subject: [PATCH 124/419] Updated pixi.js definitions to v3 --- pixi.js/pixi.js-tests.ts | 3709 ++++++++++++++++++++-------- pixi.js/pixi.js-tests.ts.tscparams | 1 - pixi.js/pixi.js.d.ts | 3196 +++++++++++------------- pixi.js/pixi.js.d.ts.tscparams | 1 - 4 files changed, 4149 insertions(+), 2758 deletions(-) delete mode 100644 pixi.js/pixi.js-tests.ts.tscparams delete mode 100644 pixi.js/pixi.js.d.ts.tscparams diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 309f7f66a..6a462fc2e 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,1177 +1,2762 @@ -/// +/// -function PixiTests() -{ +module basics { -var stage = new PIXI.Stage(0xFFFFFF); + export class Basics { -stage.interactive = true; + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; -var bg = PIXI.Sprite.fromImage("BGrotate.jpg"); -bg.anchor.x = 0.5; -bg.anchor.y = 0.5; + private stage: PIXI.Container; -bg.position.x = 620/2; -bg.position.y = 380/2; + private bunny: PIXI.Sprite; -stage.addChild(bg); + constructor() { -var container = new PIXI.DisplayObjectContainer(); -container.position.x = 620/2; -container.position.y = 380/2; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); -var bgFront = PIXI.Sprite.fromImage("SceneRotate.jpg"); -bgFront.anchor.x = 0.5; -bgFront.anchor.y = 0.5; + // create the root of the scene graph + this.stage = new PIXI.Container(); -container.addChild(bgFront); + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); -var light2 = PIXI.Sprite.fromImage("LightRotate2.png"); -light2.anchor.x = 0.5; -light2.anchor.y = 0.5; -container.addChild(light2); + // create a new Sprite using the texture + this.bunny = new PIXI.Sprite(texture); -var light1 = PIXI.Sprite.fromImage("LightRotate1.png"); -light1.anchor.x = 0.5; -light1.anchor.y = 0.5; -container.addChild(light1); + // center the sprite's anchor point + this.bunny.anchor.x = 0.5; + this.bunny.anchor.y = 0.5; -var panda = PIXI.Sprite.fromImage("panda.png"); -panda.anchor.x = 0.5; -panda.anchor.y = 0.5; + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; -container.addChild(panda); + //add it to the stage + this.stage.addChild(this.bunny); -stage.addChild(container); + this.animate(); -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(620, 380); + } -renderer.view.style.position = "absolute" -renderer.view.style.marginLeft = "-310px"; -renderer.view.style.marginTop = "-190px"; -renderer.view.style.top = "50%"; -renderer.view.style.left = "50%"; -renderer.view.style.display = "block"; + private animate = (): void => { -// add render view to DOM -document.body.appendChild(renderer.view); + requestAnimationFrame(this.animate); -// lets create moving shape -var thing = new PIXI.Graphics(); -stage.addChild(thing); -thing.position.x = 620/2; -thing.position.y = 380/2; -thing.lineStyle(0); + this.bunny.rotation += 0.1; -container.mask = thing; + this.renderer.render(this.stage); -var count = 0; + } -stage.click = stage.tap = function() -{ - container.mask = null; -} - -/* - * Add a pixi Logo! - */ -var logo = PIXI.Sprite.fromImage("../../logo_small.png") -stage.addChild(logo); - -logo.anchor.x = 1; -logo.position.x = 620 -logo.scale.x = logo.scale.y = 0.5; -logo.position.y = 320 -logo.interactive = true; -logo.buttonMode = true; - -logo.click = logo.tap = function() -{ - window.open("https://github.com/GoodBoyDigital/pixi.js", "_blank") -} - -var help = new PIXI.Text("Click to turn masking on / off.", {font:"bold 12pt Arial", fill:"white"}); -help.position.y = 350; -help.position.x = 10; -stage.addChild(help); - -requestAnimFrame(animate); - -function animate() { - - bg.rotation += 0.01; - bgFront.rotation -= 0.01; - - light1.rotation += 0.02; - light2.rotation += 0.01; - - panda.scale.x = 1 + Math.sin(count) * 0.04; - panda.scale.y = 1 + Math.cos(count) * 0.04; - - count += 0.1; - - thing.clear(); - thing.lineStyle(5, 0x16f1ff, 1); - thing.beginFill(0x8bc5ff, 0.4); - thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count)* 20); - thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count)* 20); - thing.lineTo(-120 + Math.cos(count)* 20, 100 + Math.sin(count)* 20); - thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.rotation = count * 0.1; - - renderer.render(stage); - requestAnimFrame( animate ); -} - -/* 13 */ - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0xFFFFFF); - -var sprite= PIXI.Sprite.fromImage("spinObj_02.png"); -//stage.addChild(sprite); -// create a renderer instance -// the 5the parameter is the anti aliasing -var renderer = PIXI.autoDetectRenderer(620, 380); - -// set the canvas width and height to fill the screen -//renderer.view.style.width = window.innerWidth + "px"; -//renderer.view.style.height = window.innerHeight + "px"; -renderer.view.style.display = "block"; - -// add render view to DOM -document.body.appendChild(renderer.view); - -var graphics = new PIXI.Graphics(); - - -// set a fill and line style -graphics.beginFill(0xFF3300); -graphics.lineStyle(10, 0xffd900, 1); - -// draw a shape -graphics.moveTo(50,50); -graphics.lineTo(250, 50); -graphics.lineTo(100, 100); -graphics.lineTo(250, 220); -graphics.lineTo(50, 220); -graphics.lineTo(50, 50); -graphics.endFill(); - -// set a fill and line style again -graphics.lineStyle(10, 0xFF0000, 0.8); -graphics.beginFill(0xFF700B, 1); - -// draw a second shape -graphics.moveTo(210,300); -graphics.lineTo(450,320); -graphics.lineTo(570,350); -graphics.lineTo(580,20); -graphics.lineTo(330,120); -graphics.lineTo(410,200); -graphics.lineTo(210,300); -graphics.endFill(); - -// draw a rectangel -graphics.lineStyle(2, 0x0000FF, 1); -graphics.drawRect(50, 250, 100, 100); - -// draw a circle -graphics.lineStyle(0); -graphics.beginFill(0xFFFF0B, 0.5); -graphics.drawCircle(470, 200,100); - -graphics.lineStyle(20, 0x33FF00); -graphics.moveTo(30,30); -graphics.lineTo(600, 300); - - -stage.addChild(graphics); - -// lets create moving shape -var thing = new PIXI.Graphics(); -stage.addChild(thing); -thing.position.x = 620/2; -thing.position.y = 380/2; - -var count = 0; - -stage.click = stage.tap = function() -{ - graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); - graphics.moveTo(Math.random() * 620,Math.random() * 380); - graphics.lineTo(Math.random() * 620,Math.random() * 380); -} - -requestAnimFrame(animate); - -function animate1() { - - thing.clear(); - - count += 0.1; - - thing.clear(); - thing.lineStyle(30, 0xff0000, 1); - thing.beginFill(0xffFF00, 0.5); - - thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count)* 20); - thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count)* 20); - thing.lineTo(-120 + Math.cos(count)* 20, 100 + Math.sin(count)* 20); - thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - - thing.rotation = count * 0.1; - renderer.render(stage); - requestAnimFrame( animate ); -} - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x000000); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(800, 600); - -// set the canvas width and height to fill the screen -renderer.view.style.width = window.innerWidth + "px"; -renderer.view.style.height = window.innerHeight + "px"; -renderer.view.style.display = "block"; - -// add render view to DOM -document.body.appendChild(renderer.view); - -// OOH! SHINY! -// create two render textures.. these dynamic textures will be used to draw the scene into itself -var renderTexture = new PIXI.RenderTexture(800, 600); -var renderTexture2 = new PIXI.RenderTexture(800, 600); -var currentTexture = renderTexture; - -// create a new sprite that uses the render texture we created above -var outputSprite = new PIXI.Sprite(currentTexture); - -// align the sprite -outputSprite.position.x = 800/2; -outputSprite.position.y = 600/2; -outputSprite.anchor.x = 0.5; -outputSprite.anchor.y = 0.5; - -// add to stage -stage.addChild(outputSprite); - -var stuffContainer = new PIXI.DisplayObjectContainer(); - -stuffContainer.position.x = 800/2; -stuffContainer.position.y = 600/2 - -stage.addChild(stuffContainer); - -// create an array of image ids.. -var fruits = ["spinObj_01.png", "spinObj_02.png", - "spinObj_03.png", "spinObj_04.png", - "spinObj_05.png", "spinObj_06.png", - "spinObj_07.png", "spinObj_08.png"]; - -// create an array of items -var items = []; - -// now create some items and randomly position them in the stuff container -for (var i=0; i < 20; i++) -{ - var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); - item.position.x = Math.random() * 400 - 200; - item.position.y = Math.random() * 400 - 200; - - item.anchor.x = 0.5; - item.anchor.y = 0.5; - - stuffContainer.addChild(item); - console.log("_") - items.push(item); -}; - -// used for spinning! -var count = 0; - - -requestAnimFrame(animate); - -function animate2() { - - requestAnimFrame( animate ); - - for (var i=0; i < items.length; i++) - { - // rotate each item - var item = items[i]; - item.rotation += 0.1; - }; - - count += 0.01; - - // swap the buffers.. - var temp = renderTexture; - renderTexture = renderTexture2; - renderTexture2 = temp; - - - // set the new texture - outputSprite.setTexture(renderTexture); - - // twist this up! - stuffContainer.rotation -= 0.01 - outputSprite.scale.x = outputSprite.scale.y = 1 + Math.sin(count) * 0.2; - - // render the stage to the texture - // the true clears the texture before content is rendered - renderTexture2.render(stage, new PIXI.Point(0,0), true); - - // and finally render the stage - renderer.render(stage); -} - - -//// - - - -function init() -{ - var assetsToLoader = ["desyrel.fnt"]; - - // create a new loader - var loader = new PIXI.AssetLoader(assetsToLoader, false); - - //begin load - - // create an new instance of a pixi stage - var stage = new PIXI.Stage(0x66FF99); - - loader.load(); - function onAssetsLoaded() - { - var bitmapFontText = new PIXI.BitmapText("bitmap fonts are\n now supported!", {font: "35px Desyrel", align: "right"}); - bitmapFontText.position.x = 620 - bitmapFontText.width - 20; - bitmapFontText.position.y = 20; - - stage.addChild(bitmapFontText); - - - } - - - - // add a shiney background.. - var background = PIXI.Sprite.fromImage("textDemoBG.jpg"); - stage.addChild(background); - - // create a renderer instance - var renderer = PIXI.autoDetectRenderer(620, 400); - // add the renderer view element to the DOM - document.body.appendChild(renderer.view); - - requestAnimFrame(animate); - - // create some white text using the Snippet webfont - var textSample = new PIXI.Text("Pixi.js can has\nmultiline text!", {font: "35px Snippet", fill: "white", align: "left"}); - textSample.position.x = 20; - textSample.position.y = 20; - - // create a text object with a nice stroke - var spinningText = new PIXI.Text("I'm fun!", {font: "bold 60px Podkova", fill: "#cc00ff", align: "center", stroke: "#FFFFFF", strokeThickness: 6}); - // setting the anchor point to 0.5 will center align the text... great for spinning! - spinningText.anchor.x = spinningText.anchor.y = 0.5; - spinningText.position.x = 620 / 2; - spinningText.position.y = 400 / 2; - - // create a text object that will be updated.. - var countingText = new PIXI.Text("COUNT 4EVAR: 0", {font: "bold italic 60px Arvo", fill: "#3e1707", align: "center", stroke: "#a4410e", strokeThickness: 7}); - countingText.position.x = 620 / 2; - countingText.position.y = 320; - countingText.anchor.x = 0.5; - - stage.addChild(textSample); - stage.addChild(spinningText); - stage.addChild(countingText); - - var count = 0; - var score = 0; - - function animate() { - - requestAnimFrame( animate ); - count++; - if(count == 50) - { - count = 0; - score++; - // update the text... - countingText.setText("COUNT 4EVAR: " + score); - - } - // just for fun, lets rotate the text - spinningText.rotation += 0.03; - - // render the stage - renderer.render(stage); - } -} - - -///// - - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("p2.jpeg"); - -// create a tiling sprite.. -// requires a texture, width and height -// to work in webGL the texture size must be a power of two -var tilingSprite = new PIXI.TilingSprite(texture, window.innerWidth, window.innerHeight) - -var count = 0; - -stage.addChild(tilingSprite); - -function animate33() { - - requestAnimFrame( animate ); - - - count += 0.005 - tilingSprite.tileScale.x = 2 + Math.sin(count); - tilingSprite.tileScale.y = 2 + Math.cos(count); - - tilingSprite.tilePosition.x += 1; - tilingSprite.tilePosition.y += 1; - - // just for fun, lets rotate mr rabbit a little - //stage.interactionManager.update(); - // render the stage - renderer.render(stage); -} - - - -///// - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("bunny.png"); - -for (var i=0; i < 10; i++) -{ - createBunny(Math.random() * window.innerWidth, Math.random() * window.innerHeight) -}; - - -function createBunny(x, y) -{ - // create our little bunny friend.. - var bunny = new PIXI.Sprite(texture); - // bunny.width = 300; - // enable the bunny to be interactive.. this will allow it to respond to mouse and touch events - bunny.interactive = true; - // this button mode will mean the hand cursor appears when you rollover the bunny with your mouse - bunny.buttonMode = true; - - // center the bunnys anchor point - bunny.anchor.x = 0.5; - bunny.anchor.y = 0.5; - // make it a bit bigger, so its easier to touch - bunny.scale.x = bunny.scale.y = 3; - - - // use the mousedown and touchstart - bunny.mousedown = bunny.touchstart = function(data) - { - // stop the default event... - data.originalEvent.preventDefault(); - - // store a refference to the data - // The reason for this is because of multitouch - // we want to track the movement of this particular touch - this.data = data; - this.alpha = 0.9; - this.dragging = true; - }; - - // set the events for when the mouse is released or a touch is released - bunny.mouseup = bunny.mouseupoutside = bunny.touchend = bunny.touchendoutside = function(data) - { - this.alpha = 1 - this.dragging = false; - // set the interaction data to null - this.data = null; - }; - - // set the callbacks for when the mouse or a touch moves - bunny.mousemove = bunny.touchmove = function(data) - { - if(this.dragging) - { - // need to get parent coords.. - var newPosition = this.data.getLocalPosition(this.parent); - this.position.x = newPosition.x; - this.position.y = newPosition.y; - } - } - - // move the sprite to its designated position - bunny.position.x = x; - bunny.position.y = y; - - // add it to the stage - stage.addChild(bunny); -} - -function animate44() { - - requestAnimFrame( animate ); - - // just for fun, lets rotate mr rabbit a little - //stage.interactionManager.update(); - // render the stage - renderer.render(stage); -} - - - -//// - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x66FF99); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(400, 300, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("bunny.png"); -// create a new Sprite using the texture -var bunny = new PIXI.Sprite(texture); - -// center the sprites anchor point -bunny.anchor.x = 0.5; -bunny.anchor.y = 0.5; - -// move the sprite t the center of the screen -bunny.position.x = 200; -bunny.position.y = 150; - -stage.addChild(bunny); - -function animate55() { - - requestAnimFrame( animate ); - - // just for fun, lets rotate mr rabbit a little - bunny.rotation += 0.1; - - // render the stage - renderer.render(stage); -} - - - -/////// - - - -// create an new instance of a pixi stage -// the second parameter is interactivity... -var interactive = true; -var stage = new PIXI.Stage(0x000000); - -// create a renderer instance. -var renderer = PIXI.autoDetectRenderer(620, 400); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); - -requestAnimFrame( animate ); - -// create a background.. -var background = PIXI.Sprite.fromImage("button_test_BG.jpg"); - -// add background to stage.. -stage.addChild(background); - -// create some textures from an image path -var textureButton = PIXI.Texture.fromImage("button.png"); -var textureButtonDown = PIXI.Texture.fromImage("buttonDown.png"); -var textureButtonOver = PIXI.Texture.fromImage("buttonOver.png"); - -var buttons = []; - -var buttonPositions = [175,75, - 600-145, 75, - 600/2 - 20, 400/2 + 10, - 175, 400-75, - 600-115, 400-95]; - - -for (var i=0; i < 5; i++) -{ - var button = new PIXI.Sprite(textureButton); - button.buttonMode = true; - - button.anchor.x = 0.5; - button.anchor.y = 0.5; - - button.position.x = buttonPositions[i*2]; - button.position.y = buttonPositions[i*2 + 1]; - - // make the button interactive.. - button.interactive = true; - - // set the mousedown and touchstart callback.. - button.mousedown = button.touchstart = function(data){ - - this.isdown = true; - this.setTexture(textureButtonDown); - this.alpha = 1; - } - - // set the mouseup and touchend callback.. - button.mouseup = button.touchend = button.mouseupoutside = button.touchendoutside = function(data){ - this.isdown = false; - - if(this.isOver) - { - this.setTexture(textureButtonOver); - } - else - { - this.setTexture(textureButton); - } - } - - // set the mouseover callback.. - button.mouseover = function(data){ - - this.isOver = true; - - if(this.isdown)return - - this.setTexture(textureButtonOver) - } - - // set the mouseout callback.. - button.mouseout = function(data){ - - this.isOver = false; - if(this.isdown)return - this.setTexture(textureButton) - } - - button.click = function(data){ - // click! - console.log("CLICK!"); - // alert("CLICK!") - } - - button.tap = function(data){ - // click! - console.log("TAP!!"); - //this.alpha = 0.5; - } - - // add it to the stage - stage.addChild(button); - - // add button to array - buttons.push(button); -}; - -// set some silly values.. - -buttons[0].scale.x = 1.2; - -buttons[1].scale.y = 1.2; - -buttons[2].rotation = Math.PI/10; - -buttons[3].scale.x = 0.8; -buttons[3].scale.y = 0.8; - -buttons[4].scale.x = 0.8; -buttons[4].scale.y = 1.2; -buttons[4].rotation = Math.PI; -// var button1 = -function animate66() { - - requestAnimFrame( animate ); - // render the stage - - // do a test.. - - renderer.render(stage); -} - -// add a logo! -var pixiLogo = PIXI.Sprite.fromImage("pixi.png"); -stage.addChild(pixiLogo); - -pixiLogo.position.x = 620 - 56; -pixiLogo.position.y = 400- 32; - -pixiLogo.click = pixiLogo.tap = function(){ - - var win=window.open("https://github.com/GoodBoyDigital/pixi.js", '_blank'); + } } +module basics { -////// + export class Click { + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + private stage: PIXI.Container; -var w = 1024; -var h = 768; + private sprite: PIXI.Sprite; -var n = 2000; -var d = 1; -var current = 1; -var objs = 17; -var vx = 0; -var vy = 0; -var vz = 0; -var points1 = []; -var points2 = []; -var points3 = []; -var tpoint1 = []; -var tpoint2 = []; -var tpoint3 = []; -var balls = []; + constructor() { -function start() { + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - var ballTexture = PIXI.Texture.fromImage("assets/pixel.png"); + // create the root of the scene graph + this.stage = new PIXI.Container(); - renderer = PIXI.autoDetectRenderer(w, h); + this.sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + this.sprite.position.set(230, 264); + this.sprite.interactive = true; + this.sprite.on('mousedown', this.onDown, this); + this.sprite.on('touchstart', this.onDown, this); - stage = new PIXI.Stage(0x000000); + //add it to the stage + this.stage.addChild(this.sprite); - document.body.appendChild(renderer.view); + //start animatng + this.animate(); - makeObject(0); + } - for (var i = 0; i < n; i++) - { - tpoint1[i] = points1[i]; - tpoint2[i] = points2[i]; - tpoint3[i] = points3[i]; + private onDown = (eventData: PIXI.interaction.InteractionData): void => { - var tempBall = new PIXI.Sprite(ballTexture); - tempBall.anchor.x = 0.5; - tempBall.anchor.y = 0.5; - tempBall.alpha = 0.5; - balls[i] = tempBall; + this.sprite.scale.x += 0.3; + this.sprite.scale.y += 0.3; - stage.addChild(tempBall); - } + } + private animate = (): void => { + requestAnimationFrame(this.animate); - setTimeout(nextObject, 5000); + this.renderer.render(this.stage); - requestAnimFrame(update); + } + + } } -function nextObject () { +module basics { - current++; + export class Container { - if (current > objs) - { - current = 0; - } + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - makeObject(current); + private stage: PIXI.Container; - setTimeout(nextObject, 8000); + private container: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + this.container.addChild(bunny); + + }; + + }; + + /* + * All the bunnies are added to the container with the addChild method + * when you do this, all the bunnies become children of the container, and when a container moves, + * so do all its children. + * This gives you a lot of flexibility and makes it easier to position elements on the screen + */ + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } } -function makeObject ( t ) { +module basics { - var xd; + export class CustomFilter { - switch (t) - { - case 0: + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - for (var i = 0; i < n; i++) - { - points1[i] = -50 + Math.round(Math.random() * 100); - points2[i] = 0; - points3[i] = 0; - } - break; + private stage: PIXI.Container; - case 1: + private background: PIXI.Sprite; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(t * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(t * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + private filter: CustomizedFilter; - case 2: + constructor() { - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(t * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(t * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - case 3: + // create the root of the scene graph + this.stage = new PIXI.Container(); - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + this.background = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.background.scale.set(1.3, 1); + this.stage.addChild(this.background); - case 4: - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + PIXI.loader.add('shader', '../../_assets/basics/shader.frag'); + PIXI.loader.once('complete', this.onLoaded, this); + PIXI.loader.load(); - case 5: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + private onLoaded(loader: PIXI.loaders.Loader, res: any) { - case 6: + var fragmentSrc = res.shader.data; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + this.filter = new CustomizedFilter(fragmentSrc); + this.background.filters = [this.filter]; - case 7: + this.animate(); - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - case 8: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + private animate = (): void => { - case 9: + this.filter.uniforms.customUniform.value += 0.04; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + this.renderer.render(this.stage); + requestAnimationFrame(this.animate); - case 10: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + } - case 11: + export class CustomizedFilter extends PIXI.AbstractFilter { - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + constructor(fragmentSource: string | string[]) { + super(null, fragmentSource, { + customUniform: { + type: '1f', + value: 0 + } + }) + } - case 12: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 13: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 14: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.sin(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 15: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 16: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; - - case 17: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - } + } } +module basics { + export class Graphics { -function update() -{ - var x3d, y3d, z3d, tx, ty, tz, ox; + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - if (d < 250) - { - d++; - } + private stage: PIXI.Container; - vx += 0.0075; - vy += 0.0075; - vz += 0.0075; + private graphics: PIXI.Graphics; - for (var i = 0; i < n; i++) - { - if (points1[i] > tpoint1[i]) { tpoint1[i] = tpoint1[i] + 1; } - if (points1[i] < tpoint1[i]) { tpoint1[i] = tpoint1[i] - 1; } - if (points2[i] > tpoint2[i]) { tpoint2[i] = tpoint2[i] + 1; } - if (points2[i] < tpoint2[i]) { tpoint2[i] = tpoint2[i] - 1; } - if (points3[i] > tpoint3[i]) { tpoint3[i] = tpoint3[i] + 1; } - if (points3[i] < tpoint3[i]) { tpoint3[i] = tpoint3[i] - 1; } + constructor() { - x3d = tpoint1[i]; - y3d = tpoint2[i]; - z3d = tpoint3[i]; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - ty = (y3d * Math.cos(vx)) - (z3d * Math.sin(vx)); - tz = (y3d * Math.sin(vx)) + (z3d * Math.cos(vx)); - tx = (x3d * Math.cos(vy)) - (tz * Math.sin(vy)); - tz = (x3d * Math.sin(vy)) + (tz * Math.cos(vy)); - ox = tx; - tx = (tx * Math.cos(vz)) - (ty * Math.sin(vz)); - ty = (ox * Math.sin(vz)) + (ty * Math.cos(vz)); + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; - balls[i].position.x = (512 * tx) / (d - tz) + w / 2; - balls[i].position.y = (h/2) - (512 * ty) / (d - tz); + this.graphics = new PIXI.Graphics(); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); - } + // set a fill and a line style again and draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.beginFill(0xFF700B, 1); + this.graphics.drawRect(50, 250, 120, 120); - renderer.render(stage); + // draw a rounded rectangle + this.graphics.lineStyle(2, 0xFF00FF, 1); + this.graphics.beginFill(0xFF00BB, 0.25); + this.graphics.drawRoundedRect(150, 450, 300, 100, 15); + this.graphics.endFill(); - requestAnimFrame(update); -} + // draw a circle, set the lineStyle to zero so the circle doesn't have an outline + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 90, 60); + this.graphics.endFill(); + this.stage.addChild(this.graphics); + // start animating + this.animate(); -/////// + } + private animate = (): void => { + requestAnimationFrame(this.animate); -// Globals, globals everywhere and not a drop to drink -var w = 1024; -var h = 768; -var starCount = 2500; -var sx = 1.0 + (Math.random() / 20); -var sy = 1.0 + (Math.random() / 20); -var slideX = w / 2; -var slideY = h / 2; -var stars = []; + this.renderer.render(this.stage); -function start2() { + } - var ballTexture = PIXI.Texture.fromImage("assets/bubble_32x32.png"); - - renderer = PIXI.autoDetectRenderer(w, h); - - stage = new PIXI.Stage(0x000000); - - document.body.appendChild(renderer.view); - - for (var i = 0; i < starCount; i++) - { - var tempBall = new PIXI.Sprite(ballTexture); - - tempBall.position.x = (Math.random() * w) - slideX; - tempBall.position.y = (Math.random() * h) - slideY; - tempBall.anchor.x = 0.5; - tempBall.anchor.y = 0.5; - - stars.push({ sprite: tempBall, x: tempBall.position.x, y: tempBall.position.y }); - - stage.addChild(tempBall); - } - - document.getElementById('rnd').onclick = newWave; - document.getElementById('sx').innerHTML = 'SX: ' + sx + '
        SY: ' + sy; - - - - requestAnimFrame(update); + } } -function newWave () { +module basics { - sx = 1.0 + (Math.random() / 20); - sy = 1.0 + (Math.random() / 20); - document.getElementById('sx').innerHTML = 'SX: ' + sx + '
        SY: ' + sy; + export class RenderTexture { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + + private sprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + bunny.rotation = Math.random() * (Math.PI * 2); + this.container.addChild(bunny); + + }; + + }; + + this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); + + this.sprite = new PIXI.Sprite(this.renderTexture); + this.sprite.x = 450; + this.sprite.y = 60; + this.stage.addChild(this.sprite); + + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.renderTexture.render(this.container); + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } } +module basics { + + export class SpriteSheet { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private movie: PIXI.extras.MovieClip; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader.add('../../_assets/basics/fighter.json').load((loader: PIXI.loaders.Loader, object: any): void => { + + // create an array of textures from an image path + var frames: PIXI.Texture[] = []; + + for (var i = 0; i < 30; i++) { + + var val = i < 10 ? '0' + i : i; + + // magically works since the spritesheet was loaded with the pixi loader + frames.push(PIXI.Texture.fromFrame('rollSequence00' + val + '.png')); + } -function update22() -{ - for (var i = 0; i < starCount; i++) - { - stars[i].sprite.position.x = stars[i].x + slideX; - stars[i].sprite.position.y = stars[i].y + slideY; - stars[i].x = stars[i].x * sx; - stars[i].y = stars[i].y * sy; + // create a MovieClip (brings back memories from the days of Flash, right ?) + this.movie = new PIXI.extras.MovieClip(frames); - if (stars[i].x > w) - { - stars[i].x = stars[i].x - w; - } - else if (stars[i].x < -w) - { - stars[i].x = stars[i].x + w; - } + /* + * A MovieClip inherits all the properties of a PIXI sprite + * so you can change its position, its anchor, mask it, etc + */ + this.movie.position.set(300); + this.movie.anchor.set(0.5); + this.movie.animationSpeed = 0.5; + this.movie.play(); - if (stars[i].y > h) - { - stars[i].y = stars[i].y - h; - } - else if (stars[i].y < -h) - { - stars[i].y = stars[i].y + h; - } - } + this.stage.addChild(this.movie); - renderer.render(stage); + this.animate(); + + }); + + } + + private animate = (): void => { + + this.movie.rotation += 0.01; + + //render the stage container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } - requestAnimFrame(update); } -} \ No newline at end of file +module basics { + + export class Text { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private basicText: PIXI.Text; + + private richText: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.basicText = new PIXI.Text('Basic Text in Pixi'); + this.basicText.x = 30; + this.basicText.y = 90; + + this.stage.addChild(this.basicText); + + var style: PIXI.TextStyle = { + font: '36px Arial bold italic', + fill: '#F7EDCA', + stroke: '#4a1850', + strokeThickness: 5, + dropShadow: true, + dropShadowColor: '#000000', + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440 + }; + + this.richText = new PIXI.Text('Rich Text with a lot of options and across multiple lines', style); + this.richText.x = 30; + this.richText.y = 180; + + this.stage.addChild(this.richText); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module basics { + + export class TexturedMesh { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private strip: PIXI.mesh.Rope; + + private graphics: PIXI.Graphics; + + private count: number; + + private points: PIXI.Point[]; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + this.ropeLength = 918 / 20; + this.ropeLength = 45; + + this.points = []; + + for (var i = 0; i < 25; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + }; + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.position.x = -40; + this.strip.position.y = 300; + this.stage.addChild(this.strip); + + this.graphics = new PIXI.Graphics(); + this.graphics.x = this.strip.x; + this.graphics.y = this.strip.y; + this.stage.addChild(this.graphics); + + //start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + //make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + }; + + //render the stage + this.renderer.render(this.stage); + + this.renderPoints(); + + requestAnimationFrame(this.animate); + + } + + private renderPoints(): void { + + this.graphics.clear(); + + this.graphics.lineStyle(2, 0xffc2c2); + this.graphics.moveTo(this.points[0].x, this.points[0].y); + + for (var i = 1; i < this.points.length; i++) { + this.graphics.lineTo(this.points[i].x, this.points[i].y); + }; + + for (var i = 1; i < this.points.length; i++) { + this.graphics.beginFill(0xff0022); + this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); + this.graphics.endFill(); + }; + + } + + } + +} + +module basics { + + export class TilingSprite { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private tilingSprite: PIXI.extras.TilingSprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image path + this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); + + /* create a tiling sprite ... + * requires a texture, a width and a height + * in WebGL the image size should preferably be a power of two + */ + this.tilingSprite = new PIXI.extras.TilingSprite(this.texture, this.renderer.width, this.renderer.height); + this.stage.addChild(this.tilingSprite); + + this.count = 0; + + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); + this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); + + this.tilingSprite.tilePosition.x += 1; + this.tilingSprite.tilePosition.y += 1; + + // render the root container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module basics { + + export class Video { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private videoSprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a video texture from a path + this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); + + //create a new sprite using the video texture (yes it's that easy) + this.videoSprite = new PIXI.Sprite(this.texture); + this.videoSprite.width = this.renderer.width; + this.videoSprite.height = this.renderer.height; + this.stage.addChild(this.videoSprite); + + this.stage.addChild(this.videoSprite); + + this.animate(); + + } + + private animate = (): void => { + + //render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class AlphaMask { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Container; + + private cells: PIXI.Sprite; + + private mask: PIXI.Sprite; + + private target: PIXI.Point; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.background = PIXI.Sprite.fromImage('../../_assets/bkg.jpg'); + this.stage.addChild(this.background); + + this.cells = PIXI.Sprite.fromImage('../../_assets/cells.png'); + this.cells.scale.set(1.5, 1.5); + + this.mask = PIXI.Sprite.fromImage('../../_assets/flowerTop.png'); + this.mask.anchor.set(0.5); + this.mask.position.x = 310; + this.mask.position.y = 190; + + this.cells.mask = this.mask; + + this.stage.addChild(this.mask); + + this.stage.addChild(this.cells); + + this.target = new PIXI.Point(); + + this.reset(); + + this.animate(); + + } + + private reset(): void { + + this.target.x = Math.floor(Math.random() * 550); + this.target.y = Math.floor(Math.random() * 300); + + } + + private animate = (): void => { + + this.mask.position.x += (this.target.x - this.mask.x) * 0.1; + this.mask.position.y += (this.target.y - this.mask.y) * 0.1; + + if (Math.abs(this.mask.x - this.target.x) < 1) { + this.reset(); + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class Batch { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private sprites: PIXI.ParticleContainer; + + private maggots: BatchDude[]; + + private tick: number; + + private dudeBounds: PIXI.Rectangle; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.sprites = new PIXI.ParticleContainer(10000, { + + scale: true, + position: true, + rotation: true, + uvs: true, + alpha: true + + }); + this.stage.addChild(this.sprites); + + // create an array to store all the sprites + this.maggots = []; + + var totalSprites = this.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; + + for (var i = 0; i < totalSprites; i++) { + + // create a new Sprite + var dude = new BatchDude(PIXI.Texture.fromImage('../../_assets/tinyMaggot.png')); + + dude.tint = Math.random() * 0xE8D4CD; + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // different maggots, different sizes + dude.scale.set(0.8 + Math.random() * 0.3); + + // scatter them all + dude.x = Math.random() * this.renderer.width; + dude.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0x808080; + + // create a random direction in radians + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the sprite over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed between 0 - 2, and these maggots are slooww + dude.speed = (2 + Math.random() * 2) * 0.2; + + dude.offset = Math.random() * 100; + + // finally we push the dude into the maggots array so it it can be easily accessed later + this.maggots.push(dude); + + this.sprites.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the sprites and update their position + for (var i = 0; i < this.maggots.length; i++) { + + var dude = this.maggots[i]; + dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); + dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); + dude.rotation = -dude.direction + Math.PI; + + // wrap the maggots + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BatchDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +module demos { + + export class BlendModes { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private dudeArray: BlendModesDude[]; + + private totalDudes: number; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new background sprite + this.background = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.stage.addChild(this.background); + + // create an array to store a reference to the dudes + this.dudeArray = []; + + this.totalDudes = 20; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new BlendModesDude(PIXI.Texture.fromImage('../../_assets/flowerTop.png')); + + dude.anchor.set(0.5); + + // set a random scale for the dude + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally let's set the dude to be at a random position... + dude.position.x = Math.floor(Math.random() * this.renderer.width); + dude.position.y = Math.floor(Math.random() * this.renderer.height); + + // The important bit of this example, this is how you change the default blend mode of the sprite + dude.blendMode = PIXI.BLEND_MODES.ADD; + + // create some extra properties that will control movement + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the dudeArray so it it can be easily accessed later + this.dudeArray.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update the positions + for (var i = 0; i < this.dudeArray.length; i++) { + + var dude = this.dudeArray[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BlendModesDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +module demos { + + export class CacheAsBitmap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private aliens: PIXI.Sprite[]; + + private alienContainer: PIXI.Container; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // load resources + PIXI.loader + .add('spritesheet', '../../_assets/monsters.json') + .load(this.onAssetsLoaded); + + // holder to store aliens + this.aliens = []; + + this.count = 0; + + // create an empty container + this.alienContainer = new PIXI.Container(); + this.alienContainer.position.x = 400; + this.alienContainer.position.y = 300; + + // make the stage interactive + this.stage.interactive = true; + + this.stage.addChild(this.alienContainer); + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; + + //feel free to play with what's below + //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + //this.stage.addChild(sprite); + //sprite.position.x = Math.random() * 800; + //sprite.position.y = Math.random() * 600; + + } + + private onAssetsLoaded = (): void => { + + // add a bunch of aliens with textures from image paths + + var alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; + + for (var i = 0; i < 100; i++) { + + var frameName = alienFrames[i % 4]; + + // create an alien using the frame name.. + var alien = PIXI.Sprite.fromFrame(frameName); + alien.tint = Math.random() * 0xFFFFFF; + + /* + * fun fact for the day :) + * another way of doing the above would be + * var texture = PIXI.Texture.fromFrame(frameName); + * var alien = new PIXI.Sprite(texture); + */ + alien.position.x = Math.random() * 800 - 400; + alien.position.y = Math.random() * 600 - 300; + alien.anchor.x = 0.5; + alien.anchor.y = 0.5; + this.aliens.push(alien); + this.alienContainer.addChild(alien); + + } + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // let's rotate the aliens a little bit + for (var i = 0; i < 100; i++) { + var alien = this.aliens[i]; + alien.rotation += 0.1; + } + + this.count += 0.01; + + this.alienContainer.scale.x = Math.sin(this.count); + this.alienContainer.scale.y = Math.sin(this.count); + + this.alienContainer.rotation += 0.01; + + // render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class DraggableBunny extends PIXI.Sprite { + + //todo I dont know what event.data is at this time + private data: any; + + private dragging: boolean; + + constructor(texture?: PIXI.Texture) { + + super(texture); + + // enable the bunny to be interactive... this will allow it to respond to mouse and touch events + this.interactive = true; + + // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse + this.buttonMode = true; + + // center the bunny's anchor point + this.anchor.set(0.5); + + // make it a bit bigger, so it's easier to grab + this.scale.set(3); + + // setup events + this + // events for drag start + .on('mousedown', this.onDragStart) + .on('touchstart', this.onDragStart) + // events for drag end + .on('mouseup', this.onDragEnd) + .on('mouseupoutside', this.onDragEnd) + .on('touchend', this.onDragEnd) + .on('touchendoutside', this.onDragEnd) + // events for drag move + .on('mousemove', this.onDragMove) + .on('touchmove', this.onDragMove); + + } + + private onDragStart = (event: PIXI.interaction.InteractionEvent): void => { + + // store a reference to the data + // the reason for this is because of multitouch + // we want to track the movement of this particular touch + this.data = event.data; + this.alpha = 0.5; + this.dragging = true; + + } + + private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { + + //set interactiondata to null + this.data = null; + this.alpha = 1; + this.dragging = false; + + } + + private onDragMove = (event: PIXI.interaction.InteractionEvent): void => { + + if (this.dragging) { + var newPosition = this.data.getLocalPosition(this.parent); + this.position.x = newPosition.x; + this.position.y = newPosition.y; + } + + } + + } + + export class Dragging { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private data: PIXI.interaction.InteractionData; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image + this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); + + for (var i = 0; i < 10; i++) { + this.createBunny(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600)); + } + + // start animating + this.animate(); + + } + + private createBunny(x: number, y: number): void { + + // create our little bunny friend.. + var bunny = new DraggableBunny(this.texture); + + // move the sprite to its designated position + bunny.position.x = x; + bunny.position.y = y; + + // add it to the stage + this.stage.addChild(bunny); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module demos { + + export class GraphicsDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private thing: PIXI.Graphics; + + private graphics: PIXI.Graphics; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.graphics = new PIXI.Graphics(); + + // set a fill and line style + this.graphics.beginFill(0xFF3300); + this.graphics.lineStyle(10, 0xffd900, 1); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(250, 220); + this.graphics.lineTo(50, 220); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); + + // set a fill and line style again + this.graphics.lineStyle(10, 0xFF0000, 0.8); + this.graphics.beginFill(0xFF700B, 1); + + // draw a second shape + this.graphics.moveTo(210, 300); + this.graphics.lineTo(450, 320); + this.graphics.lineTo(570, 350); + this.graphics.quadraticCurveTo(600, 0, 480, 100); + this.graphics.lineTo(330, 120); + this.graphics.lineTo(410, 200); + this.graphics.lineTo(210, 300); + this.graphics.endFill(); + + // draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.drawRect(50, 250, 100, 100); + + // draw a circle + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 200, 100); + this.graphics.endFill(); + + this.graphics.lineStyle(20, 0x33FF00); + this.graphics.moveTo(30, 30); + this.graphics.lineTo(600, 300); + + this.stage.addChild(this.graphics); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = 620 / 2; + this.thing.position.y = 380 / 2; + + this.count = 0; + + // Just click on the stage to draw random lines + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + // start animating + this.animate(); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); + this.graphics.moveTo(Math.random() * 620, Math.random() * 380); + this.graphics.bezierCurveTo(Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380); + } + + private animate = (): void => { + + this.thing.clear(); + + this.count += 0.1; + + this.thing.clear(); + this.thing.lineStyle(10, 0xff0000, 1); + this.thing.beginFill(0xffFF00, 0.5); + + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + + this.thing.rotation = this.count * 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + } + + } + +} + +module demos { + + export class Interactivity { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private buttons: InteractivityButton[]; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a background... + this.background = PIXI.Sprite.fromImage('../../_assets/button_test_BG.jpg'); + this.background.width = this.renderer.width; + this.background.height = this.renderer.height; + + // add background to stage... + this.stage.addChild(this.background); + + this.buttons = []; + + var buttonPositions = [ + 175, 75, + 655, 75, + 410, 325, + 150, 465, + 685, 445 + ]; + + function noop(): void { + console.log('click'); + } + + // create some textures from an image path + var textureButton = PIXI.Texture.fromImage('../../_assets/button.png'); + var textureButtonDown = PIXI.Texture.fromImage('../../_assets/buttonDown.png'); + var textureButtonOver = PIXI.Texture.fromImage('../../_assets/buttonOver.png'); + + for (var i = 0; i < 5; i++) { + + var button = new InteractivityButton(textureButton, textureButtonDown, textureButtonOver); + + button.position.x = buttonPositions[i * 2]; + button.position.y = buttonPositions[i * 2 + 1]; + + button.tap = noop; + button.click = noop; + + // add it to the stage + this.stage.addChild(button); + + // add button to array + this.buttons.push(button); + + } + + // set some silly values... + this.buttons[0].scale.set(1.2); + + this.buttons[2].rotation = Math.PI / 10; + + this.buttons[3].scale.set(0.8); + + this.buttons[4].scale.set(0.8, 1.2); + this.buttons[4].rotation = Math.PI; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class InteractivityButton extends PIXI.Sprite { + + private textureButton: PIXI.Texture; + private textureButtonDown: PIXI.Texture; + private textureButtonOver: PIXI.Texture; + + tap: Function; + click: Function; + + isdown: boolean; + isOver: boolean; + + constructor(textureButton: PIXI.Texture, textureButtonDown: PIXI.Texture, textureButtonOver: PIXI.Texture) { + + super(textureButton); + + // create some textures from an image path + this.textureButton = textureButton; + this.textureButtonDown = textureButtonDown; + this.textureButtonOver = textureButtonOver; + + this.buttonMode = true; + this.anchor.set(0.5); + + // make the button interactive... + this.interactive = true; + + this + // set the mousedown and touchstart callback... + .on('mousedown', this.onButtonDown) + .on('touchstart', this.onButtonDown) + + // set the mouseup and touchend callback... + .on('mouseup', this.onButtonUp) + .on('touchend', this.onButtonUp) + .on('mouseupoutside', this.onButtonUp) + .on('touchendoutside', this.onButtonUp) + + // set the mouseover callback... + .on('mouseover', this.onButtonOver) + + // set the mouseout callback... + .on('mouseout', this.onButtonOut) + + // you can also listen to click and tap events : + //.on('click', this.noop) + + } + + private onButtonDown = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = true; + this.texture = this.textureButtonDown; + this.alpha = 1; + + } + + private onButtonUp = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = false; + + if (this.isOver) { + this.texture = this.textureButtonOver; + } + else { + this.texture = this.textureButton; + } + } + + private onButtonOver = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = true; + + if (this.isdown) { + return; + } + + this.texture = this.textureButtonOver; + + } + + private onButtonOut = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = false; + + if (this.isdown) { + return; + } + + this.texture = this.textureButton; + } + + } + +} + +module demos { + + export class Masking { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + + private light1: PIXI.Sprite; + + private light2: PIXI.Sprite; + + private panda: PIXI.Sprite; + + private thing: PIXI.Graphics; + + private count: number; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, antialias: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.bg = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.bg.anchor.x = 0.5; + this.bg.anchor.y = 0.5; + + this.bg.position.x = this.renderer.width / 2; + this.bg.position.y = this.renderer.height / 2; + + this.stage.addChild(this.bg); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + // add a bunch of sprites + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.x = 0.5; + this.bgFront.anchor.y = 0.5; + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.x = 0.5; + this.light2.anchor.y = 0.5; + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.x = 0.5; + this.light1.anchor.y = 0.5; + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.x = 0.5; + this.panda.anchor.y = 0.5; + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = this.renderer.width / 2; + this.thing.position.y = this.renderer.height / 2; + this.thing.lineStyle(0); + + this.container.mask = this.thing; + + this.count = 0; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + this.help = new PIXI.Text('Click to turn masking on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 26; + this.help.position.x = 10; + this.stage.addChild(this.help); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.bg.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + this.thing.clear(); + + this.thing.beginFill(0x8bc5ff, 0.4); + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.rotation = this.count * 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + if (!this.container.mask) { + this.container.mask = this.thing; + } + else { + this.container.mask = null; + } + } + + } + +} + +module demos { + + export class MovieClipDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('spritesheet', '../../_assets/mc.json') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader): void => { + + // create an array to store the textures + var explosionTextures: PIXI.Texture[] = []; + var i: number; + + for (i = 0; i < 26; i++) { + + var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i + 1) + '.png'); + explosionTextures.push(texture); + + } + + for (i = 0; i < 50; i++) { + + // create an explosion MovieClip + var explosion = new PIXI.extras.MovieClip(explosionTextures); + + explosion.position.x = Math.random() * 800; + explosion.position.y = Math.random() * 600; + explosion.anchor.x = 0.5; + explosion.anchor.y = 0.5; + + explosion.rotation = Math.random() * Math.PI; + + explosion.scale.set(0.75 + Math.random() * 0.5); + + explosion.gotoAndPlay(Math.random() * 27); + + this.stage.addChild(explosion); + + } + + // start animating + this.animate(); + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module demos { + + export class RenderTextureDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + private renderTexture2: PIXI.RenderTexture; + private currentTexture: PIXI.RenderTexture; + + private outputSprite: PIXI.Sprite; + private stuffContainer: PIXI.Container; + private items: PIXI.Sprite[]; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create two render textures... these dynamic textures will be used to draw the scene into itself + this.renderTexture = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.renderTexture2 = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.currentTexture = this.renderTexture; + + // create a new sprite that uses the render texture we created above + this.outputSprite = new PIXI.Sprite(this.currentTexture); + + // align the sprite + this.outputSprite.position.x = 400; + this.outputSprite.position.y = 300; + this.outputSprite.anchor.set(0.5); + + // add to stage + this.stage.addChild(this.outputSprite); + + this.stuffContainer = new PIXI.Container(); + + this.stuffContainer.position.x = 400; + this.stuffContainer.position.y = 300; + + this.stage.addChild(this.stuffContainer); + + // create an array of image ids.. + var fruits = [ + '../../_assets/spinObj_01.png', + '../../_assets/spinObj_02.png', + '../../_assets/spinObj_03.png', + '../../_assets/spinObj_04.png', + '../../_assets/spinObj_05.png', + '../../_assets/spinObj_06.png', + '../../_assets/spinObj_07.png', + '../../_assets/spinObj_08.png' + ]; + + // create an array of items + this.items = []; + + // now create some items and randomly position them in the stuff container + for (var i = 0; i < 20; i++) { + + var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); + item.position.x = Math.random() * 400 - 200; + item.position.y = Math.random() * 400 - 200; + + item.anchor.set(0.5); + + this.stuffContainer.addChild(item); + + this.items.push(item); + + } + + // used for spinning! + this.count = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + for (var i = 0; i < this.items.length; i++) { + // rotate each item + var item = this.items[i]; + item.rotation += 0.1; + } + + this.count += 0.01; + + // swap the buffers ... + var temp = this.renderTexture; + this.renderTexture = this.renderTexture2; + this.renderTexture2 = temp; + + // set the new texture + this.outputSprite.texture = this.renderTexture; + + // twist this up! + this.stuffContainer.rotation -= 0.01; + this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); + + // render the stage to the texture + // the 'true' clears the texture before the content is rendered + this.renderTexture2.render(this.stage, null, false); + + // and finally render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class StripDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private count: number; + + private points: PIXI.Point[]; + + private strip: PIXI.mesh.Rope; + + private snakeContainer: PIXI.Container; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + // build a rope! + this.ropeLength = 918 / 20; + + this.points = []; + + for (var i = 0; i < 20; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + } + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.x = -459; + + this.snakeContainer = new PIXI.Container(); + this.snakeContainer.position.x = 400; + this.snakeContainer.position.y = 300; + + this.snakeContainer.scale.set(800 / 1100); + this.stage.addChild(this.snakeContainer); + + this.snakeContainer.addChild(this.strip); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + // make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class TextDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bitmapFontText: PIXI.extras.BitmapText; + + private background: PIXI.Sprite; + + private textSample: PIXI.Text; + + private spinningText: PIXI.Text; + + private countingText: PIXI.Text; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('desyrel', '../../_assets/desyrel.xml') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (): void => { + + this.bitmapFontText = new PIXI.extras.BitmapText('bitmap fonts are\n now supported!', { font: '35px Desyrel', align: 'right' }); + + this.bitmapFontText.position.x = 600 - this.bitmapFontText.textWidth; + this.bitmapFontText.position.y = 20; + + this.stage.addChild(this.bitmapFontText); + + // add a shiny background... + this.background = PIXI.Sprite.fromImage('../../_assets/textDemoBG.jpg'); + this.stage.addChild(this.background); + + // create some white text using the Snippet webfont + this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { font: '35px Snippet', fill: 'white', align: 'left' }); + this.textSample.position.set(20); + + // create a text object with a nice stroke + this.spinningText = new PIXI.Text('I\'m fun!', { font: 'bold 60px Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); + + // setting the anchor point to 0.5 will center align the text... great for spinning! + this.spinningText.anchor.set(0.5); + this.spinningText.position.x = 310; + this.spinningText.position.y = 200; + + // create a text object that will be updated... + this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { font: 'bold italic 60px Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); + + this.countingText.position.x = 310; + this.countingText.position.y = 320; + this.countingText.anchor.x = 0.5; + + this.stage.addChild(this.textSample); + this.stage.addChild(this.spinningText); + this.stage.addChild(this.countingText); + + this.count = 0; + + } + + private animate = (): void => { + + + this.renderer.render(this.stage); + + this.count += 0.05; + + // update the text with a new string + this.countingText.text = 'COUNT 4EVAR: ' + Math.floor(this.count); + + // let's spin the spinning text + this.spinningText.rotation += 0.03; + + requestAnimationFrame(this.animate); + } + + } + +} + +module demos { + + export class TextureSwap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bol: boolean; + + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + + private dude: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bol = false; + + //an image path + this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); + + // create a second texture + this.secondTexture = PIXI.Texture.fromImage('../../_assets/eggHead.png'); + + // create a new Sprite using the texture + this.dude = new PIXI.Sprite(this.texture); + + // center the sprites anchor point + this.dude.anchor.set(0.5); + + // move the sprite to the center of the screen + this.dude.position.x = this.renderer.width / 2; + this.dude.position.y = this.renderer.height / 2; + + this.stage.addChild(this.dude); + + // make the sprite interactive + this.dude.interactive = true; + + this.dude.on('click', (): void => { + this.bol = !this.bol; + + if (this.bol) { + this.dude.texture = this.secondTexture; + } + else { + this.dude.texture = this.texture; + } + }); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.dude.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class Tinting { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private totalDudes: number = 10; + private aliens: TintingDude[]; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // holder to store the aliens + this.aliens = []; + + this.tick = 0; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new TintingDude(); + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // set a random scale for the dude - no point them all being the same size! + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally lets set the dude to be at a random position.. + dude.position.x = Math.random() * this.renderer.width; + dude.position.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0xFFFFFF; + + // create some extra properties that will control movement : + // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the aliens array so it it can be easily accessed later + this.aliens.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box for the little dudes + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update their position + for (var i = 0; i < this.aliens.length; i++) { + + var dude = this.aliens[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + + } + + // increment the ticker + this.tick += 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class TintingDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + + constructor() { + super(PIXI.Texture.fromImage('../../_assets/eggHead.png')); + } + + } + +} + +module demos { + + export class TransparentBackground { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bunny: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, transparent: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new Sprite from an image path. + this.bunny = PIXI.Sprite.fromImage('../../_assets/bunny.png'); + + // center the sprite's anchor point + this.bunny.anchor.set(0.5); + + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; + + this.stage.addChild(this.bunny); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.bunny.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module filters { + + export class Blur { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private littleDudes: PIXI.Sprite; + private littleRobot: PIXI.Sprite; + + private blurFilter1: PIXI.filters.BlurFilter; + private blurFilter2: PIXI.filters.BlurFilter; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bg = PIXI.Sprite.fromImage('../../_assets/depth_blur_BG.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + this.stage.addChild(this.bg); + + this.littleDudes = PIXI.Sprite.fromImage('../../_assets/depth_blur_dudes.jpg'); + this.littleDudes.position.x = (this.renderer.width / 2) - 315; + this.littleDudes.position.y = 200; + this.stage.addChild(this.littleDudes); + + this.littleRobot = PIXI.Sprite.fromImage('../../_assets/depth_blur_moby.jpg'); + this.littleRobot.position.x = (this.renderer.width / 2) - 200; + this.littleRobot.position.y = 100; + this.stage.addChild(this.littleRobot); + + this.blurFilter1 = new PIXI.filters.BlurFilter(); + this.blurFilter2 = new PIXI.filters.BlurFilter(); + + this.littleDudes.filters = [this.blurFilter1]; + this.littleRobot.filters = [this.blurFilter2]; + + this.count = 0; + + //nimate + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + var blurAmount = Math.cos(this.count); + var blurAmount2 = Math.sin(this.count); + + this.blurFilter1.blur = 20 * (blurAmount); + this.blurFilter2.blur = 20 * (blurAmount2); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module filters { + + export class DisplacementMap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private padding: number; + + private bounds: PIXI.Rectangle; + + private maggots: DisplacementMapDude[]; + + private displacementSprite: PIXI.Sprite; + + private displacementFilter: PIXI.filters.DisplacementFilter; + + private ring: PIXI.Sprite; + + private bg: PIXI.Sprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.container = new PIXI.Container(); + this.stage.addChild(this.container); + + this.padding = 100; + + this.bounds = new PIXI.Rectangle(-this.padding, -this.padding, this.renderer.width + this.padding * 2, this.renderer.height + this.padding * 2); + this.maggots = []; + + for (var i = 0; i < 20; i++) { + + var maggot = new DisplacementMapDude(); + maggot.anchor.set(0.5); + this.container.addChild(maggot); + + maggot.direction = Math.random() * Math.PI * 2; + maggot.speed = 1; + maggot.turnSpeed = Math.random() - 0.8; + + maggot.position.x = Math.random() * this.bounds.width; + maggot.position.y = Math.random() * this.bounds.height; + + maggot.scale.set(1 + Math.random() * 0.3); + maggot.original = maggot.scale.clone(); + this.maggots.push(maggot); + + } + + this.displacementSprite = PIXI.Sprite.fromImage('../../_assets/displace.png'); + this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); + + this.stage.addChild(this.displacementSprite); + + this.container.filters = [this.displacementFilter]; + + this.displacementFilter.scale.x = 110; + this.displacementFilter.scale.y = 110; + + this.ring = PIXI.Sprite.fromImage('../../_assets/ring.png'); + + this.ring.anchor.set(0.5); + + this.ring.visible = false; + + this.stage.addChild(this.ring); + + this.bg = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + + this.bg.alpha = 0.4; + + this.container.addChild(this.bg); + + this.stage + .on('mousemove', this.onPointerMove) + .on('touchmove', this.onPointerMove); + + this.count = 0; + + this.animate(); + + } + + private onPointerMove = (eventData: PIXI.interaction.InteractionEvent): void => { + + this.ring.visible = true; + + this.displacementSprite.x = eventData.data.global.x - 100; + this.displacementSprite.y = eventData.data.global.y - this.displacementSprite.height / 2; + + this.ring.position.x = eventData.data.global.x - 25; + this.ring.position.y = eventData.data.global.y; + + }; + + private animate = (): void => { + + this.count += 0.05; + + for (var i = 0; i < this.maggots.length; i++) { + var maggot = this.maggots[i]; + + maggot.direction += maggot.turnSpeed * 0.01; + maggot.position.x += Math.sin(maggot.direction) * maggot.speed; + maggot.position.y += Math.cos(maggot.direction) * maggot.speed; + + maggot.rotation = -maggot.direction - Math.PI / 2; + + maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; + + // wrap the maggots around as the crawl + if (maggot.position.x < this.bounds.x) { + maggot.position.x += this.bounds.width; + } + else if (maggot.position.x > this.bounds.x + this.bounds.width) { + maggot.position.x -= this.bounds.width; + } + + if (maggot.position.y < this.bounds.y) { + maggot.position.y += this.bounds.height; + } + else if (maggot.position.y > this.bounds.y + this.bounds.height) { + maggot.position.y -= this.bounds.height; + } + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + }; + + } + + export class DisplacementMapDude extends PIXI.Sprite { + + direction: number; + speed: number; + turnSpeed: number; + original: PIXI.Point; + + constructor() { + + super(PIXI.Texture.fromImage('../../_assets/maggot.png')); + + } + + } + +} + +module filters { + + export class Filter { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private filter: PIXI.filters.ColorMatrixFilter; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + private light2: PIXI.Sprite; + private light1: PIXI.Sprite; + private panda: PIXI.Sprite; + + private count: number; + private switchy: boolean; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + + this.background = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); + this.background.anchor.set(0.5); + + this.background.position.x = this.renderer.width / 2; + this.background.position.y = this.renderer.height / 2; + + this.filter = new PIXI.filters.ColorMatrixFilter(); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.set(0.5); + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.set(0.5); + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.set(0.5); + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.set(0.5); + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + this.stage.filters = [this.filter]; + + this.count = 0; + this.switchy = false; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + + this.help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 25; + this.help.position.x = 10; + + this.stage.addChild(this.help); + + //nimate + this.animate(); + + } + + private onClick = (): void => { + + this.switchy = !this.switchy; + + if (!this.switchy) { + this.stage.filters = [this.filter]; + } + else { + this.stage.filters = null; + } + + } + + private animate = (): void => { + + this.background.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + var matrix = this.filter.matrix; + + matrix[1] = Math.sin(this.count) * 3; + matrix[2] = Math.cos(this.count); + matrix[3] = Math.cos(this.count) * 1.5; + matrix[4] = Math.sin(this.count / 3) * 2; + matrix[5] = Math.sin(this.count / 2); + matrix[6] = Math.sin(this.count / 4); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} diff --git a/pixi.js/pixi.js-tests.ts.tscparams b/pixi.js/pixi.js-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/pixi.js/pixi.js-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index 0452e7432..8e83cbf1e 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1,601 +1,251 @@ -// Type definitions for PIXI 2.2.8 2015-03-24 +// Type definitions for Pixi.js 3.0.7 // Project: https://github.com/GoodBoyDigital/pixi.js/ // Definitions by: clark-stevenson // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare class PIXI { + + static VERSION: string; + static PI_2: number; + static RAD_TO_DEG: number; + static DEG_TO_RAD: number; + static TARGET_FPMS: number; + static RENDER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + static BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + + }; + static DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + static SCALE_MODES: { + DEFAULT: number; + LINEAR: number; + NEAREST: number; + }; + static RETINA_PREFIX: string; + static RESOLUTION: number; + static FILTER_RESOLUTION: number; + static DEFAULT_RENDER_OPTIONS: { + view: HTMLCanvasElement; + resolution: number; + antialias: boolean; + forceFXAA: boolean; + autoResize: boolean; + transparent: boolean; + backgroundColor: number; + clearBeforeRender: boolean; + preserveDrawingBuffer: boolean; + roundPixels: boolean; + }; + static SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + static SPRITE_BATCH_SIZE: number; + +} + declare module PIXI { - export var WEBGL_RENDERER: number; - export var CANVAS_RENDERER: number; - export var VERSION: string; + export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + export var loader: PIXI.loaders.Loader; - export enum blendModes { + //https://github.com/primus/eventemitter3 + export class EventEmitter { - NORMAL, - ADD, - MULTIPLY, - SCREEN, - OVERLAY, - DARKEN, - LIGHTEN, - COLOR_DODGE, - COLOR_BURN, - HARD_LIGHT, - SOFT_LIGHT, - DIFFERENCE, - EXCLUSION, - HUE, - SATURATION, - COLOR, - LUMINOSITY + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + removeListener(event: string, fn: Function, once?: boolean): EventEmitter; + removeAllListeners(event: string): EventEmitter; + + off(event: string, fn: Function, once?: boolean): EventEmitter; + addListener(event: string, fn: Function, context?: any): EventEmitter; } - export enum scaleModes { + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////CORE////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - DEFAULT, - LINEAR, - NEAREST + //display - } + export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - export var defaultRenderOptions: PixiRendererOptions; + //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db + protected _originalRenderWebGL: WebGLRenderer; + protected _originalRenderCanvas: CanvasRenderer; + protected _originalUpdateTransform: boolean; + protected _originalHitTest: any; + protected _cachedSprite: any; + protected _originalDestroy: any; - export var INTERACTION_REQUENCY: number; - export var AUTO_PREVENT_DEFAULT: boolean; - - export var PI_2: number; - export var RAD_TO_DEG: number; - export var DEG_TO_RAD: number; - - export var RETINA_PREFIX: string; - export var identityMatrix: Matrix; - export var glContexts: WebGLRenderingContext[]; - export var instances: any[]; - - export var BaseTextureCache: { [key: string]: BaseTexture } - export var TextureCache: { [key: string]: Texture } - - export function isPowerOfTwo(width: number, height: number): boolean; - - export function rgb2hex(rgb: number[]): string; - export function hex2rgb(hex: string): number[]; - - export function autoDetectRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; - export function autoDetectRecommendedRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; - - export function canUseNewCanvasBlendModes(): boolean; - export function getNextPowerOfTwo(number: number): number; - - export function AjaxRequest(): XMLHttpRequest; - - export function CompileFragmentShader(gl: WebGLRenderingContext, shaderSrc: string[]): any; - export function CompileProgram(gl: WebGLRenderingContext, vertexSrc: string[], fragmentSrc: string[]): any; - - - export interface IEventCallback { - (e?: IEvent): void - } - - export interface IEvent { - type: string; - content: any; - } - - export interface HitArea { - contains(x: number, y: number): boolean; - } - - export interface IInteractionDataCallback { - (interactionData: InteractionData): void - } - - export interface PixiRenderer { - - autoResize: boolean; - clearBeforeRender: boolean; - height: number; - resolution: number; - transparent: boolean; - type: number; - view: HTMLCanvasElement; - width: number; - - destroy(): void; - render(stage: Stage): void; - resize(width: number, height: number): void; - - } - - export interface PixiRendererOptions { - - autoResize?: boolean; - antialias?: boolean; - clearBeforeRender?: boolean; - preserveDrawingBuffer?: boolean; - resolution?: number; - transparent?: boolean; - view?: HTMLCanvasElement; - - } - - export interface BitmapTextStyle { - - font?: string; - align?: string; - tint?: string; - - } - - export interface TextStyle { - - align?: string; - dropShadow?: boolean; - dropShadowColor?: string; - dropShadowAngle?: number; - dropShadowDistance?: number; - fill?: string; - font?: string; - lineJoin?: string; - stroke?: string; - strokeThickness?: number; - wordWrap?: boolean; - wordWrapWidth?: number; - - } - - export interface Loader { - - load(): void; - - } - - export interface MaskData { - - alpha: number; - worldTransform: number[]; - - } - - export interface RenderSession { - - context: CanvasRenderingContext2D; - maskManager: CanvasMaskManager; - scaleMode: scaleModes; - smoothProperty: string; - roundPixels: boolean; - - } - - export interface ShaderAttribute { - // TODO: Find signature of shader attributes - } - - export interface FilterBlock { - - visible: boolean; - renderable: boolean; - - } - - export class AbstractFilter { - - constructor(fragmentSrc: string[], uniforms: any); - - dirty: boolean; - padding: number; - uniforms: any; - fragmentSrc: string[]; - - apply(frameBuffer: WebGLFramebuffer): void; - syncUniforms(): void; - - } - - export class AlphaMaskFilter extends AbstractFilter { - - constructor(texture: Texture); - - map: Texture; - - onTextureLoaded(): void; - - } - - export class AsciiFilter extends AbstractFilter { - - size: number; - - } - - export class AssetLoader implements Mixin { - - assetURLs: string[]; - crossorigin: boolean; - loadersByType: { [key: string]: Loader }; - - constructor(assetURLs: string[], crossorigin?: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - - } - - export class AtlasLoader implements Mixin { - - url: string; - baseUrl: string; - crossorigin: boolean; - loaded: boolean; - - constructor(url: string, crossorigin: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class BaseTexture implements Mixin { - - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): BaseTexture; - - constructor(source: HTMLImageElement, scaleMode: scaleModes); - constructor(source: HTMLCanvasElement, scaleMode: scaleModes); - - height: number; - hasLoaded: boolean; - mipmap: boolean; - premultipliedAlpha: boolean; - resolution: number; - scaleMode: scaleModes; - source: HTMLImageElement; - width: number; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - destroy(): void; - dirty(): void; - updateSourceImage(newSrc: string): void; - unloadFromGPU(): void; - - } - - export class BitmapFontLoader implements Mixin { - - constructor(url: string, crossorigin: boolean); - - baseUrl: string; - crossorigin: boolean; - texture: Texture; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class BitmapText extends DisplayObjectContainer { - - static fonts: any; - - constructor(text: string, style: BitmapTextStyle); - - dirty: boolean; - fontName: string; - fontSize: number; - maxWidth: number; - textWidth: number; - textHeight: number; - tint: number; - style: BitmapTextStyle; - - setText(text: string): void; - setStyle(style: BitmapTextStyle): void; - - } - - export class BlurFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - - } - - export class BlurXFilter extends AbstractFilter { - - blur: number; - - } - - export class BlurYFilter extends AbstractFilter { - - blur: number; - - } - - export class CanvasBuffer { - - constructor(width: number, height: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - height: number; - width: number; - - clear(): void; - resize(width: number, height: number): void; - - } - - export class CanvasMaskManager { - - pushMask(maskData: MaskData, renderSession: RenderSession): void; - popMask(renderSession: RenderSession): void; - - } - - export class CanvasRenderer implements PixiRenderer { - - constructor(width?: number, height?: number, options?: PixiRendererOptions); - - autoResize: boolean; - clearBeforeRender: boolean; - context: CanvasRenderingContext2D; - count: number; - height: number; - maskManager: CanvasMaskManager; - refresh: boolean; - renderSession: RenderSession; - resolution: number; - transparent: boolean; - type: number; - view: HTMLCanvasElement; - width: number; - - destroy(removeView?: boolean): void; - render(stage: Stage): void; - resize(width: number, height: number): void; - - } - - export class CanvasTinter { - - static getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; - static tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static roundColor(color: number): void; - - static cacheStepsPerColorChannel: number; - static convertTintToImage: boolean; - static canUseMultiply: boolean; - static tintMethod: any; - - } - - export class Circle implements HitArea { - - constructor(x: number, y: number, radius: number); - - x: number; - y: number; - radius: number; - - clone(): Circle; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - - export class ColorMatrixFilter extends AbstractFilter { - - matrix: Matrix; - - } - - export class ColorStepFilter extends AbstractFilter { - - step: number; - - } - - export class ConvolutionFilter extends AbstractFilter { - - constructor(matrix: number[], width: number, height: number); - - matrix: Matrix; - width: number; - height: number; - - } - - export class CrossHatchFilter extends AbstractFilter { - - blur: number; - - } - - export class DisplacementFilter extends AbstractFilter { - - constructor(texture: Texture); - - map: Texture; - offset: Point; - scale: Point; - - } - - export class DotScreenFilter extends AbstractFilter { - - angle: number; - scale: Point; - - } - - export class DisplayObject { - - alpha: number; - buttonMode: boolean; cacheAsBitmap: boolean; - defaultCursor: string; - filterArea: Rectangle; - filters: AbstractFilter[]; - hitArea: HitArea; - interactive: boolean; - mask: Graphics; - parent: DisplayObjectContainer; - pivot: Point; - position: Point; - renderable: boolean; - rotation: number; - scale: Point; - stage: Stage; - visible: boolean; - worldAlpha: number; - worldVisible: boolean; - x: number; - y: number; - click(e: InteractionData): void; - displayObjectUpdateTransform(): void; - getBounds(matrix?: Matrix): Rectangle; - getLocalBounds(): Rectangle; - generateTexture(resolution: number, scaleMode: scaleModes, renderer: PixiRenderer): RenderTexture; - mousedown(e: InteractionData): void; - mouseout(e: InteractionData): void; - mouseover(e: InteractionData): void; - mouseup(e: InteractionData): void; - mousemove(e: InteractionData): void; - mouseupoutside(e: InteractionData): void; - rightclick(e: InteractionData): void; - rightdown(e: InteractionData): void; - rightup(e: InteractionData): void; - rightupoutside(e: InteractionData): void; - setStageReference(stage: Stage): void; - tap(e: InteractionData): void; - toGlobal(position: Point): Point; - toLocal(position: Point, from: DisplayObject): Point; - touchend(e: InteractionData): void; - touchendoutside(e: InteractionData): void; - touchstart(e: InteractionData): void; - touchmove(e: InteractionData): void; + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _getCachedBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + //end extras.cacheAsBitmap + + protected _sr: number; + protected _cr: number; + protected _bounds: Rectangle; + protected _currentBounds: Rectangle; + protected _mask: Rectangle; + protected _cachedObject: any; + updateTransform(): void; + position: Point; + scale: Point; + pivot: Point; + rotation: number; + renderable: boolean; + alpha: number; + visible: boolean; + parent: Container; + worldAlpha: number; + worldTransform: Matrix; + filterArea: Rectangle; + + x: number; + y: number; + worldVisible: boolean; + mask: Graphics | Sprite; + filters: AbstractFilter[]; + name: string; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + toGlobal(position: Point): Point; + toLocal(position: Point, from?: DisplayObject): Point; + generateTexture(renderer: CanvasRenderer | WebGLRenderer, scaleMode: number, resolution: number): Texture; + destroy(): void; + getChildByName(name: string): DisplayObject; + getGlobalPosition(point: Point): Point; + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + } - export class DisplayObjectContainer extends DisplayObject { + export class Container extends DisplayObject { - constructor(); + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + + protected onChildrenChange: () => void; children: DisplayObject[]; - height: number; + width: number; + height: number; addChild(child: DisplayObject): DisplayObject; addChildAt(child: DisplayObject, index: number): DisplayObject; - getBounds(): Rectangle; - getChildAt(index: number): DisplayObject; + swapChildren(child: DisplayObject, child2: DisplayObject): void; getChildIndex(child: DisplayObject): number; - getLocalBounds(): Rectangle; + setChildIndex(child: DisplayObject, index: number): void; + getChildAt(index: number): DisplayObject; removeChild(child: DisplayObject): DisplayObject; removeChildAt(index: number): DisplayObject; removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - removeStageReference(): void; - setChildIndex(child: DisplayObject, index: number): void; - swapChildren(child: DisplayObject, child2: DisplayObject): void; + destroy(destroyChildren?: boolean): void; + generateTexture(renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer, resolution?: number, scaleMode?: number): Texture; + + renderWebGL(renderer: WebGLRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + + once(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + once(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; } - export class Ellipse implements HitArea { - - constructor(x: number, y: number, width: number, height: number); - - x: number; - y: number; - width: number; - height: number; - - clone(): Ellipse; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - - export class Event { - - constructor(target: any, name: string, data: any); - - target: any; - type: string; - data: any; - timeStamp: number; - - stopPropagation(): void; - preventDefault(): void; - stopImmediatePropagation(): void; - - } - - export class EventTarget { - - static mixin(obj: any): void; - - } - - export class FilterTexture { - - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: scaleModes); - - fragmentSrc: string[]; - frameBuffer: WebGLFramebuffer; - gl: WebGLRenderingContext; - program: WebGLProgram; - scaleMode: number; - texture: WebGLTexture; - - clear(): void; - resize(width: number, height: number): void; - destroy(): void; - - } + //graphics export class GraphicsData { - constructor(lineWidth?: number, lineColor?: number, lineAlpha?: number, fillColor?: number, fillAlpha?: number, fill?: boolean, shape?: any); + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: Circle | Rectangle | Ellipse | Polygon); lineWidth: number; lineColor: number; @@ -603,137 +253,75 @@ declare module PIXI { fillColor: number; fillAlpha: number; fill: boolean; - shape: any; + shape: Circle | Rectangle | Ellipse | Polygon; type: number; + clone(): GraphicsData; + + protected _lineTint: number; + protected _fillTint: number; + } + export class Graphics extends Container { - export class Graphics extends DisplayObjectContainer { + protected boundsDirty: boolean; + protected dirty: boolean; + protected glDirty: boolean; - static POLY: number; - static RECT: number; - static CIRC: number; - static ELIP: number; - static RREC: number; - - blendMode: number; - boundsPadding: number; fillAlpha: number; - isMask: boolean; lineWidth: number; lineColor: number; tint: number; - worldAlpha: number; + blendMode: number; + isMask: boolean; + boundsPadding: number; - arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean): Graphics; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - beginFill(color?: number, alpha?: number): Graphics; + clone(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + moveTo(x: number, y: number): Graphics; + lineTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; - clear(): Graphics; - destroyCachedSprite(): void; - drawCircle(x: number, y: number, radius: number): Graphics; - drawEllipse(x: number, y: number, width: number, height: number): Graphics; - drawPolygon(...path: any[]): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; + beginFill(color: number, alpha?: number): Graphics; + endFill(): Graphics; drawRect(x: number, y: number, width: number, height: number): Graphics; drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; - drawShape(shape: Circle): GraphicsData; - drawShape(shape: Rectangle): GraphicsData; - drawShape(shape: Ellipse): GraphicsData; - drawShape(shape: Polygon): GraphicsData; - endFill(): Graphics; - lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; - lineTo(x: number, y: number): Graphics; - moveTo(x: number, y: number): Graphics; - quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(path: number[]| Point[]): Graphics; + clear(): Graphics; + //todo + generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + updateLocalBounds(): void; + drawShape(shape: Circle | Rectangle | Ellipse | Polygon): GraphicsData; } - - export class GrayFilter extends AbstractFilter { - - gray: number; - + export interface GraphicsRenderer extends ObjectRenderer { + //yikes todo + } + export interface WebGLGraphicsData { + //yikes todo! } - export class ImageLoader implements Mixin { + //math - constructor(url: string, crossorigin?: boolean); + export class Point { - texture: Texture; + x: number; + y: number; - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; + constructor(x?: number, y?: number); - load(): void; - loadFramedSpriteSheet(frameWidth: number, frameHeight: number, textureName: string): void; + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; } - - export class InteractionData { - - global: Point; - target: Sprite; - originalEvent: Event; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - - export class InteractionManager { - - currentCursorStyle: string; - last: number; - mouse: InteractionData; - mouseOut: boolean; - mouseoverEnabled: boolean; - onMouseMove: Function; - onMouseDown: Function; - onMouseOut: Function; - onMouseUp: Function; - onTouchStart: Function; - onTouchEnd: Function; - onTouchMove: Function; - pool: InteractionData[]; - resolution: number; - stage: Stage; - touches: { [id: string]: InteractionData }; - - constructor(stage: Stage); - } - - export class InvertFilter extends AbstractFilter { - - invert: number; - - } - - export class JsonLoader implements Mixin { - - constructor(url: string, crossorigin?: boolean); - - baseUrl: string; - crossorigin: boolean; - loaded: boolean; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - export class Matrix { a: number; @@ -743,175 +331,60 @@ declare module PIXI { tx: number; ty: number; - append(matrix: Matrix): Matrix; - apply(pos: Point, newPos: Point): Point; - applyInverse(pos: Point, newPos: Point): Point; - determineMatrixArrayType(): number[]; - identity(): Matrix; - rotate(angle: number): Matrix; fromArray(array: number[]): void; + toArray(transpose?: boolean, out?: number[]): number[]; + apply(pos: Point, newPos?: Point): Point; + applyInverse(pos: Point, newPos?: Point): Point; translate(x: number, y: number): Matrix; - toArray(transpose: boolean): number[]; scale(x: number, y: number): Matrix; + rotate(angle: number): Matrix; + append(matrix: Matrix): Matrix; + prepend(matrix: Matrix): Matrix; + invert(): Matrix; + identity(): Matrix; + clone(): Matrix; + copy(matrix: Matrix): Matrix; + + static IDENTITY: Matrix; + static TEMP_MATRIX: Matrix; } - export interface Mixin { + export interface HitArea { - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; + contains(x: number, y: number): boolean; } - export class MovieClip extends Sprite { + export class Circle implements HitArea { - static fromFrames(frames: string[]): MovieClip; - static fromImages(images: HTMLImageElement[]): HTMLImageElement; - - constructor(textures: Texture[]); - - animationSpeed: number; - currentFrame: number; - loop: boolean; - playing: boolean; - textures: Texture[]; - totalFrames: number; - - gotoAndPlay(frameNumber: number): void; - gotoAndStop(frameNumber: number): void; - onComplete(): void; - play(): void; - stop(): void; - - } - - export class NoiseFilter extends AbstractFilter { - - noise: number; - - } - - export class NormalMapFilter extends AbstractFilter { - - map: Texture; - offset: Point; - scale: Point; - - } - - export class PixelateFilter extends AbstractFilter { - - size: number; - - } - - export interface IPixiShader { - - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class PixiShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - - attributes: ShaderAttribute[]; - defaultVertexSrc: string[]; - dirty: boolean; - firstRun: boolean; - textureCount: number; - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - initSampler2D(): void; - initUniforms(): void; - syncUniforms(): void; - - destroy(): void; - init(): void; - - } - - export class PixiFastShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - - textureCount: number; - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class PrimitiveShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class ComplexPrimitiveShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class StripShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class Point { - - constructor(x?: number, y?: number); + constructor(x?: number, y?: number, radius?: number); x: number; y: number; + radius: number; + type: number; - clone(): Point; - set(x: number, y: number): void; + clone(): Circle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; } + export class Ellipse implements HitArea { + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + clone(): Ellipse; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } export class Polygon implements HitArea { constructor(points: Point[]); @@ -919,13 +392,15 @@ declare module PIXI { constructor(...points: Point[]); constructor(...points: number[]); - points: any[]; //number[] Point[] + closed: boolean; + points: number[]; + type: number; clone(): Polygon; contains(x: number, y: number): boolean; - } + } export class Rectangle implements HitArea { constructor(x?: number, y?: number, width?: number, height?: number); @@ -934,32 +409,14 @@ declare module PIXI { y: number; width: number; height: number; + type: number; + + static EMPTY: Rectangle; clone(): Rectangle; contains(x: number, y: number): boolean; } - - export class RGBSplitFilter extends AbstractFilter { - - red: Point; - green: Point; - blue: Point; - - } - - export class Rope extends Strip { - - points: Point[]; - vertices: number[]; - - constructor(texture: Texture, points: Point[]); - - refresh(): void; - setTexture(texture: Texture): void; - - } - export class RoundedRectangle implements HitArea { constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); @@ -969,944 +426,1295 @@ declare module PIXI { width: number; height: number; radius: number; + type: number; - clone(): RoundedRectangle; + static EMPTY: Rectangle; + + clone(): Rectangle; contains(x: number, y: number): boolean; } - export class SepiaFilter extends AbstractFilter { + //particles - sepia: number; + export interface ParticleContainerProperties { + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; } + export class ParticleContainer extends Container { - export class SmartBlurFilter extends AbstractFilter { + constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); - blur: number; + protected _maxSize: number; + protected _batchSize: number; - } - - export class SpineLoader implements Mixin { - - url: string; - crossorigin: boolean; - loaded: boolean; - - constructor(url: string, crossOrigin: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class SpineTextureLoader { - - constructor(basePath: string, crossorigin: boolean); - - load(page: AtlasPage, file: string): void; - unload(texture: BaseTexture): void; - - } - - export class Sprite extends DisplayObjectContainer { - - static fromFrame(frameId: string): Sprite; - static fromImage(url: string, crossorigin?: boolean, scaleMode?: scaleModes): Sprite; - - constructor(texture: Texture); - - anchor: Point; - blendMode: blendModes; - shader: IPixiShader; - texture: Texture; - tint: number; - - setTexture(texture: Texture): void; - - } - - export class SpriteBatch extends DisplayObjectContainer { - - constructor(texture?: Texture); - - ready: boolean; - textureThing: Texture; - - initWebGL(gl: WebGLRenderingContext): void; - - } - - export class SpriteSheetLoader implements Mixin { - - constructor(url: string, crossorigin?: boolean); - - baseUrl: string; - crossorigin: boolean; - frames: any; - texture: Texture; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class Stage extends DisplayObjectContainer { - - constructor(backgroundColor: number); - - interactionManager: InteractionManager; - - getMousePosition(): Point; - setBackgroundColor(backgroundColor: number): void; - setInteractionDelegate(domElement: HTMLElement): void; - - } - - export class Strip extends DisplayObjectContainer { - - static DrawModes: { - - TRIANGLE_STRIP: number; - TRIANGLES: number; - - } - - constructor(texture: Texture); + protected onChildrenChange: () => void; + interactiveChildren: boolean; blendMode: number; - colors: number[]; - dirty: boolean; - indices: number[]; - canvasPadding: number; - texture: Texture; - uvs: number[]; - vertices: number[]; + roundPixels: boolean; - getBounds(matrix?: Matrix): Rectangle; + setProperties(properties: ParticleContainerProperties): void; + + } + export interface ParticleBuffer { + + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; + + initBuffers(): void; + bind(): void; + destroy(): void; + + } + export interface ParticleRenderer { + + } + export interface ParticleShader { } - export class Text extends Sprite { + //renderers - constructor(text: string, style?: TextStyle); + export interface RendererOptions { - static fontPropertiesCanvas: any; - static fontPropertiesContext: any; - static fontPropertiesCache: any; + view?: HTMLCanvasElement; + transparent?: boolean + antialias?: boolean; + resolution?: number; + clearBeforeRendering?: boolean; + preserveDrawingBuffer?: boolean; + forceFXAA?: boolean; + roundPixels?: boolean; + + } + export class SystemRenderer extends EventEmitter { + + protected _backgroundColor: number; + protected _backgroundColorRgb: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: any; + protected _lastObjectRendered: DisplayObject; + + constructor(system: string, width?: number, height?: number, options?: RendererOptions); + + type: number; + width: number; + height: number; + view: HTMLCanvasElement; + resolution: number; + transparent: boolean; + autoResize: boolean; + blendModes: any; //todo? + preserveDrawingBuffer: boolean; + clearBeforeRender: boolean; + backgroundColor: number; + + render(object: DisplayObject): void; + resize(width: number, height: number): void; + destroy(removeView?: boolean): void; + + } + export class CanvasRenderer extends SystemRenderer { + + protected renderDisplayObject(displayObject: DisplayObject, context: CanvasRenderingContext2D): void; + protected _mapBlendModes(): void; + + constructor(width?: number, height?: number, options?: RendererOptions); context: CanvasRenderingContext2D; - resolution: number; - - destroy(destroyTexture: boolean): void; - setStyle(style: TextStyle): void; - setText(text: string): void; - - } - - export class Texture implements Mixin { - - static emptyTexture: Texture; - - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): Texture; - static fromFrame(frameId: string): Texture; - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): Texture; - static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture; - - constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle); - - baseTexture: BaseTexture; - crop: Rectangle; - frame: Rectangle; - height: number; - noFrame: boolean; - requiresUpdate: boolean; - trim: Point; - width: number; - scope: any; - valid: boolean; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - destroy(destroyBase: boolean): void; - setFrame(frame: Rectangle): void; - - } - - export class TilingSprite extends Sprite { - - constructor(texture: Texture, width: number, height: number); - - blendMode: number; - texture: Texture; - tint: number; - tilePosition: Point; - tileScale: Point; - tileScaleOffset: Point; - - destroy(): void; - generateTilingTexture(forcePowerOfTwo?: boolean): void; - setTexture(texture: Texture): void; - - } - - export class TiltShiftFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - } - - export class TiltShiftXFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - - export class TiltShiftYFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - - export class TwistFilter extends AbstractFilter { - - angle: number; - offset: Point; - radius: number; - - } - - export class VideoTexture extends BaseTexture { - - static baseTextureFromVideo(video: HTMLVideoElement, scaleMode: number): BaseTexture; - static textureFromVideo(video: HTMLVideoElement, scaleMode: number): Texture; - static fromUrl(videoSrc: string, scaleMode: number): Texture; - - autoUpdate: boolean; - - destroy(): void; - updateBound(): void; - onPlayStart(): void; - onPlayStop(): void; - onCanPlay(): void; - - } - - export class WebGLBlendModeManager { - + refresh: boolean; + maskManager: CanvasMaskManager; + roundPixels: boolean; + currentScaleMode: number; currentBlendMode: number; + smoothProperty: string; - destroy(): void; - setBlendMode(blendMode: number): boolean; - setContext(gl: WebGLRenderingContext): void; + render(object: DisplayObject): void; + resize(w: number, h: number): void; } + export class CanvasBuffer { - export class WebGLFastSpriteBatch { + protected clear(): void; - constructor(gl: CanvasRenderingContext2D); + constructor(width: number, height: number); - currentBatchSize: number; - currentBaseTexture: BaseTexture; - currentBlendMode: number; - renderSession: RenderSession; - drawing: boolean; - indexBuffer: any; - indices: number[]; - lastIndexCount: number; - matrix: Matrix; - maxSize: number; - shader: IPixiShader; - size: number; - vertexBuffer: any; - vertices: number[]; - vertSize: number; + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; - end(): void; - begin(spriteBatch: SpriteBatch, renderSession: RenderSession): void; - destroy(removeView?: boolean): void; - flush(): void; - render(spriteBatch: SpriteBatch): void; - renderSprite(sprite: Sprite): void; - setContext(gl: WebGLRenderingContext): void; - start(): void; - stop(): void; - - } - - export class WebGLFilterManager { - - filterStack: AbstractFilter[]; - transparent: boolean; - offsetX: number; - offsetY: number; - - applyFilterPass(filter: AbstractFilter, filterArea: Texture, width: number, height: number): void; - begin(renderSession: RenderSession, buffer: ArrayBuffer): void; - destroy(): void; - initShaderBuffers(): void; - popFilter(): void; - pushFilter(filterBlock: FilterBlock): void; - setContext(gl: WebGLRenderingContext): void; - - } - - export class WebGLGraphics { - - static graphicsDataPool: any[]; - - static renderGraphics(graphics: Graphics, renderRession: RenderSession): void; - static updateGraphics(graphics: Graphics, gl: WebGLRenderingContext): void; - static switchMode(webGL: WebGLRenderingContext, type: number): any; //WebGLData - static buildRectangle(graphicsData: GraphicsData, webGLData: any): void; - static buildRoundedRectangle(graphicsData: GraphicsData, webGLData: any): void; - static quadraticBezierCurve(fromX: number, fromY: number, cpX: number, cpY: number, toX: number, toY: number): number[]; - static buildCircle(graphicsData: GraphicsData, webGLData: any): void; - static buildLine(graphicsData: GraphicsData, webGLData: any): void; - static buildComplexPoly(graphicsData: GraphicsData, webGLData: any): void; - static buildPoly(graphicsData: GraphicsData, webGLData: any): boolean; - - reset(): void; - upload(): void; - - } - - export class WebGLGraphicsData { - - constructor(gl: WebGLRenderingContext); - - gl: WebGLRenderingContext; - glPoints: any[]; - color: number[]; - points: any[]; - indices: any[]; - buffer: WebGLBuffer; - indexBuffer: WebGLBuffer; - mode: number; - alpha: number; - dirty: boolean; - - reset(): void; - upload(): void; - - } - - export class WebGLMaskManager { - - destroy(): void; - popMask(renderSession: RenderSession): void; - pushMask(maskData: any[], renderSession: RenderSession): void; - setContext(gl: WebGLRenderingContext): void; - - } - - export class WebGLRenderer implements PixiRenderer { - - static createWebGLTexture(texture: Texture, gl: WebGLRenderingContext): void; - - constructor(width?: number, height?: number, options?: PixiRendererOptions); - - autoResize: boolean; - clearBeforeRender: boolean; - contextLost: boolean; - contextLostBound: Function; - contextRestoreLost: boolean; - contextRestoredBound: Function; - height: number; - gl: WebGLRenderingContext; - offset: Point; - preserveDrawingBuffer: boolean; - projection: Point; - resolution: number; - renderSession: RenderSession; - shaderManager: WebGLShaderManager; - spriteBatch: WebGLSpriteBatch; - maskManager: WebGLMaskManager; - filterManager: WebGLFilterManager; - stencilManager: WebGLStencilManager; - blendModeManager: WebGLBlendModeManager; - transparent: boolean; - type: number; - view: HTMLCanvasElement; width: number; + height: number; - destroy(): void; - initContext(): void; - mapBlendModes(): void; - render(stage: Stage): void; - renderDisplayObject(displayObject: DisplayObject, projection: Point, buffer: WebGLBuffer): void; resize(width: number, height: number): void; - updateTexture(texture: Texture): void; + destroy(): void; + + } + export class CanvasGraphics { + + static renderGraphicsMask(graphics: Graphics, context: CanvasRenderingContext2D): void; + static updateGraphicsTint(graphics: Graphics): void; + + static renderGraphics(graphics: Graphics, context: CanvasRenderingContext2D): void; + + } + export class CanvasMaskManager { + + pushMask(maskData: any, renderer: WebGLRenderer | CanvasRenderer): void; + popMask(renderer: WebGLRenderer | CanvasRenderer): void; + destroy(): void; + + } + export class CanvasTinter { + + static getTintedTexture(sprite: DisplayObject, color: number): HTMLCanvasElement; + static tintWithMultiply(texture: Texture, color: number, canvas: HTMLDivElement): void; + static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static roundColor(color: number): number; + static cacheStepsPerColorChannel: number; + static convertTintToImage: boolean; + static vanUseMultiply: boolean; + static tintMethod: Function; + + } + export class WebGLRenderer extends SystemRenderer { + + protected _useFXAA: boolean; + protected _FXAAFilter: filters.FXAAFilter; + protected _contextOptions: { + alpha: boolean; + antiAlias: boolean; + premultipliedAlpha: boolean; + stencil: boolean; + preseveDrawingBuffer: boolean; + } + protected _renderTargetStack: RenderTarget[]; + + protected _initContext(): void; + protected _createContext(): void; + protected handleContextLost: (event: WebGLContextEvent) => void; + protected _mapGlModes(): void; + + constructor(width?: number, height?: number, options?: RendererOptions); + + drawCount: number; + shaderManager: ShaderManager; + maskManager: MaskManager; + stencilManager: StencilManager; + filterManager: FilterManager; + blendModeManager: BlendModeManager; + currentRenderTarget: RenderTarget; + currentRenderer: ObjectRenderer; + + render(object: DisplayObject): void; + renderDisplayObject(displayObject: DisplayObject, renderTarget: RenderTarget, clear: boolean): void; + setObjectRenderer(objectRenderer: ObjectRenderer): void; + setRenderTarget(renderTarget: RenderTarget): void; + updateTexture(texture: BaseTexture | Texture): BaseTexture | Texture; + destroyTexture(texture: BaseTexture | Texture): void; + + } + export class AbstractFilter { + + protected vertexSrc: string[]; + protected fragmentSrc: string[]; + + constructor(vertexSrc?: string | string[], fragmentSrc?: string | string[], uniforms?: any); + + uniforms: any; + + padding: number; + + getShader(renderer: WebGLRenderer): Shader; + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + syncUniform(uniform: WebGLUniformLocation): void; + + } + export class SpriteMaskFilter extends AbstractFilter { + + constructor(sprite: Sprite); + + maskSprite: Sprite; + maskMatrix: Matrix; + + applyFilter(renderer: WebGLRenderbuffer, input: RenderTarget, output: RenderTarget): void; + map: Texture; + offset: Point; + + } + export class BlendModeManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + setBlendMode(blendMode: number): boolean; } - export class WebGLShaderManager { + export class FilterManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + filterStack: any[]; + renderer: WebGLRenderer; + texturePool: any[]; + + onContextChange: () => void; + setFilterStack(filterStack: any[]): void; + pushFilter(target: RenderTarget, filters: any[]): void; + popFilter(): AbstractFilter; + getRenderTarget(clear?: boolean): RenderTarget; + protected returnRenderTarget(renderTarget: RenderTarget): void; + applyFilter(shader: Shader, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + calculateMappedMatrix(filterArea: Rectangle, sprite: Sprite, outputMatrix?: Matrix): Matrix; + capFilterArea(filterArea: Rectangle): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export class MaskManager extends WebGLManager { + + stencilStack: StencilMaskStack; + reverse: boolean; + count: number; + alphaMaskPool: any[]; + + pushMask(target: RenderTarget, maskData: any): void; + popMask(target: RenderTarget, maskData: any): void; + pushSpriteMask(target: RenderTarget, maskData: any): void; + popSpriteMask(): void; + pushStencilMask(target: RenderTarget, maskData: any): void; + popStencilMask(target: RenderTarget, maskData: any): void; + + } + export class ShaderManager extends WebGLManager { + + protected _currentId: number; + protected currentShader: Shader; + + constructor(renderer: WebGLRenderer); maxAttibs: number; attribState: any[]; - stack: any[]; tempAttribState: any[]; + stack: any[]; + setAttribs(attribs: any[]): void; + setShader(shader: Shader): boolean; destroy(): void; - setAttribs(attribs: ShaderAttribute[]): void; - setContext(gl: WebGLRenderingContext): void; - setShader(shader: IPixiShader): boolean; } + export class StencilManager extends WebGLManager { - export class WebGLStencilManager { + constructor(renderer: WebGLRenderer); + + setMaskStack(stencilMaskStack: StencilMaskStack): void; + pushStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + bindGraphics(graphics: Graphics, webGLData: WebGLGraphicsData): void; + popStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + destroy(): void; + pushMask(maskData: any[]): void; + popMask(maskData: any[]): void; + + } + export class WebGLManager { + + protected onContextChange: () => void; + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + + destroy(): void; + + } + export class Shader { + + protected attributes: any; + protected textureCount: number; + protected uniforms: any; + + protected _glCompile(type: any, src: any): Shader; + + constructor(shaderManager: ShaderManager, vertexSrc: string, fragmentSrc: string, uniforms: any, attributes: any); + + uuid: number; + gl: WebGLRenderingContext; + shaderManager: ShaderManager; + program: WebGLProgram; + vertexSrc: string; + fragmentSrc: string; + + init(): void; + cachUniformLocations(keys: string): void; + cacheAttributeLocations(keys: string): void; + compile(): WebGLProgram; + syncUniform(uniform: any): void; + syncUniforms(): void; + initSampler2D(uniform: any): void; + destroy(): void; + + } + export class ComplexPrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class PrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class TextureShader extends Shader { + + constructor(shaderManager: ShaderManager, vertexSrc?: string, fragmentSrc?: string, customUniforms?: any, customAttributes?: any); + + } + export interface StencilMaskStack { stencilStack: any[]; reverse: boolean; count: number; - bindGraphics(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - destroy(): void; - popStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - pushStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - setContext(gl: WebGLRenderingContext): void; - } + export class ObjectRenderer extends WebGLManager { - export class WebGLSpriteBatch { - - blendModes: number[]; - colors: number[]; - currentBatchSize: number; - currentBaseTexture: Texture; - defaultShader: AbstractFilter; - dirty: boolean; - drawing: boolean; - indices: number[]; - lastIndexCount: number; - positions: number[]; - textures: Texture[]; - shaders: IPixiShader[]; - size: number; - sprites: any[]; //todo Sprite[]? - vertices: number[]; - vertSize: number; - - begin(renderSession: RenderSession): void; - destroy(): void; - end(): void; - flush(shader?: IPixiShader): void; - render(sprite: Sprite): void; - renderBatch(texture: Texture, size: number, startIndex: number): void; - renderTilingSprite(sprite: TilingSprite): void; - setBlendMode(blendMode: blendModes): void; - setContext(gl: WebGLRenderingContext): void; start(): void; stop(): void; + flush(): void; + render(object?: any): void; + + } + export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root: boolean); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + texture: Texture; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + stencilBuffer: WebGLRenderbuffer; + stencilMaskStack: StencilMaskStack; + filterStack: any[]; + scaleMode: number; + root: boolean; + + clear(bind?: boolean): void; + attachStencilBuffer(): void; + activate(): void; + calculateProjection(protectionFrame: Matrix): void; + resize(width: number, height: number): void; + destroy(): void; + + } + export interface Quad { + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + colors: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + + map(rect: Rectangle, rect2: Rectangle): void; + upload(): void; } + //sprites + + export class Sprite extends Container { + + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + protected _texture: Texture; + protected _width: number; + protected _height: number; + protected cachedTint: number; + + protected _onTextureUpdate(): void; + + constructor(texture?: Texture); + + anchor: Point; + tint: number; + blendMode: number; + shader: Shader; + texture: Texture; + + width: number; + height: number; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + containsPoint(point: Point): boolean; + destroy(destroyTexture?: boolean, destroyBaseTexture?: boolean): void; + + } + export class SpriteRenderer extends ObjectRenderer { + + protected renderBatch(texture: Texture, size: number, startIndex: number): void; + + vertSize: number; + vertByteSize: number; + size: number; + vertices: number[]; + positions: number[]; + colors: number[]; + indices: number[]; + currentBatchSize: number; + sprites: Sprite[]; + shader: Shader; + + render(sprite: Sprite): void; + flush(): void; + start(): void; + destroy(): void; + + } + + //text + + export interface TextStyle { + + font?: string; + fill?: string | number; + align?: string; + stroke?: string | number; + strokeThickness?: number; + wordWrap?: boolean; + wordWrapWidth?: number; + lineHeight?: number; + dropShadow?: boolean; + dropShadowColor?: string | number; + dropShadowAngle?: number; + dropShadowDistance?: number; + padding?: number; + textBaseline?: string; + lineJoin?: string; + miterLimit?: number; + + } + export class Text extends Sprite { + + static fontPropertiesCache: any; + static fontPropertiesCanvas: HTMLCanvasElement; + static fontPropertiesContext: CanvasRenderingContext2D; + + protected _text: string; + protected _style: TextStyle; + + protected updateText(): void; + protected updateTexture(): void; + protected determineFontProperties(fontStyle: TextStyle): TextStyle; + protected wordWrap(text: string): boolean; + + constructor(text?: string, style?: TextStyle, resolution?: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + dirty: boolean; + resolution: number; + text: string; + style: TextStyle; + + width: number; + height: number; + + } + + //textures + + export class BaseTexture extends EventEmitter { + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + + protected _glTextures: any[]; + + protected _sourceLoaded(): void; + + constructor(source: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); + + uuid: number; + resolution: number; + width: number; + height: number; + realWidth: number; + realHeight: number; + scaleMode: number; + hasLoaded: boolean; + isLoading: boolean; + source: HTMLImageElement | HTMLCanvasElement; + premultipliedAlpha: boolean; + imageUrl: string; + isPowerOfTwo: boolean; + mipmap: boolean; + + update(): void; + loadSource(source: HTMLImageElement | HTMLCanvasElement): void; + destroy(): void; + dispose(): void; + updateSourceImage(newSrc: string): void; + + on(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + } export class RenderTexture extends Texture { - constructor(width?: number, height?: number, renderer?: PixiRenderer, scaleMode?: scaleModes, resolution?: number); + protected renderWebGL(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + protected renderCanvas(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - frame: Rectangle; - baseTexture: BaseTexture; - renderer: PixiRenderer; + constructor(renderer: CanvasRenderer | WebGLRenderer, width?: number, height?: number, scaleMode?: number, resolution?: number); + + width: number; + height: number; resolution: number; + renderer: CanvasRenderer | WebGLRenderer; valid: boolean; + render(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + resize(width: number, height: number, updateBase?: boolean): void; clear(): void; + destroy(): void; + getImage(): HTMLImageElement; + getPixels(): number[]; + getPixel(x: number, y: number): number[]; getBase64(): string; getCanvas(): HTMLCanvasElement; - getImage(): HTMLImageElement; - resize(width: number, height: number, updateBase: boolean): void; - render(displayObject: DisplayObject, position?: Point, clear?: boolean): void; } - - //SPINE - - export class BoneData { - - constructor(name: string, parent?: any); - - name: string; - parent: any; - length: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - - } - - export class SlotData { - - constructor(name: string, boneData: BoneData); - - name: string; - boneData: BoneData; - r: number; - g: number; - b: number; - a: number; - attachmentName: string; - - } - - export class Bone { - - constructor(boneData: BoneData, parent?: any); - - data: BoneData; - parent: any; - yDown: boolean; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - worldRotation: number; - worldScaleX: number; - worldScaleY: number; - - updateWorldTransform(flipX: boolean, flip: boolean): void; - setToSetupPose(): void; - - } - - export class Slot { - - constructor(slotData: SlotData, skeleton: Skeleton, bone: Bone); - - data: SlotData; - skeleton: Skeleton; - bone: Bone; - r: number; - g: number; - b: number; - a: number; - attachment: RegionAttachment; - setAttachment(attachment: RegionAttachment): void; - setAttachmentTime(time: number): void; - getAttachmentTime(): number; - setToSetupPose(): void; - - } - - export class Skin { - - constructor(name: string); - - name: string; - attachments: any; - - addAttachment(slotIndex: number, name: string, attachment: RegionAttachment): void; - getAttachment(slotIndex: number, name: string): void; - - } - - export class Animation { - - constructor(name: string, timelines: ISpineTimeline[], duration: number); - - name: string; - timelines: ISpineTimeline[]; - duration: number; - apply(skeleton: Skeleton, time: number, loop: boolean): void; - min(skeleton: Skeleton, time: number, loop: boolean, alpha: number): void; - - } - - export class Curves { - - constructor(frameCount: number); - - curves: number[]; - - setLinear(frameIndex: number): void; - setStepped(frameIndex: number): void; - setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; - getCurvePercent(frameIndex: number, percent: number): number; - - } - - export interface ISpineTimeline { - - curves: Curves; - frames: number[]; - - getFrameCount(): number; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class RotateTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, angle: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class TranslateTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class ScaleTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class ColorTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class AttachmentTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - attachmentNames: string[]; - slotIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, attachmentName: string): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class SkeletonData { - - bones: Bone[]; - slots: Slot[]; - skins: Skin[]; - animations: Animation[]; - defaultSkin: Skin; - - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - findSkin(skinName: string): Skin; - findAnimation(animationName: string): Animation; - - } - - export class Skeleton { - - constructor(skeletonData: SkeletonData); - - data: SkeletonData; - bones: Bone[]; - slots: Slot[]; - drawOrder: any[]; - x: number; - y: number; - skin: Skin; - r: number; - g: number; - b: number; - a: number; - time: number; - flipX: boolean; - flipY: boolean; - - updateWorldTransform(): void; - setToSetupPose(): void; - setBonesToSetupPose(): void; - setSlotsToSetupPose(): void; - getRootBone(): Bone; - findBone(boneName: string): Bone; - fineBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - setSkinByName(skinName: string): void; - setSkin(newSkin: Skin): void; - getAttachmentBySlotName(slotName: string, attachmentName: string): RegionAttachment; - getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): RegionAttachment; - setAttachment(slotName: string, attachmentName: string): void; - update(data: number): void; - - } - - export class RegionAttachment { - - offset: number[]; - uvs: number[]; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; + export class Texture extends BaseTexture { + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number): Texture; + static fromFrame(frameId: string): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; + static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + static EMPTY: Texture; + + protected _frame: Rectangle; + protected _uvs: TextureUvs; + + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected _updateUvs(): void; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle, rotate?: boolean); + + noFrame: boolean; + baseTexture: BaseTexture; + trim: Rectangle; + valid: boolean; + requiresUpdate: boolean; width: number; height: number; - rendererObject: any; - regionOffsetX: number; - regionOffsetY: number; - regionWidth: number; - regionHeight: number; - regionOriginalWidth: number; - regionOriginalHeight: number; - - setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; - updateOffset(): void; - computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; - - } - - export class AnimationStateData { - - constructor(skeletonData: SkeletonData); - - skeletonData: SkeletonData; - animationToMixTime: any; - defaultMix: number; - - setMixByName(fromName: string, toName: string, duration: number): void; - setMix(from: string, to: string): number; - - } - - export class AnimationState { - - constructor(stateData: any); - - animationSpeed: number; - current: any; - previous: any; - currentTime: number; - previousTime: number; - currentLoop: boolean; - previousLoop: boolean; - mixTime: number; - mixDuration: number; - queue: Animation[]; - - update(delta: number): void; - apply(skeleton: any): void; - clearAnimation(): void; - setAnimation(animation: any, loop: boolean): void; - setAnimationByName(animationName: string, loop: boolean): void; - addAnimationByName(animationName: string, loop: boolean, delay: number): void; - addAnimation(animation: any, loop: boolean, delay: number): void; - isComplete(): number; - - } - - export class SkeletonJson { - - constructor(attachmentLoader: AtlasAttachmentLoader); - - attachmentLoader: AtlasAttachmentLoader; - scale: number; - - readSkeletonData(root: any): SkeletonData; - readAttachment(skin: Skin, name: string, map: any): RegionAttachment; - readAnimation(name: string, map: any, skeletonData: SkeletonData): void; - readCurve(timeline: ISpineTimeline, frameIndex: number, valueMap: any): void; - toColor(hexString: string, colorIndex: number): number; - - } - - export class Atlas { - - static FORMAT: { - - alpha: number; - intensity: number; - luminanceAlpha: number; - rgb565: number; - rgba4444: number; - rgb888: number; - rgba8888: number; - - } - - static TextureFilter: { - - nearest: number; - linear: number; - mipMap: number; - mipMapNearestNearest: number; - mipMapLinearNearest: number; - mipMapNearestLinear: number; - mipMapLinearLinear: number; - - } - - static textureWrap: { - - mirroredRepeat: number; - clampToEdge: number; - repeat: number; - - } - - constructor(atlasText: string, textureLoader: AtlasLoader); - - textureLoader: AtlasLoader; - pages: AtlasPage[]; - regions: AtlasRegion[]; - - findRegion(name: string): AtlasRegion; - dispose(): void; - updateUVs(page: AtlasPage): void; - - } - - export class AtlasPage { - - name: string; - format: number; - minFilter: number; - magFilter: number; - uWrap: number; - vWrap: number; - rendererObject: any; - width: number; - height: number; - - } - - export class AtlasRegion { - - page: AtlasPage; - name: string; - x: number; - y: number; - width: number; - height: number; - u: number; - v: number; - u2: number; - v2: number; - offsetX: number; - offsetY: number; - originalWidth: number; - originalHeight: number; - index: number; + crop: Rectangle; rotate: boolean; - splits: any[]; - pads: any[]; + + frame: Rectangle; + + update(): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; } + export class TextureUvs { - export class AtlasReader { + x0: number; + y0: number; + x1: number; + y1: number; + x2: number; + y2: number; + x3: number; + y3: number; - constructor(text: string); - - lines: string[]; - index: number; - - trim(value: string): string; - readLine(): string; - readValue(): string; - readTuple(tuple: number): number; + set(frame: Rectangle, baseFrame: Rectangle, rotate: boolean): void; } + export class VideoBaseTexture extends BaseTexture { - export class AtlasAttachmentLoader { + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[]| any[]): VideoBaseTexture; - constructor(atlas: Atlas); + protected _loaded: boolean; - atlas: Atlas; + protected _onUpdate(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; + protected _onCanPlay(): void; - newAttachment(skin: Skin, type: number, name: string): RegionAttachment; - - } - - export class Spine extends DisplayObjectContainer { - - constructor(url: string); + constructor(source: HTMLVideoElement, scaleMode?: number); autoUpdate: boolean; - spineData: any; - skeleton: Skeleton; - stateData: AnimationStateData; - state: AnimationState; - slotContainers: DisplayObjectContainer[]; - createSprite(slot: Slot, descriptor: { name: string }): Sprite[]; - update(dt: number): void; + destroy(): void; } + //utils + + export class utils { + + static uuid(): number; + static hex2rgb(hex: number, out?: number[]): number[]; + static hex2String(hex: number): string; + static rbg2hex(rgb: Number[]): number; + static canUseNewCanvasBlendModel(): boolean; + static getNextPowerOfTwo(number: number): number; + static isPowerOfTwo(width: number, height: number): boolean; + static getResolutionOfUrl(url: string): boolean; + static sayHello(type: string): void; + static isWebGLSupported(): boolean; + static sign(n: number): number; + static TextureCache: any; + static BaseTextureCache: any; + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRAS//////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module extras { + + export interface BitmapTextStyle { + + font?: string | { + + name?: string; + size?: number; + + }; + align?: string; + tint?: number; + + } + export class BitmapText extends Container { + + static fonts: any; + + protected _glyphs: Sprite[]; + protected _font: string | { + tint: number; + align: string; + name: string; + size: number; + } + protected _text: string; + + protected updateText(): void; + + constructor(text: string, style?: BitmapTextStyle); + + textWidth: number; + textHeight: number; + maxWidth: number; + dirty: boolean; + + tint: number; + align: string; + font: string | { + tint: number; + align: string; + name: string; + size: number; + } + text: string; + + } + export class MovieClip extends Sprite { + + static fromFrames(frame: string[]): MovieClip; + static fromImages(images: string[]): MovieClip; + + protected _textures: Texture; + protected _currentTime: number; + + protected update(deltaTime: number): void; + + constructor(textures: Texture[]); + + animationSpeed: number; + loop: boolean; + onComplete: () => void; + currentFrame: number; + playing: boolean; + + totalFrames: number; + textures: Texture[]; + + stop(): void; + play(): void; + gotoAndStop(frameName: number): void; + gotoAndPlay(frameName: number): void; + destroy(): void; + + } + export class TilingSprite extends Sprite { + + //This is really unclean but is the only way :( + //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 + //Thanks bas! + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + protected _tileScaleOffset: Point; + protected _tilingTexture: boolean; + protected _refreshTexture: boolean; + protected _uvs: TextureUvs[]; + + constructor(texture: Texture, width: number, height: number); + + tileScale: Point; + tilePosition: Point; + + width: number; + height: number; + originalTexture: Texture; + + getBounds(): Rectangle; + generateTilingTexture(renderer: WebGLRenderer | CanvasRenderer, texture: Texture, forcePowerOfTwo?: boolean): Texture; + containsPoint(point: Point): boolean; + destroy(): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FILTERS//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + module filters { + + export class AsciiFilter extends AbstractFilter { + size: number; + } + export class BloomFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + + } + export class BlurFilter extends AbstractFilter { + + protected blurXFilter: BlurXFilter; + protected blurYFilter: BlurYFilter; + + blur: number; + passes: number; + blurX: number; + blurY: number; + + } + export class BlurXFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class BlurYFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class SmartBlurFilter extends AbstractFilter { + + } + export class ColorMatrixFilter extends AbstractFilter { + + protected _loadMatrix(matrix: number[], multiply: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; + + matrix: number[]; + + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class ColorStepFilter extends AbstractFilter { + + step: number; + + } + export class ConvolutionFilter extends AbstractFilter { + + constructor(matrix: number[], width: number, height: number); + + matrix: number[]; + width: number; + height: number; + + } + export class CrossHatchFilter extends AbstractFilter { + + } + export class DisplacementFilter extends AbstractFilter { + + constructor(sprite: Sprite, scale?: number); + + map: Texture; + + scale: Point; + + } + export class DotScreenFilter extends AbstractFilter { + + scale: number; + angle: number; + + } + export class BlurYTintFilter extends AbstractFilter { + + blur: number; + + } + export class DropShadowFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + color: number; + alpha: number; + distance: number; + angle: number; + + } + export class GrayFilter extends AbstractFilter { + + gray: number; + + } + export class InvertFilter extends AbstractFilter { + + invert: number; + + } + export class NoiseFilter extends AbstractFilter { + + noise: number; + + } + export class PixelateFilter extends AbstractFilter { + + size: Point; + + } + export class RGBSplitFilter extends AbstractFilter { + + red: number; + green: number; + blue: number; + + } + export class SepiaFilter extends AbstractFilter { + + sepia: number; + + } + export class ShockwaveFilter extends AbstractFilter { + + center: number[]; + params: any; + time: number; + + } + export class TiltShiftAxisFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + + } + export class TiltShiftFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + } + export class TiltShiftXFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TiltShiftYFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TwistFilter extends AbstractFilter { + + offset: Point; + radius: number; + angle: number; + + } + export class FXAAFilter extends AbstractFilter { + + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////INTERACTION/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module interaction { + + export interface InteractionEvent { + + stopped: boolean; + target: any; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + + export class InteractionData { + + global: Point; + target: DisplayObject; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + + export class InteractionManager { + + protected interactionDOMElement: HTMLElement; + protected eventsAdded: boolean; + protected _tempPoint: Point; + + protected setTargetElement(element: HTMLElement, resolution: number): void; + protected addEvents(): void; + protected removeEvents(): void; + protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; + protected onMouseDown: (event: Event) => void; + protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseUp: (event: Event) => void; + protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseMove: (event: Event) => void; + protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOut: (event: Event) => void; + protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchStart: (event: Event) => void; + protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; + protected onTouchEnd: (event: Event) => void; + protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchMove: (event: Event) => void; + protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; + protected getTouchData(touchEvent: InteractionData): InteractionData; + protected returnTouchData(touchData: InteractionData): void; + + constructor(renderer: CanvasRenderer | WebGLRenderer, options?: { autoPreventDefault?: boolean; interactionFrequence?: number; }); + + renderer: CanvasRenderer | WebGLRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + eventData: { + stopped: boolean; + target: any; + type: any; + data: InteractionData; + }; + interactiveDataPool: InteractionData[]; + last: number; + currentCursorStyle: string; + resolution: number; + update(deltaTime: number): void; + + mapPositionToPoint(point: Point, x: number, y: number): void; + processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; + destroy(): void; + + } + + export interface InteractiveTarget { + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////LOADER///////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + //https://github.com/englercj/resource-loader/blob/master/src/Loader.js + + export module loaders { + export interface LoaderOptions { + + crossOrigin?: boolean; + loadType?: number; + xhrType?: string; + + } + export class Loader extends EventEmitter { + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + resources: Resource[]; + + add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; + add(url: string, options?: LoaderOptions, cb?: () => void): Loader; + //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; + + on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + on(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + once(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + before(fn: Function): Loader; + pre(fn: Function): Loader; + + after(fn: Function): Loader; + use(fn: Function): Loader; + + reset(): void; + + load(cb?: (loader: loaders.Loader, object: any) => void): Loader; + + } + export class Resource extends EventEmitter { + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_READ_STATE: { + UNSENT: number; + OPENED: number; + HEADERS_RECIEVED: number; + LOADING: number; + DONE: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: number; + BUFFER: number; + BLOB: number; + DOCUMENT: number; + JSON: number; + TEXT: number; + }; + + constructor(name?: string, url?: string | string[], options?: LoaderOptions); + + name: string; + texture: Texture; + url: string; + data: any; + crossOrigin: string; + loadType: number; + xhrType: string; + error: Error; + xhr: XMLHttpRequest; + + complete(): void; + load(cb?: () => void): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MESH/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module mesh { + + export class Mesh extends Container { + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + } + + constructor(texture: Texture, vertices?: number[], uvs?: number[], indices?: number[], drawMode?: number); + + texture: Texture; + uvs: number[]; + vertices: number[]; + indices: number[]; + dirty: boolean; + blendMode: number; + canvasPadding: number; + drawMode: number; + + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + + protected _texture: Texture; + + protected _renderCanvasTriangleMesh(context: CanvasRenderingContext2D): void; + protected _renderCanvasTriangles(context: CanvasRenderingContext2D): void; + protected _renderCanvasDrawTriangle(context: CanvasRenderingContext2D, vertices: number, uvs: number, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(Mesh: Mesh): void; + protected _onTextureUpdate(): void; + + } + export class Rope extends Mesh { + + protected _ready: boolean; + + protected getTextureUvs(): TextureUvs; + + constructor(texture: Texture, points: Point[]); + + points: Point[]; + colors: number[]; + + refresh(): void; + + } + + export class MeshRenderer extends ObjectRenderer { + + protected _initWebGL(mesh: Mesh): void; + + indices: number[]; + + constructor(renderer: WebGLRenderer); + + render(mesh: Mesh): void; + flush(): void; + start(): void; + destroy(): void; + + } + + export interface MeshShader extends Shader { } + + } + + module ticker { + + export var shared: Ticker; + + export class Ticker { + + protected _tick(time: number): void; + protected _emitter: EventEmitter; + protected _requestId: number; + protected _maxElapsedMS: number; + + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; + + autoStart: boolean; + deltaTime: number; + elapsedMS: number; + lastTime: number; + speed: number; + started: boolean; + + FPS: number; + minFPS: number; + + add(fn: (deltaTime: number) => void, context?: any): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; + remove(fn: (deltaTime: number) => void, context?: any): Ticker; + start(): void; + stop(): void; + update(): void; + + } + + } } -declare function requestAnimFrame(callback: Function): void; - -declare module PIXI.PolyK { - export function Triangulate(p: number[]): number[]; +declare module 'pixi.js' { + export = PIXI; } \ No newline at end of file diff --git a/pixi.js/pixi.js.d.ts.tscparams b/pixi.js/pixi.js.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/pixi.js/pixi.js.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - From 95fe96133fdb83bb295e5ee6a27725dd5a91e725 Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:43:34 +0200 Subject: [PATCH 125/419] Added definitions for the "Pixi.js plugin that enables Spine support." --- pixi-spine/pixi-spine-tests.ts | 312 +++++++++++++ pixi-spine/pixi-spine.d.ts | 812 +++++++++++++++++++++++++++++++++ 2 files changed, 1124 insertions(+) create mode 100644 pixi-spine/pixi-spine-tests.ts create mode 100644 pixi-spine/pixi-spine.d.ts diff --git a/pixi-spine/pixi-spine-tests.ts b/pixi-spine/pixi-spine-tests.ts new file mode 100644 index 000000000..71ecf3147 --- /dev/null +++ b/pixi-spine/pixi-spine-tests.ts @@ -0,0 +1,312 @@ +/// +/// + +module Spine { + + export class Dragon { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private dragon: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader.add('dragon', '../../_assets/spine/dragon.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.dragon = new PIXI.spine.Spine(res.dragon.spineData); + this.dragon.skeleton.setToSetupPose(); + this.dragon.update(0); + this.dragon.autoUpdate = false; + + //create a container for the spin animation and add the animation to it + var dragonCage: PIXI.Container = new PIXI.Container(); + dragonCage.addChild(this.dragon); + + // measure the spine animation and position it inside its container to align it to the origin + var localRect: PIXI.Rectangle = this.dragon.getLocalBounds(); + this.dragon.position.set(-localRect.x, -localRect.y); + + // now we can scale, position and rotate the container as any other display object + var scale = Math.min((this.renderer.width * 0.7) / dragonCage.width, (this.renderer.height * 0.7) / dragonCage.height); + dragonCage.scale.set(scale, scale); + dragonCage.position.set((this.renderer.width - dragonCage.width) * 0.5, (this.renderer.height - dragonCage.height) * 0.5); + + // add the container to the stage + this.stage.addChild(dragonCage); + + // once position and scaled, set the animation to play + this.dragon.state.setAnimationByName(0, 'flying', true); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + // update the spine animation, only needed if dragon.autoupdate is set to false + this.dragon.update(0.01666666666667); // HARDCODED FRAMERATE! + + this.renderer.render(this.stage); + + } + + } + +} + +module Spine { + + export class Goblin { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private goblin: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('goblins', '../../_assets/spine/goblins.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.goblin = new PIXI.spine.Spine(res.goblins.spineData); + this.goblin.skeleton.setSkinByName('goblin'); + this.goblin.skeleton.setSlotsToSetupPose(); + + this.goblin.position.x = 400; + this.goblin.position.y = 600; + this.goblin.scale.set(1.5); + + this.goblin.state.setAnimationByName(0, 'walk', true); + + this.stage.addChild(this.goblin); + + this.stage.on('click', () => { + + // change current skin + var currentSkinName = this.goblin.skeleton.skin.name; + var newSkinName = (currentSkinName === 'goblin' ? 'goblingirl' : 'goblin'); + this.goblin.skeleton.setSkinByName(newSkinName); + this.goblin.skeleton.setSlotsToSetupPose(); + + }); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module Spine { + + export class Pixie { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private pixie: PIXI.spine.Spine; + + private position: number; + private background: PIXI.Sprite; + private background2: PIXI.Sprite; + private foreground: PIXI.Sprite; + private foreground2: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('pixie', '../../_assets/spine/pixie.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + this.background = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); + this.background2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); + this.stage.addChild(this.background); + this.stage.addChild(this.background2); + + this.foreground = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); + this.foreground2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); + this.stage.addChild(this.foreground); + this.stage.addChild(this.foreground2); + this.foreground.position.y = this.foreground2.position.y = 640 - this.foreground2.height; + + this.pixie = new PIXI.spine.Spine(res.pixie.spineData); + + var scale = 0.3; + + this.pixie.position.x = 1024 / 3; + this.pixie.position.y = 500; + + this.pixie.scale.x = this.pixie.scale.y = scale; + + this.stage.addChild(this.pixie); + + this.pixie.stateData.setMixByName('running', 'jump', 0.2); + this.pixie.stateData.setMixByName('jump', 'running', 0.4); + + this.pixie.state.setAnimationByName(0, 'running', true); + + this.stage.on('mousedown', this.onTouchStart); + this.stage.on('touchstart', this.onTouchStart); + + this.animate(); + + } + + private onTouchStart = (): void => { + + this.pixie.state.setAnimationByName(0, 'jump', false); + this.pixie.state.addAnimationByName(0, 'running', true, 0); + + } + + private animate = (): void => { + + this.position += 10; + + this.background.position.x = -(this.position * 0.6); + this.background.position.x %= 1286 * 2; + if (this.background.position.x < 0) { + this.background.position.x += 1286 * 2; + } + this.background.position.x -= 1286; + + this.background2.position.x = -(this.position * 0.6) + 1286; + this.background2.position.x %= 1286 * 2; + if (this.background2.position.x < 0) { + this.background2.position.x += 1286 * 2; + } + this.background2.position.x -= 1286; + + this.foreground.position.x = -this.position; + this.foreground.position.x %= 1286 * 2; + if (this.foreground.position.x < 0) { + this.foreground.position.x += 1286 * 2; + } + this.foreground.position.x -= 1286; + + this.foreground2.position.x = -this.position + 1286; + this.foreground2.position.x %= 1286 * 2; + if (this.foreground2.position.x < 0) { + this.foreground2.position.x += 1286 * 2; + } + this.foreground2.position.x -= 1286; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + module Spine { + + export class SpineBoy { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private spineboy: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('spineboy', '../../_assets/spine/spineboy.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.spineboy = new PIXI.spine.Spine(res.spineboy.spineData); + this.spineboy.position.x = this.renderer.width / 2; + this.spineboy.position.y = this.renderer.height; + this.spineboy.scale.set(1.5); + + // set up the mixes! + this.spineboy.stateData.setMixByName('walk', 'jump', 0.2); + this.spineboy.stateData.setMixByName('jump', 'walk', 0.4); + + // play animation + this.spineboy.state.setAnimationByName(0, 'walk', true); + + this.stage.addChild(this.spineboy); + + + this.stage.on('click', () => { + + this.spineboy.state.setAnimationByName(0, 'jump', false); + this.spineboy.state.addAnimationByName(0, 'walk', true, 0); + + }); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + } + +} \ No newline at end of file diff --git a/pixi-spine/pixi-spine.d.ts b/pixi-spine/pixi-spine.d.ts new file mode 100644 index 000000000..e39dffa42 --- /dev/null +++ b/pixi-spine/pixi-spine.d.ts @@ -0,0 +1,812 @@ +// Type definitions for pixi-spine 1.0.4 +// Project: https://github.com/pixijs/pixi-spine/ +// Definitions by: martijncroezen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module PIXI { + + export module spine { + + export interface Timeline { + + frames: number[]; + + getFrameCount(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export interface Attachment { + + name: string; + type: number; + + } + + export class Animation { + + constructor(name: string, timelines?: Timeline[], duration?: number); + + apply(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: Event[]): void; + mix(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: any[], alpha?: number): void; + binarySearch(values: number[], target: number, step: number): number; + binarySearch1(values: number[], target: number): number; + linearSearch(values: number[], target: number, step: number): number; + + name: string; + timelines: Timeline[]; + duration: number; + + } + + export class AnimationState { + + data: AnimationStateData; + tracks: TrackEntry[]; + events: Event[]; + onStart: (index: number) => void; + onEnd: (trackIndex: number) => void; + onComplete: (i: number, count: number) => void; + onEvent: (i: number, event: Event) => void; + timeScale: number; + + constructor(stateData: AnimationStateData); + + update(delta: number): void; + apply(skeleton: Skeleton): void; + clearTracks(): void; + clearTrack(trackIndex: number): void; + private _expandToIndex(index: number): TrackEntry; + setCurrent(index: number, entry: TrackEntry): void; + setAnimationByName(trackIndex: number, animationName: string, loop: boolean): TrackEntry; + setAnimation(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; + addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; + addAnimation(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; + getCurrent(trackIndex: number): TrackEntry; + + } + + export class Spine extends PIXI.Container { + + constructor(spineData: any); + + static fromAtlas(resourceName: string): Spine; + + update(dt: number): void; + + private autoUpdateTransform(): void; + private createSprite(slot: Slot, attachment: Attachment): Sprite; + private createMesh(slot, attachment) + + spineData: any; + skeleton: Skeleton; + stateData: AnimationStateData; + state: AnimationState; + slotContainers: PIXI.Container[]; + autoUpdate: boolean; + + } + + export class AnimationStateData { + + constructor(skeletonData: SkeletonData); + + private _skelentonData: SkeletonData; + private animationToMixTime: number; + defaultMix: number; + skeletonData: SkeletonData; + setMixByName(fromName: string, toName: string, duration: number): void; + setMix(from: Animation, to: Animation, duration: number): void; + getMix(from: Animation, to: Animation): number; + + } + + export class AttachmentType { + + static region: number; + static boundingbox: number; + static mesh: number; + static skinnedmesh: number; + + } + + export class Bone { + + data: BoneData; + skeleton: Skeleton; + parent: Bone; + + constructor(boneData: BoneData, skeleton: Skeleton, parent: Bone); + + x: number; + y: number; + rotation: number; + rotationIK: number; + scaleX: number; + scaleY: number; + flipX: boolean; + flipY: boolean; + m00: number; + m01: number; + worldX: number; + m10: number; + m11: number; + worldY: number; + worldRotation: number;; + worldScaleX: number; + worldScaleY: number; + worldFlipX: boolean; + worldFlipY: boolean; + + updateWorldTransform(): void; + setToSetupPose(): void; + worldToLocal(world: number[]): void; + localToWorld(local: number[]): void; + + } + + export class BoneData { + + name: string; + parent: Bone; + + constructor(name: string, parent: Bone); + + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + inheritScale: boolean; + inheritRotation: boolean; + flipX: boolean; + flipY: boolean; + + } + + export class BoundingBoxAttachment implements Attachment { + + constructor(name: string); + + name: string; + vertices: number[]; + type: number; + + computeWorldVertices(x: number, y: number, bone: Bone, worldVertices: number[]): void; + + } + + export class ColorTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + slotIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Curves { + + constructor(frameCount: number[]); + + curves: number[]; + + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + + } + + export class DrawOrderTimeline implements Timeline { + + constructor(frameCount: number); + + frames: number[]; + drawOrders: number[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, drawOrder: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Event { + + constructor(data: any); + + data: any; + intValue: number; + floatValue: number; + stringValue: string; + + } + + export class EventData { + + constructor(name: string); + + name: string; + + intValue: number; + floatValue: number; + stringValue: string; + + } + + export class EventTimeline implements Timeline { + + constructor(frameCount: number); + + frames: number[]; + events: Event[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, event: Event): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + + export class FfdTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + frameVertices: number[]; + slotIndex: number; + attachment: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class FlipXTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class FlipYTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class IkConstraint { + + constructor(data: IkConstraintData, skeleton: Skeleton); + + data: IkConstraintData; + mix: number; + bendDirection: number; + bones: Bone[]; + target: Bone; + + apply(): void; + apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; + apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDirection: number, alpha: number): void; + + } + + export class IkConstraintData { + + constructor(name: string); + + name: string; + bones: Bone[]; + target: Bone; + bendDirection: number; + mix: number; + + } + + export class IkConstraintTimeline implements Timeline { + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + ikConstraintIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class MeshAttachment implements Attachment { + + constructor(name: string); + + name: string; + type: number; + vertices: number[]; + uvs: number[] + regionUVs: number[] + triangles: number[] + hullLength: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionU: number; + regionV: number; + regionU2: number; + regionV2: number; + regionRotate: boolean; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + edges: number[]; + width: number; + height: number; + + updateUVs(): void; + computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; + + } + + export class RegionAttachment implements Attachment { + + constructor(name: string); + + name: string; + offset: number[]; + uvs: number[] + type: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + width: number; + height: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + + updateOffset(): void; + setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; + computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; + + } + + export class RotateTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class ScaleTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Skeleton { + + constructor(skeletonData: SkeletonData); + + data: SkeletonData; + bones: Bone[]; + slots: Slot[]; + drawOrder: Slot[]; + ikConstraints: IkConstraint[]; + boneCache: Bone[][]; + x: number; + y: number; + skin: Skin; + r: number; + g: number; + b: number; + a: number; + time: number; + flipX: boolean; + flipY: boolean; + + updateCache(): void; + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): Skin; + setSkin(newSkin: Skin): void; + getAttachmentBySlotName(slotName: string, attachmentName: string): Attachment; + getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): Attachment + setAttachment(slotName: string, attachmentName: string): void; + findIkConstraint(ikConstraintName: string): IkConstraint; + update(delta: number): void; + resetDrawOrder(): void; + + } + + export class SkeletonBounds { + + polygonPool: Polygon[]; + polygons: Polygon[]; + boundingBoxes: BoundingBoxAttachment[]; + minX: number; + minY: number; + maxX: number; + maxY: number; + + update(skeleton: Skeleton, updateAabb: boolean): void; + aabbCompute(): void; + aabbContainsPoint(x: number, y: number): void; + aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; + aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; + containsPoint(x: number, y: number): BoundingBoxAttachment; + intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; + polygonContainsPoint(polygon: Polygon, x: number, y: number): boolean; + polygonIntersectsSegment(polygon: Polygon, x1: number, y1: number, x2: number, y2: number): boolean; + getPolygon(attachment: Attachment): Polygon; + getWidth(): number; + getHeight(): number; + + } + + export class SkeletonData { + + bones: Bone[]; + slots: Slot[]; + skins: Skin[]; + events: Event[]; + animations: Animation[]; + ikConstraints: IkConstraint[]; + name: string; + defaultSkin: Skin; + width: number; + height: number; + version: any; + hash: any; + + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findEvent(eventName: string): Event; + findAnimation(animationName: string): Animation + findIkConstraint(ikConstraintName: string): IkConstraint; + + } + + export class SkeletonJsonParser { + + constructor(attachmentLoader: any); + + attachmentLoader: any; + scale: number; + + readSkeletonData(root: Bone, name: string): void; + readAttachment(skin: Skin, name: string, map: any): void; + readAnimation(name: string, map: any, skeletonData: SkeletonData): void; + readCurve(timeline: Timeline, frameIndex: number, valueMap: any): void; + toColor(hexString: string, colorIndex: string): number; + getFloatArray(map: any, name: string, scale: number): number[]; + getIntArray(map: any, name: string): number[]; + + } + + export class Skin { + + constructor(name: string); + + name: string; + attachments: Attachment[]; + addAttachment(slotIndex: number, name: string, attachment: Attachment): void; + getAttachment(slotIndex: number, name: string): Attachment; + + protected _attachAll(skeleton: Skeleton, oldSkin: Skin): void; + + } + + export class SkinnedMeshAttachment implements Attachment { + + constructor(name: string); + + name: string; + type: number; + bones: number[]; + weights: number[]; + uvs: number[]; + regionUVs: number[]; + triangles: number[]; + hullLength: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionU: number; + regionV: number; + regionU2: number; + regionV2: number; + regionRotate: boolean; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + edges: number[]; + width: number; + height: number; + + updateUVs(u: number, v: number, u2: number, v2: number, rotate: boolean): void; + computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; + + } + + export class Slot { + + constructor(slotData: SlotData, bone: Bone); + + data: SlotData; + bone: Bone; + r: number; + g: number; + b: number; + a: number; + _attachmentTime: number; + attachment: Attachment; + attachmentVertices: number[]; + setAttachment(attachment: Attachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + + } + + export class SlotData { + + constructor(name: string, boneData: BoneData); + + name: string; + boneData: BoneData; + + static PIXI_BLEND_MODE_MAP: { + multiply: number; + screen: number; + additive: number; + normal: number; + }; + r: number; + g: number; + b: number; + a: number; + attachmentName: string; + blendMode: number; + + } + + export class TrackEntry { + + next: TrackEntry; + previous: TrackEntry; + animation: Animation; + loop: boolean; + delay: number; + time: number; + lastTime: number; + endTime: number; + timeScale: number; + mixTime: number; + mixDuration: number; + mix: number; + onStart: (index: number) => void; + onEnd: (trackIndex: number) => void; + onComplete: (i: number, count: number) => void; + onEvent: (i: number, event: Event) => void; + + } + + export class TranslateTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves[]; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Atlas { + + constructor(atlasText: string, baseUrl: string, crossOrigin: any); + + pages: AtlasPage[]; + regions: AtlasRegion[]; + texturesLoading: number; + + findRegion(name: string): AtlasRegion; + dispose(): void; + updateUVs(page: AtlasPage): void; + + Format: { + + alpha: number; + intensity: number; + luminanceAlpha: number; + rgb565: number; + rgba4444: number; + rgb888: number; + rgba8888: number; + + }; + + TextureFilter: { + + nearest: number; + linear: number; + mipMap: number; + mipMapNearestNearest: number; + mipMapLinearNearest: number; + mipMapNearestLinear: number; + mipMapLinearLinear: number; + + }; + + TextureWrap: { + + mirroredRepeat: number; + clampToEdge: number; + repeat: number; + + }; + + } + + export class AtlasAttachmentParser { + + constructor(atlas: Atlas); + + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; + newSkinnedMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + + } + + export class AtlasPage { + name: string; + format: any; + minFilter: any; + magFilter: any; + uWrap: any; + vWrap: any; + rendererObject: any; + width: number; + height: number; + + } + + export class AtlasReader { + constructor(text: string); + + lines: string[]; + index: number; + + trim(value: string): string; + readLine(): string; + readValue(): string; + readTuple(tuple: number): number; + + } + + export class AtlasRegion { + + page: AtlasPage; + name: string; + x: number; + y: number; + width: number; + height: number; + u: number; + v: number; + u2: number; + v2: number; + offsetX: number; + offsetY: number; + originalWidth: number; + originalHeight: number; + index: number; + rotate: boolean; + splits: any; + pads: any; + + + } + + export class AttachmentTimeline implements Timeline { + + constructor(frameCount: number); + + slotIndex: number; + frames: number[]; + attachmentNames: string[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class atlasParser { + + constructor(resource: any, next: any); + + AnimCache: any; + enableCaching: boolean; + + } + + } + +} \ No newline at end of file From 438b76380941ce70be75797e2b46d4da81a3ca35 Mon Sep 17 00:00:00 2001 From: Filipe Date: Fri, 31 Jul 2015 12:02:31 +0100 Subject: [PATCH 126/419] adds esprima.Syntax object with constants --- esprima/esprima.d.ts | 98 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 84 insertions(+), 14 deletions(-) diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index 10e37a530..c46f20b28 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -6,29 +6,99 @@ /// declare module esprima { - var version: string - function parse(code: string, options?: Options): ESTree.Program - function tokenize(code: string, options?: Options): Array + + const version: string; + + function parse(code: string, options?: Options): ESTree.Program; + function tokenize(code: string, options?: Options): Array; interface Token { - type: string - value: string + type: string; + value: string; } interface Comment extends ESTree.Node { - value: string + value: string; } interface Options { - loc?: boolean - range?: boolean - raw?: boolean - tokens?: boolean - comment?: boolean - attachComment?: boolean - tolerant?: boolean - source?: boolean + loc?: boolean; + range?: boolean; + raw?: boolean; + tokens?: boolean; + comment?: boolean; + attachComment?: boolean; + tolerant?: boolean; + source?: boolean; } + + const Syntax: { + AssignmentExpression: string, + AssignmentPattern: string, + ArrayExpression: string, + ArrayPattern: string, + ArrowFunctionExpression: string, + BlockStatement: string, + BinaryExpression: string, + BreakStatement: string, + CallExpression: string, + CatchClause: string, + ClassBody: string, + ClassDeclaration: string, + ClassExpression: string, + ConditionalExpression: string, + ContinueStatement: string, + DoWhileStatement: string, + DebuggerStatement: string, + EmptyStatement: string, + ExportAllDeclaration: string, + ExportDefaultDeclaration: string, + ExportNamedDeclaration: string, + ExportSpecifier: string, + ExpressionStatement: string, + ForStatement: string, + ForOfStatement: string, + ForInStatement: string, + FunctionDeclaration: string, + FunctionExpression: string, + Identifier: string, + IfStatement: string, + ImportDeclaration: string, + ImportDefaultSpecifier: string, + ImportNamespaceSpecifier: string, + ImportSpecifier: string, + Literal: string, + LabeledStatement: string, + LogicalExpression: string, + MemberExpression: string, + MethodDefinition: string, + NewExpression: string, + ObjectExpression: string, + ObjectPattern: string, + Program: string, + Property: string, + RestElement: string, + ReturnStatement: string, + SequenceExpression: string, + SpreadElement: string, + Super: string, + SwitchCase: string, + SwitchStatement: string, + TaggedTemplateExpression: string, + TemplateElement: string, + TemplateLiteral: string, + ThisExpression: string, + ThrowStatement: string, + TryStatement: string, + UnaryExpression: string, + UpdateExpression: string, + VariableDeclaration: string, + VariableDeclarator: string, + WhileStatement: string, + WithStatement: string, + YieldExpression: string + }; + } declare module "esprima" { From 7ea45fcc6cdd42a12e84f9d98cf722ea4aef17ef Mon Sep 17 00:00:00 2001 From: Ben Coveney Date: Fri, 31 Jul 2015 13:44:56 +0100 Subject: [PATCH 127/419] Fixed spelling mistakes, inconsistency --- backbone/backbone.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/backbone/backbone.d.ts b/backbone/backbone.d.ts index fae1c7486..25ef05655 100644 --- a/backbone/backbone.d.ts +++ b/backbone/backbone.d.ts @@ -148,7 +148,7 @@ declare module Backbone { unset(attribute: string, options?: Silenceable): Model; validate(attributes: any, options?: any): any; - private _validate(attrs: any, options: any): boolean; + private _validate(attributes: any, options: any): boolean; // mixins from underscore @@ -201,10 +201,10 @@ declare module Backbone { shift(options?: Silenceable): TModel; sort(options?: Silenceable): Collection; unshift(model: TModel, options?: AddOptions): TModel; - where(properies: any): TModel[]; + where(properties: any): TModel[]; findWhere(properties: any): TModel; - private _prepareModel(attrs?: any, options?: any): any; + private _prepareModel(attributes?: any, options?: any): any; private _removeReference(model: TModel): void; private _onModelEvent(event: string, model: TModel, collection: Collection, options: any): void; From c12257bc528680aae57dbeb6e56420ec51e9a883 Mon Sep 17 00:00:00 2001 From: Salehen Shovon Rahman Date: Fri, 31 Jul 2015 09:07:55 -0700 Subject: [PATCH 128/419] Added an override for support for jQuery Gridster's `add_widget` ultimately passes on the first parameter to jQuery, and jQuery accepts either a string, a DOM element, or a jQuery object. `add_widget`'s first parameter should reflect what jQuer supports. --- jquery.gridster/gridster.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/jquery.gridster/gridster.d.ts b/jquery.gridster/gridster.d.ts index 53f26704e..0459b2f70 100644 --- a/jquery.gridster/gridster.d.ts +++ b/jquery.gridster/gridster.d.ts @@ -184,6 +184,11 @@ interface Gridster { **/ add_widget(html: HTMLElement, size_x?: number, size_y?: number, col?: number, row?: number): JQuery; + /** + * @see add_widget + **/ + add_widget(html: JQuery, size_x?: number, size_y?: number, col?: number, row?: number): JQuery; + /** * Change the size of a widget. * @param $widget The jQuery wrapped HTMLElement that represents the widget is going to be resized. From c963dad1ac8ebeb575cb6b1f008e25df9c5e3caf Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 31 Jul 2015 17:17:34 +0100 Subject: [PATCH 129/419] Type definitions and tests for param-case --- param-case/param-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 param-case/param-case.d.ts diff --git a/param-case/param-case.d.ts b/param-case/param-case.d.ts new file mode 100644 index 000000000..db8f2aba1 --- /dev/null +++ b/param-case/param-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for param-case +// Project: https://github.com/blakeembrey/param-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "param-case" { + function paramCase(string: string, locale?: string): string; + export = paramCase; +} From 1f3eb8b90967fa7861fcdbf11a68fd9935c9f7b8 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Fri, 31 Jul 2015 17:19:22 +0100 Subject: [PATCH 130/419] Type definitions and tests for param-case --- param-case/param-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 param-case/param-case-tests.ts diff --git a/param-case/param-case-tests.ts b/param-case/param-case-tests.ts new file mode 100644 index 000000000..1ac68a3d1 --- /dev/null +++ b/param-case/param-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import paramCase = require('param-case'); + +console.log(paramCase('string')); // => "string" +console.log(paramCase('camelCase')); // => "camel-case" +console.log(paramCase('sentence case')); // => "sentence-case" + +console.log(paramCase('MY STRING', 'tr')); // => "my-strıng" From ab8808f2ed70e4f6a4c794924cc4a64e11b3ba9f Mon Sep 17 00:00:00 2001 From: Marcin Porebski Date: Fri, 31 Jul 2015 19:30:26 +0200 Subject: [PATCH 131/419] traverson definitions --- traverson/traverson-tests.ts | 19 ++++++++++++ traverson/traverson.d.ts | 60 ++++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 traverson/traverson-tests.ts create mode 100644 traverson/traverson.d.ts diff --git a/traverson/traverson-tests.ts b/traverson/traverson-tests.ts new file mode 100644 index 000000000..0aceced33 --- /dev/null +++ b/traverson/traverson-tests.ts @@ -0,0 +1,19 @@ +/// + +import traverson = require('traverson'); + +function testTraverson() +{ + var mediaTypeHandler: any = {}; + + traverson.registerMediaType('application/some-fancy+json', mediaTypeHandler); + + traverson.from('http://example.api.com/') + .follow('link_to') + .withTemplateParameters({'id': 1}) + .get(function(error, document, traversal) { + traversal.continue().follow('link_back').get(function(error, document, traversal) { + /// + }); + }); +} diff --git a/traverson/traverson.d.ts b/traverson/traverson.d.ts new file mode 100644 index 000000000..8a8755091 --- /dev/null +++ b/traverson/traverson.d.ts @@ -0,0 +1,60 @@ +// Type definitions for Traverson v2.0.1 +// Project: http://github.com/iriscouch/traceback +// Definitions by: Marcin Porębski +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module Traverson +{ + interface TraversonMethods + { + from(uri: string): Builder; + registerMediaType(name: string, handler: any): TraversonMethods; + } + + interface Builder + { + withRequestOptions(options: any): Builder; + withTemplateParameters(parameters: any): Builder; + json(): Builder; + jsonHal(): Builder; + + setMediaType(type_name: string): Builder; + + follow(first_pattern: string, ... rest_patterns: string[]): Builder; + + get(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + getResource(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + getUrl(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + post(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + put(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + patch(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + delete(callback: (err: any, document: any, traversal?: Traversal) => void): InAction; + + newRequest(): Builder; + } + + interface Json + { + parseJson(): any; + } + + interface Traversal + { + continue(): Builder; + } + + interface InAction + { + abort(): void; + } + + + +} + +declare module "traverson" +{ + var traverson: Traverson.TraversonMethods; + + export = traverson; +} From 4df20c9706ce6ca27137617770b57f3a0d3f9689 Mon Sep 17 00:00:00 2001 From: Alex Eagle Date: Thu, 30 Jul 2015 14:48:55 -0700 Subject: [PATCH 132/419] Update angular2 to alpha33 --- angular2/angular2-2.0.0-alpha.33.d.ts | 6310 +++++++++++++++++++++++++ angular2/angular2.d.ts | 2865 ++++++----- 2 files changed, 7876 insertions(+), 1299 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.33.d.ts diff --git a/angular2/angular2-2.0.0-alpha.33.d.ts b/angular2/angular2-2.0.0-alpha.33.d.ts new file mode 100644 index 000000000..8007ebb06 --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.33.d.ts @@ -0,0 +1,6310 @@ +// Type definitions for Angular v2.0.0-alpha.33 +// 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[]): any; + } + + // 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 ; + + + /** + * 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 `