From ee872c633411d2524cafc68d339f016acbfa1fd6 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Sun, 14 Sep 2014 00:08:00 +0300 Subject: [PATCH 001/309] 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 0000000000..a3f5ea10e1 --- /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 0000000000..92fdd9634e --- /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 0000000000..9d59bd65e1 --- /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 0000000000..2000e9bcd2 --- /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/309] 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 f054c12d09..afc3aa9038 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/309] 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 a900680bc6..cce6e67503 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/309] 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 cce6e67503..c7add11655 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 5bf40c59d1cc2c29a79dbfa9e09892d43d2f21d7 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Sat, 16 May 2015 15:25:33 -0400 Subject: [PATCH 005/309] 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 951fc40457..ad9eb174d5 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 2f1df1f63590f9b97134414eab0ea53eea206c94 Mon Sep 17 00:00:00 2001 From: Nick Lee Date: Tue, 2 Jun 2015 12:21:16 -0400 Subject: [PATCH 006/309] 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 5e4bfc37bf..3df8ada9e0 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 007/309] 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 d0f05065cf..e1539d21b3 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 008/309] 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 26048a9dc7..fc1f8ef25a 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 5e4bfc37bf..20ef52a66c 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 f02d001d3d809136f507048113369660ee9876ef Mon Sep 17 00:00:00 2001 From: Daisuke Aoki Date: Tue, 21 Jul 2015 18:37:43 +0900 Subject: [PATCH 009/309] 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 8766745b80..58d85086de 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 1bb6be593e..eb5b0296f4 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 4bfe4cfc5821a779e8ad1393765ffd0d269c5120 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Fri, 24 Jul 2015 23:07:41 +0200 Subject: [PATCH 010/309] 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 0000000000..7316987c98 --- /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 6befcf5e84a99dcee756f5f304c3e003683e7f8e Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:51:07 -0400 Subject: [PATCH 011/309] MediaStream typings --- webrtc/MediaStream.d.ts | 310 +++++++++++++++++++++------------------- 1 file changed, 166 insertions(+), 144 deletions(-) diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 54de34e386..6db34de949 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 MediaStreamConstraints { - audio: any; - video: any; +/// + +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 { + 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 012/309] 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 3ccc78b78a..80823700a7 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 7f8dfda9a76069741b448ca029d273c68ef98e38 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:34:16 -0400 Subject: [PATCH 013/309] 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 0d4e710b83..516abcb028 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 6db34de949..f52551a146 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 014/309] 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 1df792b421..a8a48b82ea 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 015/309] 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 516abcb028..c309a281be 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 016/309] 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 7316987c98..259babf3f9 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 017/309] 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 259babf3f9..afdc5f25a7 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 7518bed77b54c4f2dfc4a1d8254bcdd8c5941729 Mon Sep 17 00:00:00 2001 From: Matthias Bussonnier Date: Sat, 25 Jul 2015 18:14:47 -0700 Subject: [PATCH 018/309] [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 5fc335ed64..6574005e3d 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 b0b86846bd466b9ff2cbd60f131be06980e03b0b Mon Sep 17 00:00:00 2001 From: Matt DeKrey Date: Mon, 27 Jul 2015 15:40:53 -0400 Subject: [PATCH 019/309] 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 627dda565c..ca5ad80d15 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 7bc1df648d..d49e4104f8 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 8c18f7d318940a780470c703d2bd06efd3977839 Mon Sep 17 00:00:00 2001 From: benishouga Date: Thu, 30 Jul 2015 01:03:33 +0900 Subject: [PATCH 020/309] 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 5fbad0d227..c27d523f04 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 d8dc5313d895cf55d3fec1c6c777163d3f49c50c Mon Sep 17 00:00:00 2001 From: Eric Pelz Date: Mon, 27 Jul 2015 13:51:19 -0700 Subject: [PATCH 021/309] 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 0000000000..244144029c --- /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 0000000000..86eab01cdb --- /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 d7637bf1a687afbea36ac198d03d1fd2c66bb53e Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Thu, 30 Jul 2015 17:58:20 +0100 Subject: [PATCH 022/309] 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 0000000000..d79637d478 --- /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 0000000000..c10209e07a --- /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 023/309] 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 d79637d478..163903fefe 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 c10209e07a..7d5ad27d12 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 024/309] [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 198eaa0a4d..2feaab0805 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 b8130a65bc3284dd1ac1cde827370771b35dc6ee Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 11:52:32 +0200 Subject: [PATCH 025/309] 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 6600bb121e..65fb7458aa 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 026/309] 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 65fb7458aa..309f7f66a2 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 c86c1bd47f..0452e7432b 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 027/309] 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 309f7f66a2..6a462fc2eb 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 d3f5a12faa..0000000000 --- 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 0452e7432b..8e83cbf1e3 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 d3f5a12faa..0000000000 --- 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 028/309] 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 0000000000..71ecf31472 --- /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 0000000000..e39dffa421 --- /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 c12257bc528680aae57dbeb6e56420ec51e9a883 Mon Sep 17 00:00:00 2001 From: Salehen Shovon Rahman Date: Fri, 31 Jul 2015 09:07:55 -0700 Subject: [PATCH 029/309] 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 53f26704e3..0459b2f702 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 a586fa0f3688e8db70b3a2ed1970172b6e0e0d5d Mon Sep 17 00:00:00 2001 From: Salehen Shovon Rahman Date: Fri, 31 Jul 2015 11:40:23 -0700 Subject: [PATCH 030/309] Added remove_widget as well. --- jquery.gridster/gridster.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/jquery.gridster/gridster.d.ts b/jquery.gridster/gridster.d.ts index 0459b2f702..e003f0ebcc 100644 --- a/jquery.gridster/gridster.d.ts +++ b/jquery.gridster/gridster.d.ts @@ -213,6 +213,16 @@ interface Gridster { **/ remove_widget(el: HTMLElement, callback: (el: HTMLElement) => void): Gridster; + /** + * @see remove_widget + **/ + remove_widget(el: JQuery, silent?: boolean, callback?: (el: HTMLElement) => void): Gridster; + + /** + * @see remove_widget + **/ + remove_widget(el: JQuery, callback: (el: HTMLElement) => void): Gridster; + /** * Returns a serialized array of the widgets in the grid. * @param $widgets The collection of jQuery wrap ed HTMLElements you want to serialize. If no argument is passed a l widgets will be serialized. From 2ee0d57fae6bb5a7a298a563da13233bb59f5fdf Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Fri, 31 Jul 2015 14:46:55 -0600 Subject: [PATCH 031/309] Update definitions and tests --- yamljs/yamljs-tests.ts | 12 +++--------- yamljs/yamljs.d.ts | 4 ++-- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/yamljs/yamljs-tests.ts b/yamljs/yamljs-tests.ts index 9780c504d4..d4e6376d68 100644 --- a/yamljs/yamljs-tests.ts +++ b/yamljs/yamljs-tests.ts @@ -1,13 +1,7 @@ /// -import yamljs = require('yamljs'); +var yamlObj = YAML.parse("test: some yaml"); -yamljs.load('yaml-testfile.yml'); +YAML.stringify(yamlObj); -yamljs.parse('this_is_no_ymlstring'); - -yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}); - -yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}, 1); - -yamljs.stringify({ a : 'val', b : { ba : 123, bb : 'nothing' }}, 1, 2); \ No newline at end of file +YAML.load("path/to/file.yaml"); \ No newline at end of file diff --git a/yamljs/yamljs.d.ts b/yamljs/yamljs.d.ts index 65d2fd9239..96c9d33c77 100644 --- a/yamljs/yamljs.d.ts +++ b/yamljs/yamljs.d.ts @@ -1,9 +1,9 @@ -// Type definitions for yamljs 0.2.1 +// Type definitions for yamljs 0.2.3 // Project: https://github.com/jeremyfa/yaml.js // Definitions by: Tim Jonischkat // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module "yamljs" { +declare module YAML { export function load(path : string) : any; From 0143f1c13a3d5930dbbb1397f4773e1942332147 Mon Sep 17 00:00:00 2001 From: Timothy Boyce Date: Sun, 2 Aug 2015 17:25:26 +0000 Subject: [PATCH 032/309] Update angular-localForage.d.ts Correct the signature and return type for bind --- angular-localForage/angular-localForage.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/angular-localForage/angular-localForage.d.ts b/angular-localForage/angular-localForage.d.ts index ee2aeeb6d8..6186d79d34 100644 --- a/angular-localForage/angular-localForage.d.ts +++ b/angular-localForage/angular-localForage.d.ts @@ -46,14 +46,14 @@ declare module angular.localForage { iterate(iteratorCallback:(value:string | number, key:string)=>T):angular.IPromise; - bind($scope:ng.IScope, key:string):void; + bind($scope:ng.IScope, key:string):angular.IPromise; bind($scope:ng.IScope, config:{ key:string; - defaultValue:any; - scopeKey:string; - name:string; - }):void; + defaultValue?:any; + scopeKey?:string; + name?:string; + }):angular.IPromise; unbind($scope:ng.IScope, key:string, scopeKey?:string):void; From 8155d032f3629412ed5cccab6339a9347df4bcd6 Mon Sep 17 00:00:00 2001 From: Timothy Boyce Date: Sun, 2 Aug 2015 17:48:02 +0000 Subject: [PATCH 033/309] update angular-localForage-tests.ts --- angular-localForage/angular-localForage-tests.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/angular-localForage/angular-localForage-tests.ts b/angular-localForage/angular-localForage-tests.ts index 8b31143c2b..3ea776ebf8 100644 --- a/angular-localForage/angular-localForage-tests.ts +++ b/angular-localForage/angular-localForage-tests.ts @@ -124,3 +124,18 @@ $localForage.iterate(function (value, key) { } }).then(function (data) { }); + +$localForage.bind($rootScope, 'key').then(function(data) { +}); + +$localForage.bind($rootScope, {key: 'key'}).then(function(data) { +}); + +$localForage.bind($rootScope, {key: 'key', defaultValue: 'defaultValue'}).then(function(data) { +}); + +$localForage.bind($rootScope, {key: 'key', scopeKey: 'scopeKey'}).then(function(data) { +}); + +$localForage.bind($rootScope, {key: 'key', name: 'name'}).then(function(data) { +}); From c48ecfcb12a0519094e285ce99dd564ba711809d Mon Sep 17 00:00:00 2001 From: Paul Jolly Date: Sun, 2 Aug 2015 23:45:43 +0100 Subject: [PATCH 034/309] Postal.js v1.0.6 --- postal/postal-0.8.9.d.ts | 71 ++++++++++++++++++++++++++++ postal/postal.d.ts | 99 +++++++++++++++++++++++++++------------- 2 files changed, 138 insertions(+), 32 deletions(-) create mode 100644 postal/postal-0.8.9.d.ts diff --git a/postal/postal-0.8.9.d.ts b/postal/postal-0.8.9.d.ts new file mode 100644 index 0000000000..0ef40c5d51 --- /dev/null +++ b/postal/postal-0.8.9.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 diff --git a/postal/postal.d.ts b/postal/postal.d.ts index 0ef40c5d51..e1bad48cce 100644 --- a/postal/postal.d.ts +++ b/postal/postal.d.ts @@ -1,33 +1,48 @@ -// Type definitions for Postal v0.8.9 +// Type definitions for Postal v1.0.6 // Project: https://github.com/postaljs/postal.js -// Definitions by: Lokesh Peta +// Definitions by: Lokesh Peta , Paul Jolly // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - -interface IConfiguration{ +interface IConfiguration { SYSTEM_CHANNEL: string; DEFAULT_CHANNEL: string; - resolver: any; + resolver: IResolver; } -interface ISubscriptionDefinition{ - unsubscribe(): void; - subscribe(callback: (data: any, envelope: IEnvelope)=> void): void; - defer():ISubscriptionDefinition; +interface IResolver { + compare(binding: string, topic: string, headerOptions: {}): boolean; + reset(): void; + purge(options?: {topic?: string, binding?: string, compact?: boolean}): void; +} + +interface ICallback { + (data: any, envelope: IEnvelope): void +} + +interface ISubscriptionDefinition { + channel: string; + topic: string; + callback: ICallback; + + // after and before lack documentation + + constraint(predicateFn: (data: any, envelope: IEnvelope) => boolean): ISubscriptionDefinition; + constraints(predicateFns: ((data: any, envelope: IEnvelope) => boolean)[]): ISubscriptionDefinition; + context(theContext: any): ISubscriptionDefinition; + debounce(interval: number): ISubscriptionDefinition; + defer(): ISubscriptionDefinition; + delay(waitTime: number): ISubscriptionDefinition; disposeAfter(maxCalls: number): ISubscriptionDefinition; + distinct(): ISubscriptionDefinition; distinctUntilChanged(): ISubscriptionDefinition; + logError(): 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; + throttle(interval: number): ISubscriptionDefinition; + subscribe(callback: ICallback): ISubscriptionDefinition; + unsubscribe(): void; } -interface IEnvelope{ +interface IEnvelope { topic: string; data?: any; @@ -39,26 +54,45 @@ interface IEnvelope{ interface IChannelDefinition { - subscribe(topic: string): ISubscriptionDefinition; - subscribe(topic: string, callback: (data: any, envelope: IEnvelope)=> void): ISubscriptionDefinition; + subscribe(topic: string, callback: ICallback): ISubscriptionDefinition; publish(topic: string, data?: any): void; - publish(envelope: IEnvelope): void; channel: string; } -interface IPostalUtils{ - getSubscribersFor(channel: string, tpc: any): any; - reset(): void; +interface ISourceArg { + topic: string; + channel?: string; +} + +interface IDestinationArg { + topic: string | ((topic: string) => string); + channel?: string; } interface IPostal { - channel(name?:string): IChannelDefinition; - - linkChannels(sources: IEnvelope | IEnvelope[], destinations: IEnvelope | IEnvelope[]): ISubscriptionDefinition[]; - - utils: IPostalUtils; + subscriptions: {}; + wiretaps: ICallback[]; + + addWireTap(callback: ICallback): () => void; + + channel(name?: string): IChannelDefinition; + + getSubscribersFor(): ISubscriptionDefinition[]; + getSubscribersFor(options: {channel?: string, topic?: string, context?: any}): ISubscriptionDefinition[]; + getSubscribersFor(predicateFn: (sub: ISubscriptionDefinition) => boolean): ISubscriptionDefinition[]; + + linkChannels(source: ISourceArg | ISourceArg[], destination: IDestinationArg | IDestinationArg[]): void; + + publish(envelope: IEnvelope): void; + + reset(): void; + + subscribe(options: {channel?: string, topic: string, callback: ICallback}): ISubscriptionDefinition; + unsubscribe(sub: ISubscriptionDefinition): void; + unsubscribeFor(): void; + unsubscribeFor(options: {channel?: string, topic?: string, context?: any}): void; configuration: IConfiguration; } @@ -66,6 +100,7 @@ interface IPostal { declare var postal: IPostal; declare module "postal" { - var postal: IPostal; - export = postal; -} \ No newline at end of file + var postal: IPostal; + export = postal; +} + From 1bd72e00bf6a2ef7b1664f5ece54aaaab046d15d Mon Sep 17 00:00:00 2001 From: Sebastian Clausen Date: Mon, 3 Aug 2015 11:31:47 +0200 Subject: [PATCH 035/309] Restangular: ICollection extends Array to inherit splice and indexOf --- restangular/restangular.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 5b19cdad79..0c5f698ca1 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -115,13 +115,13 @@ declare module restangular { patch(queryParams?: any, headers?: any): IPromise; clone(): IElement; plain(): any; - plain(): T; + plain(): T; withHttpConfig(httpConfig: IRequestConfig): IElement; save(queryParams?: any, headers?: any): IPromise; getRestangularUrl(): string; } - interface ICollection extends IService { + interface ICollection extends IService, Array { getList(queryParams?: any, headers?: any): ICollectionPromise; getList(queryParams?: any, headers?: any): ICollectionPromise; post(elementToPost: any, queryParams?: any, headers?: any): IPromise; @@ -132,9 +132,9 @@ declare module restangular { patch(queryParams?: any, headers?: any): IPromise; putElement(idx: any, params: any, headers: any): IPromise; withHttpConfig(httpConfig: IRequestConfig): ICollection; - clone(): ICollection; + clone(): ICollection; plain(): any; - plain(): T[]; + plain(): T[]; getRestangularUrl(): string; } } From 62bb9fd8073c969c84bf27347ff7d51e6199b7cb Mon Sep 17 00:00:00 2001 From: benishouga Date: Tue, 4 Aug 2015 00:01:32 +0900 Subject: [PATCH 036/309] SVGAttributes inherit HTMLAttributes. fixed react-addons.d.ts and react-global.d.ts. --- react/react-addons.d.ts | 5 +---- react/react-global.d.ts | 4 +--- react/react.d.ts | 6 +----- 3 files changed, 3 insertions(+), 12 deletions(-) diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index 37cde636dc..9479cc722d 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -518,9 +518,7 @@ declare module "react/addons" { unselectable?: boolean; } - interface SVGAttributes extends DOMAttributes { - ref?: string | ((component: SVGComponent) => void); - + interface SVGAttributes extends HTMLAttributes { cx?: number | string; cy?: number | string; d?: string; @@ -1048,4 +1046,3 @@ declare module "react/addons" { identifiedTouch(identifier: number): Touch; } } - diff --git a/react/react-global.d.ts b/react/react-global.d.ts index 3c1a69e439..ea032100c4 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -524,9 +524,7 @@ declare module React { preserveAspectRatio?: string; } - interface SVGAttributes extends DOMAttributes { - ref?: string | ((component: SVGComponent) => void); - + interface SVGAttributes extends HTMLAttributes { cx?: number | string; cy?: number | string; d?: string; diff --git a/react/react.d.ts b/react/react.d.ts index c27d523f04..74d6eab4f4 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -524,9 +524,7 @@ declare module __React { preserveAspectRatio?: string; } - interface SVGAttributes extends DOMAttributes { - ref?: string | ((component: SVGComponent) => void); - + interface SVGAttributes extends HTMLAttributes { cx?: number | string; cy?: number | string; d?: string; @@ -540,7 +538,6 @@ declare module __React { fy?: number | string; gradientTransform?: string; gradientUnits?: string; - height?: number | string; markerEnd?: string; markerMid?: string; markerStart?: string; @@ -565,7 +562,6 @@ declare module __React { transform?: string; version?: string; viewBox?: string; - width?: number | string; x1?: number | string; x2?: number | string; x?: number | string; From cc6ccf4737a32db214856dfc5f61a1644bcb7077 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Mon, 3 Aug 2015 16:38:57 +0100 Subject: [PATCH 037/309] Type definitions and tests for pascal-case --- pascal-case/pascal-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 pascal-case/pascal-case.d.ts diff --git a/pascal-case/pascal-case.d.ts b/pascal-case/pascal-case.d.ts new file mode 100644 index 0000000000..9e52ed3e01 --- /dev/null +++ b/pascal-case/pascal-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for pascal-case +// Project: https://github.com/blakeembrey/pascal-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "pascal-case" { + function pascalCase(string: string, locale?: string): string; + export = pascalCase; +} From b9afb4c0f2b0d04684740d1f703b38fd7a44a0b1 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Mon, 3 Aug 2015 16:40:35 +0100 Subject: [PATCH 038/309] Type definitions and tests for pascal-case --- pascal-case/pascal-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 pascal-case/pascal-case-tests.ts diff --git a/pascal-case/pascal-case-tests.ts b/pascal-case/pascal-case-tests.ts new file mode 100644 index 0000000000..b13ed26657 --- /dev/null +++ b/pascal-case/pascal-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import pascalCase = require('pascal-case'); + +console.log(pascalCase('string')); // => "String" +console.log(pascalCase('camelCase')); // => "CamelCase" +console.log(pascalCase('sentence case')); // => "SentenceCase" + +console.log(pascalCase('MY STRING', 'tr')); // => "MyStrıng" From 7c27233ae47768442b9b0a40d7f03fadf593fad2 Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 4 Aug 2015 01:22:49 +0900 Subject: [PATCH 039/309] fix angular-ui-bootstrap/angular-ui-bootstrap-tests.ts --- 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 a5dc969ed1..9a5c1cd7c4 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -121,7 +121,7 @@ testApp.config(( placement: 'bottom', animation: false, popupDelay: 1000, - appendToBody: true + appendToBody: true, useContentExp: true }); $tooltipProvider.setTriggers({ From cc1daf7d8484e79259142163a002d8c672affb05 Mon Sep 17 00:00:00 2001 From: Eric Pelz Date: Mon, 3 Aug 2015 09:44:58 -0700 Subject: [PATCH 040/309] Rename React DnD test file --- react-dnd/{react-dnd-test.ts => react-dnd-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename react-dnd/{react-dnd-test.ts => react-dnd-tests.ts} (100%) diff --git a/react-dnd/react-dnd-test.ts b/react-dnd/react-dnd-tests.ts similarity index 100% rename from react-dnd/react-dnd-test.ts rename to react-dnd/react-dnd-tests.ts From d9062429c30ae4e5fc2245509fc2c6dd773f086d Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 4 Aug 2015 02:09:12 +0900 Subject: [PATCH 041/309] refactor constructor interface of codemirror --- codemirror/codemirror.d.ts | 203 +++++++++++++++++++------------------ 1 file changed, 105 insertions(+), 98 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 537f892235..1e766a1ce8 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -7,8 +7,8 @@ declare function CodeMirror(host: HTMLElement, options?: CodeMirror.EditorConfig declare function CodeMirror(callback: (host: HTMLElement) => void , options?: CodeMirror.EditorConfiguration): CodeMirror.Editor; declare module CodeMirror { - export var Doc : CodeMirror.Doc; - export var Pos: CodeMirror.Position; + export var Doc : CodeMirror.DocConstructor; + export var Pos: CodeMirror.PositionConstructor; export var Pass: any; function fromTextArea(host: HTMLTextAreaElement, options?: EditorConfiguration): CodeMirror.EditorFromTextArea; @@ -88,84 +88,84 @@ declare module CodeMirror { or the line the widget is on require the widget to be redrawn. */ function on(line: LineWidget, eventName: 'redraw', handler: () => void ): void; function off(line: LineWidget, eventName: 'redraw', handler: () => void ): void; - - /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. - Handlers for such events can be registered with the on and off methods on the objects that the event fires on. + + /** Various CodeMirror-related objects emit events, which allow client code to react to various situations. + Handlers for such events can be registered with the on and off methods on the objects that the event fires on. To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object. */ function signal(target: any, name: string, ...args: any[]): void; interface Editor { - + /** Tells you whether the editor currently has focus. */ hasFocus(): boolean; - + /** Used to find the target position for horizontal cursor motion.start is a { line , ch } object, amount an integer(may be negative), and unit one of the string "char", "column", or "word". Will return a position that is produced by moving amount times the distance specified by unit. When visually is true , motion in right - to - left text will be visual rather than logical. When the motion was clipped by hitting the end or start of the document, the returned value will have a hitSide property set to true. */ findPosH(start: CodeMirror.Position, amount: number, unit: string, visually: boolean): { line: number; ch: number; hitSide?: boolean; }; - + /** Similar to findPosH , but used for vertical motion.unit may be "line" or "page". The other arguments and the returned value have the same interpretation as they have in findPosH. */ findPosV(start: CodeMirror.Position, amount: number, unit: string): { line: number; ch: number; hitSide?: boolean; }; - - + + /** Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option. */ setOption(option: string, value: any): void; - + /** Retrieves the current value of the given option for this editor instance. */ getOption(option: string): any; - + /** Attach an additional keymap to the editor. This is mostly useful for add - ons that need to register some key handlers without trampling on the extraKeys option. Maps added in this way have a higher precedence than the extraKeys and keyMap options, and between them, the maps added earlier have a lower precedence than those added later, unless the bottom argument was passed, in which case they end up below other keymaps added with this method. */ addKeyMap(map: any, bottom?: boolean): void; - + /** Disable a keymap added with addKeyMap.Either pass in the keymap object itself , or a string, which will be compared against the name property of the active keymaps. */ removeKeyMap(map: any): void; - + /** Enable a highlighting overlay.This is a stateless mini - mode that can be used to add extra highlighting. For example, the search add - on uses it to highlight the term that's currently being searched. mode can be a mode spec or a mode object (an object with a token method). The options parameter is optional. If given, it should be an object. Currently, only the opaque option is recognized. This defaults to off, but can be given to allow the overlay styling, when not null, to override the styling of the base mode entirely, instead of the two being applied together. */ addOverlay(mode: any, options?: any): void; - + /** Pass this the exact argument passed for the mode parameter to addOverlay to remove an overlay again. */ removeOverlay(mode: any): void; - - + + /** Retrieve the currently active document from an editor. */ getDoc(): CodeMirror.Doc; - + /** Attach a new document to the editor. Returns the old document, which is now no longer associated with an editor. */ swapDoc(doc: CodeMirror.Doc): CodeMirror.Doc; - - - + + + /** Sets the gutter marker for the given gutter (identified by its CSS class, see the gutters option) to the given value. Value can be either null, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line. */ setGutterMarker(line: any, gutterID: string, value: HTMLElement): CodeMirror.LineHandle; - + /** Remove all gutter markers in the gutter with the given ID. */ clearGutter(gutterID: string): void; - + /** Set a CSS class name for the given line.line can be a number or a line handle. where determines to which element this class should be applied, can can be one of "text" (the text element, which lies in front of the selection), "background"(a background element that will be behind the selection), or "wrap" (the wrapper node that wraps all of the line's elements, including gutter elements). class should be the name of the class to apply. */ addLineClass(line: any, where: string, _class_: string): CodeMirror.LineHandle; - + /** Remove a CSS class from a line.line can be a line handle or number. where should be one of "text", "background", or "wrap"(see addLineClass). class can be left off to remove all classes for the specified node, or be a string to remove only a specific class. */ removeLineClass(line: any, where: string, class_: string): CodeMirror.LineHandle; - + /** Returns the line number, text content, and marker status of the given line, which can be either a number or a line handle. */ lineInfo(line: any): { line: any; @@ -179,12 +179,12 @@ declare module CodeMirror { /** Array of line widgets attached to this line. */ widgets: any; }; - + /** Puts node, which should be an absolutely positioned DOM node, into the editor, positioned right below the given { line , ch } position. When scrollIntoView is true, the editor will ensure that the entire node is visible (if possible). To remove the widget again, simply use DOM methods (move it somewhere else, or call removeChild on its parent). */ addWidget(pos: CodeMirror.Position, node: HTMLElement, scrollIntoView: boolean): void; - + /** Adds a line widget, an element shown below a line, spanning the whole of the editor's width, and moving the lines below it downwards. line should be either an integer or a line handle, and node should be a DOM node, which will be displayed below the given line. options, when given, should be an object that configures the behavior of the widget. @@ -199,16 +199,16 @@ declare module CodeMirror { /** When true, will cause the widget to be rendered even if the line it is associated with is hidden. */ showIfHidden: boolean; }): CodeMirror.LineWidget; - - + + /** Programatically set the size of the editor (overriding the applicable CSS rules). width and height height can be either numbers(interpreted as pixels) or CSS units ("100%", for example). You can pass null for either of them to indicate that that dimension should not be changed. */ setSize(width: any, height: any): void; - + /** Scroll the editor to a given(pixel) position.Both arguments may be left as null or undefined to have no effect. */ scrollTo(x: number, y: number): void; - + /** Get an { left , top , width , height , clientWidth , clientHeight } object that represents the current scroll position, the size of the scrollable area, and the size of the visible area(minus scrollbars). */ getScrollInfo(): { @@ -219,53 +219,53 @@ declare module CodeMirror { clientWidth: any; clientHeight: any; } - + /** Scrolls the given element into view. pos is a { line , ch } position, referring to a given character, null, to refer to the cursor. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ scrollIntoView(pos: CodeMirror.Position, margin?: number): void; - + /** Scrolls the given element into view. pos is a { left , top , right , bottom } object, in editor-local coordinates. The margin parameter is optional. When given, it indicates the amount of pixels around the given area that should be made visible as well. */ scrollIntoView(pos: { left: number; top: number; right: number; bottom: number; }, margin: number): void; - + /** Returns an { left , top , bottom } object containing the coordinates of the cursor position. If mode is "local" , they will be relative to the top-left corner of the editable document. If it is "page" or not given, they are relative to the top-left corner of the page. where is a boolean indicating whether you want the start(true) or the end(false) of the selection. */ cursorCoords(where: boolean, mode: string): { left: number; top: number; bottom: number; }; - + /** Returns an { left , top , bottom } object containing the coordinates of the cursor position. If mode is "local" , they will be relative to the top-left corner of the editable document. If it is "page" or not given, they are relative to the top-left corner of the page. where specifies the precise position at which you want to measure. */ cursorCoords(where: CodeMirror.Position, mode: string): { left: number; top: number; bottom: number; }; - + /** Returns the position and dimensions of an arbitrary character.pos should be a { line , ch } object. This differs from cursorCoords in that it'll give the size of the whole character, rather than just the position that the cursor would have when it would sit at that position. */ charCoords(pos: CodeMirror.Position, mode: string): { left: number; right: number; top: number; bottom: number; }; - + /** Given an { left , top } object , returns the { line , ch } position that corresponds to it. The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window" , "page"(the default) , or "local". */ coordsChar(object: { left: number; top: number; }, mode?: string): CodeMirror.Position; - + /** Returns the line height of the default font for the editor. */ defaultTextHeight(): number; - + /** Returns the pixel width of an 'x' in the default font for the editor. (Note that for non - monospace fonts , this is mostly useless, and even for monospace fonts, non - ascii characters might have a different width). */ defaultCharWidth(): number; - + /** Returns a { from , to } object indicating the start (inclusive) and end (exclusive) of the currently rendered part of the document. In big documents, when most content is scrolled out of view, CodeMirror will only render the visible part, and a margin around it. See also the viewportChange event. */ getViewport(): { from: number; to: number }; - + /** If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended. */ refresh(): void; - - + + /** Retrieves information about the token the current mode found before the given position (a {line, ch} object). */ getTokenAt(pos: CodeMirror.Position): { /** The character(on the given line) at which the token starts. */ @@ -277,20 +277,20 @@ declare module CodeMirror { /** The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null). */ type: string; /** The mode's state at the end of this token. */ - state: any; + state: any; }; - + /** Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line. */ getStateAfter(line?: number): any; - + /** CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function. */ operation(fn: ()=> T): T; - + /** Adjust the indentation of the given line. The second argument (which defaults to "smart") may be one of: "prev" Base indentation on the indentation of the previous line. @@ -298,35 +298,35 @@ declare module CodeMirror { "add" Increase the indentation of the line by one indent unit. "subtract" Reduce the indentation of the line. */ indentLine(line: number, dir?: string): void; - - + + /** Give the editor focus. */ focus(): void; - + /** Returns the hidden textarea used to read input. */ getInputField(): HTMLTextAreaElement; - + /** Returns the DOM node that represents the editor, and controls its size. Remove this from your tree to delete an editor instance. */ getWrapperElement(): HTMLElement; - + /** Returns the DOM node that is responsible for the scrolling of the editor. */ getScrollerElement(): HTMLElement; - + /** Fetches the DOM node that contains the editor gutters. */ getGutterElement(): HTMLElement; - - - + + + /** Events are registered with the on method (and removed with the off method). These are the events that fire on the instance object. The name of the event is followed by the arguments that will be passed to the handler. The instance argument always refers to the editor instance. */ on(eventName: string, handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: string, handler: (instance: CodeMirror.Editor) => void ): void; - + /** 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; - + /** 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. Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. @@ -334,64 +334,67 @@ declare module CodeMirror { probably cause the editor to become corrupted. */ on(eventName: 'beforeChange', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeCancellable) => void ): void; off(eventName: 'beforeChange', handler: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeCancellable) => void ): void; - + /** Will be fired when the cursor or selection moves, or any change is made to the editor content. */ on(eventName: 'cursorActivity', handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: 'cursorActivity', handler: (instance: CodeMirror.Editor) => void ): void; - + /** This event is fired before the selection is moved. Its handler may modify the resulting selection head and anchor. Handlers for this event have the same restriction as "beforeChange" handlers � they should not do anything to directly update the state of the editor. */ on(eventName: 'beforeSelectionChange', handler: (instance: CodeMirror.Editor, selection: { head: CodeMirror.Position; anchor: CodeMirror.Position; }) => void ): void; off(eventName: 'beforeSelectionChange', handler: (instance: CodeMirror.Editor, selection: { head: CodeMirror.Position; anchor: CodeMirror.Position; }) => void ): void; - + /** Fires whenever the view port of the editor changes (due to scrolling, editing, or any other factor). The from and to arguments give the new start and end of the viewport. */ on(eventName: 'viewportChange', handler: (instance: CodeMirror.Editor, from: number, to: number) => void ): void; off(eventName: 'viewportChange', handler: (instance: CodeMirror.Editor, from: number, to: number) => void ): void; - + /** Fires when the editor gutter (the line-number area) is clicked. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw mousedown event object as fourth argument. */ on(eventName: 'gutterClick', handler: (instance: CodeMirror.Editor, line: number, gutter: string, clickEvent: Event) => void ): void; off(eventName: 'gutterClick', handler: (instance: CodeMirror.Editor, line: number, gutter: string, clickEvent: Event) => void ): void; - + /** Fires whenever the editor is focused. */ on(eventName: 'focus', handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: 'focus', handler: (instance: CodeMirror.Editor) => void ): void; - + /** Fires whenever the editor is unfocused. */ on(eventName: 'blur', handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: 'blur', handler: (instance: CodeMirror.Editor) => void ): void; - + /** Fires when the editor is scrolled. */ on(eventName: 'scroll', handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: 'scroll', handler: (instance: CodeMirror.Editor) => void ): void; - + /** Will be fired whenever CodeMirror updates its DOM display. */ on(eventName: 'update', handler: (instance: CodeMirror.Editor) => void ): void; off(eventName: 'update', handler: (instance: CodeMirror.Editor) => void ): void; - + /** Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor. */ on(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; off(eventName: 'renderLine', handler: (instance: CodeMirror.Editor, line: number, element: HTMLElement) => void ): void; } - + interface EditorFromTextArea extends Editor { - + /** Copy the content of the editor into the textarea. */ save(): void; - + /** Remove the editor, and restore the original textarea (with the editor's current content). */ toTextArea(): void; - + /** Returns the textarea that the instance was based on. */ getTextArea(): HTMLTextAreaElement; } - interface Doc { - new (text: string, mode?: any, firstLineNumber?: number): Doc; + interface DocConstructor { + new (text: string, mode?: any, firstLineNumber?: number, lineSep?: string): Doc; + (text: string, mode?: any, firstLineNumber?: number, lineSep?: string): Doc; + } + interface Doc { /** Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n"). */ getValue(seperator?: string): string; @@ -551,7 +554,7 @@ declare module CodeMirror { /** Returns an array of all the bookmarks and marked ranges present at the given position. */ findMarksAt(pos: CodeMirror.Position): TextMarker[]; - + /** Returns an array containing all marked ranges in the document. */ getAllMarks(): CodeMirror.TextMarker[]; @@ -619,8 +622,12 @@ declare module CodeMirror { cancel(): void; } - interface Position { + interface PositionConstructor { new (line: number, ch: number): Position; + (line: number, ch: number): Position; + } + + interface Position { ch: number; line: number; } @@ -654,7 +661,7 @@ declare module CodeMirror { /** Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). Default is true. */ electricChars?: boolean; - + /** Determines whether horizontal cursor movement through right-to-left (Arabic, Hebrew) text is visual (pressing the left arrow moves the cursor left) or logical (pressing the left arrow moves to the next lower index in the string, which is visually right in right-to-left text). @@ -664,16 +671,16 @@ declare module CodeMirror { /** Configures the keymap to use. The default is "default", which is the only keymap defined in codemirror.js itself. Extra keymaps are found in the keymap directory. See the section on keymaps for more information. */ keyMap?: string; - + /** Can be used to specify extra keybindings for the editor, alongside the ones defined by keyMap. Should be either null, or a valid keymap value. */ extraKeys?: any; - + /** Whether CodeMirror should scroll or wrap for long lines. Defaults to false (scroll). */ lineWrapping?: boolean; - + /** Whether to show line numbers to the left of the editor. */ lineNumbers?: boolean; - + /** At which number to start counting lines. Default is 1. */ firstLineNumber?: number; @@ -686,23 +693,23 @@ declare module CodeMirror { May include the CodeMirror-linenumbers class, in order to explicitly set the position of the line number gutter (it will default to be to the right of all other gutters). These class names are the keys passed to setGutterMarker. */ gutters?: string[]; - + /** Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). */ fixedGutter?: boolean; - + /** boolean|string. This disables editing of the editor content by the user. If the special value "nocursor" is given (instead of simply true), focusing of the editor is also disallowed. */ readOnly?: any; - + /**Whether the cursor should be drawn when a selection is active. Defaults to false. */ showCursorWhenSelecting?: boolean; - + /** The maximum number of undo levels that the editor stores. Defaults to 40. */ undoDepth?: number; - + /** The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. Defaults to 500. */ historyEventDelay?: number; - + /** The tab index to assign to the editor. If not given, no tab index will be assigned. */ tabindex?: number; @@ -775,21 +782,21 @@ declare module CodeMirror { interface TextMarkerOptions { /** Assigns a CSS class to the marked stretch of text. */ className?: string; - + /** Determines whether text inserted on the left of the marker will end up inside or outside of it. */ inclusiveLeft?: boolean; - + /** 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 respectively directly before and directly after the range. */ atomic?: boolean; - + /** Collapsed ranges do not show up in the display.Setting a range to be collapsed will automatically make it atomic. */ collapsed?: boolean; - + /** When enabled, will cause the mark to clear itself whenever the cursor enters its range. 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. */ @@ -797,7 +804,7 @@ declare module CodeMirror { /** 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; @@ -807,18 +814,18 @@ declare module CodeMirror { * 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, because existing undo events being partially nullified by read - only spans would corrupt the history (in the current implementation). */ readOnly?: boolean; - + /** When set to true (default is false), adding this marker will create an event in the undo history that can be individually undone(clearing the marker). */ addToHistory?: boolean; - + /** Can be used to specify an extra CSS class to be applied to the leftmost span that is part of the marker. */ startStyle?: string; - + /** Equivalent to startStyle, but for the rightmost span. */ endStyle?: string; @@ -827,12 +834,12 @@ declare module CodeMirror { /** 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; } - + interface StringStream { lastColumnPos: number; lastColumnValue: number; From d67ace5d6fc8d280b82672d64c7a1ed86ea7a214 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: Mon, 3 Aug 2015 16:38:59 -0400 Subject: [PATCH 042/309] Fix for AMD require import of Dropzone --- dropzone/dropzone.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 655db62203..475925469d 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -1,6 +1,6 @@ // Type definitions for Dropzone 3.7.1 // Project: http://www.dropzonejs.com/ -// Definitions by: Natan Vivo +// Definitions by: Natan Vivo , Andy Hawkins // Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -93,3 +93,7 @@ declare class Dropzone { interface JQuery { dropzone(options: DropzoneOptions): Dropzone; } + +declare module "Dropzone" { + export = Dropzone; +} From 51bcadbed05822b9f701ffddb8158cdc955a2fe5 Mon Sep 17 00:00:00 2001 From: Adam Babcock Date: Mon, 3 Aug 2015 16:28:52 -0500 Subject: [PATCH 043/309] Add typing for data-driven --- data-driven/data-driven-tests.ts | 8 ++++++++ data-driven/data-driven.d.ts | 9 +++++++++ 2 files changed, 17 insertions(+) create mode 100644 data-driven/data-driven-tests.ts create mode 100644 data-driven/data-driven.d.ts diff --git a/data-driven/data-driven-tests.ts b/data-driven/data-driven-tests.ts new file mode 100644 index 0000000000..b91c8361a2 --- /dev/null +++ b/data-driven/data-driven-tests.ts @@ -0,0 +1,8 @@ +/// + +import data_driven = require('data-driven'); + +data_driven([ + {key:"value"}, + {key:"foobar"} + ],() => {}); diff --git a/data-driven/data-driven.d.ts b/data-driven/data-driven.d.ts new file mode 100644 index 0000000000..79bb80b315 --- /dev/null +++ b/data-driven/data-driven.d.ts @@ -0,0 +1,9 @@ +// Type definitions for data-driven.js +// Project: https://github.com/fluentsoftware/data-driven +// Definitions by: Adam Babcock +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "data-driven" { + function data_driven(data:T[], callback:()=>any):any; + export = data_driven +} From 207710d2a0446e4f5ac7936352ffa7a968b86321 Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Mon, 3 Aug 2015 16:52:18 -0700 Subject: [PATCH 044/309] React: Include required render() function in base Component class. The new TSX mode in the TypeScript compiler has the requirements that the element class constructor produces an element instance type that is assignable to the type JSX.ElementClass. To meet this Component must declare `render(): JSX.Element`. Derived classes can be more specific. This should resolve Microsoft/TypeScript#3928. --- react/react-global.d.ts | 1 + react/react.d.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/react/react-global.d.ts b/react/react-global.d.ts index 3c1a69e439..4ba7266eb2 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -136,6 +136,7 @@ declare module React { setState(f: (prevState: S, props: P) => S, callback?: () => any): void; setState(state: S, callback?: () => any): void; forceUpdate(): void; + render(): JSX.Element; props: P; state: S; context: any; diff --git a/react/react.d.ts b/react/react.d.ts index 5fbad0d227..0ed794f1e8 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -136,6 +136,7 @@ declare module __React { setState(f: (prevState: S, props: P) => S, callback?: () => any): void; setState(state: S, callback?: () => any): void; forceUpdate(): void; + render(): JSX.Element; props: P; state: S; context: any; From a8643986acbfff0e6b37728ee023546a09205964 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 03:12:43 +0200 Subject: [PATCH 045/309] fixed definition of Vex.Flow.Bend --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index afdc5f25a7..2d3cae9660 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -222,7 +222,7 @@ declare module Vex { 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 { + class Bend extends Modifier { constructor(text : string, release? : boolean, phrase? : {type : number, text : string, width : number}[]); static CATEGORY : string; static UP : number; From d64b972ee9095b53fc8f6078680068b72c00ddae Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 03:21:29 +0200 Subject: [PATCH 046/309] fixed definition of Vex.Flow.GraceNote --- vexflow/vexflow.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 2d3cae9660..ab995f3f1a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -468,6 +468,7 @@ declare module Vex { } class GraceNote extends StaveNote { + constructor(note_struct : {slash? : boolean, type? : string, dots? : number, duration : string, clef? : string, keys : string[], octave_shift? : number, auto_stem? : boolean, stem_direction? : number}); getStemExtension() : number; getCategory() : string; draw() : void; From b2d719a615fe0766ef0f21db4c3e8897114ee593 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 03:36:32 +0200 Subject: [PATCH 047/309] fixed definition of Vex.Flow.GraceNoteGroup --- vexflow/vexflow.d.ts | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index ab995f3f1a..2ffc1e6482 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -474,15 +474,19 @@ declare module Vex { draw() : void; } - class GraceNoteGroup { + class GraceNoteGroup extends Modifier { + //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed + setWidth(width : number) : Modifier; + setNote(note : StaveNote) : Modifier; + 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; + setNote(note : Note) : void; //inconsistent type: void -> GraceNoteGroup + setWidth(width : number) : void; //inconsistent type: void -> GraceNoteGroup getWidth() : number; setXShift(x_shift : number) : void; draw() : void; From 25288cd386bf1168eb621a00be3665e7ef073cf3 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 04:10:16 +0200 Subject: [PATCH 048/309] changed difinition of Vex.Flow.Music - changed NUM_TONES from static to const - added definitions of helper tables --- vexflow/vexflow.d.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 2ffc1e6482..75908add3a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -552,8 +552,21 @@ declare module Vex { postFormat() : void; } + module Music { + const NUM_TONES : number; + const roots : string[]; + const root_values : number[]; + const root_indices : {[root : string] : number}; + const canonical_notes : string[]; + const diatonic_intervals : string[]; + const diatonic_accidentals : {[diatonic_interval : string] : {note : number, accidental : number}}; + const intervals : {[interval : string] : number}; + const scales : {[scale : string] : number[]}; + const accidentals : string[]; + const noteValues : {[value : string] : {root_index : number, int_val : number}}; + } + class Music { - static NUM_TONES : number; isValidNoteValue(note : number) : boolean; isValidIntervalValue(interval : number) : boolean; getNoteParts(noteString : string) : {root : string, accidental : string}; From d94584436795ad9b610b175ec18fba7d85ec18b5 Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Tue, 4 Aug 2015 00:17:05 -0400 Subject: [PATCH 049/309] Angularjs: Add bind-to-controller to IControllerService --- angularjs/angular.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 11f46b0642..9fc2ffb0e3 100755 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1227,8 +1227,8 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// interface IControllerService { // Although the documentation doesn't state this, locals are optional - (controllerConstructor: Function, locals?: any): any; - (controllerName: string, locals?: any): any; + (controllerConstructor: Function, locals?: any, bindToController?: any): any; + (controllerName: string, locals?: any, bindToController?: any): any; } interface IControllerProvider extends IServiceProvider { From 89c1517a8acbf3ab1bd513e395cc4065264d2170 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 4 Aug 2015 12:12:26 +0500 Subject: [PATCH 050/309] lodash: added _.ary() method --- lodash/lodash-tests.ts | 4 ++++ lodash/lodash.d.ts | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 14f68e1c41..aff134772b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -759,6 +759,10 @@ _.forEach(saves, function (type) { asyncSave({ 'type': type, 'complete': done }); }); +// _.ary +result = ['6', '8', '10'].map(_.ary<(s: string) => number>(parseInt, 1)); +result = ['6', '8', '10'].map(_(parseInt).ary<(s: string) => number>(1).value()); + // _.backflow var testBackflowSquareFn = (n: number) => n * n; var testBackflowAddFn = (n: number, m: number) => n + m; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ee21347665..a644381e03 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5149,6 +5149,25 @@ declare module _ { after(func: Function): LoDashObjectWrapper; } + //_.ary + interface LoDashStatic { + /** + * Creates a function that accepts up to n arguments ignoring any additional arguments. + * @param func The function to cap arguments for. + * @param n The arity cap. + * @param guard Enables use as a callback for functions like `_.map`. + * @returns Returns the new function. + */ + ary(func: Function, n?: number, guard?: Object): TResult; + } + + interface LoDashObjectWrapper { + /** + * @see _.ary + */ + ary(n?: number, guard?: Object): LoDashObjectWrapper; + } + //_.backflow interface LoDashStatic { /** From 3e2a590f8f6bcf3bf72a6d7b939894c38b3a65a4 Mon Sep 17 00:00:00 2001 From: "Ciuca, Alexandru" Date: Tue, 4 Aug 2015 10:57:41 +0300 Subject: [PATCH 051/309] angularjs - Switched any to generics for type safety. See https://github.com/Microsoft/TypeScript/issues/4126 --- angularjs/angular-tests.ts | 4 ++-- angularjs/angular.d.ts | 21 +++++++++------------ 2 files changed, 11 insertions(+), 14 deletions(-) mode change 100755 => 100644 angularjs/angular-tests.ts mode change 100755 => 100644 angularjs/angular.d.ts diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts old mode 100755 new mode 100644 index fed501acd7..6b79b93ccf --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -30,7 +30,7 @@ class AuthService { '$rootScope', '$injector', function($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) { var $http: ng.IHttpService; //initialized later because of circular dependency problem function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) { - $http = $http || $injector.get('$http'); + $http = $http || $injector.get('$http'); $http(config).then(function (response) { deferred.resolve(response); }); @@ -285,7 +285,7 @@ test_IAttributes({ $addClass: function (classVal){}, $removeClass: function(classVal){}, $set: function(key, value){}, - $observe: function(name, fn){ + $observe: function(name: any, fn: any){ return fn; }, $attr: {} diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts old mode 100755 new mode 100644 index 11f46b0642..4b3702c229 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -237,7 +237,7 @@ declare module angular { forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; fromJson(json: string): any; - identity(arg?: any): any; + identity(arg?: T): T; injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; isArray(value: any): boolean; isDate(value: any): boolean; @@ -453,7 +453,7 @@ declare module angular { * following compilation. The observer is then invoked whenever the * interpolated value changes. */ - $observe(name: string, fn: (value?: any) => any): Function; + $observe(name: string, fn: (value?: T) => any): Function; /** * A map of DOM element attribute names to the normalized name. This is needed @@ -708,7 +708,6 @@ declare module angular { // see http://docs.angularjs.org/api/ng.$window /////////////////////////////////////////////////////////////////////////// interface IWindowService extends Window { - [key: string]: any; } /////////////////////////////////////////////////////////////////////////// @@ -717,7 +716,6 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// interface IBrowserService { defer: angular.ITimeoutService; - [key: string]: any; } /////////////////////////////////////////////////////////////////////////// @@ -725,7 +723,7 @@ declare module angular { // see http://docs.angularjs.org/api/ng.$timeout /////////////////////////////////////////////////////////////////////////// interface ITimeoutService { - (func: Function, delay?: number, invokeApply?: boolean): IPromise; + (func: (...args: any[]) => T, delay?: number, invokeApply?: boolean): IPromise; cancel(promise: IPromise): boolean; } @@ -996,8 +994,7 @@ declare module angular { * See http://docs.angularjs.org/api/ng/service/$q */ interface IQService { - new (resolver: (resolve: IQResolveReject) => any): IPromise; - new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject) => any): IPromise; new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; /** @@ -1156,7 +1153,7 @@ declare module angular { * * @param key the key of the data to be retrieved */ - get(key: string): any; + get(key: string): T; /** * Removes an entry from the Cache object. @@ -1587,7 +1584,7 @@ declare module angular { scope: IScope, instanceElement: IAugmentedJQuery, instanceAttributes: IAttributes, - controller: any, + controller: {}, transclude: ITranscludeFunction ): void; } @@ -1607,7 +1604,7 @@ declare module angular { interface IDirective { compile?: IDirectiveCompileFn; - controller?: any; + controller?: {}; controllerAs?: string; bindToController?: boolean|Object; link?: IDirectiveLinkFn | IDirectivePrePost; @@ -1682,9 +1679,9 @@ declare module angular { interface IInjectorService { annotate(fn: Function): string[]; annotate(inlineAnnotatedFunction: any[]): string[]; - get(name: string): any; + get(name: string): T; has(name: string): boolean; - instantiate(typeConstructor: Function, locals?: any): any; + instantiate(typeConstructor: Function, locals?: any): T; invoke(inlineAnnotatedFunction: any[]): any; invoke(func: Function, context?: any, locals?: any): any; } From 1a9ee560ef02abec59b6e2218c585be93905cfbb Mon Sep 17 00:00:00 2001 From: "Ciuca, Alexandru" Date: Tue, 4 Aug 2015 11:03:12 +0300 Subject: [PATCH 052/309] react - Replaced any with {} for context See https://github.com/Microsoft/TypeScript/issues/4126 --- react/react-addons-tests.ts | 2 ++ react/react-addons.d.ts | 2 +- react/react-global.d.ts | 2 +- react/react-tests.ts | 2 ++ react/react.d.ts | 2 +- 5 files changed, 7 insertions(+), 3 deletions(-) diff --git a/react/react-addons-tests.ts b/react/react-addons-tests.ts index 492fe4d817..6976d9959d 100644 --- a/react/react-addons-tests.ts +++ b/react/react-addons-tests.ts @@ -84,6 +84,8 @@ class ModernComponent extends React.Component someOtherValue: React.PropTypes.string } + context: Context; + getChildContext() { return { someOtherValue: 'foo' diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index 37cde636dc..49c8ab0ba6 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -137,7 +137,7 @@ declare module "react/addons" { forceUpdate(): void; props: P; state: S; - context: any; + context: {}; refs: { [key: string]: Component }; diff --git a/react/react-global.d.ts b/react/react-global.d.ts index 3c1a69e439..3f261297b2 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -138,7 +138,7 @@ declare module React { forceUpdate(): void; props: P; state: S; - context: any; + context: {}; refs: { [key: string]: Component }; diff --git a/react/react-tests.ts b/react/react-tests.ts index 1fd2670dec..a4d2c4f7ac 100644 --- a/react/react-tests.ts +++ b/react/react-tests.ts @@ -82,6 +82,8 @@ class ModernComponent extends React.Component someOtherValue: React.PropTypes.string } + context: Context; + getChildContext() { return { someOtherValue: 'foo' diff --git a/react/react.d.ts b/react/react.d.ts index 5fbad0d227..1e5c358992 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -138,7 +138,7 @@ declare module __React { forceUpdate(): void; props: P; state: S; - context: any; + context: {}; refs: { [key: string]: Component }; From 4b1040d341a9a9a19c2fde0790412b5f40be3731 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 4 Aug 2015 13:32:16 +0500 Subject: [PATCH 053/309] lodash: added _.before() method --- lodash/lodash-tests.ts | 18 ++++++++++++++++++ lodash/lodash.d.ts | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 14f68e1c41..f60472eefe 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -765,6 +765,24 @@ var testBackflowAddFn = (n: number, m: number) => n + m; result = _.backflow<(n: number, m: number) => number>(testBackflowSquareFn, testBackflowAddFn)(1, 2); result = _(testBackflowSquareFn).backflow<(n: number, m: number) => number>(testBackflowAddFn).value()(1, 2); +// _.before +var testBeforeFn = ((n: number) => () => ++n)(0); +var testBeforeResultFn = <() => number>_.before<() => number>(3, testBeforeFn); +result = testBeforeResultFn(); +// → 1 +result = testBeforeResultFn(); +// → 2 +result = testBeforeResultFn(); +// → 2 +var testBeforeFn = ((n: number) => () => ++n)(0); +var testBeforeResultFn = <() => number>_(3).before<() => number>(testBeforeFn); +result = testBeforeResultFn(); +// → 1 +result = testBeforeResultFn(); +// → 2 +result = testBeforeResultFn(); +// → 2 + var funcBind = function(greeting: string, punctuation: string) { return greeting + ' ' + this.user + punctuation; }; var funcBound1: (punctuation: string) => any = _.bind(funcBind, { 'name': 'moe' }, 'hi'); funcBound1('!'); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ee21347665..1e92962fcd 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5164,6 +5164,26 @@ declare module _ { backflow(...funcs: Function[]): LoDashObjectWrapper; } + //_.before + interface LoDashStatic { + /** + * Creates a function that invokes func, with the this binding and arguments of the created function, while + * it is called less than n times. Subsequent calls to the created function return the result of the last func + * invocation. + * @param n The number of calls at which func is no longer invoked. + * @param func The function to restrict. + * @return Returns the new restricted function. + */ + before(n: number, func: TFunc): TFunc; + } + + interface LoDashWrapper { + /** + * @sed _.before + */ + before(func: TFunc): TFunc; + } + //_.bind interface LoDashStatic { /** From 3bbbea2814a5556aaf6e8100f61a5372d5a2d53a Mon Sep 17 00:00:00 2001 From: Chris Apers Date: Tue, 4 Aug 2015 11:15:43 +0200 Subject: [PATCH 054/309] Fixed #3728: Modernizr Prefixed definition returns boolean --- modernizr/modernizr.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modernizr/modernizr.d.ts b/modernizr/modernizr.d.ts index 5827bbf9eb..6fd8fd4f77 100644 --- a/modernizr/modernizr.d.ts +++ b/modernizr/modernizr.d.ts @@ -1,3 +1,4 @@ + // Type definitions for Modernizr 2.6.2 // Project: http://modernizr.com/ // Definitions by: Boris Yankov , Theodore Brown @@ -96,9 +97,8 @@ interface ModernizrStatic { load(resourceObject: any): void; load(resourceString: string): void; - prefixed(): boolean; - prefixed(property: string): boolean; - prefixed(property: string, obj: any, element?: any): boolean; + prefixed(property: string): any; + prefixed(property: string, obj: any, element?: any): any; mq(mediaQuery: string): boolean; From 1128507d08029cf01fe76610909f2d48a2757d06 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Tue, 4 Aug 2015 14:18:43 +0500 Subject: [PATCH 055/309] lodash: added _.restParam() method --- lodash/lodash-tests.ts | 12 ++++++++++++ lodash/lodash.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 14f68e1c41..16ff862775 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -951,6 +951,18 @@ var optionsPartialRight = { defaultsDeep(optionsPartialRight, _.templateSettings); +//_.restParam +var testRestParamFn = (a: string, b: string, c: number[]) => a + ' ' + b + ' ' + c.join(' '); +interface testRestParamFunc { + (a: string, b: string, c: number[]): string; +} +interface testRestParamResult { + (a: string, b: string, ...c: number[]): string; +} +result = (_.restParam(testRestParamFn, 2))('a', 'b', 1, 2, 3); +result = (_.restParam(testRestParamFn, 2))('a', 'b', 1, 2, 3); +result = (_(testRestParamFn).restParam(2).value())('a', 'b', 1, 2, 3); + var throttled = _.throttle(function () { }, 100); jQuery(window).on('scroll', throttled); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ee21347665..811c633a73 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5595,6 +5595,30 @@ declare module _ { ...args: any[]): Function; } + //_.restParam + interface LoDashStatic { + /** + * Creates a function that invokes func with the this binding of the created function and arguments from start + * and beyond provided as an array. + * @param func The function to apply a rest parameter to. + * @param start The start position of the rest parameter. + * @return Returns the new function. + */ + restParam(func: Function, start?: number): TResult; + + /** + * @see _.restParam + */ + restParam(func: TFunc, start?: number): TResult; + } + + interface LoDashObjectWrapper { + /** + * @see _.restParam + */ + restParam(start?: number): LoDashObjectWrapper; + } + //_.throttle interface LoDashStatic { /** From 52dbf6cb6f6875b2ce9355ecaf6e74f334abd962 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 11:41:33 +0200 Subject: [PATCH 056/309] fixed definition of Vex.Flow.NoteHead --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 75908add3a..a69baaba89 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -628,7 +628,7 @@ declare module Vex { } 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}); + constructor(head_options : {x? : number, y? : number, note_type? : string, duration : string, displaced? : boolean, stem_direction? : number, line : number, x_shift : number, custom_glyph_code? : string, style? : string, slashed? : boolean, glyph_font_scale? : number}); static DEBUG : boolean; getCategory() : string; setContext(context : IRenderContext) : NoteHead; From 09154f4618f532f7290d43f30db56df4b8cd2ec4 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Tue, 4 Aug 2015 11:47:58 +0200 Subject: [PATCH 057/309] changed definition of Vex.Flow.Pedalmarking - added GLYPHS const - changed Styles enum from static to const --- vexflow/vexflow.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index a69baaba89..5786f1dbe8 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -662,7 +662,8 @@ declare module Vex { } export module PedalMarking { - enum Styles {TEXT, BRACKET, MIXED} + const enum Styles {TEXT, BRACKET, MIXED} + const GLYPHS : {[name : string] : {code : string, x_shift : number, y_shift : number}}; } class PedalMarking { From 4fd66c5614446dbf18266f9e13a72eee39b8998b 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, 4 Aug 2015 05:55:47 -0400 Subject: [PATCH 058/309] Update dropzone.d.ts to v4.0.1 support. --- dropzone/dropzone.d.ts | 175 ++++++++++++++++++++++++----------------- 1 file changed, 102 insertions(+), 73 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 475925469d..137604772c 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Dropzone 3.7.1 +// Type definitions for Dropzone 4.0.1 // Project: http://www.dropzonejs.com/ // Definitions by: Natan Vivo , Andy Hawkins // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -6,94 +6,123 @@ /// interface DropzoneFile extends File { - previewElement: HTMLElement; - previewTemplate: HTMLElement; - previewsContainer: HTMLElement; - status: string; - accepted: boolean; + previewElement: HTMLElement; + previewTemplate: HTMLElement; + previewsContainer: HTMLElement; + status: string; + accepted: boolean; } interface DropzoneOptions { - url?: string; - method?: string; - withCredentials?: boolean; - parallelUploads?: number; - maxFilesize?: number; - paramName?: string; - uploadMultiple?: boolean; - headers?: any; - addRemoveLinks?: boolean; - previewsContainer?: string; - clickable?: any; - createImageThumbnails?: boolean; - maxThumbnailFilesize?: number; - thumbnailWidth?: number; - thumbnailHeight?: number; - maxFiles?: number; - resize?: (file?: any) => any; - init?: () => void; - acceptedFiles?: string; - accept?: (file: DropzoneFile, doneCallback: (...args) => void) => void; - autoProcessQueue?: boolean; - previewTemplate?: string; - forceFallback?: boolean; - fallback?: () => void; + url?: string; + method?: string; + withCredentials?: boolean; + parallelUploads?: number; + maxFilesize?: number; + paramName?: string; + uploadMultiple?: boolean; + headers?: any; + addRemoveLinks?: boolean; + previewsContainer?: string; + clickable?: any; + createImageThumbnails?: boolean; + maxThumbnailFilesize?: number; + thumbnailWidth?: number; + thumbnailHeight?: number; + maxFiles?: number; + resize?: ( file?: any ) => any; + init?: () => void; + acceptedFiles?: string; + accept?: ( file: DropzoneFile, doneCallback: ( ...args ) => void ) => void; + autoProcessQueue?: boolean; + previewTemplate?: string; + forceFallback?: boolean; + fallback?: () => void; - // dictionary options - dictDefaultMessage?: string; - dictFallbackMessage?: string; - dictFallbackText?: string; - dictInvalidFileType?: string; - dictFileTooBig?: string; - dictResponseError?: string; - dictCancelUpload?: string; - dictCancelUploadConfirmation?: string; - dictRemoveFile?: string; - dictRemoveFileConfirmation?: string; - dictMaxFilesExceeded?: string; + // dictionary options + dictDefaultMessage?: string; + dictFallbackMessage?: string; + dictFallbackText?: string; + dictInvalidFileType?: string; + dictFileTooBig?: string; + dictResponseError?: string; + dictCancelUpload?: string; + dictCancelUploadConfirmation?: string; + dictRemoveFile?: string; + dictRemoveFileConfirmation?: string; + dictMaxFilesExceeded?: string; } declare class Dropzone { - constructor(container: string, options?: DropzoneOptions); - constructor(container: HTMLElement, options?: DropzoneOptions); - static autoDiscover: boolean; - static options: any; - static confirm: (question: string, accepted: () => void, rejected?: () => void) => void; + constructor( container: string, options?: DropzoneOptions ); + constructor( container: HTMLElement, options?: DropzoneOptions ); - files: DropzoneFile[]; + static autoDiscover: boolean; + static options: any; + static confirm: ( question: string, accepted: () => void, rejected?: () => void ) => void; - on(eventName, callback: (...args) => any); - off(eventName): void; + files: DropzoneFile[]; - removeFile(file: DropzoneFile): void; - removeAllFiles(cancelIfNecessary?: boolean): void; - processQueue(): void; - getAcceptedFiles(): DropzoneFile[]; - getRejectedFiles(): DropzoneFile[]; - getQueuedFiles(): DropzoneFile[]; - getUploadingFiles(): DropzoneFile[]; + enable(): void; + disable(): void; + destroy(): Dropzone; - emit(eventName: string, file: DropzoneFile, str?: string); - emit(eventName: "thumbnail", file: DropzoneFile, path: string); - emit(eventName: "addedfile", file: DropzoneFile); - emit(eventName: "removedfile", file: DropzoneFile); - emit(eventName: "processing", file: DropzoneFile); - emit(eventName: "canceled", file: DropzoneFile); - emit(eventName: "complete", file: DropzoneFile); + on( eventName, callback: ( ...args ) => any ); - emit(eventName: string, e: Event); - emit(eventName: "drop", e: Event); - emit(eventName: "dragstart", e: Event); - emit(eventName: "dragend", e: Event); - emit(eventName: "dragenter", e: Event); - emit(eventName: "dragover", e: Event); - emit(eventName: "dragleave", e: Event); + off( eventName ): void; + + addFile( file: DropzoneFile ): void; + + removeFile( file: DropzoneFile ): void; + + removeAllFiles( cancelIfNecessary?: boolean ): void; + + processQueue(): void; + + cancelUpload( file: DropzoneFile ): void; + + processFiles ( files: DropzoneFile[] ): void; + processFile( file: DropzoneFile ): void; + + uploadFile( file: DropzoneFile ): void; + + getAcceptedFiles(): DropzoneFile[]; + + getRejectedFiles(): DropzoneFile[]; + + getQueuedFiles(): DropzoneFile[]; + + getUploadingFiles(): DropzoneFile[]; + + accept( file: DropzoneFile, done: ( error?: string ) => {} ):void; + getActiveFiles(): DropzoneFile[]; + getFilesWithStatus( status: string ): DropzoneFile[]; + enqueueFile( file: DropzoneFile ): void; + enqueueFiles( file: DropzoneFile[] ): void; + createThumbnail( file: DropzoneFile, callback?: (...any) => {}): any; + createThumbnailFromUrl( file: DropzoneFile, url: string, callback?: ( ...any ) => any ): any; + + emit( eventName: string, file: DropzoneFile, str?: string ); + emit( eventName: "thumbnail", file: DropzoneFile, path: string ); + emit( eventName: "addedfile", file: DropzoneFile ); + emit( eventName: "removedfile", file: DropzoneFile ); + emit( eventName: "processing", file: DropzoneFile ); + emit( eventName: "canceled", file: DropzoneFile ); + emit( eventName: "complete", file: DropzoneFile ); + + emit( eventName: string, e: Event ); + emit( eventName: "drop", e: Event ); + emit( eventName: "dragstart", e: Event ); + emit( eventName: "dragend", e: Event ); + emit( eventName: "dragenter", e: Event ); + emit( eventName: "dragover", e: Event ); + emit( eventName: "dragleave", e: Event ); } interface JQuery { - dropzone(options: DropzoneOptions): Dropzone; + dropzone( options: DropzoneOptions ): Dropzone; } declare module "Dropzone" { - export = Dropzone; + export = Dropzone; } From febcd082a03dd186cccb02da8aa5959fcc390179 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Tue, 4 Aug 2015 11:33:59 +0100 Subject: [PATCH 059/309] Rename resemble to resemblejs --- resemble/resemble-tests.ts => resemblejs/resemblejs-tests.ts | 0 resemble/resemble.d.ts => resemblejs/resemblejs.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename resemble/resemble-tests.ts => resemblejs/resemblejs-tests.ts (100%) rename resemble/resemble.d.ts => resemblejs/resemblejs.d.ts (100%) diff --git a/resemble/resemble-tests.ts b/resemblejs/resemblejs-tests.ts similarity index 100% rename from resemble/resemble-tests.ts rename to resemblejs/resemblejs-tests.ts diff --git a/resemble/resemble.d.ts b/resemblejs/resemblejs.d.ts similarity index 100% rename from resemble/resemble.d.ts rename to resemblejs/resemblejs.d.ts From 14ae003c6278f67609270e612991872e1ca1edba Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Tue, 4 Aug 2015 12:14:44 +0100 Subject: [PATCH 060/309] Add _.flattenDeep to lodash --- lodash/lodash-tests.ts | 4 ++++ lodash/lodash.d.ts | 26 +++++++++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 14f68e1c41..ae43c3b28f 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -253,11 +253,15 @@ result = >_.flatten([1, [2], [[3]]], true); result = >_.flatten([1, [2], [3, [[4]]]], true); result = >_.flatten([1, [2], [3, [[false]]]], true); +result = >_.flattenDeep([[[[1]]]]); + result = <_.LoDashArrayWrapper>_([[1, 2], [3, 4], 5, 6]).flatten(); result = <_.LoDashArrayWrapper>>>_([1, [2], [3, [[4]]]]).flatten(); result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flatten(true); +result = <_.LoDashArrayWrapper>_([1, [2], [3, [[4]]]]).flattenDeep(); + result = _.indexOf([1, 2, 3, 1, 2, 3], 2); result = _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); result = _.indexOf([1, 1, 2, 2, 3, 3], 2, true); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ee21347665..7b99962349 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -800,7 +800,9 @@ declare module _ { //_.flatten interface LoDashStatic { /** - * Flattens a nested array. + * Flattens a nested array a single level. + * + * _.flatten(x) is equivalent to _.flatten(x, false); * * @param array The array to flatten. * @return `array` flattened. @@ -811,11 +813,24 @@ declare module _ { * Flattens a nested array. If isDeep is true the array is recursively flattened, otherwise it is only * flattened a single level. * + * If you know whether or not this should be recursively at compile time, you typically want to use a + * version without a boolean parameter (i.e. `_.flatten(x)` or `_.flattenDeep(x)`). + * * @param array The array to flatten. * @param deep Specify a deep flatten. * @return `array` flattened. **/ flatten(array: RecursiveList, isDeep: boolean): List | RecursiveList; + + /** + * Recursively flattens a nested array. + * + * _.flattenDeep(x) is equivalent to _.flatten(x, true); + * + * @param array The array to flatten + * @return `array` recursively flattened + */ + flattenDeep(array: RecursiveList): List } interface LoDashArrayWrapper { @@ -825,9 +840,14 @@ declare module _ { flatten(): LoDashArrayWrapper; /** - * @see _.flatten - **/ + * @see _.flatten + **/ flatten(isShallow: boolean): LoDashArrayWrapper; + + /** + * @see _.flattenDeep + */ + flattenDeep(): LoDashArrayWrapper; } //_.indexOf From dccc81ea05777bfed0307e4123974b682e6b46ab Mon Sep 17 00:00:00 2001 From: Stefan Profanter Date: Tue, 4 Aug 2015 13:45:01 +0100 Subject: [PATCH 061/309] Added transformcontrols and missing fields --- threejs/three-trackballcontrols.d.ts | 6 +++++- threejs/three-transformcontrols.d.ts | 19 +++++++++++++++++++ threejs/three.d.ts | 3 +++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 threejs/three-transformcontrols.d.ts diff --git a/threejs/three-trackballcontrols.d.ts b/threejs/three-trackballcontrols.d.ts index e969bcb5e5..17f45ec914 100644 --- a/threejs/three-trackballcontrols.d.ts +++ b/threejs/three-trackballcontrols.d.ts @@ -28,6 +28,10 @@ declare module THREE { maxDistance:number; keys:number[]; + position0: THREE.Vector3; + target0: THREE.Vector3; + up0: THREE.Vector3; + update():void; reset():void; checkDistances():void; @@ -38,4 +42,4 @@ declare module THREE { handleResize():void; handleEvent(event: any):void; } -} +} \ No newline at end of file diff --git a/threejs/three-transformcontrols.d.ts b/threejs/three-transformcontrols.d.ts new file mode 100644 index 0000000000..bf9e7a48c2 --- /dev/null +++ b/threejs/three-transformcontrols.d.ts @@ -0,0 +1,19 @@ + +/// + +declare module THREE { + class TransformControls extends Object3D { + constructor(object:Camera, domElement?:HTMLElement); + + object: Object3D; + + update():void; + detach(object: Object3D): void; + attach(object: Object3D): void; + setMode(mode: string): void; + setSnap(snap: any): void; + setSize(size:number):void; + setSpace(space:string):void; + + } +} \ No newline at end of file diff --git a/threejs/three.d.ts b/threejs/three.d.ts index d87541145c..993a228c36 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -5673,6 +5673,7 @@ declare module THREE { export class BoundingBoxHelper extends Mesh { constructor(object: Object3D, hex?: number); + constructor(); object: Object3D; box: Box3; @@ -5791,6 +5792,8 @@ declare module THREE { export class WireframeHelper extends Line { constructor(object: Object3D, hex?: number); + object: Object3D; + } // Extras / Objects ///////////////////////////////////////////////////////////////////// From d7b3ef8b9ea3f7e85eb3ed4f1f44bf904a48cd30 Mon Sep 17 00:00:00 2001 From: Stefan Profanter Date: Tue, 4 Aug 2015 14:48:56 +0200 Subject: [PATCH 062/309] Added header --- threejs/three-transformcontrols.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/threejs/three-transformcontrols.d.ts b/threejs/three-transformcontrols.d.ts index bf9e7a48c2..5be96cd032 100644 --- a/threejs/three-transformcontrols.d.ts +++ b/threejs/three-transformcontrols.d.ts @@ -1,3 +1,7 @@ +// Type definitions for three.js (TransformControls.js) +// Project: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/TransformControls.js +// Definitions by: Stefan Profanter +// Definitions: https://github.com/borisyankov/DefinitelyTyped /// @@ -16,4 +20,4 @@ declare module THREE { setSpace(space:string):void; } -} \ No newline at end of file +} From d5050e48433c16e87a1d9e6a38b0fdc1de1b91d2 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, 4 Aug 2015 08:55:15 -0400 Subject: [PATCH 063/309] lowercase module. --- dropzone/dropzone.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 137604772c..106e103132 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -123,6 +123,6 @@ interface JQuery { dropzone( options: DropzoneOptions ): Dropzone; } -declare module "Dropzone" { +declare module "dropzone" { export = Dropzone; } From 84a8620a8234b471e76ff57ff2c350642a18ca56 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 4 Aug 2015 14:04:25 +0100 Subject: [PATCH 064/309] Type definitions and tests for path-case --- path-case/path-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 path-case/path-case.d.ts diff --git a/path-case/path-case.d.ts b/path-case/path-case.d.ts new file mode 100644 index 0000000000..bb577cac8c --- /dev/null +++ b/path-case/path-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for path-case +// Project: https://github.com/blakeembrey/path-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "path-case" { + function pathCase(string: string, locale?: string): string; + export = pathCase; +} From 6a43c576ef95f57e5e4f48e0e94b5f02d27679c1 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 4 Aug 2015 14:05:01 +0100 Subject: [PATCH 065/309] Create path-case-tests.ts --- path-case/path-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 path-case/path-case-tests.ts diff --git a/path-case/path-case-tests.ts b/path-case/path-case-tests.ts new file mode 100644 index 0000000000..863559b2eb --- /dev/null +++ b/path-case/path-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import pathCase = require('path-case'); + +console.log(pathCase('string')); // => "string" +console.log(pathCase('camelCase')); // => "camel/case" +console.log(pathCase('sentence case')); // => "sentence/case" + +console.log(pathCase('MY STRING', 'tr')); // => "my.strıng" From 471c254078813643aad9c278c58121eccf58df66 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 4 Aug 2015 14:05:44 +0100 Subject: [PATCH 066/309] Type definitions and tests for path-case --- path-case/path-case-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/path-case/path-case-tests.ts b/path-case/path-case-tests.ts index 863559b2eb..8c17cbd44b 100644 --- a/path-case/path-case-tests.ts +++ b/path-case/path-case-tests.ts @@ -6,4 +6,4 @@ console.log(pathCase('string')); // => "string" console.log(pathCase('camelCase')); // => "camel/case" console.log(pathCase('sentence case')); // => "sentence/case" -console.log(pathCase('MY STRING', 'tr')); // => "my.strıng" +console.log(pathCase('MY STRING', 'tr')); // => "my.strıng" From 8f0a389126ab29145684c7a8108cb3871b14edfc Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 16:01:43 +0200 Subject: [PATCH 067/309] minorTickInterval can be "auto" as well as a number. --- highcharts/highcharts.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 9bda29782d..c0326d1c2a 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -114,7 +114,7 @@ interface HighchartsAxisOptions { minRange?: number; minTickInterval?: number; minorTickColor?: string; - minorTickInterval?: number; + minorTickInterval?: number|string; minorTickLength?: number; minorTickPosition?: string; // 'inside' 'outside' minorTickWidth?: number; @@ -191,11 +191,11 @@ interface HighchartsChartResetZoomButton { } interface HighchartsChartResetZoomButtonTheme { - fill?: string; //css HEX colours. - stroke?: string;//css HEX colours. + fill?: string; //css HEX colours. + stroke?: string;//css HEX colours. r?: number; // Radius % - states?: any; // HTML element states eg: hover, with css attributes in object. - display?: string; // css attr eg: 'none' + states?: any; // HTML element states eg: hover, with css attributes in object. + display?: string; // css attr eg: 'none' } interface HighchartsChartOptions { From b9ba90e8ef52371cf05ab9818fa41f265ecb021f Mon Sep 17 00:00:00 2001 From: Alex Manekovskiy Date: Tue, 4 Aug 2015 17:03:10 +0300 Subject: [PATCH 068/309] Added missing CodeMirror.Doc method - listSelections The missing method is listed in documentation in [Selection](https://codemirror.net/doc/manual.html#api_selection) section between `doc.getCursor` and `doc.somethingSelected` methods. --- codemirror/codemirror.d.ts | 146 +++++++++++++++++++------------------ 1 file changed, 75 insertions(+), 71 deletions(-) diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts index 71113ee828..86c01141e1 100644 --- a/codemirror/codemirror.d.ts +++ b/codemirror/codemirror.d.ts @@ -326,15 +326,15 @@ 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. */ + + /** 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. + + /** 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. Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, @@ -471,6 +471,10 @@ declare module CodeMirror { It may be "start" , "end" , "head"(the side of the selection that moves when you press shift + arrow), or "anchor"(the fixed side of the selection).Omitting the argument is the same as passing "head".A { line , ch } object will be returned. */ getCursor(start?: string): CodeMirror.Position; + + /** Retrieves a list of all current selections. These will always be sorted, and never overlap (overlapping selections are merged). + Each object in the array contains anchor and head properties referring to {line, ch} objects. */ + listSelections(): { anchor: CodeMirror.Position; head: CodeMirror.Position }[]; /** Return true if any text is selected. */ somethingSelected(): boolean; @@ -612,7 +616,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; } @@ -780,9 +784,9 @@ declare module CodeMirror { This affects the amount of updates needed when scrolling, and the amount of work that such an update does. You should usually leave it at its default, 10. Can be set to Infinity to make sure the whole document is always rendered, and thus the browser's text search works on it. This will have bad effects on performance of big documents. */ - viewportMargin?: number; - - /** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */ + viewportMargin?: number; + + /** Optional lint configuration to be used in conjunction with CodeMirror's linter addon. */ lint?: LintOptions; } @@ -796,8 +800,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; @@ -808,19 +812,19 @@ 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; + + /** 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; + + /** 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, @@ -835,12 +839,12 @@ 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; + + /** 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. */ @@ -1041,48 +1045,48 @@ declare module CodeMirror { * Both modes get to parse all of the text, but when both assign a non-null style to a piece of code, the overlay wins, unless * the combine argument was true and not overridden, or state.overlay.combineTokens was true, in which case the styles are combined. */ - function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode - - /** - * async specifies that the lint process runs asynchronously. hasGutters specifies that lint errors should be displayed in the CodeMirror - * gutter, note that you must use this in conjunction with [ "CodeMirror-lint-markers" ] as an element in the gutters argument on - * initialization of the CodeMirror instance. - */ - interface LintStateOptions { - async: boolean; - hasGutters: boolean; - } - - /** - * Adds the getAnnotations callback to LintStateOptions which may be overridden by the user if they choose use their own - * linter. - */ - interface LintOptions extends LintStateOptions { - getAnnotations: AnnotationsCallback; - } - - /** - * A function that calls the updateLintingCallback with any errors found during the linting process. - */ - interface AnnotationsCallback { - (content: string, updateLintingCallback: UpdateLintingCallback, options: LintStateOptions, codeMirror: Editor): void; - } - - /** - * A function that, given an array of annotations, updates the CodeMirror linting GUI with those annotations - */ - interface UpdateLintingCallback { - (codeMirror: Editor, annotations: Annotation[]): void; - } - - /** - * An annotation contains a description of a lint error, detailing the location of the error within the code, the severity of the error, - * and an explaination as to why the error was thrown. - */ - interface Annotation { - from: Position; - message?: string; - severity?: string; - to?: Position; + function overlayMode(base: Mode, overlay: Mode, combine?: boolean): Mode + + /** + * async specifies that the lint process runs asynchronously. hasGutters specifies that lint errors should be displayed in the CodeMirror + * gutter, note that you must use this in conjunction with [ "CodeMirror-lint-markers" ] as an element in the gutters argument on + * initialization of the CodeMirror instance. + */ + interface LintStateOptions { + async: boolean; + hasGutters: boolean; + } + + /** + * Adds the getAnnotations callback to LintStateOptions which may be overridden by the user if they choose use their own + * linter. + */ + interface LintOptions extends LintStateOptions { + getAnnotations: AnnotationsCallback; + } + + /** + * A function that calls the updateLintingCallback with any errors found during the linting process. + */ + interface AnnotationsCallback { + (content: string, updateLintingCallback: UpdateLintingCallback, options: LintStateOptions, codeMirror: Editor): void; + } + + /** + * A function that, given an array of annotations, updates the CodeMirror linting GUI with those annotations + */ + interface UpdateLintingCallback { + (codeMirror: Editor, annotations: Annotation[]): void; + } + + /** + * An annotation contains a description of a lint error, detailing the location of the error within the code, the severity of the error, + * and an explaination as to why the error was thrown. + */ + interface Annotation { + from: Position; + message?: string; + severity?: string; + to?: Position; } } From 7931d62c5469cb8cb90cd006fa87fcded24e3b28 Mon Sep 17 00:00:00 2001 From: Chris Apers Date: Tue, 4 Aug 2015 16:06:37 +0200 Subject: [PATCH 069/309] Blank line --- modernizr/modernizr.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/modernizr/modernizr.d.ts b/modernizr/modernizr.d.ts index 6fd8fd4f77..a9104fd226 100644 --- a/modernizr/modernizr.d.ts +++ b/modernizr/modernizr.d.ts @@ -1,4 +1,3 @@ - // Type definitions for Modernizr 2.6.2 // Project: http://modernizr.com/ // Definitions by: Boris Yankov , Theodore Brown From ad926271e86a4d4861f0aaa97e01f93303d810f4 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Tue, 4 Aug 2015 16:24:39 +0200 Subject: [PATCH 070/309] Visible property should be boolean, not number --- highcharts/highcharts.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index c0326d1c2a..c29eb65f0b 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -877,7 +877,7 @@ interface HighchartsLineChart { stickyTracking?: boolean; tooltip?: HighchartsTooltipOptions; turboThreshold?: number; - visible?: number; + visible?: boolean; zIndex?: number; } @@ -911,7 +911,7 @@ interface HighchartsPieChart { }; stickyTracking?: boolean; tooltip?: HighchartsTooltipOptions; - visible?: number; + visible?: boolean; zIndex?: number; } @@ -953,7 +953,7 @@ interface HighchartsScatterChart { stickyTracking?: boolean; tooltip?: HighchartsTooltipOptions; turboThreshold?: number; - visible?: number; + visible?: boolean; zIndex?: number; } @@ -1006,7 +1006,7 @@ interface HighchartsSeriesChart { stickyTracking?: boolean; tooltip?: HighchartsTooltipOptions; turboThreshold?: number; - visible?: number; + visible?: boolean; zIndex?: number; } From f4442b0842860cc6eec384b5e21e5cc478aac554 Mon Sep 17 00:00:00 2001 From: Matija Grcic Date: Tue, 4 Aug 2015 16:16:58 +0100 Subject: [PATCH 071/309] Adding umbraco type definitions --- umbraco/umbraco-resources.d.ts | 1737 +++++++++++++++++++++++ umbraco/umbraco-services.d.ts | 2387 ++++++++++++++++++++++++++++++++ umbraco/umbraco-tests.ts | 93 ++ umbraco/umbraco.d.ts | 20 + 4 files changed, 4237 insertions(+) create mode 100644 umbraco/umbraco-resources.d.ts create mode 100644 umbraco/umbraco-services.d.ts create mode 100644 umbraco/umbraco-tests.ts create mode 100644 umbraco/umbraco.d.ts diff --git a/umbraco/umbraco-resources.d.ts b/umbraco/umbraco-resources.d.ts new file mode 100644 index 0000000000..6ddb05cc15 --- /dev/null +++ b/umbraco/umbraco-resources.d.ts @@ -0,0 +1,1737 @@ +// Type definitions for Umbraco v7.2.8 +// Project: https://github.com/umbraco +// Definitions by: DeCareSystemsIreland +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module umbraco.resources{ + + /** + * ResourcePromise object + * The success callback returns the data which will be resolved by the deferred object. + * The error callback returns an object containing: {errorMsg: errorMessage, data: originalData, status: status } + */ + export interface IResourcePromise { + errorMsg: string; + data: any; + status: number; + } + + /** + * Can be Ascending or Descending - Default: Ascending + */ + enum Direction { + Ascending, + Descending + } + + /** + * Property to order items by, default: `SortOrder` + */ + enum OrderItemsBy { + SortOrder + } + +/** + * @ngdoc service + * @name umbraco.resources.authResource + * @description + * This Resource perfomrs actions to common authentication tasks for the Umbraco backoffice user + * + * @requires $q + * @requires $http + * @requires umbRequestHelper + * @requires angularHelper + */ +interface IAuthResource{ + + /** + * @ngdoc method + * @name umbraco.resources.authResource#performLogin + * @methodOf umbraco.resources.authResource + * + * @description + * Logs the Umbraco backoffice user in if the credentials are good + * + * ##usage + *

+         * authResource.performLogin(login, password)
+         *    .then(function(data) {
+         *        //Do stuff for login...
+         *    });
+         * 
+ * @param {string} login Username of backoffice user + * @param {string} password Password of backoffice user + * @returns {Promise} resourcePromise object + * + */ + performLogin(username: string, password: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.authResource#performLogout + * @methodOf umbraco.resources.authResource + * + * @description + * Logs out the Umbraco backoffice user + * + * ##usage + *
+         * authResource.performLogout()
+         *    .then(function(data) {
+         *        //Do stuff for logging out...
+         *    });
+         * 
+ * @returns {Promise} resourcePromise object + * + */ + performLogout(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.authResource#getCurrentUser + * @methodOf umbraco.resources.authResource + * + * @description + * Sends a request to the server to get the current user details, will return a 401 if the user is not logged in + * + * ##usage + *
+         * authResource.getCurrentUser()
+         *    .then(function(data) {
+         *        //Do stuff for fetching the current logged in Umbraco backoffice user
+         *    });
+         * 
+ * @returns {Promise} resourcePromise object + * + */ + getCurrentUser(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.authResource#isAuthenticated + * @methodOf umbraco.resources.authResource + * + * @description + * Checks if the user is logged in or not - does not return 401 or 403 + * + * ##usage + *
+         * authResource.isAuthenticated()
+         *    .then(function(data) {
+         *        //Do stuff to check if user is authenticated
+         *    });
+         * 
+ * @returns {Promise} resourcePromise object + * + */ + isAuthenticated(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.authResource#getRemainingTimeoutSeconds + * @methodOf umbraco.resources.authResource + * + * @description + * Gets the user's remaining seconds before their login times out + * + * ##usage + *
+         * authResource.getRemainingTimeoutSeconds()
+         *    .then(function(data) {
+         *        //Number of seconds is returned
+         *    });
+         * 
+ * @returns {Promise} resourcePromise object + * + */ + getRemainingTimeoutSeconds(): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.contentResource + * @description Handles all transactions of content data + * from the angular application to the Umbraco database, using the Content WebApi controller + * + * all methods returns a resource promise async, so all operations won't complete untill .then() is completed. + * + * @requires $q + * @requires $http + * @requires umbDataFormatter + * @requires umbRequestHelper + * + * ##usage + * To use, simply inject the contentResource into any controller or service that needs it, and make + * sure the umbraco.resources module is accesible - which it should be by default. + * + *
+  *    contentResource.getById(1234)
+  *          .then(function(data) {
+  *              $scope.content = data;
+  *          });
+  * 
+ **/ +interface IContentResource{ + /** + * @ngdoc method + * @name umbraco.resources.contentResource#sort + * @methodOf umbraco.resources.contentResource + * + * @description + * Sorts all children below a given parent node id, based on a collection of node-ids + * + * ##usage + *
+         * var ids = [123,34533,2334,23434];
+         * contentResource.sort({ parentId: 1244, sortedIds: ids })
+         *    .then(function() {
+         *        $scope.complete = true;
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.parentId the ID of the parent node + * @param {Array} options.sortedIds array of node IDs as they should be sorted + * @returns {Promise} resourcePromise object. + * + */ + sort(...args: any[]): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#move + * @methodOf umbraco.resources.contentResource + * + * @description + * Moves a node underneath a new parentId + * + * ##usage + *
+         * contentResource.move({ parentId: 1244, id: 123 })
+         *    .then(function() {
+         *        alert("node was moved");
+         *    }, function(err){
+         *      alert("node didnt move:" + err.data.Message);
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.id the ID of the node to move + * @param {Int} args.parentId the ID of the parent node to move to + * @returns {Promise} resourcePromise object. + * + */ + move(...args: any[]): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#copy + * @methodOf umbraco.resources.contentResource + * + * @description + * Copies a node underneath a new parentId + * + * ##usage + *
+         * contentResource.copy({ parentId: 1244, id: 123 })
+         *    .then(function() {
+         *        alert("node was copied");
+         *    }, function(err){
+         *      alert("node wasnt copy:" + err.data.Message);
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.id the ID of the node to copy + * @param {Int} args.parentId the ID of the parent node to copy to + * @param {Boolean} args.relateToOriginal if true, relates the copy to the original through the relation api + * @returns {Promise} resourcePromise object. + * + */ + copy(...args: any[]): ng.IPromise; + + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#unPublish + * @methodOf umbraco.resources.contentResource + * + * @description + * Unpublishes a content item with a given Id + * + * ##usage + *
+         * contentResource.unPublish(1234)
+         *    .then(function() {
+         *        alert("node was unpulished");
+         *    }, function(err){
+         *      alert("node wasnt unpublished:" + err.data.Message);
+         *    });
+         * 
+ * @param {Int} id the ID of the node to unpublish + * @returns {Promise} resourcePromise object. + * + */ + unPublish(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#emptyRecycleBin + * @methodOf umbraco.resources.contentResource + * + * @description + * Empties the content recycle bin + * + * ##usage + *
+         * contentResource.emptyRecycleBin()
+         *    .then(function() {
+         *        alert('its empty!');
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object. + * + */ + emptyRecycleBin(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#deleteById + * @methodOf umbraco.resources.contentResource + * + * @description + * Deletes a content item with a given id + * + * ##usage + *
+         * contentResource.deleteById(1234)
+         *    .then(function() {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {Int} id id of content item to delete + * @returns {Promise} resourcePromise object. + * + */ + deleteById(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getById + * @methodOf umbraco.resources.contentResource + * + * @description + * Gets a content item with a given id + * + * ##usage + *
+         * contentResource.getById(1234)
+         *    .then(function(content) {
+         *        var myDoc = content;
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id id of content item to return + * @returns {Promise} resourcePromise object containing the content item. + * + */ + getById(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getByIds + * @methodOf umbraco.resources.contentResource + * + * @description + * Gets an array of content items, given a collection of ids + * + * ##usage + *
+         * contentResource.getByIds( [1234,2526,28262])
+         *    .then(function(contentArray) {
+         *        var myDoc = contentArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {Array} ids ids of content items to return as an array + * @returns {Promise} resourcePromise object containing the content items array. + * + */ + getByIds(ids: number[]): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getScaffold + * @methodOf umbraco.resources.contentResource + * + * @description + * Returns a scaffold of an empty content item, given the id of the content item to place it underneath and the content type alias. + * + * - Parent Id must be provided so umbraco knows where to store the content + * - Content Type alias must be provided so umbraco knows which properties to put on the content scaffold + * + * The scaffold is used to build editors for content that has not yet been populated with data. + * + * ##usage + *
+         * contentResource.getScaffold(1234, 'homepage')
+         *    .then(function(scaffold) {
+         *        var myDoc = scaffold;
+         *        myDoc.name = "My new document";
+         *
+         *        contentResource.publish(myDoc, true)
+         *            .then(function(content){
+         *                alert("Retrieved, updated and published again");
+         *            });
+         *    });
+         * 
+ * + * @param {Int} parentId id of content item to return + * @param {String} alias contenttype alias to base the scaffold on + * @returns {Promise} resourcePromise object containing the content scaffold. + * + */ + getScaffold(parentId: number, alias: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getNiceUrl + * @methodOf umbraco.resources.contentResource + * + * @description + * Returns a url, given a node ID + * + * ##usage + *
+         * contentResource.getNiceUrl(id)
+         *    .then(function(url) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id Id of node to return the public url to + * @returns {Promise} resourcePromise object containing the url. + * + */ + getNiceUrl(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getChildren + * @methodOf umbraco.resources.contentResource + * + * @description + * Gets children of a content item with a given id + * + * ##usage + *
+         * contentResource.getChildren(1234, {pageSize: 10, pageNumber: 2})
+         *    .then(function(contentArray) {
+         *        var children = contentArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {Int} parentid id of content item to return children of + * @param {Object} options optional options object + * @param {Int} options.pageSize if paging data, number of nodes per page, default = 0 + * @param {Int} options.pageNumber if paging data, current page index, default = 0 + * @param {String} options.filter if provided, query will only return those with names matching the filter + * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` + * @param {String} options.orderBy property to order items by, default: `SortOrder` + * @returns {Promise} resourcePromise object containing an array of content items. + * + */ + getChildren(parentId: number, options?: { pageSize: number; pageNumber: number; filter: string; orderDirection: Direction; orderBy: OrderItemsBy }): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#hasPermission + * @methodOf umbraco.resources.contentResource + * + * @description + * Returns true/false given a permission char to check against a nodeID + * for the current user + * + * ##usage + *
+         * contentResource.hasPermission('p',1234)
+         *    .then(function() {
+         *        alert('You are allowed to publish this item');
+         *    });
+         * 
+ * + * @param {String} permission char representing the permission to check + * @param {Int} id id of content item to delete + * @returns {Promise} resourcePromise object. + * + */ + checkPermission(permission: string, id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#save + * @methodOf umbraco.resources.contentResource + * + * @description + * Saves changes made to a content item to its current version, if the content item is new, the isNew paramater must be passed to force creation + * if the content item needs to have files attached, they must be provided as the files param and passed seperately + * + * + * ##usage + *
+         * contentResource.getById(1234)
+         *    .then(function(content) {
+         *          content.name = "I want a new name!";
+         *          contentResource.save(content, false)
+         *            .then(function(content){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @param {Object} content The content item object with changes applied + * @param {Bool} isNew set to true to create a new item or to update an existing + * @param {Array} files collection of files for the document + * @returns {Promise} resourcePromise object containing the saved content item. + * + */ + save(content, isNew: boolean, files): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#publish + * @methodOf umbraco.resources.contentResource + * + * @description + * Saves and publishes changes made to a content item to a new version, if the content item is new, the isNew paramater must be passed to force creation + * if the content item needs to have files attached, they must be provided as the files param and passed seperately + * + * + * ##usage + *
+         * contentResource.getById(1234)
+         *    .then(function(content) {
+         *          content.name = "I want a new name, and be published!";
+         *          contentResource.publish(content, false)
+         *            .then(function(content){
+         *                alert("Retrieved, updated and published again");
+         *            });
+         *    });
+         * 
+ * + * @param {Object} content The content item object with changes applied + * @param {Bool} isNew set to true to create a new item or to update an existing + * @param {Array} files collection of files for the document + * @returns {Promise} resourcePromise object containing the saved content item. + * + */ + publish(content, isNew: boolean, files): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#sendToPublish + * @methodOf umbraco.resources.contentResource + * + * @description + * Saves changes made to a content item, and notifies any subscribers about a pending publication + * + * ##usage + *
+         * contentResource.getById(1234)
+         *    .then(function(content) {
+         *          content.name = "I want a new name, and be published!";
+         *          contentResource.sendToPublish(content, false)
+         *            .then(function(content){
+         *                alert("Retrieved, updated and notication send off");
+         *            });
+         *    });
+         * 
+ * + * @param {Object} content The content item object with changes applied + * @param {Bool} isNew set to true to create a new item or to update an existing + * @param {Array} files collection of files for the document + * @returns {Promise} resourcePromise object containing the saved content item. + * + */ + sendToPublish(content, isNew: boolean, files): ng.IPromise; + + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#publishByid + * @methodOf umbraco.resources.contentResource + * + * @description + * Publishes a content item with a given ID + * + * ##usage + *
+         * contentResource.publishById(1234)
+         *    .then(function(content) {
+         *        alert("published");
+         *    });
+         * 
+ * + * @param {Int} id The ID of the conten to publish + * @returns {Promise} resourcePromise object containing the published content item. + * + */ + publishById(id: number): ng.IPromise; + +} + +/** + * @ngdoc service + * @name umbraco.resources.contentTypeResource + * @description Loads in data for content types + **/ +interface IContentTypeResource{ + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getAllowedTypes + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns a list of allowed content types underneath a content item with a given ID + * + * ##usage + *
+         * contentTypeResource.getAllowedTypes(1234)
+         *    .then(function(array) {
+         *        $scope.type = type;
+         *    });
+         * 
+ * @param {Int} contentId id of the content item to retrive allowed child types for + * @returns {Promise} resourcePromise object. + * + */ + getAllowedTypes(contentId: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.contentTypeResource#getAllPropertyTypeAliases + * @methodOf umbraco.resources.contentTypeResource + * + * @description + * Returns a list of defined property type aliases + * + * @returns {Promise} resourcePromise object. + * + */ + getAllPropertyTypeAliases(): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.currentUserResource + * @description Used for read/updates for the currently logged in user + * + * + **/ +interface ICurrentUserResource{ + + /** + * @ngdoc method + * @name umbraco.resources.currentUserResource#changePassword + * @methodOf umbraco.resources.currentUserResource + * + * @description + * Changes the current users password + * + * @returns {Promise} resourcePromise object containing the user array. + * + */ + changePassword(changePasswordArgs): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.currentUserResource#getMembershipProviderConfig + * @methodOf umbraco.resources.currentUserResource + * + * @description + * Gets the configuration of the user membership provider which is used to configure the change password form + */ + getMembershipProviderConfig(); + +} + +/** + * @ngdoc service + * @name umbraco.resources.dashboardResource + * @description Handles loading the dashboard manifest + **/ +interface IDashboardResource{ + /** + * @ngdoc method + * @name umbraco.resources.dashboardResource#getDashboard + * @methodOf umbraco.resources.dashboardResource + * + * @description + * Retrieves the dashboard configuration for a given section + * + * @param {string} section Alias of section to retrieve dashboard configuraton for + * @returns {Promise} resourcePromise object containing the user array. + * + */ + getDashboard(section: string): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.dataTypeResource + * @description Loads in data for data types + **/ +interface IDataTypeResource{ + /** + * @ngdoc method + * @name umbraco.resources.dataTypeResource#getPreValues + * @methodOf umbraco.resources.dataTypeResource + * + * @description + * Retrieves available prevalues for a given data type + editor + * + * ##usage + *
+         * dataTypeResource.getPrevalyes("Umbraco.MediaPicker", 1234)
+         *    .then(function(prevalues) {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {String} editorAlias string alias of editor type to retrive prevalues configuration for + * @param {Int} id id of datatype to retrieve prevalues for + * @returns {Promise} resourcePromise object. + * + */ + getPreValues(editorAlias: string, dataTypeId: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.dataTypeResource#getById + * @methodOf umbraco.resources.dataTypeResource + * + * @description + * Gets a data type item with a given id + * + * ##usage + *
+         * dataTypeResource.getById(1234)
+         *    .then(function() {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {Int} id id of data type to retrieve + * @returns {Promise} resourcePromise object. + * + */ + getById(id: number): ng.IPromise; + + getAll(); + + /** + * @ngdoc method + * @name umbraco.resources.contentResource#getScaffold + * @methodOf umbraco.resources.contentResource + * + * @description + * Returns a scaffold of an empty data type item + * + * The scaffold is used to build editors for data types that has not yet been populated with data. + * + * ##usage + *
+         * dataTypeResource.getScaffold()
+         *    .then(function(scaffold) {
+         *        var myType = scaffold;
+         *        myType.name = "My new data type";
+         *
+         *        dataTypeResource.save(myType, myType.preValues, true)
+         *            .then(function(type){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object containing the data type scaffold. + * + */ + getScaffold(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.dataTypeResource#deleteById + * @methodOf umbraco.resources.dataTypeResource + * + * @description + * Deletes a data type with a given id + * + * ##usage + *
+         * dataTypeResource.deleteById(1234)
+         *    .then(function() {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {Int} id id of content item to delete + * @returns {Promise} resourcePromise object. + * + */ + deleteById(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.dataTypeResource#save + * @methodOf umbraco.resources.dataTypeResource + * + * @description + * Saves or update a data type + * + * @param {Object} dataType data type object to create/update + * @param {Array} preValues collection of prevalues on the datatype + * @param {Bool} isNew set to true if type should be create instead of updated + * @returns {Promise} resourcePromise object. + * + */ + save(dataType, preValues: any[], isNew: boolean): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.entityResource + * @description Loads in basic data for all entities + * + * ##What is an entity? + * An entity is a basic **read-only** representation of an Umbraco node. It contains only the most + * basic properties used to display the item in trees, lists and navigation. + * + * ##What is the difference between entity and content/media/etc...? + * the entity only contains the basic node data, name, id and guid, whereas content + * nodes fetched through the content service also contains additional all of the content property data, etc.. + * This is the same principal for all entity types. Any user that is logged in to the back office will have access + * to view the basic entity information for all entities since the basic entity information does not contain sensitive information. + * + * ##Entity object types? + * You need to specify the type of object you want returned. + * + * The core object types are: + * + * - Document + * - Media + * - Member + * - Template + * - DocumentType + * - MediaType + * - MemberType + * - Macro + * - User + * - Language + * - Domain + * - DataType + **/ +interface IEntityResource{ + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getPath + * @methodOf umbraco.resources.entityResource + * + * @description + * Returns a path, given a node ID and type + * + * ##usage + *
+         * entityResource.getPath(id)
+         *    .then(function(pathArray) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id Id of node to return the public url to + * @param {string} type Object type name + * @returns {Promise} resourcePromise object containing the url. + * + */ + getPath(id: number, type: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getById + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets an entity with a given id + * + * ##usage + *
+         * //get media by id
+         * entityResource.getEntityById(0, "Media")
+         *    .then(function(ent) {
+         *        var myDoc = ent;
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id id of entity to return + * @param {string} type Object type name + * @returns {Promise} resourcePromise object containing the entity. + * + */ + getById(id: number, type: string); + + getByQuery(query, nodeContextId, type: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getByIds + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets an array of entities, given a collection of ids + * + * ##usage + *
+         * //Get templates for ids
+         * entityResource.getEntitiesByIds( [1234,2526,28262], "Template")
+         *    .then(function(templateArray) {
+         *        var myDoc = contentArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {Array} ids ids of entities to return as an array + * @param {string} type type name + * @returns {Promise} resourcePromise object containing the entity array. + * + */ + getByIds(ids: number[], type: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getEntityById + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets an entity with a given id + * + * ##usage + *
+         *
+         * //Only return media
+         * entityResource.getAll("Media")
+         *    .then(function(ent) {
+         *        var myDoc = ent;
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {string} type Object type name + * @param {string} postFilter optional filter expression which will execute a dynamic where clause on the server + * @param {string} postFilterParams optional parameters for the postFilter expression + * @returns {Promise} resourcePromise object containing the entity. + * + */ + getAll(type: string, postFilter: string, postFilterParams: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getAncestors + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets ancestor entities for a given item + * + * + * @param {string} type Object type name + * @returns {Promise} resourcePromise object containing the entity. + * + */ + getAncestors(id: number, type: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#getAncestors + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets children entities for a given item + * + * + * @param {string} type Object type name + * @returns {Promise} resourcePromise object containing the entity. + * + */ + getChildren(id: number, type: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#searchMedia + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets an array of entities, given a lucene query and a type + * + * ##usage + *
+         * entityResource.search("news", "Media")
+         *    .then(function(mediaArray) {
+         *        var myDoc = mediaArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {String} Query search query + * @param {String} Type type of conten to search + * @returns {Promise} resourcePromise object containing the entity array. + * + */ + search(query: string, type: string, searchFrom, canceler): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.entityResource#searchAll + * @methodOf umbraco.resources.entityResource + * + * @description + * Gets an array of entities from all available search indexes, given a lucene query + * + * ##usage + *
+         * entityResource.searchAll("bob")
+         *    .then(function(array) {
+         *        var myDoc = array;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {String} Query search query + * @returns {Promise} resourcePromise object containing the entity array. + * + */ + searchAll(query: string, canceler): ng.IPromise; +} + + /** + * LogType + */ + enum LogType{ + Debug, + Info +} + +/** + * @ngdoc service + * @name umbraco.resources.logResource + * @description Retrives log history from umbraco + * + * + **/ +interface ILogResource{ + /** + * @ngdoc method + * @name umbraco.resources.logResource#getEntityLog + * @methodOf umbraco.resources.logResource + * + * @description + * Gets the log history for a give entity id + * + * ##usage + *
+         * logResource.getEntityLog(1234)
+         *    .then(function(log) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id id of entity to return log history + * @returns {Promise} resourcePromise object containing the log. + * + */ + getEntityLog(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.logResource#getUserLog + * @methodOf umbraco.resources.logResource + * + * @description + * Gets the current users' log history for a given type of log entry + * + * ##usage + *
+         * logResource.getUserLog("save", new Date())
+         *    .then(function(log) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {String} type logtype to query for + * @param {DateTime} since query the log back to this date, by defalt 7 days ago + * @returns {Promise} resourcePromise object containing the log. + * + */ + getUserLog(type: LogType, since: Date): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.logResource#getLog + * @methodOf umbraco.resources.logResource + * + * @description + * Gets the log history for a given type of log entry + * + * ##usage + *
+         * logResource.getLog("save", new Date())
+         *    .then(function(log) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {String} type logtype to query for + * @param {DateTime} since query the log back to this date, by defalt 7 days ago + * @returns {Promise} resourcePromise object containing the log. + * + */ + getLog(type: LogType, since: Date): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.macroResource + * @description Deals with data for macros + * + **/ +interface IMacroResource{ + + /** + * @ngdoc method + * @name umbraco.resources.macroResource#getMacroParameters + * @methodOf umbraco.resources.macroResource + * + * @description + * Gets the editable macro parameters for the specified macro alias + * + * @param {int} macroId The macro id to get parameters for + * + */ + getMacroParameters(macroId: number); + + /** + * @ngdoc method + * @name umbraco.resources.macroResource#getMacroResult + * @methodOf umbraco.resources.macroResource + * + * @description + * Gets the result of a macro as html to display in the rich text editor + * + * @param {int} macroId The macro id to get parameters for + * @param {int} pageId The current page id + * @param {Array} macroParamDictionary A dictionary of macro parameters + * + */ + getMacroResultAsHtmlForEditor(macroId:number, pageId:number, macroParamDictionary: any[]); +} + +/** + * @ngdoc service + * @name umbraco.resources.mediaResource + * @description Loads in data for media + **/ +interface IMediaResource{ + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#sort + * @methodOf umbraco.resources.mediaResource + * + * @description + * Sorts all children below a given parent node id, based on a collection of node-ids + * + * ##usage + *
+         * var ids = [123,34533,2334,23434];
+         * mediaResource.sort({ sortedIds: ids })
+         *    .then(function() {
+         *        $scope.complete = true;
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.parentId the ID of the parent node + * @param {Array} options.sortedIds array of node IDs as they should be sorted + * @returns {Promise} resourcePromise object. + * + */ + sort(...args: any[]): ng.IPromise; + + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#move + * @methodOf umbraco.resources.mediaResource + * + * @description + * Moves a node underneath a new parentId + * + * ##usage + *
+         * mediaResource.move({ parentId: 1244, id: 123 })
+         *    .then(function() {
+         *        alert("node was moved");
+         *    }, function(err){
+         *      alert("node didnt move:" + err.data.Message);
+         *    });
+         * 
+ * @param {Object} args arguments object + * @param {Int} args.idd the ID of the node to move + * @param {Int} args.parentId the ID of the parent node to move to + * @returns {Promise} resourcePromise object. + * + */ + move(...args: any[]): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#getById + * @methodOf umbraco.resources.mediaResource + * + * @description + * Gets a media item with a given id + * + * ##usage + *
+         * mediaResource.getById(1234)
+         *    .then(function(media) {
+         *        var myMedia = media;
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Int} id id of media item to return + * @returns {Promise} resourcePromise object containing the media item. + * + */ + getById(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#deleteById + * @methodOf umbraco.resources.mediaResource + * + * @description + * Deletes a media item with a given id + * + * ##usage + *
+         * mediaResource.deleteById(1234)
+         *    .then(function() {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {Int} id id of media item to delete + * @returns {Promise} resourcePromise object. + * + */ + deleteById(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#getByIds + * @methodOf umbraco.resources.mediaResource + * + * @description + * Gets an array of media items, given a collection of ids + * + * ##usage + *
+         * mediaResource.getByIds( [1234,2526,28262])
+         *    .then(function(mediaArray) {
+         *        var myDoc = contentArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {Array} ids ids of media items to return as an array + * @returns {Promise} resourcePromise object containing the media items array. + * + */ + getByIds(ids: number[]): ng.IPromise; + + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#getScaffold + * @methodOf umbraco.resources.mediaResource + * + * @description + * Returns a scaffold of an empty media item, given the id of the media item to place it underneath and the media type alias. + * + * - Parent Id must be provided so umbraco knows where to store the media + * - Media Type alias must be provided so umbraco knows which properties to put on the media scaffold + * + * The scaffold is used to build editors for media that has not yet been populated with data. + * + * ##usage + *
+         * mediaResource.getScaffold(1234, 'folder')
+         *    .then(function(scaffold) {
+         *        var myDoc = scaffold;
+         *        myDoc.name = "My new media item";
+         *
+         *        mediaResource.save(myDoc, true)
+         *            .then(function(media){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @param {Int} parentId id of media item to return + * @param {String} alias mediatype alias to base the scaffold on + * @returns {Promise} resourcePromise object containing the media scaffold. + * + */ + getScaffold(parentId: number, alias: string): ng.IPromise; + + rootMedia(); + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#getChildren + * @methodOf umbraco.resources.mediaResource + * + * @description + * Gets children of a media item with a given id + * + * ##usage + *
+         * mediaResource.getChildren(1234, {pageSize: 10, pageNumber: 2})
+         *    .then(function(contentArray) {
+         *        var children = contentArray;
+         *        alert('they are here!');
+         *    });
+         * 
+ * + * @param {Int} parentid id of content item to return children of + * @param {Object} options optional options object + * @param {Int} options.pageSize if paging data, number of nodes per page, default = 0 + * @param {Int} options.pageNumber if paging data, current page index, default = 0 + * @param {String} options.filter if provided, query will only return those with names matching the filter + * @param {String} options.orderDirection can be `Ascending` or `Descending` - Default: `Ascending` + * @param {String} options.orderBy property to order items by, default: `SortOrder` + * @returns {Promise} resourcePromise object containing an array of content items. + * + */ + getChildren(parentId: number, options?: { pageSize: number; pageNumber: number; filter: string; orderDirection: Direction; orderBy: OrderItemsBy }): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#save + * @methodOf umbraco.resources.mediaResource + * + * @description + * Saves changes made to a media item, if the media item is new, the isNew paramater must be passed to force creation + * if the media item needs to have files attached, they must be provided as the files param and passed seperately + * + * + * ##usage + *
+         * mediaResource.getById(1234)
+         *    .then(function(media) {
+         *          media.name = "I want a new name!";
+         *          mediaResource.save(media, false)
+         *            .then(function(media){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @param {Object} media The media item object with changes applied + * @param {Bool} isNew set to true to create a new item or to update an existing + * @param {Array} files collection of files for the media item + * @returns {Promise} resourcePromise object containing the saved media item. + * + */ + save(media: Object, isNew: boolean, files: any[]): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#addFolder + * @methodOf umbraco.resources.mediaResource + * + * @description + * Shorthand for adding a media item of the type "Folder" under a given parent ID + * + * ##usage + *
+         * mediaResource.addFolder("My gallery", 1234)
+         *    .then(function(folder) {
+         *        alert('New folder');
+         *    });
+         * 
+ * + * @param {string} name Name of the folder to create + * @param {int} parentId Id of the media item to create the folder underneath + * @returns {Promise} resourcePromise object. + * + */ + addFolder(name: string, parentId: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.mediaResource#emptyRecycleBin + * @methodOf umbraco.resources.mediaResource + * + * @description + * Empties the media recycle bin + * + * ##usage + *
+         * mediaResource.emptyRecycleBin()
+         *    .then(function() {
+         *        alert('its empty!');
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object. + * + */ + emptyRecycleBin(): ng.IPromise; + +} + +/** + * @ngdoc service + * @name umbraco.resources.mediaTypeResource + * @description Loads in data for media types + **/ +interface IMediaTypeResource{ + /** + * @ngdoc method + * @name umbraco.resources.mediaTypeResource#getAllowedTypes + * @methodOf umbraco.resources.mediaTypeResource + * + * @description + * Returns a list of allowed media types underneath a media item with a given ID + * + * ##usage + *
+         * mediaTypeResource.getAllowedTypes(1234)
+         *    .then(function(array) {
+         *        $scope.type = type;
+         *    });
+         * 
+ * @param {Int} mediaId id of the media item to retrive allowed child types for + * @returns {Promise} resourcePromise object. + * + */ + getAllowedTypes(mediaId: number): ng.IPromise; +} + +/** + * @ngdoc service + * @name umbraco.resources.memberResource + * @description Loads in data for members + **/ +interface IMemberResource{ + + getPagedResults(memberTypeAlias: string, options); + + getListNode(listName: string); + + /** + * @ngdoc method + * @name umbraco.resources.memberResource#getByKey + * @methodOf umbraco.resources.memberResource + * + * @description + * Gets a member item with a given key + * + * ##usage + *
+         * memberResource.getByKey("0000-0000-000-00000-000")
+         *    .then(function(member) {
+         *        var mymember = member;
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @param {Guid} key key of member item to return + * @returns {Promise} resourcePromise object containing the member item. + * + */ + getByKey(key: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.memberResource#deleteByKey + * @methodOf umbraco.resources.memberResource + * + * @description + * Deletes a member item with a given key + * + * ##usage + *
+         * memberResource.deleteByKey("0000-0000-000-00000-000")
+         *    .then(function() {
+         *        alert('its gone!');
+         *    });
+         * 
+ * + * @param {Guid} key id of member item to delete + * @returns {Promise} resourcePromise object. + * + */ + deleteByKey(key: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.memberResource#getScaffold + * @methodOf umbraco.resources.memberResource + * + * @description + * Returns a scaffold of an empty member item, given the id of the member item to place it underneath and the member type alias. + * + * - Member Type alias must be provided so umbraco knows which properties to put on the member scaffold + * + * The scaffold is used to build editors for member that has not yet been populated with data. + * + * ##usage + *
+         * memberResource.getScaffold('client')
+         *    .then(function(scaffold) {
+         *        var myDoc = scaffold;
+         *        myDoc.name = "My new member item";
+         *
+         *        memberResource.save(myDoc, true)
+         *            .then(function(member){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @param {String} alias membertype alias to base the scaffold on + * @returns {Promise} resourcePromise object containing the member scaffold. + * + */ + getScaffold(alias: string): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.memberResource#save + * @methodOf umbraco.resources.memberResource + * + * @description + * Saves changes made to a member, if the member is new, the isNew paramater must be passed to force creation + * if the member needs to have files attached, they must be provided as the files param and passed seperately + * + * + * ##usage + *
+         * memberResource.getBykey("23234-sd8djsd-3h8d3j-sdh8d")
+         *    .then(function(member) {
+         *          member.name = "Bob";
+         *          memberResource.save(member, false)
+         *            .then(function(member){
+         *                alert("Retrieved, updated and saved again");
+         *            });
+         *    });
+         * 
+ * + * @param {Object} media The member item object with changes applied + * @param {Bool} isNew set to true to create a new item or to update an existing + * @param {Array} files collection of files for the media item + * @returns {Promise} resourcePromise object containing the saved media item. + * + */ + save(member: Object, isNew: boolean, files: any[]): ng.IPromise; + +} + +/** + * @ngdoc service + * @name umbraco.resources.memberTypeResource + * @description Loads in data for member types + **/ +interface IMemberTypeResource{ + //return all member types + getTypes(); +} + +/** + * @ngdoc service + * @name umbraco.resources.packageInstallResource + * @description handles data for package installations + **/ +interface IPackageResource{ + + /** + * @ngdoc method + * @name umbraco.resources.packageInstallResource#fetchPackage + * @methodOf umbraco.resources.packageInstallResource + * + * @description + * Downloads a package file from our.umbraco.org to the website server. + * + * ##usage + *
+         * packageResource.download("guid-guid-guid-guid")
+         *    .then(function(path) {
+         *        alert('downloaded');
+         *    });
+         * 
+ * + * @param {String} the unique package ID + * @returns {String} path to the downloaded zip file. + * + */ + fetch(id: string): string; + + /** + * @ngdoc method + * @name umbraco.resources.packageInstallResource#createmanifest + * @methodOf umbraco.resources.packageInstallResource + * + * @description + * Creates a package manifest for a given folder of files. + * This manifest keeps track of all installed files and data items + * so a package can be uninstalled at a later time. + * After creating a manifest, you can use the ID to install files and data. + * + * ##usage + *
+         * packageResource.createManifest("packages/id-of-install-file")
+         *    .then(function(summary) {
+         *        alert('unzipped');
+         *    });
+         * 
+ * + * @param {String} folder the path to the temporary folder containing files + * @returns {Int} the ID assigned to the saved package manifest + * + */ + import(package: string): number; + + installFiles(package: string); + + installData(package: string); + + cleanUp(package: string); + +} + +/** + * @ngdoc service + * @name umbraco.resources.sectionResource + * @description Loads in data for section + **/ +interface ISectionResource{ + /** Loads in the data to display the section list */ + getSections(); +} + +/** + * @ngdoc service + * @name umbraco.resources.stylesheetResource + * @description service to retrieve available stylesheets + * + * + **/ +interface IStylesheetResource{ + /** + * @ngdoc method + * @name umbraco.resources.stylesheetResource#getAll + * @methodOf umbraco.resources.stylesheetResource + * + * @description + * Gets all registered stylesheets + * + * ##usage + *
+         * stylesheetResource.getAll()
+         *    .then(function(stylesheets) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object containing the stylesheets. + * + */ + getAll(): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.stylesheetResource#getRules + * @methodOf umbraco.resources.stylesheetResource + * + * @description + * Returns all defined child rules for a stylesheet with a given ID + * + * ##usage + *
+         * stylesheetResource.getRules(2345)
+         *    .then(function(rules) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object containing the rules. + * + */ + getRules(id: number): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.resources.stylesheetResource#getRulesByName + * @methodOf umbraco.resources.stylesheetResource + * + * @description + * Returns all defined child rules for a stylesheet with a given name + * + * ##usage + *
+         * stylesheetResource.getRulesByName("ie7stylesheet")
+         *    .then(function(rules) {
+         *        alert('its here!');
+         *    });
+         * 
+ * + * @returns {Promise} resourcePromise object containing the rules. + * + */ + getRulesByName(name: string): ng.IPromise; + + +} + +/** + * @ngdoc service + * @name umbraco.resources.treeResource + * @description Loads in data for trees + **/ +interface ITreeResource{ + /** Loads in the data to display the nodes menu */ + loadMenu(node); + + /** Loads in the data to display the nodes for an application */ + loadApplication(options); + + /** Loads in the data to display the child nodes for a given node */ + loadNodes(options); +} + +/** + * @ngdoc service + * @name umbraco.resources.userResource + **/ +interface IUserResource{ + disableUser(userId: number); +} + } + + + + + diff --git a/umbraco/umbraco-services.d.ts b/umbraco/umbraco-services.d.ts new file mode 100644 index 0000000000..85fb8fefcd --- /dev/null +++ b/umbraco/umbraco-services.d.ts @@ -0,0 +1,2387 @@ +// Type definitions for Umbraco v7.2.8 +// Project: https://github.com/umbraco +// Definitions by: DeCareSystemsIreland +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module umbraco.services { + + /** + * @ngdoc service + * @name umbraco.services.angularHelper + * @function + * + * @description + * Some angular helper/extension methods + */ + interface IAngularHelper { + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#rejectedPromise + * @methodOf umbraco.services.angularHelper + * @function + * + * @description + * In some situations we need to return a promise as a rejection, normally based on invalid data. This + * is a wrapper to do that so we can save on writing a bit of code. + * + * @param {object} objReject The object to send back with the promise rejection + */ + rejectedPromise(objReject: Object); + + /** + * @ngdoc function + * @name safeApply + * @methodOf umbraco.services.angularHelper + * @function + * + * @description + * This checks if a digest/apply is already occuring, if not it will force an apply call + */ + safeApply(scope: ng.IScope, fn: Function); + + /** + * @ngdoc function + * @name getCurrentForm + * @methodOf umbraco.services.angularHelper + * @function + * + * @description + * Returns the current form object applied to the scope or null if one is not found + */ + getCurrentForm(scope: ng.IScope); + + /** + * @ngdoc function + * @name validateHasForm + * @methodOf umbraco.services.angularHelper + * @function + * + * @description + * This will validate that the current scope has an assigned form object, if it doesn't an exception is thrown, if + * it does we return the form object. + */ + getRequiredCurrentForm(scope: ng.IScope): Object; + + /** + * @ngdoc function + * @name getNullForm + * @methodOf umbraco.services.angularHelper + * @function + * + * @description + * Returns a null angular FormController, mostly for use in unit tests + * NOTE: This is actually the same construct as angular uses internally for creating a null form but they don't expose + * any of this publicly to us, so we need to create our own. + * + * @param {string} formName The form name to assign + */ + getNullForm(formName: string); + } + + + /** + * Global State + */ + interface IGlobalState { + showNavigation: boolean; + touchDevice: boolean; + showTray: boolean; + stickyNavigation: any; + navMode: any; + isReady: boolean; + } + + /** + * Section State + */ + interface ISectionState { + //The currently active section + currentSection: any; + showSearchResults: boolean; + } + + + /** + * Tree State + */ + interface ITreeState { + //The currently selected node + selectedNode: any; + //The currently loaded root node reference - depending on the section loaded this could be a section root or a normal root. + //We keep this reference so we can lookup nodes to interact with in the UI via the tree service + currentRootNode: any; + } + + /** + * Menu State + */ + interface IMenuState { + //this list of menu items to display + menuActions: any; + //the title to display in the context menu dialog + dialogTitle: string; + //The tree node that the ctx menu is launched for + currentNode: any; + //Whether the menu's dialog is being shown or not + showMenuDialog: boolean; + //Whether the context menu is being shown or not + showMenu: boolean; + } + + /** + * State Object + */ + interface IStateObject { + id: number; + parentId: number; + name: string; + } + + /** + * @ngdoc service + * @name umbraco.services.appState + * @function + * + * @description + * Tracks the various application state variables when working in the back office, raises events when state changes. + */ + interface IAppState { + + /** function to validate and set the state on a state object */ + setState(stateObj: IStateObject, key: string, value, stateObjName: string): void; + + /** function to validate and set the state on a state object */ + getState(stateObj: IStateObject, key: string, stateObjName: string): IStateObject; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#getGlobalState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Returns the current global state value by key - we do not return an object reference here - we do NOT want this + * to be publicly mutable and allow setting arbitrary values + */ + getGlobalState(key: string): IGlobalState; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#setGlobalState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Sets a global state value by key + */ + setGlobalState(key: string, value: boolean): void; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#getSectionState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Returns the current section state value by key - we do not return an object here - we do NOT want this + * to be publicly mutable and allow setting arbitrary values + */ + getSectionState(key: string): ISectionState; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#setSectionState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Sets a section state value by key + */ + setSectionState(key: string, value: ISectionState): void; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#getTreeState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Returns the current tree state value by key - we do not return an object here - we do NOT want this + * to be publicly mutable and allow setting arbitrary values + */ + getTreeState(key: string): ITreeState; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#setTreeState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Sets a section state value by key + */ + setTreeState(key: string, value: ITreeState): void; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#getMenuState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Returns the current menu state value by key - we do not return an object here - we do NOT want this + * to be publicly mutable and allow setting arbitrary values + */ + getMenuState(key: string): IStateObject; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#setMenuState + * @methodOf umbraco.services.appState + * @function + * + * @description + * Sets a section state value by key + */ + setMenuState(key: string, value: IMenuState): void; + + } + + /*Tracks the parent object for complex editors by exposing it as an object reference via editorState.current.entity + * it is possible to modify this object, so should be used with care */ + interface IState { + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#set + * @methodOf umbraco.services.editorState + * @function + * + * @description + * Sets the current entity object for the currently active editor + * This is only used when implementing an editor with a complex model + * like the content editor, where the model is modified by several + * child controllers. + */ + set(entity): void; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#reset + * @methodOf umbraco.services.editorState + * @function + * + * @description + * Since the editorstate entity is read-only, you cannot set it to null + * only through the reset() method + */ + reset(): void; + + /** + * @ngdoc function + * @name umbraco.services.angularHelper#getCurrent + * @methodOf umbraco.services.editorState + * @function + * + * @description + * Returns an object reference to the current editor entity. + * the entity is the root object of the editor. + * EditorState is used by property/parameter editors that need + * access to the entire entity being edited, not just the property/parameter + * + * editorState.current can not be overwritten, you should only read values from it + * since modifying individual properties should be handled by the property editors + */ + getCurrent(): any; + + } + + /** + * @ngdoc service + * @name umbraco.services.assetsService + * + * @requires $q + * @requires angularHelper + * + * @description + * Promise-based utillity service to lazy-load client-side dependencies inside angular controllers. + */ + interface IAssetsService { + + /** + * @ngdoc method + * @name umbraco.services.assetsService#loadCss + * @methodOf umbraco.services.assetsService + * + * @description + * Injects a file as a stylesheet into the document head + * + * @param {String} path path to the css file to load + * @param {Scope} scope optional scope to pass into the loader + * @param {Object} keyvalue collection of attributes to pass to the stylesheet element + * @param {Number} timeout in milliseconds + * @returns {Promise} Promise object which resolves when the file has loaded + */ + loadCss(path: string, scope: ng.IScope, attributes: Object, timeout: number); + + /** + * @ngdoc method + * @name umbraco.services.assetsService#loadJs + * @methodOf umbraco.services.assetsService + * + * @description + * Injects a file as a javascript into the document + * + * @param {String} path path to the js file to load + * @param {Scope} scope optional scope to pass into the loader + * @param {Object} keyvalue collection of attributes to pass to the script element + * @param {Number} timeout in milliseconds + * @returns {Promise} Promise object which resolves when the file has loaded + */ + loadJs(path: string, scope: ng.IScope, attributes: Object, timeout: number); + + /** + * @ngdoc method + * @name umbraco.services.assetsService#load + * @methodOf umbraco.services.assetsService + * + * @description + * Injects a collection of files, this can be ONLY js files + * + * + * @param {Array} pathArray string array of paths to the files to load + * @param {Scope} scope optional scope to pass into the loader + * @returns {Promise} Promise object which resolves when all the files has loaded + */ + load(pathArray: string[], scope: ng.IScope); + } + + /** + * @ngdoc service + * @name umbraco.services.contentEditingHelper + * @description A helper service for most editors, some methods are specific to content/media/member model types but most are used by + * all editors to share logic and reduce the amount of replicated code among editors. + */ + interface IContentEditingHelper { + + /** + * @ngdoc method + * @name umbraco.services.contentEditingHelper#getAllProps + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * Returns all propertes contained for the content item (since the normal model has properties contained inside of tabs) + */ + getAllProps(content); + + /** + * @ngdoc method + * @name umbraco.services.contentEditingHelper#configureButtons + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * Returns a letter array for buttons, with the primary one first based on content model, permissions and editor state + */ + getAllowedActions(content, creating); + + /** + * @ngdoc method + * @name umbraco.services.contentEditingHelper#getButtonFromAction + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * Returns a button object to render a button for the tabbed editor + * currently only returns built in system buttons for content and media actions + * returns label, alias, action char and hot-key + */ + getButtonFromAction(ch: string); + + /** + * @ngdoc method + * @name umbraco.services.contentEditingHelper#reBindChangedProperties + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * re-binds all changed property values to the origContent object from the savedContent object and returns an array of changed properties. + */ + reBindChangedProperties(origContent, savedContent); + + /** + * @ngdoc function + * @name umbraco.services.contentEditingHelper#handleSaveError + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * A function to handle what happens when we have validation issues from the server side + */ + handleSaveError(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.contentEditingHelper#handleSuccessfulSave + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * A function to handle when saving a content item is successful. This will rebind the values of the model that have changed + * ensure the notifications are displayed and that the appropriate events are fired. This will also check if we need to redirect + * when we're creating new content. + */ + handleSuccessfulSave(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.contentEditingHelper#redirectToCreatedContent + * @methodOf umbraco.services.contentEditingHelper + * @function + * + * @description + * Changes the location to be editing the newly created content after create was successful. + * We need to decide if we need to redirect to edito mode or if we will remain in create mode. + * We will only need to maintain create mode if we have not fulfilled the basic requirements for creating an entity which is at least having a name. + */ + redirectToCreatedContent(id: number, modelState: any); + } + + /** + * @ngdoc service + * @name umbraco.services.cropperHelper + * @description A helper object used for dealing with image cropper data + */ + interface ICropperHelper { + + /** + * @ngdoc method + * @name umbraco.services.cropperHelper#configuration + * @methodOf umbraco.services.cropperHelper + * + * @description + * Returns a collection of plugins available to the tinyMCE editor + * + */ + configuration(mediaTypeAlias: string): any; + } + + + /** + * Rendering options + */ + interface IDialogRenderingOptions { + /*the DOM element to inject the modal into, by default set to body*/ + container?: HTMLElement; + /*function called when the modal is submitted*/ + callback: Function; + /*the url of the template*/ + template: string; + /*animation css class, by default set to "fade"*/ + animation?: string; + /*modal css class, by default "umb-modal"*/ + modalClass?: string; + /*show the modal instantly*/ + show?: boolean; + /*load template in an iframe, only needed for serverside templates*/ + iframe: boolean; + /*set a width on the modal, only needed for iframes*/ + width?: number; + /*strips the modal from any animation and wrappers, used when you want to inject a dialog into an existing container*/ + inline?: boolean; + } + + /** + * Modal + */ + interface IModal { + + } + + + /** + * Mediapicker dialog options object + */ + interface IMediaPickerOptions { + /*Only display files that have an image file-extension*/ + onlyImages: boolean; + /*callback function*/ + callback: Function; + } + + + /** + * Content picker dialog options object + */ + interface IContentPickerOptions { + /*should the picker return one or multiple items*/ + multipicker: boolean; + /*callback function*/ + callback: Function; + } + + /** + * Iconpicker dialog options object + */ + interface IIconPickerOptions { + /*callback function*/ + callback: Function; + } + + /** + * Linkpicker dialog options object + */ + interface ILinkPickerOptions { + /*callback function*/ + callback: Function; + } + + /** + * Macropicker dialog options object + */ + interface IMacroPickerOptions { + /*callback function*/ + callback: Function; + } + + /** + * Member group picker dialog options object + */ + interface IMemberGroupPickerOptions { + /*should the tree pick one or multiple members before returning*/ + multiPicker: boolean; + /*callback function*/ + callback: Function; + } + + /** + * Member picker dialog options object + */ + interface IMemberPickerOptions { + /*should the tree pick one or multiple members before returning*/ + multiPicker: boolean; + /*callback function*/ + callback: Function; + } + + /** + * Property dialog options object + */ + interface IPropertyDialogOptions { + /*callback function*/ + callback: Function; + /*editor to use to edit a given value and return on callback*/ + editor: string; + /*value sent to the property editor*/ + value: Object; + } + + /** + * Iconpicker dialog options object + */ + interface ITreePickerOptions { + /*tree section to display*/ + section: string; + /*specific tree to display*/ + treeAlias: string; + /*should the tree pick one or multiple items before returning*/ + multiPicker: boolean; + /*callback function*/ + callback: Function; + } + + /** + * Dialog options object + */ + interface IDialog { + + } + + /* + * Application-wide service for handling modals, overlays and dialogs By default it + * injects the passed template url into a div to body of the document And renders it, + * but does also support rendering items in an iframe, incase serverside processing is needed, or its a non-angular page + */ + interface IDialogService { + + dialogs?: any[]; + + /** Internal method that removes all dialogs */ + removeAllDialogs(...args: any[]): void; + + /** Internal method that closes the dialog properly and cleans up resources */ + closeDialog(dialog: IDialog): void; + + /** Internal method that handles opening all dialogs */ + openDialog(options: IDialogRenderingOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#open + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a modal rendering a given template url. + * + * @param {Object} options rendering options + * @param {DomElement} options.container the DOM element to inject the modal into, by default set to body + * @param {Function} options.callback function called when the modal is submitted + * @param {String} options.template the url of the template + * @param {String} options.animation animation csss class, by default set to "fade" + * @param {String} options.modalClass modal css class, by default "umb-modal" + * @param {Bool} options.show show the modal instantly + * @param {Bool} options.iframe load template in an iframe, only needed for serverside templates + * @param {Int} options.width set a width on the modal, only needed for iframes + * @param {Bool} options.inline strips the modal from any animation and wrappers, used when you want to inject a dialog into an existing container + * @returns {Object} modal object + */ + open(options: IDialogRenderingOptions): IModal; + + + /** + * @ngdoc method + * @name umbraco.services.dialogService#close + * @methodOf umbraco.services.dialogService + * + * @description + * Closes a specific dialog + * @param {Object} dialog the dialog object to close + * @param {Object} args if specified this object will be sent to any callbacks registered on the dialogs. + */ + close(dialog: IDialog, ...args: any[]): void; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#closeAll + * @methodOf umbraco.services.dialogService + * + * @description + * Closes all dialogs + * @param {Object} args if specified this object will be sent to any callbacks registered on the dialogs. + */ + closeAll(...args: any[]): void; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#mediaPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a media picker in a modal, the callback returns an array of selected media items + * @param {Object} options mediapicker dialog options object + * @param {Boolean} options.onlyImages Only display files that have an image file-extension + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + mediaPicker(options: IMediaPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#contentPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a content picker tree in a modal, the callback returns an array of selected documents + * @param {Object} options content picker dialog options object + * @param {Boolean} options.multipicker should the picker return one or multiple items + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + contentPicker(options: IContentPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#linkPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a link picker tree in a modal, the callback returns a single link + * @param {Object} options content picker dialog options object + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + linkPicker(options: ILinkPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#macroPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a mcaro picker in a modal, the callback returns a object representing the macro and it's parameters + * @param {Object} options macropicker dialog options object + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + macroPicker(options: IMacroPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#memberPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a member picker in a modal, the callback returns a object representing the selected member + * @param {Object} options member picker dialog options object + * @param {Boolean} options.multiPicker should the tree pick one or multiple members before returning + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + memberPicker(options: IMemberPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#memberGroupPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a member group picker in a modal, the callback returns a object representing the selected member + * @param {Object} options member group picker dialog options object + * @param {Boolean} options.multiPicker should the tree pick one or multiple members before returning + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + memberGroupPicker(options: IMemberGroupPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#iconPicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a icon picker in a modal, the callback returns a object representing the selected icon + * @param {Object} options iconpicker dialog options object + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + iconPicker(options: IIconPickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#treePicker + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a tree picker in a modal, the callback returns a object representing the selected tree item + * @param {Object} options iconpicker dialog options object + * @param {String} options.section tree section to display + * @param {String} options.treeAlias specific tree to display + * @param {Boolean} options.multiPicker should the tree pick one or multiple items before returning + * @param {Function} options.callback callback function + * @returns {Object} modal object + */ + treePicker(options: ITreePickerOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#propertyDialog + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a dialog with a chosen property editor in, a value can be passed to the modal, and this value is returned in the callback + * @param {Object} options mediapicker dialog options object + * @param {Function} options.callback callback function + * @param {String} editor editor to use to edit a given value and return on callback + * @param {Object} value value sent to the property editor + * @returns {Object} modal object + */ + propertyDialog(options: IPropertyDialogOptions): IModal; + + /** + * @ngdoc method + * @name umbraco.services.dialogService#ysodDialog + * @methodOf umbraco.services.dialogService + * @description + * Opens a dialog to an embed dialog + */ + embedDialog(options); + + /** + * @ngdoc method + * @name umbraco.services.dialogService#ysodDialog + * @methodOf umbraco.services.dialogService + * + * @description + * Opens a dialog to show a custom YSOD + */ + ysodDialog(ysodError); + } + + /** Used to broadcast and listen for global events and allow the ability to add async listeners to the callbacks */ + /** + Core app events: + app.ready + app.authenticated + app.notAuthenticated + app.closeDialogs + */ + interface IEventService { + + } + + /** + * File + */ + interface IFile { + + } + + /** + * @ngdoc service + * @name umbraco.services.fileManager + * @function + * + * @description + * Used by editors to manage any files that require uploading with the posted data, normally called by property editors + * that need to attach files. + * When a route changes successfully, we ensure that the collection is cleared. + */ + interface IFileManager { + + /** + * @ngdoc function + * @name umbraco.services.fileManager#addFiles + * @methodOf umbraco.services.fileManager + * @function + * + * @description + * Attaches files to the current manager for the current editor for a particular property, if an empty array is set + * for the files collection that effectively clears the files for the specified editor. + */ + setFiles(propertyAlias: string, files: IFile[]); + + /** + * @ngdoc function + * @name umbraco.services.fileManager#getFiles + * @methodOf umbraco.services.fileManager + * @function + * + * @description + * Returns all of the files attached to the file manager + */ + getFiles(): IFile[]; + + + /** + * @ngdoc function + * @name umbraco.services.fileManager#clearFiles + * @methodOf umbraco.services.fileManager + * @function + * + * @description + * Removes all files from the manager + */ + clearFiles(); + } + + /** + * Model state + */ + interface IModelState { + + } + + /** + * @ngdoc service + * @name umbraco.services.formHelper + * @function + * + * @description + * A utility class used to streamline how forms are developed, to ensure that validation is check and displayed consistently and to ensure that the correct events + * fire when they need to. + */ + interface IFormHelper { + + /** + * @ngdoc function + * @name umbraco.services.formHelper#submitForm + * @methodOf umbraco.services.formHelper + * @function + * + * @description + * Called by controllers when submitting a form - this ensures that all client validation is checked, + * server validation is cleared, that the correct events execute and status messages are displayed. + * This returns true if the form is valid, otherwise false if form submission cannot continue. + * + * @param {object} args An object containing arguments for form submission + */ + submitForm(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.formHelper#submitForm + * @methodOf umbraco.services.formHelper + * @function + * + * @description + * Called by controllers when a form has been successfully submitted. the correct events execute + * and that the notifications are displayed if there are any. + * + * @param {object} args An object containing arguments for form submission + */ + resetForm(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.formHelper#handleError + * @methodOf umbraco.services.formHelper + * @function + * + * @description + * Needs to be called when a form submission fails, this will wire up all server validation errors in ModelState and + * add the correct messages to the notifications. If a server error has occurred this will show a ysod. + * + * @param {object} err The error object returned from the http promise + */ + handleError(err: Object); + + /** + * @ngdoc function + * @name umbraco.services.formHelper#handleServerValidation + * @methodOf umbraco.services.formHelper + * @function + * + * @description + * This wires up all of the server validation model state so that valServer and valServerField directives work + * + * @param {object} err The error object returned from the http promise + */ + handleServerValidation(modelState: IModelState); + } + + + /** + * History item + */ + interface IHistoryItem { + //css class for the list, ex: "icon-image", "icon-doc" + icon: string; + //route to the editor, ex: "/content/edit/1234" + link: string; + //friendly name for the history listing + name: string; + } + + /** + * @ngdoc service + * @name umbraco.services.historyService + * + * @requires $rootScope + * @requires $timeout + * @requires angularHelper + * + * @description + * Service to handle the main application navigation history. Responsible for keeping track + * of where a user navigates to, stores an icon, url and name in a collection, to make it easy + * for the user to go back to a previous editor / action + * + * **Note:** only works with new angular-based editors, not legacy ones + * + * ##usage + * To use, simply inject the historyService into any controller that needs it, and make + * sure the umbraco.services module is accesible - which it should be by default. + */ + interface IHistoryService { + + /** + * @ngdoc method + * @name umbraco.services.historyService#add + * @methodOf umbraco.services.historyService + * + * @description + * Adds a given history item to the users history collection. + * + * @param {Object} item the history item + * @param {String} item.icon icon css class for the list, ex: "icon-image", "icon-doc" + * @param {String} item.link route to the editor, ex: "/content/edit/1234" + * @param {String} item.name friendly name for the history listing + * @returns {Object} history item object + */ + add(item: IHistoryItem): IHistoryItem; + + /** + * @ngdoc method + * @name umbraco.services.historyService#remove + * @methodOf umbraco.services.historyService + * + * @description + * Removes a history item from the users history collection, given an index to remove from. + * + * @param {Int} index index to remove item from + */ + remove(index: number); + + /** + * @ngdoc method + * @name umbraco.services.historyService#removeAll + * @methodOf umbraco.services.historyService + * + * @description + * Removes all history items from the users history collection + */ + removeAll(): void; + + /** + * @ngdoc method + * @name umbraco.services.historyService#getCurrent + * @methodOf umbraco.services.historyService + * + * @description + * Method to return the current history collection. + */ + getCurrent(): IHistoryItem[]; + } + + /** + * @ngdoc service + * @name umbraco.services.macroService + * + * + * @description + * A service to return macro information such as generating syntax to insert a macro into an editor + */ + interface IMacroService { + + /** + * @ngdoc function + * @name umbraco.services.macroService#generateWebFormsSyntax + * @methodOf umbraco.services.macroService + * @function + * + * @description + * generates the syntax for inserting a macro into a rich text editor - this is the very old umbraco style syntax + * + * @param {object} args an object containing the macro alias and it's parameter values + */ + generateMacroSyntax(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.macroService#generateWebFormsSyntax + * @methodOf umbraco.services.macroService + * @function + * + * @description + * generates the syntax for inserting a macro into a webforms templates + * + * @param {object} args an object containing the macro alias and it's parameter values + */ + generateWebFormsSyntax(...args: any[]); + + /** + * @ngdoc function + * @name umbraco.services.macroService#generateMvcSyntax + * @methodOf umbraco.services.macroService + * @function + * + * @description + * generates the syntax for inserting a macro into an mvc template + * + * @param {object} args an object containing the macro alias and it's parameter values + */ + generateMvcSyntax(...args: any[]); + } + + + /** + * Media model + */ + interface IMediaModel { + + } + + /** + * Media options + */ + interface IMediaOptions { + mediaModel: IMediaModel; + imageOnly: boolean; + } + + /** + * Media entity + */ + interface IMediaEntity { + + } + + /** + * @ngdoc service + * @name umbraco.services.mediaHelper + * @description A helper object used for dealing with media items + */ + interface IMediaHelper { + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#getImagePropertyValue + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Returns the file path associated with the media property if there is one + * + * @param {object} options Options object + * @param {object} options.mediaModel The media object to retrieve the image path from + * @param {object} options.imageOnly Optional, if true then will only return a path if the media item is an image + */ + getMediaPropertyValue(options: IMediaOptions): string; + + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#getImagePropertyValue + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Returns the actual image path associated with the image property if there is one + * + * @param {object} options Options object + * @param {object} options.imageModel The media object to retrieve the image path from + */ + getImagePropertyValue(options: IMediaOptions): string; + + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#getThumbnail + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * formats the display model used to display the content to the model used to save the content + * + * @param {object} options Options object + * @param {object} options.imageModel The media object to retrieve the image path from + */ + getThumbnail(options: IMediaOptions): string; + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#resolveFileFromEntity + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Gets the media file url for a media entity returned with the entityResource + * + * @param {object} mediaEntity A media Entity returned from the entityResource + * @param {boolean} thumbnail Whether to return the thumbnail url or normal url + */ + resolveFileFromEntity(mediaEntity: IMediaEntity, thumbnail: boolean): string; + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#resolveFile + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Gets the media file url for a media object returned with the mediaResource + * + * @param {object} mediaEntity A media Entity returned from the entityResource + * @param {boolean} thumbnail Whether to return the thumbnail url or normal url + */ + resolveFile(mediaItem: IMediaEntity, thumbnail: boolean): string; + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#scaleToMaxSize + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Finds the corrct max width and max height, given maximum dimensions and keeping aspect ratios + * + * @param {number} maxSize Maximum width & height + * @param {number} width Current width + * @param {number} height Current height + */ + scaleToMaxSize(maxSize: number, width: number, height: number); + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#getThumbnailFromPath + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Returns the path to the thumbnail version of a given media library image path + * + * @param {string} imagePath Image path, ex: /media/1234/my-image.jpg + */ + getThumbnailFromPath(imagePath: string): string; + + /** + * @ngdoc function + * @name umbraco.services.mediaHelper#detectIfImageByExtension + * @methodOf umbraco.services.mediaHelper + * @function + * + * @description + * Returns true/false, indicating if the given path has an allowed image extension + * + * @param {string} imagePath Image path, ex: /media/1234/my-image.jpg + */ + detectIfImageByExtension(imagePath: string): boolean; + } + + /** + * Tracks the parent object for complex editors by exposing it as an object reference via editorState.current.entity + * it is possible to modify this object, so should be used with care + */ + interface IEditorState { + current: any; + state: IState; + } + + /** + * Sync tree args + */ + interface ISyncTreeArgs { + /*the tree alias to sync to*/ + tree: string; + /*the path to sync the tree to*/ + path: string; + /* optional, specifies whether to force reload the node data from the server even if it already exists in the tree currently*/ + forceReload: boolean; + /* optional, specifies whether to set the synced node to be the active node, this will default to true if not specified*/ + activate: boolean; + } + + /** + * Show dialog action + */ + interface IShowDialogAction { + name: string; + alias: string; + } + + /** + * Show dialog args + */ + interface IShowDialogArgs { + scope: ng.IScope; + action: IShowDialogAction; + } + + /** + * @ngdoc service + * @name umbraco.services.navigationService + * + * @requires $rootScope + * @requires $routeParams + * @requires $log + * @requires $location + * @requires dialogService + * @requires treeService + * @requires sectionResource + * + * @description + * Service to handle the main application navigation. Responsible for invoking the tree + * Section navigation and search, and maintain their state for the entire application lifetime + * + */ + interface INavigationService { + + /** + * @ngdoc method + * @name umbraco.services.navigationService#load + * @methodOf umbraco.services.navigationService + * + * @description + * Shows the legacy iframe and loads in the content based on the source url + * @param {String} source The URL to load into the iframe + */ + loadLegacyIFrame(source: string): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#changeSection + * @methodOf umbraco.services.navigationService + * + * @description + * Changes the active section to a given section alias + * If the navigation is 'sticky' this will load the associated tree + * and load the dashboard related to the section + * @param {string} sectionAlias The alias of the section + */ + changeSection(sectionAlias: string, force: boolean): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showTree + * @methodOf umbraco.services.navigationService + * + * @description + * Displays the tree for a given section alias but turning on the containing dom element + * only changes if the section is different from the current one + * @param {string} sectionAlias The alias of the section to load + * @param {Object} syncArgs Optional object of arguments for syncing the tree for the section being shown + */ + showTree(sectionAlias: string, syncArgs: ISyncTreeArgs): void; + + showTray(): void; + + hideTray(): void; + + /** + Called to assign the main tree event handler - this is called by the navigation controller. + TODO: Potentially another dev could call this which would kind of mung the whole app so potentially there's a better way. + */ + setupTreeEvents(treeEventHandler): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#syncTree + * @methodOf umbraco.services.navigationService + * + * @description + * Syncs a tree with a given path, returns a promise + * The path format is: ["itemId","itemId"], and so on + * so to sync to a specific document type node do: + *
+        * navigationService.syncTree({tree: 'content', path: ["-1","123d"], forceReload: true});
+        * 
+ * @param {Object} args arguments passed to the function + * @param {String} args.tree the tree alias to sync to + * @param {Array} args.path the path to sync the tree to + * @param {Boolean} args.forceReload optional, specifies whether to force reload the node data from the server even if it already exists in the tree currently + * @param {Boolean} args.activate optional, specifies whether to set the synced node to be the active node, this will default to true if not specified + */ + syncTree(args: ISyncTreeArgs): any; + + /** + Internal method that should ONLY be used by the legacy API wrapper, the legacy API used to + have to set an active tree and then sync, the new API does this in one method by using syncTree + */ + _syncPath(path: string[], forceReload: boolean): void; + + //TODO: This should return a promise + reloadNode(node): void; + + //TODO: This should return a promise + reloadSection(sectionAlias: string): void; + + /** + Internal method that should ONLY be used by the legacy API wrapper, the legacy API used to + have to set an active tree and then sync, the new API does this in one method by using syncTreePath + */ + _setActiveTreeType(treeAlias: string, loadChildren: boolean): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#hideTree + * @methodOf umbraco.services.navigationService + * + * @description + * Hides the tree by hiding the containing dom element + */ + hideTree(): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showMenu + * @methodOf umbraco.services.navigationService + * + * @description + * Hides the tree by hiding the containing dom element. + * This always returns a promise! + * + * @param {Event} event the click event triggering the method, passed from the DOM element + */ + showMenu(event: Event, ...args: any[]): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#hideMenu + * @methodOf umbraco.services.navigationService + * + * @description + * Hides the menu by hiding the containing dom element + */ + hideMenu(): void; + + /** Executes a given menu action */ + executeMenuAction(action, node, section): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showUserDialog + * @methodOf umbraco.services.navigationService + * + * @description + * Opens the user dialog, next to the sections navigation + * template is located in views/common/dialogs/user.html + */ + showUserDialog(): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showUserDialog + * @methodOf umbraco.services.navigationService + * + * @description + * Opens the user dialog, next to the sections navigation + * template is located in views/common/dialogs/user.html + */ + showHelpDialog(): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showDialog + * @methodOf umbraco.services.navigationService + * + * @description + * Opens a dialog, for a given action on a given tree node + * uses the dialogService to inject the selected action dialog + * into #dialog div.umb-panel-body + * the path to the dialog view is determined by: + * "views/" + current tree + "/" + action alias + ".html" + * The dialog controller will get passed a scope object that is created here with the properties: + * scope.currentNode = the selected tree node + * scope.currentAction = the selected menu item + * so that the dialog controllers can use these properties + * + * @param {Object} args arguments passed to the function + * @param {Scope} args.scope current scope passed to the dialog + * @param {Object} args.action the clicked action containing `name` and `alias` + */ + showDialog(args: IShowDialogArgs): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#hideDialog + * @methodOf umbraco.services.navigationService + * + * @description + * hides the currently open dialog + */ + hideDialog(showMenu: boolean): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#showSearch + * @methodOf umbraco.services.navigationService + * + * @description + * shows the search pane + */ + showSearch(): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#hideSearch + * @methodOf umbraco.services.navigationService + * + * @description + * hides the search pane + */ + hideSearch(): void; + + /** + * @ngdoc method + * @name umbraco.services.navigationService#hideNavigation + * @methodOf umbraco.services.navigationService + * + * @description + * hides any open navigation panes and resets the tree, actions and the currently selected node + */ + hideNavigation(): void; + + } + + /** + * Notification + */ + interface INotification { + + } + + /** + * Notification Type + */ + enum NotificationType { + success, + error, + warning, + info + } + + /** + * Notification args + */ + interface INotificationArgs { + type: NotificationType; + header: string; + message: string; + } + + /** + * Button Action + */ + interface IButtonAction { + + } + + /** + * Notification Item + */ + interface INotificationItem { + /*Short headline*/ + headline: string; + /*longer text for the notication, trimmed after 200 characters, which can then be exanded*/ + message: string; + /*Notification type, can be: "success", "warning", "error" or "info"*/ + type: NotificationType; + /*url to open when notification is clicked*/ + url: string; + /*path to custom view to load into the notification box*/ + view: string; + /*Collection of button actions to append (label, func, cssClass)*/ + actions: IButtonAction[]; + /*if set to true, the notification will not auto- close*/ + sticky: boolean; + } + + /** + * @ngdoc service + * @name umbraco.services.navigationService + * + * @requires $rootScope + * @requires $routeParams + * @requires $log + * @requires $location + * @requires dialogService + * @requires treeService + * @requires sectionResource + * + * @description + * Service to handle the main application navigation. Responsible for invoking the tree + * Section navigation and search, and maintain their state for the entire application lifetime + * + */ + interface INotificationsService { + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#add + * @methodOf umbraco.services.notificationsService + * + * @description + * Lower level api for adding notifcations, support more advanced options + * @param {Object} item The notification item + * @param {String} item.headline Short headline + * @param {String} item.message longer text for the notication, trimmed after 200 characters, which can then be exanded + * @param {String} item.type Notification type, can be: "success","warning","error" or "info" + * @param {String} item.url url to open when notification is clicked + * @param {String} item.view path to custom view to load into the notification box + * @param {Array} item.actions Collection of button actions to append (label, func, cssClass) + * @param {Boolean} item.sticky if set to true, the notification will not auto-close + * @returns {Object} args notification object + */ + add(item: INotificationItem): INotification; + + hasView(view: string): boolean; + + addView(view: string, ...args: any[]): void; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#showNotification + * @methodOf umbraco.services.notificationsService + * + * @description + * Shows a notification based on the object passed in, normally used to render notifications sent back from the server + * + * @returns {Object} args notification object + */ + showNotification(args: INotificationArgs): INotification; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#success + * @methodOf umbraco.services.notificationsService + * + * @description + * Adds a green success notication to the notications collection + * This should be used when an operations *completes* without errors + * + * @param {String} headline Headline of the notification + * @param {String} message longer text for the notication, trimmed after 200 characters, which can then be exanded + * @returns {Object} notification object + */ + success(headline: string, message: string): INotification; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#error + * @methodOf umbraco.services.notificationsService + * + * @description + * Adds a red error notication to the notications collection + * This should be used when an operations *fails* and could not complete + * + * @param {String} headline Headline of the notification + * @param {String} message longer text for the notication, trimmed after 200 characters, which can then be exanded + * @returns {Object} notification object + */ + error(headline: string, message: string): INotification; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#warning + * @methodOf umbraco.services.notificationsService + * + * @description + * Adds a yellow warning notication to the notications collection + * This should be used when an operations *completes* but something was not as expected + * + * + * @param {String} headline Headline of the notification + * @param {String} message longer text for the notication, trimmed after 200 characters, which can then be exanded + * @returns {Object} notification object + */ + warning(headline: string, message: string): INotification; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#warning + * @methodOf umbraco.services.notificationsService + * + * @description + * Adds a yellow warning notication to the notications collection + * This should be used when an operations *completes* but something was not as expected + * + * + * @param {String} headline Headline of the notification + * @param {String} message longer text for the notication, trimmed after 200 characters, which can then be exanded + * @returns {Object} notification object + */ + info(headline: string, message: string): INotification; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#remove + * @methodOf umbraco.services.notificationsService + * + * @description + * Removes a notification from the notifcations collection at a given index + * + * @param {Int} index index where the notication should be removed from + */ + remove(index: number): void; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#removeAll + * @methodOf umbraco.services.notificationsService + * + * @description + * Removes all notifications from the notifcations collection + */ + removeAll(): void; + + /** + * @ngdoc property + * @name umbraco.services.notificationsService#current + * @propertyOf umbraco.services.notificationsService + * + * @description + * Returns an array of current notifications to display + * + * @returns {string} returns an array + */ + current: string[]; + + /** + * @ngdoc method + * @name umbraco.services.notificationsService#getCurrent + * @methodOf umbraco.services.notificationsService + * + * @description + * Method to return all notifications from the notifcations collection + */ + getCurrent(): INotification[]; + + } + + /** + * Search args + */ + interface ISearchArgs { + term: string; + } + + /** + * Search members + */ + interface ISearchMember { + name: string; + id: number; + menuUrl: string; + editorPath: string; + metaData: Object; + subtitle: string; + } + + /** + * Search content + */ + interface ISearchContent { + menuUrl: string; + id: number; + editorPath: string; + metaData: {Url: string}; + subTitle: string; + } + + /** + * Search media + */ + interface ISearchMedia extends ISearchContent { + + } + + /** + * @ngdoc service + * @name umbraco.services.searchService + * + * + * @description + * Service for handling the main application search, can currently search content, media and members + * + */ + interface ISearchService { + + /** + * @ngdoc method + * @name umbraco.services.searchService#searchMembers + * @methodOf umbraco.services.searchService + * + * @description + * Searches the default member search index + * @param {Object} args argument object + * @param {String} args.term seach term + * @returns {Promise} returns promise containing all matching members + */ + searchMembers(args: ISearchArgs): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.services.searchService#searchContent + * @methodOf umbraco.services.searchService + * + * @description + * Searches the default internal content search index + * @param {Object} args argument object + * @param {String} args.term seach term + * @returns {Promise} returns promise containing all matching content items + */ + searchContent(args: ISearchArgs): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.services.searchService#searchMedia + * @methodOf umbraco.services.searchService + * + * @description + * Searches the default media search index + * @param {Object} args argument object + * @param {String} args.term seach term + * @returns {Promise} returns promise containing all matching media items + */ + searchMedia(args: ISearchArgs): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.services.searchService#searchAll + * @methodOf umbraco.services.searchService + * + * @description + * Searches all available indexes and returns all results in one collection + * @param {Object} args argument object + * @param {String} args.term seach term + * @returns {Promise} returns promise containing all matching items + */ + searchAll(args: ISearchArgs): ng.IPromise; + } + + /** + * @ngdoc service + * @name umbraco.services.serverValidationManager + * @function + * + * @description + * Used to handle server side validation and wires up the UI with the messages. There are 2 types of validation messages, one + * is for user defined properties (called Properties) and the other is for field properties which are attached to the native + * model objects (not user defined). The methods below are named according to these rules: Properties vs Fields. + */ + interface IServerValidationManager { + + /** + * @ngdoc function + * @name umbraco.services.serverValidationManager#subscribe + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * This method needs to be called once all field and property errors are wired up. + * + * In some scenarios where the error collection needs to be persisted over a route change + * (i.e. when a content item (or any item) is created and the route redirects to the editor) + * the controller should call this method once the data is bound to the scope + * so that any persisted validation errors are re-bound to their controls. Once they are re-binded this then clears the validation + * colleciton so that if another route change occurs, the previously persisted validation errors are not re-bound to the new item. + */ + executeAndClearAllSubscriptions(): void; + + /** + * @ngdoc function + * @name umbraco.services.serverValidationManager#subscribe + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Adds a callback method that is executed whenever validation changes for the field name + property specified. + * This is generally used for server side validation in order to match up a server side validation error with + * a particular field, otherwise we can only pinpoint that there is an error for a content property, not the + * property's specific field. This is used with the val-server directive in which the directive specifies the + * field alias to listen for. + * If propertyAlias is null, then this subscription is for a field property (not a user defined property). + */ + subscribe(propertyAlias: string, fieldName: string, callback: Function): void; + + /** + * @ngdoc function + * @name getPropertyCallbacks + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Gets all callbacks that has been registered using the subscribe method for the propertyAlias + fieldName combo. + * This will always return any callbacks registered for just the property (i.e. field name is empty) and for ones with an + * explicit field name set. + */ + getPropertyCallbacks(propertyAlias: string, fieldName: string): void; + + /** + * @ngdoc function + * @name getFieldCallbacks + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Gets all callbacks that has been registered using the subscribe method for the field. + */ + getFieldCallbacks(fieldName: string); + + /** + * @ngdoc function + * @name addFieldError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Adds an error message for a native content item field (not a user defined property, for Example, 'Name') + */ + addFieldError(fieldName: string, errorMsg: string): void; + + /** + * @ngdoc function + * @name addPropertyError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Adds an error message for the content property + */ + addPropertyError(propertyAlias: string, fieldName: string, errorMsg: string): void; + + /** + * @ngdoc function + * @name removePropertyError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Removes an error message for the content property + */ + removePropertyError(propertyAlias: string, fieldName: string): void; + + /** + * @ngdoc function + * @name reset + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Clears all errors and notifies all callbacks that all server errros are now valid - used when submitting a form + */ + reset(): void; + + /** + * @ngdoc function + * @name clear + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Clears all errors + */ + clear(): void; + + /** + * @ngdoc function + * @name getPropertyError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Gets the error message for the content property + */ + getPropertyError(propertyAlias: string, fieldName: string): string; + + /** + * @ngdoc function + * @name getFieldError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Gets the error message for a content field + */ + getFieldError(fieldName: string): string; + + /** + * @ngdoc function + * @name hasPropertyError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Checks if the content property + field name combo has an error + */ + hasPropertyError(propertyAlias: string, fieldName: string): boolean; + + /** + * @ngdoc function + * @name hasFieldError + * @methodOf umbraco.services.serverValidationManager + * @function + * + * @description + * Checks if a content field has an error + */ + hasFieldError(fieldName: string): boolean; + } + + /** + * TinyMcePlugin + */ + interface ITinyMcePlugin { + + } + + /** + * Dimension + */ + interface IDimension { + height: number; + width: number; + } + + /** + * Configuration + */ + interface IConfiguration { + toolbar: string[]; + stylesheets: string[]; + dimensions: IDimension; + maxImageSize: number; + } + + /** + * @ngdoc service + * @name umbraco.services.tinyMceService + * + * + * @description + * A service containing all logic for all of the Umbraco TinyMCE plugins + */ + interface ITinyMceService { + + /** + * @ngdoc method + * @name umbraco.services.tinyMceService#configuration + * @methodOf umbraco.services.tinyMceService + * + * @description + * Returns a collection of plugins available to the tinyMCE editor + * + */ + configuration(): ITinyMcePlugin[]; + + /** + * @ngdoc method + * @name umbraco.services.tinyMceService#defaultPrevalues + * @methodOf umbraco.services.tinyMceService + * + * @description + * Returns a default configration to fallback on in case none is provided + * + */ + defaultPrevalues(); IConfiguration; + + /** + * @ngdoc method + * @name umbraco.services.tinyMceService#createInsertEmbeddedMedia + * @methodOf umbraco.services.tinyMceService + * + * @description + * Creates the umbrco insert embedded media tinymce plugin + * + * @param {Object} editor the TinyMCE editor instance + * @param {Object} $scope the current controller scope + */ + createInsertEmbeddedMedia(editor: Object, $scope: ng.IScope): void; + + /** + * @ngdoc method + * @name umbraco.services.tinyMceService#createMediaPicker + * @methodOf umbraco.services.tinyMceService + * + * @description + * Creates the umbrco insert media tinymce plugin + * + * @param {Object} editor the TinyMCE editor instance + * @param {Object} $scope the current controller scope + */ + createMediaPicker(editor: Object): void; + + /** + * @ngdoc method + * @name umbraco.services.tinyMceService#createUmbracoMacro + * @methodOf umbraco.services.tinyMceService + * + * @description + * Creates the insert umbrco macro tinymce plugin + * + * @param {Object} editor the TinyMCE editor instance + * @param {Object} $scope the current controller scope + */ + createInsertMacro(editor: Object, $scope: ng.IScope); + } + + /** + * Package Folder + */ + interface IPackageFolder { + + } + + /** + * Cache args + */ + interface ICacheArgs { + cacheKey: string; + section?: string; + childrenOf?: number; + } + + /** + * Node args + */ + interface INodeArgs { + node: any; + section: any; + } + + /** + * Tree args + */ + interface ITreeArgs { + cacheKey?: string; + section: string; + } + + /** + * @ngdoc service + * @name umbraco.services.treeService + * @function + * + * @description + * The tree service factory, used internally by the umbTree and umbTreeItem directives + */ + interface ITreeService { + + /** + * @ngdoc method + * @name umbraco.services.treeService#getTreePackageFolder + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Determines if the current tree is a plugin tree and if so returns the package folder it has declared + * so we know where to find it's views, otherwise it will just return undefined. + * + * @param {String} treeAlias The tree alias to check + */ + getTreePackageFolder(treeAlias: string): IPackageFolder; + + /** + * @ngdoc method + * @name umbraco.services.treeService#clearCache + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Clears the tree cache - with optional cacheKey, optional section or optional filter. + * + * @param {Object} args arguments + * @param {String} args.cacheKey optional cachekey - this is used to clear specific trees in dialogs + * @param {String} args.section optional section alias - clear tree for a given section + * @param {String} args.childrenOf optional parent ID - only clear the cache below a specific node + */ + clearCache(args?: ICacheArgs): void; + + /** + * @ngdoc method + * @name umbraco.services.treeService#loadNodeChildren + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Clears all node children, gets it's up-to-date children from the server and re-assigns them and then + * returns them in a promise. + * @param {object} args An arguments object + * @param {object} args.node The tree node + * @param {object} args.section The current section + */ + loadNodeChildren(args: INodeArgs): ng.IPromise; + + /** + * @ngdoc method + * @name umbraco.services.treeService#removeNode + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Removes a given node from the tree + * @param {object} treeNode the node to remove + */ + removeNode(treeNode: Object): void; + + /** + * @ngdoc method + * @name umbraco.services.treeService#removeChildNodes + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Removes all child nodes from a given tree node + * @param {object} treeNode the node to remove children from + */ + removeChildNodes(treeNode: Object): void; + + /** + * @ngdoc method + * @name umbraco.services.treeService#getChildNode + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Gets a child node with a given ID, from a specific treeNode + * @param {object} treeNode to retrive child node from + * @param {int} id id of child node + */ + getChildNode(treeNode: Object, id: number); + + /** + * @ngdoc method + * @name umbraco.services.treeService#getDescendantNode + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Gets a descendant node by id + * @param {object} treeNode to retrive descendant node from + * @param {int} id id of descendant node + * @param {string} treeAlias - optional tree alias, if fetching descendant node from a child of a listview document + */ + getDescendantNode(treeNode: Object, id: number, treeAlias: string); + + /** + * @ngdoc method + * @name umbraco.services.treeService#getTreeRoot + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Gets the root node of the current tree type for a given tree node + * @param {object} treeNode to retrive tree root node from + */ + getTreeRoot(treeNode: Object); + + /** + * @ngdoc method + * @name umbraco.services.treeService#getTreeAlias + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Gets the node's tree alias, this is done by looking up the meta-data of the current node's root node + * @param {object} treeNode to retrive tree alias from + */ + getTreeAlias(treeNode: Object): string; + + /** + * @ngdoc method + * @name umbraco.services.treeService#getTree + * @methodOf umbraco.services.treeService + * @function + * + * @description + * gets the tree, returns a promise + * @param {object} args Arguments + * @param {string} args.section Section alias + * @param {string} args.cacheKey Optional cachekey + */ + getTree(args: ITreeArgs) + + /** + * @ngdoc method + * @name umbraco.services.treeService#getMenu + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Returns available menu actions for a given tree node + * @param {object} args Arguments + * @param {string} args.treeNode tree node object to retrieve the menu for + */ + getMenu(...args: any[]); + + /** + * @ngdoc method + * @name umbraco.services.treeService#getChildren + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Gets the children from the server for a given node + * @param {object} args Arguments + * @param {object} args.node tree node object to retrieve the children for + * @param {string} args.section current section alias + */ + getChildren(...args: any[]); + + /** + * @ngdoc method + * @name umbraco.services.treeService#reloadNode + * @methodOf umbraco.services.treeService + * @function + * + * @description + * Re-loads the single node from the server + * @param {object} node Tree node to reload + */ + reloadNode(node: Object); + + /** + * @ngdoc method + * @name umbraco.services.treeService#getPath + * @methodOf umbraco.services.treeService + * @function + * + * @description + * This will return the current node's path by walking up the tree + * @param {object} node Tree node to retrieve path for + */ + getPath(node: Object): string; + } + + /** + * @ngdoc service + * @name umbraco.services.umbRequestHelper + * @description A helper object used for sending requests to the server + */ + interface IUmbracoRequestHelper { + + /** + * @ngdoc method + * @name umbraco.services.umbRequestHelper#convertVirtualToAbsolutePath + * @methodOf umbraco.services.umbRequestHelper + * @function + * + * @description + * This will convert a virtual path (i.e. ~/App_Plugins/Blah/Test.html ) to an absolute path + * + * @param {string} a virtual path, if this is already an absolute path it will just be returned, if this is a relative path an exception will be thrown + */ + convertVirtualToAbsolutePath(virtualPath: string): string; + + /** + * @ngdoc method + * @name umbraco.services.umbRequestHelper#dictionaryToQueryString + * @methodOf umbraco.services.umbRequestHelper + * @function + * + * @description + * This will turn an array of key/value pairs into a query string + * + * @param {Array} queryStrings An array of key/value pairs + */ + dictionaryToQueryString(queryStrings); + + /** + * @ngdoc method + * @name umbraco.services.umbRequestHelper#getApiUrl + * @methodOf umbraco.services.umbRequestHelper + * @function + * + * @description + * This will return the webapi Url for the requested key based on the servervariables collection + * + * @param {string} apiName The webapi name that is found in the servervariables["umbracoUrls"] dictionary + * @param {string} actionName The webapi action name + * @param {object} queryStrings Can be either a string or an array containing key/value pairs + */ + getApiUrl(apiName: string, actionName: string, queryStrings): string; + + /** + * @ngdoc function + * @name umbraco.services.umbRequestHelper#resourcePromise + * @methodOf umbraco.services.umbRequestHelper + * @function + * + * @description + * This returns a promise with an underlying http call, it is a helper method to reduce + * the amount of duplicate code needed to query http resources and automatically handle any + * Http errors. See /docs/source/using-promises-resources.md + * + * @param {object} opts A mixed object which can either be a string representing the error message to be + * returned OR an object containing either: + * { success: successCallback, errorMsg: errorMessage } + * OR + * { success: successCallback, error: errorCallback } + * In both of the above, the successCallback must accept these parameters: data, status, headers, config + * If using the errorCallback it must accept these parameters: data, status, headers, config + * The success callback must return the data which will be resolved by the deferred object. + * The error callback must return an object containing: {errorMsg: errorMessage, data: originalData, status: status } + */ + resourcePromise(httpPromise: ng.IPromise, opts: string | + { success: ng.IHttpPromiseCallback; errorMsg: string } | + { success: ng.IHttpPromiseCallback; error: ng.IHttpPromiseCallback }); + } +} + + + + + diff --git a/umbraco/umbraco-tests.ts b/umbraco/umbraco-tests.ts new file mode 100644 index 0000000000..9afccd4747 --- /dev/null +++ b/umbraco/umbraco-tests.ts @@ -0,0 +1,93 @@ +/// +/// +/// + +var navigationService: umb.services.INavigationService; +var notificationsService: umb.services.INotificationsService; +var dialogService: umb.services.IDialogService; +var editorState: umb.services.IEditorState; +var appState: umb.services.IAppState; + +/** +* Sync tree for specific path +*/ +navigationService.syncTree({ tree: "content", path: "", forceReload: true, activate: false }) + .then(() => { + //do something +}); + +/** +* Open Modal +*/ +dialogService.open({ + + // set the location of the view + template: "", + iframe: true, + + // function called when dialog is closed + callback: () => { + // close all + dialogService.closeAll(); + } +}); + +/** +* Hide/show navigation in custom sections so we have full screen for complex dashboards +*/ +var toggleNavigation = () => { + + var isNavigationShown = appState.getGlobalState("showNavigation"); + if (isNavigationShown) { + appState.setGlobalState("showNavigation", false); + $("#contentwrapper").css("left", "80px"); + } else { + appState.setGlobalState("showNavigation", true); + $("#contentwrapper").css("left", "440px"); + } +} + +/** +* Get current node +*/ +var getCurrentNode = () => { + return appState.getMenuState("currentNode"); +} + +/** +* Check if a node is published +*/ +var isPublishedNode = () => { + + // check that we have an active node + if (_.isUndefined(editorState.current)) { + return false; + } + return editorState.current.published; +}; + +/** +* Gets the "active" node id to use for any api request +* Note that this retrieves the parent node id if the current node is in an unpublished state +* Note also that in Umbraco 7 the right click custom menu may be brought up without changing the editorState to the node that we right clicked on. +* So the editorState still gives the active node id not the right clicked node is +*/ +var getActiveNodeId = () => { + + // check that we have an active node + if (_.isUndefined(editorState.current)) { + return 0; + } + // get the parent id of the current node - we get parent because if we create a new module then the current node will be unpublished and this "id" will be 0 + return editorState.current.id > 0 ? editorState.current.id : editorState.current.parentId; +} + +/** +* Display error notification +*/ +notificationsService.error("Error", "An unknown error has occured."); + +/** +* Display success notification +*/ +notificationsService.success("Success", "Operation completed."); diff --git a/umbraco/umbraco.d.ts b/umbraco/umbraco.d.ts new file mode 100644 index 0000000000..f00d25b1a0 --- /dev/null +++ b/umbraco/umbraco.d.ts @@ -0,0 +1,20 @@ +// Type definitions for Umbraco v7.2.8 +// Project: https://github.com/umbraco +// Definitions by: DeCareSystemsIreland +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +// Collapse umbraco into umb +import umb = umbraco; + +// Support AMD require +declare module 'umbraco' { + export = umbraco; +} + +declare module umbraco { + +} + From 9d461e546e9be5bfdac16cb943da288f6f9c681a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alexandre=20Par=C3=A9?= Date: Tue, 4 Aug 2015 11:46:20 -0400 Subject: [PATCH 072/309] Invalid partition return type in chain Chain is an array of T. Partition should return _Chain. --- underscore/underscore.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/underscore/underscore.d.ts b/underscore/underscore.d.ts index 4842224c91..4aed7a855f 100644 --- a/underscore/underscore.d.ts +++ b/underscore/underscore.d.ts @@ -2833,7 +2833,7 @@ interface _Chain { * Wrapped type `any[]`. * @see _.partition **/ - partition(iterator: _.ListIterator, context?: any): _Chain; + partition(iterator: _.ListIterator, context?: any): _Chain; /** * Wrapped type `any[][]`. From 05a1465f2c15df0d6918c7e1dbdaee61815f7fb7 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 4 Aug 2015 17:03:37 +0100 Subject: [PATCH 073/309] Type definitions and tests for sentence-case --- sentence-case/sentence-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 sentence-case/sentence-case.d.ts diff --git a/sentence-case/sentence-case.d.ts b/sentence-case/sentence-case.d.ts new file mode 100644 index 0000000000..3f86396480 --- /dev/null +++ b/sentence-case/sentence-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for sentence-case +// Project: https://github.com/blakeembrey/sentence-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "sentence-case" { + function sentenceCase(string: string, locale?: string, repl?: string): string; + export = sentenceCase; +} From 3fbe532959e7595621114fb1b323c2a37644da04 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Tue, 4 Aug 2015 17:04:44 +0100 Subject: [PATCH 074/309] Type definitions and tests for sentence-case --- sentence-case/sentence-case-tests.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 sentence-case/sentence-case-tests.ts diff --git a/sentence-case/sentence-case-tests.ts b/sentence-case/sentence-case-tests.ts new file mode 100644 index 0000000000..569d35233f --- /dev/null +++ b/sentence-case/sentence-case-tests.ts @@ -0,0 +1,13 @@ +/// + +import sentenceCase = require('sentence-case'); + +console.log(sentenceCase(null)); // => "" +console.log(sentenceCase('string')); // => "stringe" +console.log(sentenceCase('dot.case')); // => "dot case" +console.log(sentenceCase('camelCase')); // => "camel case" +console.log(sentenceCase('Beyoncé Knowles')); // => "beyoncé knowles" + +console.log(sentenceCase('A STRING', 'tr')); // => "a strıng" + +console.log(sentenceCase('HELLO WORLD!', null, '_')); // => "hello_world" From 6d590692165d293e5f96841a366b03fa526756d4 Mon Sep 17 00:00:00 2001 From: Lars Magnusson Date: Wed, 29 Jul 2015 21:32:05 +0200 Subject: [PATCH 075/309] Support for defaultValue and defaultChecked in HTMLAttributes (used on input and textarea and others) --- react/react-addons.d.ts | 2 ++ react/react-global.d.ts | 2 ++ react/react.d.ts | 2 ++ 3 files changed, 6 insertions(+) diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index 37cde636dc..5e74e15c87 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -428,6 +428,8 @@ declare module "react/addons" { crossOrigin?: string; data?: string; dateTime?: string; + defaultChecked?: boolean; + defaultValue?: string; defer?: boolean; dir?: string; disabled?: boolean; diff --git a/react/react-global.d.ts b/react/react-global.d.ts index 4ba7266eb2..cf91cf6bb4 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -430,6 +430,8 @@ declare module React { crossOrigin?: string; data?: string; dateTime?: string; + defaultChecked?: boolean; + defaultValue?: string; defer?: boolean; dir?: string; disabled?: boolean; diff --git a/react/react.d.ts b/react/react.d.ts index 0ed794f1e8..d174dca9b0 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -430,6 +430,8 @@ declare module __React { crossOrigin?: string; data?: string; dateTime?: string; + defaultChecked?: boolean; + defaultValue?: string; defer?: boolean; dir?: string; disabled?: boolean; From fb0e5543eede498cadff5ab40bbb6c5f7432f914 Mon Sep 17 00:00:00 2001 From: Danilo Faria Date: Tue, 4 Aug 2015 15:05:53 -0400 Subject: [PATCH 076/309] Ui-grid improvements --- ui-grid/ui-grid.d.ts | 64 +++++++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 15c65e50d3..896a2d60e2 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -112,7 +112,7 @@ declare module uiGrid { } scrollbars: { NEVER: number; - ALWAYS: number; + ALWAYS: number; } } export interface IGridInstance { @@ -247,7 +247,7 @@ declare module uiGrid { clearAllFilters(refreshRows?: boolean, clearConditions?: boolean, clearFlags?: boolean): ng.IPromise>; clearRowInvisible(rowEntity: any): void; getVisibleRows(grid: IGridInstance): Array; - handleWindowResize(): void; + handleWindowResize(): void; notifiyDataChange(type: string): void; refreshRows(): ng.IPromise; registerColumnsProcessor(processorFunction: IColumnProcessor, priority: number): void; @@ -257,23 +257,23 @@ declare module uiGrid { scrollToIfNecessary(gridRow: IGridRow, gridCol: IGridColumn): void; setRowInvisible(rowEntity: any): void; sortHandleNulls(a: any,b: any): number; - queueGridRefresh(): void; + queueGridRefresh(): void; queueRefresh(): void; on: { sortChanged: (scope: ng.IScope, handler: (grid: IGridInstance, sortColumns: Array) => void) => void; - columnVisiblityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; + columnVisibilityChanged: (scope: ng.IScope, handler: (grid: IGridColumn) => void) => void; canvasHeightChanged: (scope: ng.IScope, handler: (oldHeight: number, newHeight: number) => void) => void; - + /** - * filterChangedis raised after the filter is changed. The nature of the watch expression doesn't allow notification + * filterChangedis raised after the filter is changed. The nature of the watch expression doesn't allow notification * of what changed, so the receiver of this event will need to re-extract the filter conditions from the columns. * http://ui-grid.info/docs/#/api/ui.grid.core.api:PublicApi */ filterChanged: (scope: ng.IScope, handler: () => void) => void; - rowsRendered: (scope: ng.IScope, handler: () => void) => void; + rowsRendered: (scope: ng.IScope, handler: () => void) => void; rowsVisibleChanged: (scope: ng.IScope, handler: () => void) => void; scrollBegin: (scope: ng.IScope, handler: () => void) => void; - scrollEnd: (scope: ng.IScope, handler: () => void) => void; + scrollEnd: (scope: ng.IScope, handler: () => void) => void; } } export interface IGridSelectionApi { @@ -291,7 +291,7 @@ declare module uiGrid { getSelectAllState: () => boolean; on: { rowSelectionChanged: (scope: ng.IScope, handler: (row: IGridRow, event?: Event) => void) => void; - rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: Array, event?: Event) => void) => void; + rowSelectionChangedBatch: (scope: ng.IScope, handler: (row: Array, event?: Event) => void) => void; } } export interface IGridPaginationApi { @@ -303,18 +303,23 @@ declare module uiGrid { on: { paginationChanged: (scope: ng.IScope, handler: (newPage: number, pageSize: number) => void) => void; } - } + } export interface IGridRowEditApi { flushDirtyRows(grid?: IGridInstance): ng.IPromise; getDirtyRows(grid?: IGridInstance): Array; - getErrorRows(grid?: IGridInstance): Array; + getErrorRows(grid?: IGridInstance): Array; setRowsClean(dataRows: Array): Array; setRowsDirty(dataRows: Array): Array; - setSavePromise(rowEntity: Object, savePromise: ng.IPromise): void; + setSavePromise(rowEntity: Object, savePromise: ng.IPromise): void; on: { - saveRow: (scope: ng.IScope, handler: (rowEntity: Array) => void) => void + saveRow: (scope: ng.IScope, handler: (rowEntity: Array) => void) => void; } - } + } + export interface IGridRowResizableApi { + on: { + columnSizeChanged: (scope: ng.IScope, handler: (coldDef: IColumnDef) => void) => void; + } + } export interface IGridApiConstructor { new (grid: IGridInstance): IGridApi; @@ -375,25 +380,30 @@ declare module uiGrid { core: IGridCoreApi; /** - * Selection api - */ + * Selection api + */ selection: IGridSelectionApi; - + /** - * Pagination api + * Pagination api */ pagination: IGridPaginationApi; - - + + /** - * Grid Row Edit Api - */ + * Grid Row Edit Api + */ rowEdit: IGridRowEditApi; - + + /** + * Grid row resizable Api + */ + colResizable: IGridRowResizableApi; + /** * A grid instance is made available in the gridApi. - */ + */ grid: IGridInstance; } export interface IGridRowConstructor { @@ -522,6 +532,8 @@ declare module uiGrid { } export interface IGridColumn { + /** Column definition */ + colDef: uiGrid.IColumnDef; /** * Column name that will be shown in the header. * If displayName is not provided then one is generated using the name. @@ -540,9 +552,11 @@ declare module uiGrid { filters?: Array; name?: string; /** Sort on this column */ - sort?: ISortInfo + sort?: ISortInfo; /** Algorithm to use for sorting this column. Takes 'a' and 'b' parameters like any normal sorting function. */ sortingAlgorithm?: (a: any, b: any) => number; + /** Column width */ + width: number; /** * Initializes a column * @param colDef the column def to associate with this column From 8850b96dc9e4034150574e622595ede0ad03ffb3 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Tue, 4 Aug 2015 17:43:57 -0600 Subject: [PATCH 077/309] Added definitions for gulp-load-plugins --- gulp-load-plugins/gulp-load-plugins-tests.ts | 53 ++++++++++++++++++++ gulp-load-plugins/gulp-load-plugins.d.ts | 42 ++++++++++++++++ 2 files changed, 95 insertions(+) create mode 100644 gulp-load-plugins/gulp-load-plugins-tests.ts create mode 100644 gulp-load-plugins/gulp-load-plugins.d.ts diff --git a/gulp-load-plugins/gulp-load-plugins-tests.ts b/gulp-load-plugins/gulp-load-plugins-tests.ts new file mode 100644 index 0000000000..b527fd6a36 --- /dev/null +++ b/gulp-load-plugins/gulp-load-plugins-tests.ts @@ -0,0 +1,53 @@ +/// +/// +/// +/// + +import gulp = require('gulp'); +import gulpConcat = require('gulp-concat'); +import gulpLoadPlugins = require('gulp-load-plugins'); + +interface GulpPlugins extends IGulpPlugins { + concat: typeof gulpConcat; +} + +var plugins = gulpLoadPlugins({ + pattern: ['gulp-*', 'gulp.*'], + config: 'package.json', + scope: ['dependencies', 'devDependencies', 'peerDependencies'], + replaceString: /^gulp(-|\.)/, + camelize: true, + lazy: true, + rename: {} +}); +plugins = gulpLoadPlugins(); + +gulp.task('taskName', () => { + gulp.src('*.*') + .pipe(plugins.concat('concatenated.js')) + .pipe(gulp.dest('output')); +}); + +/* + * From 0.8.0, you can pass in an object of mappings for renaming plugins. For example, + * imagine you want to load the gulp-ruby-sass plugin, but want to refer to it as just + * sass : + */ +plugins = gulpLoadPlugins({ + rename: { + 'gulp-ruby-sass': 'sass' + } +}); +/* + * gulp-load-plugins comes with npm scope support. The major difference is that scoped + * plugins are accessible through an object on plugins that represents the scope. For + * example, if the plugin is @myco/gulp-test-plugin then you can access the plugin as + * shown in the following example: + */ +interface GulpPlugins { + myco: { + testPlugin(): NodeJS.ReadWriteStream; + } +} + +plugins.myco.testPlugin(); diff --git a/gulp-load-plugins/gulp-load-plugins.d.ts b/gulp-load-plugins/gulp-load-plugins.d.ts new file mode 100644 index 0000000000..a1aad053e8 --- /dev/null +++ b/gulp-load-plugins/gulp-load-plugins.d.ts @@ -0,0 +1,42 @@ +// Type definitions for gulp-load-plugins +// Project: https://github.com/jackfranklin/gulp-load-plugins +// Definitions by: Joe Skeen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +/** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */ +declare module 'gulp-load-plugins' { + + interface IOptions { + /** the glob(s) to search for, default ['gulp-*', 'gulp.*'] */ + pattern?: string[]; + /** where to find the plugins, searched up from process.cwd(), default 'package.json' */ + config?: string; + /** which keys in the config to look within, default ['dependencies', 'devDependencies', 'peerDependencies'] */ + scope?: string[]; + /** what to remove from the name of the module when adding it to the context, default /^gulp(-|\.)/ */ + replaceString?: RegExp; + /** if true, transforms hyphenated plugin names to camel case, default true */ + camelize?: boolean; + /** whether the plugins should be lazy loaded on demand, default true */ + lazy?: boolean; + /** a mapping of plugins to rename, the key being the NPM name of the package, and the value being an alias you define */ + rename?: IPluginNameMappings; + } + + interface IPluginNameMappings { + [npmPackageName: string]: string + } + + /** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */ + function gulpLoadPlugins(options?: IOptions): IGulpPlugins; + + export = gulpLoadPlugins; +} + +/** + * Extend this interface to use Gulp plugins in your gulpfile.js + */ +interface IGulpPlugins { +} From 8f8e8c55bfa090cb9cf7efcf7b2ce191643cccfd Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Tue, 4 Aug 2015 17:48:06 -0600 Subject: [PATCH 078/309] fix comment --- gulp-load-plugins/gulp-load-plugins.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gulp-load-plugins/gulp-load-plugins.d.ts b/gulp-load-plugins/gulp-load-plugins.d.ts index a1aad053e8..6b31993a9a 100644 --- a/gulp-load-plugins/gulp-load-plugins.d.ts +++ b/gulp-load-plugins/gulp-load-plugins.d.ts @@ -1,6 +1,6 @@ // Type definitions for gulp-load-plugins // Project: https://github.com/jackfranklin/gulp-load-plugins -// Definitions by: Joe Skeen +// Definitions by: Joe Skeen // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 52ef0043e7d64e5cdc63d56bd883e048ead05df0 Mon Sep 17 00:00:00 2001 From: Kyle Gretchev Date: Tue, 4 Aug 2015 20:47:16 -0400 Subject: [PATCH 079/309] Converted imports to ES6 module syntax --- body-parser/body-parser.d.ts | 2 +- express/express-tests.ts | 2 +- express/express.d.ts | 6 ++-- mime/mime-tests.ts | 2 +- node/node-tests.ts | 28 ++++++++--------- node/node.d.ts | 50 +++++++++++++++--------------- serve-static/serve-static-tests.ts | 4 +-- serve-static/serve-static.d.ts | 8 ++--- 8 files changed, 50 insertions(+), 52 deletions(-) diff --git a/body-parser/body-parser.d.ts b/body-parser/body-parser.d.ts index 994aa4e1b4..bf318d946e 100644 --- a/body-parser/body-parser.d.ts +++ b/body-parser/body-parser.d.ts @@ -6,7 +6,7 @@ /// declare module "body-parser" { - import express = require('express'); + import * as express from "express"; /** * bodyParser: use individual json/urlencoded middlewares diff --git a/express/express-tests.ts b/express/express-tests.ts index 22ae73e72f..72beb0790f 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,6 +1,6 @@ /// -import express = require('express'); +import * as express from 'express'; var app = express(); app.engine('jade', require('jade').__express); diff --git a/express/express.d.ts b/express/express.d.ts index 1cba6909c3..97b4ef2b88 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -5,7 +5,7 @@ /* =================== USAGE =================== - import express = require('express'); + import * as express from "express"; var app = express(); =============================================== */ @@ -24,8 +24,8 @@ declare module Express { declare module "express" { - import http = require('http'); - import serveStatic = require('serve-static'); + import * as http from "http"; + import * as serveStatic from "serve-static"; function e(): e.Express; diff --git a/mime/mime-tests.ts b/mime/mime-tests.ts index 36f0e5c15d..abfee0bd64 100644 --- a/mime/mime-tests.ts +++ b/mime/mime-tests.ts @@ -1,6 +1,6 @@ /// -import mime = require('mime'); +import * as mime from "mime"; var str: string; var obj: Object; diff --git a/node/node-tests.ts b/node/node-tests.ts index fe63dc6315..25a19db082 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1,18 +1,16 @@ -/// - -import assert = require("assert"); -import fs = require("fs"); -import events = require("events"); -import zlib = require("zlib"); -import url = require('url'); -import util = require("util"); -import crypto = require("crypto"); -import tls = require("tls"); -import http = require("http"); -import net = require("net"); -import dgram = require("dgram"); -import querystring = require('querystring'); -import path = require("path"); +import * as assert from "assert"; +import * as fs from "fs"; +import * as events from "events"; +import * as zlib from "zlib"; +import * as url from "url"; +import * as util from "util"; +import * as crypto from "crypto"; +import * as tls from "tls"; +import * as http from "http"; +import * as net from "net"; +import * as dgram from "dgram"; +import * as querystring from "querystring"; +import * as path from "path"; assert(1 + 1 - 2 === 0, "The universe isn't how it should."); diff --git a/node/node.d.ts b/node/node.d.ts index d260c19660..1b661d8fad 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -422,9 +422,9 @@ declare module "events" { } declare module "http" { - import events = require("events"); - import net = require("net"); - import stream = require("stream"); + import * as events from "events"; + import * as net from "net"; + import * as stream from "stream"; export interface Server extends events.EventEmitter { listen(port: number, hostname?: string, backlog?: number, callback?: Function): Server; @@ -568,8 +568,8 @@ declare module "http" { } declare module "cluster" { - import child = require("child_process"); - import events = require("events"); + import * as child from "child_process"; + import * as events from "events"; export interface ClusterSettings { exec?: string; @@ -608,7 +608,7 @@ declare module "cluster" { } declare module "zlib" { - import stream = require("stream"); + import * as stream from "stream"; export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; } export interface Gzip extends stream.Transform { } @@ -693,9 +693,9 @@ declare module "os" { } declare module "https" { - import tls = require("tls"); - import events = require("events"); - import http = require("http"); + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; export interface ServerOptions { pfx?: any; @@ -759,8 +759,8 @@ declare module "punycode" { } declare module "repl" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as events from "events"; export interface ReplOptions { prompt?: string; @@ -777,8 +777,8 @@ declare module "repl" { } declare module "readline" { - import events = require("events"); - import stream = require("stream"); + import * as events from "events"; + import * as stream from "stream"; export interface ReadLine extends events.EventEmitter { setPrompt(prompt: string, length: number): void; @@ -812,8 +812,8 @@ declare module "vm" { } declare module "child_process" { - import events = require("events"); - import stream = require("stream"); + import * as events from "events"; + import * as stream from "stream"; export interface ChildProcess extends events.EventEmitter { stdin: stream.Writable; @@ -939,7 +939,7 @@ declare module "dns" { } declare module "net" { - import stream = require("stream"); + import * as stream from "stream"; export interface Socket extends stream.Duplex { // Extended base methods @@ -1007,7 +1007,7 @@ declare module "net" { } declare module "dgram" { - import events = require("events"); + import * as events from "events"; interface RemoteInfo { address: string; @@ -1037,8 +1037,8 @@ declare module "dgram" { } declare module "fs" { - import stream = require("stream"); - import events = require("events"); + import * as stream from "stream"; + import * as events from "events"; interface Stats { isFile(): boolean; @@ -1476,9 +1476,9 @@ declare module "string_decoder" { } declare module "tls" { - import crypto = require("crypto"); - import net = require("net"); - import stream = require("stream"); + import * as crypto from "crypto"; + import * as net from "net"; + import * as stream from "stream"; var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; @@ -1654,7 +1654,7 @@ declare module "crypto" { } declare module "stream" { - import events = require("events"); + import * as events from "events"; export interface Stream extends events.EventEmitter { pipe(destination: T, options?: { end?: boolean; }): T; @@ -1819,7 +1819,7 @@ declare module "assert" { } declare module "tty" { - import net = require("net"); + import * as net from "net"; export function isatty(fd: number): boolean; export interface ReadStream extends net.Socket { @@ -1833,7 +1833,7 @@ declare module "tty" { } declare module "domain" { - import events = require("events"); + import * as events from "events"; export class Domain extends events.EventEmitter { run(fn: Function): void; diff --git a/serve-static/serve-static-tests.ts b/serve-static/serve-static-tests.ts index 36d2761cdd..9813794a6f 100644 --- a/serve-static/serve-static-tests.ts +++ b/serve-static/serve-static-tests.ts @@ -1,7 +1,7 @@ /// -import express = require('express'); -import serveStatic = require('serve-static'); +import * as express from 'express'; +import * as serveStatic from 'serve-static'; var app = express(); app.use(serveStatic('/1')); diff --git a/serve-static/serve-static.d.ts b/serve-static/serve-static.d.ts index cbf9406d74..ef59fa2bcf 100644 --- a/serve-static/serve-static.d.ts +++ b/serve-static/serve-static.d.ts @@ -5,8 +5,8 @@ /* =================== USAGE =================== - import serveStatic = require('serve-static'); - app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']})) + import * as serveStatic from "serve-static"; + app.use(serveStatic("public/ftp", {"index": ["default.html", "default.htm"]})) =============================================== */ @@ -14,7 +14,7 @@ /// declare module "serve-static" { - import express = require('express'); + import * as express from "express"; /** * Create a new middleware function to serve files from within a given root directory. @@ -76,7 +76,7 @@ declare module "serve-static" { setHeaders?: (res: express.Response, path: string, stat: any) => any; }): express.Handler; - import m = require('mime'); + import * as m from "mime"; module serveStatic { var mime: typeof m; From 0e10cf0d522294e3f2f2185d339ac563386f2b9e Mon Sep 17 00:00:00 2001 From: Kyle Gretchev Date: Tue, 4 Aug 2015 21:25:45 -0400 Subject: [PATCH 080/309] Added node.d.ts reference for CI test --- node/node-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node-tests.ts b/node/node-tests.ts index 25a19db082..7978766eb6 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1,3 +1,4 @@ +/// import * as assert from "assert"; import * as fs from "fs"; import * as events from "events"; From bcf0b2807b638eaad8893473eee167bce1369034 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Pa=CC=88rsson?= Date: Wed, 5 Aug 2015 09:47:32 +0200 Subject: [PATCH 081/309] Add test for Jasmine's jasmine.clock().mockDate(baseTime) --- jasmine/jasmine-tests.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/jasmine/jasmine-tests.ts b/jasmine/jasmine-tests.ts index d5eb228c95..9f57219b84 100644 --- a/jasmine/jasmine-tests.ts +++ b/jasmine/jasmine-tests.ts @@ -721,6 +721,17 @@ describe("Manually ticking the Jasmine Clock", function () { jasmine.clock().tick(50); expect(timerCallback.calls.count()).toEqual(2); }); + + describe("Mocking the Date object", function(){ + it("mocks the Date object and sets it to a given time", function() { + var baseTime = new Date(2013, 9, 23); + + jasmine.clock().mockDate(baseTime); + + jasmine.clock().tick(50); + expect(new Date().getTime()).toEqual(baseTime.getTime() + 50); + }); + }); }); describe("Asynchronous specs", function () { From 75e813a5d8afa7ed6a4e2df6d2fcbd8c3325858a Mon Sep 17 00:00:00 2001 From: "Ciuca, Alexandru" Date: Wed, 5 Aug 2015 10:57:40 +0300 Subject: [PATCH 082/309] angular.d.ts - Reverted controller definition in IDirective to any. --- 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 fb34759de7..4893cd0b3c 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1604,7 +1604,7 @@ declare module angular { interface IDirective { compile?: IDirectiveCompileFn; - controller?: {}; + controller?: any; controllerAs?: string; bindToController?: boolean|Object; link?: IDirectiveLinkFn | IDirectivePrePost; From ccaf6162aa95c5b4872cebd90840480e45484b67 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Wed, 5 Aug 2015 10:54:49 +0200 Subject: [PATCH 083/309] Added some missing methods and properties. Also some fixes to existing methods and properties which didn't match implementation. --- highcharts/highcharts.d.ts | 66 ++++++++++++++------------------------ 1 file changed, 24 insertions(+), 42 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index c29eb65f0b..5104eedb4b 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -191,11 +191,11 @@ interface HighchartsChartResetZoomButton { } interface HighchartsChartResetZoomButtonTheme { - fill?: string; //css HEX colours. - stroke?: string;//css HEX colours. + fill?: string; //css HEX colours. + stroke?: string;//css HEX colours. r?: number; // Radius % - states?: any; // HTML element states eg: hover, with css attributes in object. - display?: string; // css attr eg: 'none' + states?: any; // HTML element states eg: hover, with css attributes in object. + display?: string; // css attr eg: 'none' } interface HighchartsChartOptions { @@ -873,7 +873,7 @@ interface HighchartsLineChart { states?: { hover: HighchartsAreaStates; }; - step?: boolean; + step?: boolean|string; stickyTracking?: boolean; tooltip?: HighchartsTooltipOptions; turboThreshold?: number; @@ -986,7 +986,6 @@ interface HighchartsSeriesChart { dataLabels?: HighchartsDataLabels; enableMouseTracking?: boolean; events?: HighchartsPlotEvents; - id?: string; lineWidth?: number; marker?: HighchartsMarker; point?: { @@ -1041,13 +1040,14 @@ interface HighchartsPlotOptions { */ interface HighchartsIndividualSeriesOptions { data?: number[]|[number, number][]| HighchartsDataPoint[]; // [value1,value2, ... ] | [[x1,y1],[x2,y2],... ] | HighchartsDataPoint[] + id?: string; index?: number; legendIndex?: number; name?: string; stack?: any; // type doesn't matter, as long as grouped series' stack options match each other. type?: string; - xAxis?: number; - yAxis?: number; + xAxis?: string | number; + yAxis?: string | number; } interface HighchartsSeriesOptions extends HighchartsIndividualSeriesOptions, HighchartsSeriesChart { } @@ -1095,8 +1095,8 @@ interface HighchartsSeriesOptions extends HighchartsSeriesChart { legendIndex?: number; name?: string; stack?: string | number; - xAxis?: number; - yAxis?: number; + xAxis?: string | number; + yAxis?: string | number; } interface HighchartsSubtitleOptions { @@ -1180,6 +1180,7 @@ interface HighchartsAxisObject { addPlotBand(options: HighchartsPlotBands): void; addPlotLine(options: HighchartsPlotLines): void; getExtremes(): HighchartsExtremes; + remove(redraw?: boolean): void; removePlotBand(id: string): void; removePlotLine(id: string): void; setCategories(categories: string[]): void; @@ -1187,8 +1188,10 @@ interface HighchartsAxisObject { setExtremes(min: number, max: number): void; setExtremes(min: number, max: number, redraw: boolean): void; setExtremes(min: number, max: number, redraw: boolean, animation: boolean | HighchartsAnimation): void; - setTitle(title: HighchartsAxisTitle): void; - setTitle(title: HighchartsAxisTitle, redraw: boolean): void; + setTitle(title: HighchartsAxisTitle, redraw?: boolean): void; + toPixels(value: number, paneCoordinates?: boolean): number; + toValue(pixel: number, paneCoordinates?: boolean): number; + update(options: HighchartsAxisOptions, redraw?: boolean): void; } interface HighchartsChartObject { @@ -1275,52 +1278,31 @@ declare var Highcharts: HighchartsStatic; interface HighchartsPointObject { category: string | number; percentage: number; - remove(): void; - remove(redraw: boolean): void; - remove(redraw: boolean, animation: boolean): void; - remove(redraw: boolean, animation: HighchartsAnimation): void; + remove(redraw?: boolean, animation?: boolean|HighchartsAnimation): void; select(): void; select(select: boolean): void; select(select: boolean, accumulate: boolean): void; selected: boolean; series: HighchartsSeriesObject; - slice(): void; - slice(sliced: boolean): void; - slice(sliced: boolean, redraw: boolean): void; - slice(sliced: boolean, redraw: boolean, animation: boolean): void; - slice(sliced: boolean, redraw: boolean, animation: HighchartsAnimation): void; + slice(sliced?: boolean, redraw?: boolean, animation?: boolean|HighchartsAnimation): void; total: number; - update(options: any): void; - update(options: any, redraw: boolean): void; - update(options: any, redraw: boolean, animation: boolean): void; - update(options: any, redraw: boolean, animation: HighchartsAnimation): void; + update(options: number | [number, number] | HighchartsDataPoint, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; x: number; y: number; } interface HighchartsSeriesObject { - addPoint(options: number |[number, number]| HighchartsDataPoint): void; - addPoint(options: number |[number, number]| HighchartsDataPoint, redraw: boolean, shift: boolean): void; - addPoint(options: number |[number, number]| HighchartsDataPoint, redraw: boolean, shift: boolean, animation: boolean): void; - addPoint(options: number |[number, number]| HighchartsDataPoint, redraw: boolean, shift: boolean, animation: HighchartsAnimation): void; + addPoint(options: number |[number, number]| HighchartsDataPoint, redraw?: boolean, shift?: boolean, animation?: boolean | HighchartsAnimation): void; chart: HighchartsChartObject; - data: HighchartsDataPoint[]; + data: HighchartsPointObject[]; hide(): void; name: string; options: HighchartsSeriesOptions; - remove(): void; - remove(redraw: boolean): void; - select(): void; - select(selected: boolean): void; + remove(redraw?: boolean): void; + select(selected?: boolean): void; selected: boolean; - setData(data: number[]): void; // [value1,value2, ... ] - setData(data: number[], redraw: boolean): void; - setData(data: number[][]): void; // [[x1,y1],[x2,y2],... ] - setData(data: number[][], redraw: boolean): void; - setData(data: HighchartsDataPoint[]): void; // HighchartsDataPoint[] - setData(data: HighchartsDataPoint[], redraw: boolean): void; - setVisible(visible: boolean): void; - setVisible(visible: boolean, redraw: boolean): void; + setData(data: number[] | number[][] | HighchartsDataPoint[], redraw?: boolean, animation?: boolean | HighchartsAnimation, updatePoints?: boolean); + setVisible(visible: boolean, redraw?: boolean): void; show(): void; type: string; update(options: HighchartsSeriesOptions, redraw?: boolean): void; From 808cedd2ec29b4da0d42c15b209d1fda16d4ced9 Mon Sep 17 00:00:00 2001 From: Dan Lewi Harkestad Date: Wed, 5 Aug 2015 11:05:52 +0200 Subject: [PATCH 084/309] Fixed forgotten return type. --- highcharts/highcharts.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index 5104eedb4b..ee3a2ce4c1 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -191,11 +191,11 @@ interface HighchartsChartResetZoomButton { } interface HighchartsChartResetZoomButtonTheme { - fill?: string; //css HEX colours. - stroke?: string;//css HEX colours. + fill?: string; //css HEX colours. + stroke?: string;//css HEX colours. r?: number; // Radius % - states?: any; // HTML element states eg: hover, with css attributes in object. - display?: string; // css attr eg: 'none' + states?: any; // HTML element states eg: hover, with css attributes in object. + display?: string; // css attr eg: 'none' } interface HighchartsChartOptions { @@ -1301,7 +1301,7 @@ interface HighchartsSeriesObject { remove(redraw?: boolean): void; select(selected?: boolean): void; selected: boolean; - setData(data: number[] | number[][] | HighchartsDataPoint[], redraw?: boolean, animation?: boolean | HighchartsAnimation, updatePoints?: boolean); + setData(data: number[] | number[][] | HighchartsDataPoint[], redraw?: boolean, animation?: boolean | HighchartsAnimation, updatePoints?: boolean): void; setVisible(visible: boolean, redraw?: boolean): void; show(): void; type: string; From ab3767301dec55be28d77c639bddc575bd1ae19e Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 5 Aug 2015 10:18:58 +0100 Subject: [PATCH 085/309] Type definitions and tests for snake-case --- snake-case/snake-case.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snake-case/snake-case.d.ts diff --git a/snake-case/snake-case.d.ts b/snake-case/snake-case.d.ts new file mode 100644 index 0000000000..96db37535d --- /dev/null +++ b/snake-case/snake-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for snake-case +// Project: https://github.com/blakeembrey/snake-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "snake-case" { + function snakeCase(string: string, locale?: string): string; + export = snakeCase; +} From d26e7564997d11b634b763ff4d7ce8accdf76b47 Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Wed, 5 Aug 2015 10:19:50 +0100 Subject: [PATCH 086/309] Type definitions and tests for snake-case --- snake-case/snake-case-tests.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 snake-case/snake-case-tests.ts diff --git a/snake-case/snake-case-tests.ts b/snake-case/snake-case-tests.ts new file mode 100644 index 0000000000..e8d6db7bca --- /dev/null +++ b/snake-case/snake-case-tests.ts @@ -0,0 +1,9 @@ +/// + +import camelCase = require('snake-case'); + +console.log(camelCase('string')); // => "string" +console.log(camelCase('camelCase')); // => "camel_case" +console.log(camelCase('sentence case')); // => "sentence_case" + +console.log(camelCase('MY STRING', 'tr')); // => "my_strıng" From 4ded082c5d4243ea9d2ffcf38a449fda7ee46b98 Mon Sep 17 00:00:00 2001 From: John Reilly Date: Wed, 5 Aug 2015 13:27:04 +0100 Subject: [PATCH 087/309] Update protobufjs.d.ts This PR includes the [ProtoBuf.Long](https://github.com/dcodeIO/ProtoBuf.js/blob/master/src/ProtoBuf.js#L19) property. I based the definition on the existing long.d.ts. I didn't use it directly because I didn't want to create a dependency and because the long.d.ts would have to be changed to do this in the first place. @panuhorsmalahti - does this look okay to you? --- protobufjs/protobufjs.d.ts | 64 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/protobufjs/protobufjs.d.ts b/protobufjs/protobufjs.d.ts index 55d2bea66e..7133df6f69 100644 --- a/protobufjs/protobufjs.d.ts +++ b/protobufjs/protobufjs.d.ts @@ -11,6 +11,7 @@ declare module ProtoBuf { var Builder: Builder; var ByteBuffer: Buffer; + var Long: LongStatic; var DotProto: DotProto; var Reflect: Reflect; @@ -33,6 +34,69 @@ declare module ProtoBuf { export function newBuilder(options?: {[key: string]: any}): ProtoBuilder; + export interface LongStatic { + new(low?: number, high?: number, unsigned?:boolean): Long; + + MAX_UNSIGNED_VALUE: Long; + MAX_VALUE: Long; + MIN_VALUE: Long; + NEG_ONE: Long; + ONE: Long; + UONE: Long; + UZERO: Long; + ZERO: Long; + + fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long; + fromInt(value: number, unsigned?: boolean): Long; + fromNumber(value: number, unsigned?: boolean): Long; + fromString(str: string, unsigned?: boolean | number, radix?: number): Long; + fromValue(val: Long | number | string): Long; + + isLong(obj: any): boolean; + } + + // Based on https://github.com/dcodeIO/Long.js and https://github.com/borisyankov/DefinitelyTyped/blob/master/long/long.d.ts + export interface Long { + high: number; + low: number; + unsigned :boolean; + + add(other: Long | number | string): Long; + and(other: Long | number | string): Long; + compare(other: Long | number | string): number; + div(divisor: Long | number | string): Long; + equals(other: Long | number | string): boolean; + getHighBits(): number; + getHighBitsUnsigned(): number; + getLowBits(): number; + getLowBitsUnsigned(): number; + getNumBitsAbs(): number; + greaterThan(other: Long | number | string): boolean; + greaterThanOrEqual(other: Long | number | string): boolean; + isEven(): boolean; + isNegative(): boolean; + isOdd(): boolean; + isPositive(): boolean; + isZero(): boolean; + lessThan(other: Long | number | string): boolean; + lessThanOrEqual(other: Long | number | string): boolean; + modulo(divisor: Long | number | string): Long; + multiply(multiplier: Long | number | string): Long; + negate(): Long; + not(): Long; + notEquals(other: Long | number | string): boolean; + or(other: Long | number | string): Long; + shiftLeft(numBits: number | Long): Long; + shiftRight(numBits: number | Long): Long; + shiftRightUnsigned(numBits: number | Long): Long; + subtract(other: Long | number | string): Long; + toInt(): number; + toNumber(): number; + toSigned(): Long; + toString(radix?: number): string; + toUnsigned(): Long; + xor(other: Long | number | string): Long; + } // ========== // protobufjs/src/ProtoBuf/Builder.js From bbf926bcf0868edcd6891f6798e4cd9da393af09 Mon Sep 17 00:00:00 2001 From: Joe Skeen Date: Wed, 5 Aug 2015 11:46:31 -0600 Subject: [PATCH 088/309] Utilize generics in plugin loading --- gulp-load-plugins/gulp-load-plugins-tests.ts | 6 +++--- gulp-load-plugins/gulp-load-plugins.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/gulp-load-plugins/gulp-load-plugins-tests.ts b/gulp-load-plugins/gulp-load-plugins-tests.ts index b527fd6a36..f479be00cd 100644 --- a/gulp-load-plugins/gulp-load-plugins-tests.ts +++ b/gulp-load-plugins/gulp-load-plugins-tests.ts @@ -11,7 +11,7 @@ interface GulpPlugins extends IGulpPlugins { concat: typeof gulpConcat; } -var plugins = gulpLoadPlugins({ +var plugins = gulpLoadPlugins({ pattern: ['gulp-*', 'gulp.*'], config: 'package.json', scope: ['dependencies', 'devDependencies', 'peerDependencies'], @@ -20,7 +20,7 @@ var plugins = gulpLoadPlugins({ lazy: true, rename: {} }); -plugins = gulpLoadPlugins(); +plugins = gulpLoadPlugins(); gulp.task('taskName', () => { gulp.src('*.*') @@ -33,7 +33,7 @@ gulp.task('taskName', () => { * imagine you want to load the gulp-ruby-sass plugin, but want to refer to it as just * sass : */ -plugins = gulpLoadPlugins({ +plugins = gulpLoadPlugins({ rename: { 'gulp-ruby-sass': 'sass' } diff --git a/gulp-load-plugins/gulp-load-plugins.d.ts b/gulp-load-plugins/gulp-load-plugins.d.ts index 6b31993a9a..c8a11091d2 100644 --- a/gulp-load-plugins/gulp-load-plugins.d.ts +++ b/gulp-load-plugins/gulp-load-plugins.d.ts @@ -30,7 +30,7 @@ declare module 'gulp-load-plugins' { } /** Loads in any gulp plugins and attaches them to an object, freeing you up from having to manually require each gulp plugin. */ - function gulpLoadPlugins(options?: IOptions): IGulpPlugins; + function gulpLoadPlugins(options?: IOptions): T; export = gulpLoadPlugins; } From a117cbd73edf88c2e6bc72811a36301630fb72ee Mon Sep 17 00:00:00 2001 From: benishouga Date: Thu, 6 Aug 2015 03:22:04 +0900 Subject: [PATCH 089/309] add svg attribute width and height for rect element. SVGAttribute inherit DOMAttributes. --- react/react-addons.d.ts | 6 +++++- react/react-global.d.ts | 6 +++++- react/react.d.ts | 6 +++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/react/react-addons.d.ts b/react/react-addons.d.ts index 9479cc722d..151511339c 100644 --- a/react/react-addons.d.ts +++ b/react/react-addons.d.ts @@ -518,7 +518,9 @@ declare module "react/addons" { unselectable?: boolean; } - interface SVGAttributes extends HTMLAttributes { + interface SVGAttributes extends DOMAttributes { + ref?: string | ((component: SVGComponent) => void); + cx?: number | string; cy?: number | string; d?: string; @@ -532,6 +534,7 @@ declare module "react/addons" { fy?: number | string; gradientTransform?: string; gradientUnits?: string; + height?: number | string; markerEnd?: string; markerMid?: string; markerStart?: string; @@ -556,6 +559,7 @@ declare module "react/addons" { transform?: string; version?: string; viewBox?: string; + width?: number | string; x1?: number | string; x2?: number | string; x?: number | string; diff --git a/react/react-global.d.ts b/react/react-global.d.ts index ea032100c4..fd84d982e3 100644 --- a/react/react-global.d.ts +++ b/react/react-global.d.ts @@ -524,7 +524,9 @@ declare module React { preserveAspectRatio?: string; } - interface SVGAttributes extends HTMLAttributes { + interface SVGAttributes extends DOMAttributes { + ref?: string | ((component: SVGComponent) => void); + cx?: number | string; cy?: number | string; d?: string; @@ -538,6 +540,7 @@ declare module React { fy?: number | string; gradientTransform?: string; gradientUnits?: string; + height?: number | string; markerEnd?: string; markerMid?: string; markerStart?: string; @@ -562,6 +565,7 @@ declare module React { transform?: string; version?: string; viewBox?: string; + width?: number | string; x1?: number | string; x2?: number | string; x?: number | string; diff --git a/react/react.d.ts b/react/react.d.ts index 74d6eab4f4..c27d523f04 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -524,7 +524,9 @@ declare module __React { preserveAspectRatio?: string; } - interface SVGAttributes extends HTMLAttributes { + interface SVGAttributes extends DOMAttributes { + ref?: string | ((component: SVGComponent) => void); + cx?: number | string; cy?: number | string; d?: string; @@ -538,6 +540,7 @@ declare module __React { fy?: number | string; gradientTransform?: string; gradientUnits?: string; + height?: number | string; markerEnd?: string; markerMid?: string; markerStart?: string; @@ -562,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 9522b37f7e4f5625f31db4006e4c54efc449041a Mon Sep 17 00:00:00 2001 From: Austen Talbot Date: Wed, 5 Aug 2015 12:21:02 -0700 Subject: [PATCH 090/309] Added type def and test for diff-match-patch library --- diff-match-patch/diff-match-patch-tests.ts | 32 +++++++++++++++ diff-match-patch/diff-match-patch.d.ts | 46 ++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 diff-match-patch/diff-match-patch-tests.ts create mode 100644 diff-match-patch/diff-match-patch.d.ts diff --git a/diff-match-patch/diff-match-patch-tests.ts b/diff-match-patch/diff-match-patch-tests.ts new file mode 100644 index 0000000000..f1e5d2d42e --- /dev/null +++ b/diff-match-patch/diff-match-patch-tests.ts @@ -0,0 +1,32 @@ +/// + +import DiffMatchPatch = require("diff-match-patch"); + +var oldValue = "hello world, how are you?"; +var newValue = "hello again world. how have you been?"; + +var diffEngine = new DiffMatchPatch.diff_match_patch(); +var diffs = diffEngine.diff_main(oldValue, newValue); +diffEngine.diff_cleanupSemantic(diffs); + +var changes = ""; +var pattern = ""; + +diffs.forEach(function(diff) { + var operation = diff[0]; // Operation (insert, delete, equal) + var text = diff[1]; // Text of change + + switch (operation) { + case DiffMatchPatch.DIFF_INSERT: + pattern += "I"; + break; + case DiffMatchPatch.DIFF_DELETE: + pattern += "D"; + break; + case DiffMatchPatch.DIFF_EQUAL: + pattern += "E"; + break; + } + + changes += text; +}); diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts new file mode 100644 index 0000000000..3a55b77692 --- /dev/null +++ b/diff-match-patch/diff-match-patch.d.ts @@ -0,0 +1,46 @@ +// Type definitions for diff-match-patch v1.0.0 +// Project: https://www.npmjs.com/package/diff-match-patch +// Definitions by: Austen Talbot +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "diff-match-patch" { + interface Diff { + 0: number; + 1: string; + } + + export class DiffMatchPatch { + Diff_Timeout: number; + Diff_EditCost: number; + Match_Threshold: number; + Match_Distance: number; + Patch_DeleteThreshold: number; + Patch_Margin: number; + Match_MaxBits: number; + + diff_main(text1: string, text2: string, opt_checklines?: boolean, opt_deadline?: number): Diff[]; + diff_commonPrefix(text1: string, text2: string): number; + diff_commonSuffix(text1: string, text2: string): number; + diff_cleanupSemantic(diffs: Diff[]): void; + diff_cleanupSemanticLossless(diffs: Diff[]): void; + diff_cleanupEfficiency(diffs: Diff[]): void; + diff_cleanupMerge(diffs: Diff[]): void; + diff_xIndex(diffs: Diff[], loc: number): number; + diff_prettyHtml(diffs: Diff[]): string; + diff_text1(diffs: Diff[]): string; + diff_text2(diffs: Diff[]): string; + diff_levenshtein(diffs: Diff[]): number; + diff_toDelta(diffs: Diff[]): string; + diff_fromDelta(text1: string, delta: string): Diff[]; + + new (): DiffMatchPatch; + } + + export var DIFF_DELETE: number; + export var DIFF_INSERT: number; + export var DIFF_EQUAL: number; + + export var diff_match_patch: { + new (): DiffMatchPatch; + }; +} From 84dc21b73b9a04f6d90806aee64c3fa9d541ff8f Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Wed, 5 Aug 2015 15:04:49 -0600 Subject: [PATCH 091/309] Update definitions according to the pattern provided by Masahiro Wakame in order to work with nodejs as well --- yamljs/yamljs.d.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/yamljs/yamljs.d.ts b/yamljs/yamljs.d.ts index 96c9d33c77..a0f948fe6d 100644 --- a/yamljs/yamljs.d.ts +++ b/yamljs/yamljs.d.ts @@ -3,12 +3,14 @@ // Definitions by: Tim Jonischkat // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module YAML { +declare var YAML: { + load(path : string) : any; - export function load(path : string) : any; + stringify(nativeObject : any, inline? : number, spaces? : number) : string; - export function stringify(nativeObject : any, inline? : number, spaces? : number) : string; + parse(yamlString : string) : any; +}; - export function parse(yamlString : string) : any; - -} \ No newline at end of file +declare module "yamljs" { + export = YAML; +} From 882139ded1547391ad968353c042e92744176791 Mon Sep 17 00:00:00 2001 From: Daniel Chao Date: Wed, 5 Aug 2015 17:38:47 -0700 Subject: [PATCH 092/309] Add an authuser paramter http://stackoverflow.com/questions/13366254/is-it-possible-to-be-able-to-correctly-select-any-available-google-account-to-us --- gapi/gapi.d.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gapi/gapi.d.ts b/gapi/gapi.d.ts index 8c50826d4c..cce0a2244d 100644 --- a/gapi/gapi.d.ts +++ b/gapi/gapi.d.ts @@ -48,7 +48,11 @@ declare module gapi.auth { /** * The auth scope or scopes to authorize. Auth scopes for individual APIs can be found in their documentation. */ - scope?: any + scope?: any; + /** + * The user to sign in as. -1 to toggle a multi-account chooser, 0 to default to the user's current account, and 1 to automatically sign in if the user is signed into Google Plus. + */ + authuser?: number; }, callback: (token: GoogleApiOAuth2TokenObject) => any): void; /** * Initializes the authorization feature. Call this when the client loads to prevent popup blockers from blocking the auth window on gapi.auth.authorize calls. From e8bdd1be7c8a81dcf9f4cdae126690c7bf249501 Mon Sep 17 00:00:00 2001 From: Paul Welter Date: Wed, 5 Aug 2015 23:00:03 -0500 Subject: [PATCH 093/309] add dragula definition --- dragula/dragula-amd-tests.ts | 37 +++++++++++++++++++++ dragula/dragula-amd-tests.ts.tscparams | 1 + dragula/dragula-tests.ts | 31 +++++++++++++++++ dragula/dragula-tests.ts.tscparams | 1 + dragula/dragula.d.ts | 46 ++++++++++++++++++++++++++ 5 files changed, 116 insertions(+) create mode 100644 dragula/dragula-amd-tests.ts create mode 100644 dragula/dragula-amd-tests.ts.tscparams create mode 100644 dragula/dragula-tests.ts create mode 100644 dragula/dragula-tests.ts.tscparams create mode 100644 dragula/dragula.d.ts diff --git a/dragula/dragula-amd-tests.ts b/dragula/dragula-amd-tests.ts new file mode 100644 index 0000000000..99cb5e043f --- /dev/null +++ b/dragula/dragula-amd-tests.ts @@ -0,0 +1,37 @@ +import dragula = require("dragula"); + +// containers +var d1 = dragula([document.querySelector('#left'), document.querySelector('#right')]); + +// all options +var d2 = dragula({ + isContainer: function (el) { + return false; + }, + moves: function (el, container, handle) { + return true; + }, + accepts: function (el, target, source, sibling) { + return true; + }, + invalid: function (el, target) { + return el.tagName === 'A' || el.tagName === 'BUTTON'; + }, + direction: 'vertical', + copy: false, + revertOnSpill: false, + removeOnSpill: false, + delay: false, + mirrorContainer: document.body +}); + +// empty call +var d3 = dragula(); + + +// drake API +var drake = dragula({ + copy: true +}); + +drake.containers.push(document.querySelector('#container')); diff --git a/dragula/dragula-amd-tests.ts.tscparams b/dragula/dragula-amd-tests.ts.tscparams new file mode 100644 index 0000000000..7c5a0c2f95 --- /dev/null +++ b/dragula/dragula-amd-tests.ts.tscparams @@ -0,0 +1 @@ +--experimentalDecorators --target ES5 --module amd diff --git a/dragula/dragula-tests.ts b/dragula/dragula-tests.ts new file mode 100644 index 0000000000..f5481f1d89 --- /dev/null +++ b/dragula/dragula-tests.ts @@ -0,0 +1,31 @@ +/// + +var d1 = dragula([document.querySelector('#left'), document.querySelector('#right')]); + +var d2 = dragula({ + isContainer: function (el) { + return false; + }, + moves: function (el, container, handle) { + return true; + }, + accepts: function (el, target, source, sibling) { + return true; + }, + invalid: function (el, target) { + return el.tagName === 'A' || el.tagName === 'BUTTON'; + }, + direction: 'vertical', + copy: false, + revertOnSpill: false, + removeOnSpill: false, + delay: false, + mirrorContainer: document.body +}); + +var d3 = dragula(); + +var drake = dragula({ + copy: true +}); +drake.containers.push(document.querySelector('#container')); diff --git a/dragula/dragula-tests.ts.tscparams b/dragula/dragula-tests.ts.tscparams new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/dragula/dragula-tests.ts.tscparams @@ -0,0 +1 @@ + diff --git a/dragula/dragula.d.ts b/dragula/dragula.d.ts new file mode 100644 index 0000000000..8a707ef6fc --- /dev/null +++ b/dragula/dragula.d.ts @@ -0,0 +1,46 @@ +// Type definitions for dragula v2.1.2 +// Project: http://bevacqua.github.io/dragula/ +// Definitions by: Paul Welter +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module dragula { + interface DragulaOptions { + containers?: Element[]; + isContainer?: (el?: Element) => boolean; + moves?: (el?: Element, container?: Element, handle?: Element) => boolean; + accepts?: (el?: Element, target?: Element, source?: Element, sibling?: Element) => boolean; + invalid?: (el?: Element, target?: Element) => boolean; + direction?: string; + copy?: boolean; + revertOnSpill?: boolean; + removeOnSpill?: boolean; + delay?: boolean | number; + mirrorContainer?: Element; + } + + interface Drake { + containers: Element[]; + dragging: boolean; + start(item:Element): void; + end(): void; + cancel(revert:boolean): void; + cancel(): void; + remove(): void; + on(events: string, callback: Function): void; + destroy(): void; + } + + interface Dragula { + (containers: Element[], options: DragulaOptions): Drake; + (containers: Element, options: DragulaOptions): Drake; + (containers: Element[]): Drake; + (options: DragulaOptions): Drake; + (): Drake; + } +} + +declare var dragula: dragula.Dragula; + +declare module "dragula" { + export = dragula; +} From 66135fcdb6c3e2d0dc03acbf06b72829140b7063 Mon Sep 17 00:00:00 2001 From: Alexandru Ciuca Date: Thu, 6 Aug 2015 08:13:50 +0300 Subject: [PATCH 094/309] angular.d.ts - Reverted window and browser services to any --- angularjs/angular.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 4893cd0b3c..73629204a5 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -708,6 +708,7 @@ declare module angular { // see http://docs.angularjs.org/api/ng.$window /////////////////////////////////////////////////////////////////////////// interface IWindowService extends Window { + [key: string]: any; } /////////////////////////////////////////////////////////////////////////// @@ -716,6 +717,7 @@ declare module angular { /////////////////////////////////////////////////////////////////////////// interface IBrowserService { defer: angular.ITimeoutService; + [key: string]: any; } /////////////////////////////////////////////////////////////////////////// From 21cda213a2445ab28d2bf2f40e2fdcbfaf7bd18e Mon Sep 17 00:00:00 2001 From: sourcebits-robertbiggs Date: Wed, 5 Aug 2015 22:16:08 -0700 Subject: [PATCH 095/309] Added Fetch API. --- chocolatechipjs/chocolatechipjs-tests.ts | 212 +- chocolatechipjs/chocolatechipjs.d.ts | 2661 +++++++++++----------- 2 files changed, 1444 insertions(+), 1429 deletions(-) diff --git a/chocolatechipjs/chocolatechipjs-tests.ts b/chocolatechipjs/chocolatechipjs-tests.ts index e0eec9c53a..cfb2ce8549 100644 --- a/chocolatechipjs/chocolatechipjs-tests.ts +++ b/chocolatechipjs/chocolatechipjs-tests.ts @@ -16,7 +16,6 @@ var nodeName = divTag2[0].nodeName; var version = $.version; var libraryName = $.libraryName; var els = $('li'); -var listItems = $.slice(els); var madeEls = $.make('

Stuff

'); var moreEls = $.html('

Stuff

'); var oldTag = $('#oldTag'); @@ -241,108 +240,119 @@ var myPromise = new Promise(function(resolve, reject) { myPromise.then(function(value) { // Success: console.log(value); -}, - // Opps! There was a problem: - function(reason) { - console.log(reason); - }); + }, + // Opps! There was a problem: + function(reason) { + console.log(reason); +}); -// Ajax: -$.ajax({ - url: "announcement.html", - dataType: "html", - success: function(data) { - // Insert the fragment into the page: - $("#content").html(data); - }, - error: function(data) { - $("#content").html("

There was an error while trying to get the file.

"); - } +// Fetch API +//=========== +// GET: +interface WineObject { + data: Array; +} +interface WineInterface { + wine: { + name: string; + } +} +fetch('../data/wines.json') +.then($.json) +.then(function(obj: any):any { + $('#message_ajax').empty(); + obj.data.forEach(function(wine: any) { + $('#message_ajax').append('
  • ' + wine.name + '
  • '); + }) }); -$.ajax({ - url: "me.json", - success: function(data) { - // Before using a JSON object, you need to parse it. - // Here we parse it and assign it to a variable: - var me = JSON.parse(data); - // Here we access the properties of the JSON object: - $("#content").html(me.firstName + " " + me.lastName); - }, - error: function(data) { - $('#content').html("

    There was an error while trying to get the file.

    "); - } -}); -var myData = { - "name": "Bozo the Clown", - "occupation": "Clown" -}; -var mySuccessCallback = function() { - console.log('The post was a success!'); -}; -var myErrorCallback = function() { - console.log('Ooops! There was a problem posting this.'); -}; -$.ajax({ - url: "/path/to/controller", - method: 'POST', - headers: { - "Content-Type": "application/x-www-form-urlencoded", - "async": true, - "Access-Control-Allow-Origin": "*", - "Accept": "text/plain" - }, - data: myData, - success: mySuccessCallback, - error: myErrorCallback -}); -$.get('http://my.com/data/stuff.html') - .then(function(response) { - console.log("Success!", response); - }, function(error) { - console.error("Failed!", error); - }); -$.get('http://my.com/data/stuff.html') - .then(function(response) { - console.log("Success!", response); - }) - .catch(function(error) { - console.error("Failed!", error); - }); -$.get('story.json') - .then(JSON.parse) - .then(function(response) { - console.log("Yey JSON!", response); - }); -$.getJSON('/data/deserts.json', function(desserts: Array) { - desserts.forEach(function(dessert) { - $('#deserts').append('
  • ' + dessert.name + '
  • '); - }); -}); -$.post("updateUser.php", - { "name": "Joe", "time": "10PM" }, - function() { - console.log('The POST was successful.') - }, - "json" - ); -$.JSONP({ url: 'https://api.github.com/users/yui?callback=?' }) - .then(function(users) { - $('.list').append('
  • The name of the library

    ' + users.data.name + '

  • '); - }) - .catch(function(err) { - console.log('Unable to get data.') - }); - -$.JSONP({ - url: 'http://www.geonames.org/postalCodeLookupJSON?postalcode=94102&' +// POST: +interface postData { + email: string; + name: string; + msg: string; +} +var formData = $.serialize($('form')[0]); +fetch('../controllers/php-post.php', { + method: 'post', + headers: { + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + }, + body: formData }) - .then(function(data) { - $('.list').append('
  • My Location

    ' + data.postalcodes[0].adminName2 + ', ' + data.postalcodes[0].adminName1 + '

  • '); - }) - .catch(function(err) { - console.log('Unable to get data.') - }); +.then($.json) +.then(function(data: any): any { + if(data.email_check == "valid"){ + $("#message_ajax").html("
    " + data.email + " is a valid e-mail address. Thank you, " + data.name + ".
    "); + $("#message_ajax").append('

    ' + data.msg + '

    '); + } else { + $("#message_ajax").html("
    Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.
    "); + } +}); +// PUT: +interface putData { + base: string; + result: string; + fileName: string; +} +var putData = $('#fileText').val(); +fetch('../controllers/php-put.php', { + method: 'put', + headers: { + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + }, + body: putData +}) +.then($.json) +.then(function(data:any): any { + console.dir(data.base); + $("#message_ajax").append('

    ' + data.result + '

    '); + $("#message_ajax").append('

    The file name is: ' + data.fileName + '

    '); +}) +.catch(function(error:Error) { + console.log(error); + $("#message_ajax").html("
    Sorry, put was not successful.
    "); +}); + + +// DELETE: +interface deleteData { + result: string; +} +var file = $('#fileName').val(); +fetch('../controllers/php-delete.php', { + method: 'delete', + headers: { + "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" + }, + body: file +}) +.then($.json) +.then(function(data: any): any { + $("#message_ajax").html("
    DELETE was sent to the server successfully.
    "); + $("#message_ajax").append('

    ' + data.result + '

    '); +}, +function(data: any) { + console.log('PROBLEM') + console.log(data); +}) +.catch(function(error: any) { + $("#message_ajax").html("
    Sorry, 'DELETE' was not successful.
    "); + error.reject(); +}); + +// $.jsonp: +$.jsonp('https://api.github.com/users/rbiggs/repos?name=chipper', {timeout: 10000}) +.then($.json) +.then(function(obj: any): any { + console.log(obj); + obj.data.forEach(function(repo: any): any { + $('#message_ajax').append("
  • " + repo.name + "
  • "); + }); +}) +.catch(function(error: any): any { + $('#message_ajax').append("
  • " + error.message + "
  • ") +}); // Templates: var myTemplate = '
  • Name: [[= data.name]]
  • '; @@ -376,10 +386,10 @@ var repeaterTmplate2 = '
  • [[= data.firstName ]], [[= data.lastName]]
  • '; $.template.repeater($('#objectArrayList'), repeaterTmplate2, luminaries.persons); // Pub/Sub: -var arraySubscriber = function(topic: string, data: any) { +var arraySubscriber = function(topic: string, data: any): any { $('.list').append('
  • ' + topic + '

    ' + data + '

  • '); - var newsSubscription = $.subscribe('news/update', arraySubscriber); }; +var newsSubscription = $.subscribe('news/update', arraySubscriber); $.publish('news/update', 'The New York Stock Exchange rose an unprecedented 1000 points in just three minutes. Analysts and investors are confused and uncertain how to respond.'); $.unsubscribe('news/update'); // Due to being unsubscribed above, this does nothing: diff --git a/chocolatechipjs/chocolatechipjs.d.ts b/chocolatechipjs/chocolatechipjs.d.ts index 9b79934b7f..9a1b4c8498 100644 --- a/chocolatechipjs/chocolatechipjs.d.ts +++ b/chocolatechipjs/chocolatechipjs.d.ts @@ -1,526 +1,502 @@ -// Type definitions for chocolatechip v3.8.11 +// Type definitions for chocolatechip v4.0.0 // Project: https://github.com/chocolatechipui/ChocolateChipJS // Definitions by: Robert Biggs // Definitions: https://github.com/borisyankov/DefinitelyTyped - - -/** - * Defines the base object namespace for ChocolateChipJS. - */ -declare var $chocolatechipjs: ChocolateChipStatic; -declare var $: ChocolateChipStatic; - -/** - * Static members of ChocolateChip (those on $ and ChocolateChipJS themselves) - */ interface ChocolateChipStatic { - /** - * Contains the version of ChocolateChipJS in use. - */ - version: string; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM HTMLElement to use as context + * @return HTMLElement[] + */ + (selector: string | HTMLElement | Document, context?: HTMLElement | ChocolateChipElementArray): ChocolateChipElementArray; - /** - * Contains the name of the library (ChocolateChip). - */ - libraryName: string; + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + * @return void + */ + (callback: () => any): void; - /* - * This method takes an array-like object and returns its members as an array. + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in an array. + * @return HTMLElement[] + */ + (element: HTMLElement): ChocolateChipElementArray; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array of DOM elements to convert into a ChocolateChip Collection. + * @return HTMLElement[] + */ + (elementArray: ChocolateChipElementArray): ChocolateChipElementArray; + + (document: Document): Document[]; + /** + * If no argument is provided, return the document as a ChocolateChipElementArray. + * @return Document[] + */ + (): Document[]; + + /** + * Extend the ChocolateChipJS object itself with the provided object. + * + * @param object The object to add to ChocolateChipJS. + * @return The ChocolateChipJS object. + */ + extend(object: Object): Object; + + /** + * Extend a target object with another object. + * + * @param target An object to extend. + * @param object The object to add to the target. + * @return The extended object. + */ + extend(target: Object, object: Object): Object; + + /** + * The base for extending ChocolateChipJS collections, which are arrays of elements. + */ + fn: { + /** + * This method adds the provided object to the Array prototype to make it available to all arrays of HTML elements. * - * @param arrayLikeObject Either the arguents object or an node collection. - */ - slice(arrayLikeObject: any): Array; - - /** - * Merge the contents of one object into the first object. If only one argument is provided, it is merged into ChocolateChipStatic. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will extend the ChocolateChipStatic namespace if there is a single argument. - * @param object An object containing additional properties to merge in. - */ - extend(target: any, object?: any): any; - - /** - * Create a ChocolateChip collection object by creating elements from an HTML string. - * - * @param selector - * @return any - */ - make(selector: string): ChocolateChipElementArray; - - /** - * Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make. - * - * @param selector - * @return any - */ - html(selector: string): ChocolateChipElementArray; - - /** - * Replace one element with another. - * - * @param new HTMLElement - * @param old HTMLElement - * @return HTMLElement[] - */ - replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void; - - /** - * Load a JavaScript file from a url, then execute it. - * - * @param url A string containing the URL where the script resides. - * @param callback A callback function that is executed after the script loads. - * @return void - */ - require(url: string, callback: Function): Function; - - /** - * Process JavaScript returned by Ajax request. An optional name can be used to create a custom variable name by which the data is exposed, otherwise it is exposed with the variable "data". - * - * @param url A string containing the URL where the script resides. - * @param callback A callback function that is executed after the script loads. - * @return Function - */ - processJSON(json: string, name?: string): any; - - /** - * This method will defer the execution of a function until the call stack is clear. - * - * @param callback A function to execute. - * @param duration The number of milliseconds to delay execution. - * @return any - */ - delay(callback: Function, duration?: number): any; - - /** - * The method will defer the execution of its callback until the call stack is clear. - * - * @param callback A callback to execute after a delay. - * @return Function. - */ - defer(callback: Function): Function; - - /** - * An empty function. - * - * @return any - */ - noop(): void; - - /** - * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. - * - * @param string or number A comma separated series of strings to concatenate. - * @return string - */ - concat(...string: string[]): string; - - /** - * This method takes a space-delimited string of words and returns it as an array where the individual words are indices. - * - * @param string Any string with values separated by spaces. - * @return string[] - */ - w(string: string): string[]; - - /** - * Determine whether the argument is a string. - * - * @param obj Object to test whether or not it is a string. - * @return boolean - */ - isString(obj: any): boolean; - - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - * @return boolean - */ - isArray(obj: any): boolean; - - /** - * Determine whether the argument is a function. - * - * @param obj Object to test whether or not it is an function. - * @return boolean - */ - isFunction(obj: any): boolean; - - /** - * Determine whether the argument is an object. - * - * @param obj Object to test whether or not it is an object. - * @return boolean - */ - isObject(obj: any): boolean; - - /** - * Determine whether the argument is an empty object. - * - * @param obj Object to test whether or not it is an empty object. - * @return boolean - */ - isEmptyObject(obj: any): boolean; - - /** - * Determine whether the argument is an empty object. - * - * @param obj Object to test whether or not it is an empty object. - * @return boolean - */ - isEmptyObject(obj: any): boolean; - - /** - * Determine whether the argument is a number. - * - * @param obj Object to test whether or not it is a number. - * @return boolean - */ - isNumber(obj: any): boolean; - - /** - * Determine whether the argument is an integer. - * - * @param obj Object to test whether or not it is an integer. - * @return boolean - */ - isInteger(obj: any): boolean; - - /** - * Determine whether the argument is a float. - * - * @param obj Object to test whether or not it is a float. - * @return boolean - */ - isFloat(obj: any): boolean; - - /** - * Creates a Uuid and returns it as a string with the prefix: "chch_". - */ - makeUuid(): string; - - /** - * A generic iterator function, which can be used to seamlessly iterate over arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. - * - * @param collection The object or array to iterate over. - * @param callback The function that will be executed on every object. - * @return any - */ - each( - collection: any, - callback: (valueOfElement: any, indexInArray: number) => any - ): any; - - - /** - * This method converts a string of hyphenated tokens into a camel cased string. - * - * @param string A string of hyphenated tokens. - * @return string - */ - camelize(string: string): string; - - /** - * This method converts a camel case string into lowercase with hyphens. - * - * @param string A camel case string. - * @return string - */ - deCamelize(string: string): string; - - /** - * This method capitalizes the first letter of a string. - * - * @param string A string. - * @param boolean A boolean value. - * @return string - */ - capitalize(string: string, boolean?: boolean): string; - - /** - * Object used to store string templates and parsed templates. - * - * @param string A string defining the template. - * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. - * @return void - */ - templates: Object; - - /** - * This method returns a parsed template. - * - */ - template: ChocolateChipTemplate; - - - /** - * This is the base for the plugin "extend" interface, which allows you to add methods that can iterate over element collections. - */ - fn: ChocolateChipPlugin; - - /** - * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * - * param newContent The content to insert. May be an HTML string, DOM element, or an array of DOM elements. - * @return void - */ - replace(newELement: HTMLElement, oldElement: HTMLElement): void; - - /** - * Perform an asynchronous HTTP (Ajax) request. - */ - ajax(settings: ChocolateChipAjaxSettings): Promise; - - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (json, or html). - * @return Promise - */ - get(url: string, data?: any, success?: (data: any) => any, dataType?: string): Promise; - - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @param dataType The type of data expected from the server. - * @return Promise - */ - post(url: string, data?: any, success?: () => any, dataType?: string): Promise; - - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @return Promise - */ - //each(func: (ctx: any, idx: number) => any): void; - getJSON(url: string, data?: any, success?: (data: any) => any): Promise; - - /** - * Load JSON from a remote server using the JSONP technique. - * - * @param url A string - * @return Promise - */ - JSONP(options: ChocolateChipJSONP): Promise; - //JSONP({url: string, success?: (data: any), callbackType?: string, timeout?: number}): Promise; - - - - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - * @return any - */ - ready(handler: () => any): void; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM HTMLElement to use as context - * @return HTMLElement[] - */ - (selector: string, context?: HTMLElement|ChocolateChipElementArray): ChocolateChipElementArray; - - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback A function to execute after the DOM is ready. - * @return void - */ - (callback: () => any): void; - - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param element A DOM element to wrap in an array. - * @return HTMLElement[] - */ - (element: HTMLElement): ChocolateChipElementArray; - - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param elementArray An array of DOM elements to convert into a ChocolateChip Collection. - * @return HTMLElement[] - */ - (elementArray: ChocolateChipElementArray): ChocolateChipElementArray; - - /** - * If no argument is provided, return the document as a ChocolateChipElementArray. - * @return Document[] - */ - (): Document[]; - - /** - * Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs. - * Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic. - * - * @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. - * @data any You can receive any type: string, number, array, object, etc. - * @return any - */ - subscribe(topic: string, callback: (topic: string, data: any) => any):any; - - /** - * Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately. - * - * @param topic string The name of the topic to unsubscribe from. - * @return void - */ - unsubscribe(topic: string): void; - - /** - * Publish a topic with data for the topic's subscribers to receive. - * - * @param topic string The topic you wish to publish. - * @param data The data to send with the publication. This can be of any type: string, number, array, object, etc. - * @return void - */ - publish(topic: string, data: any): void; - - /** - * Whether device is iPhone. - */ - isiPhone: boolean; - - /** - * Whether device is iPad. - */ - isiPad: boolean; - - /** - * Whether device is iPod. - */ - isiPod: boolean; - - /** - * Whether OS is iOS. - */ - isiOS: boolean; - - /** - * Whether OS is Android - */ - isAndroid: boolean; - - /** - * Whether OS is WebOS. - */ - isWebOS: boolean; - - /** - * Whether OS is Blackberry. - */ - isBlackberry: boolean; - - /** - * Whether OS supports touch events. - */ - isTouchEnabled: boolean; - - /** - * Whether there is a network connection. - */ - isOnline: boolean; - - /** - * Whether app is running in stanalone mode. - */ - isStandalone: boolean; - - /** - * Whether OS is iOS 6. - */ - isiOS6: boolean; - - /** - * Whether OS i iOS 7. - */ - isiOS7: boolean; - - /** - * Whether OS is Windows. - */ - isWin: boolean; - - /** - * Whether device is Windows Phone. - */ - isWinPhone: boolean; - - /** - * Whether browser is IE10. - */ - isIE10: boolean; - - /** - * Whether browser is IE11. - */ - isIE11: boolean; - - /** - * Whether browser is Webkit based. - */ - isWebkit: boolean; - - /** - * Whether browser is running on mobile device. - */ - isMobile: boolean; - - /** - * Whether browser is running on desktop. - */ - isDesktop: boolean; - - /** - * Whether browser is Safari. - */ - isSafari: boolean; - - /** - * Whether browser is Chrome. - */ - isChrome: boolean; - - /** - * Is native Android browser (not mobile Chrome). - */ - isNativeAndroid: boolean; - - /** - * Grabs values from a form and converts them into a JSON object. - * - * @param rootNode: string|HTMLElement A form whose values you want to convert to JSON. - * @param delimiter string A delimiter to namespace your form values. The default is "." - * You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first". - */ - form2JSON(rootNode: string | HTMLElement, delimiter: string): Object; -} - -interface ChocolateChipPlugin { - /** - * This method extends ChocolateChipElementArray, enabling iteration over collection items. - * - * @param object Object literal of properties and values. Value can be strings, number, array, objects or functions. - * @return HTMLElement[] - */ - extend: (object: any) => ChocolateChipElementArray; -} + * @param object And object to add to element arrays. + * @return The extended array of elements. + */ + extend(object: Object): HTMLElement[]; + }; + + /** + * Contains the version of ChocolateChipJS in use. + */ + version: string; + + /** + * Contains the name of the library (ChocolateChip). + */ + libraryName: string; + + /** + * An empty function. + * + * @return void. + */ + noop(): void; + + /** + * Uuid number. + */ + uuid: number; + + /** + * Create a random number to use as a uuid. + * + * @return number. + */ + uuidNum(): number; + + /** + * Creates a Uuid and returns it as a string with the prefix: "chch_". + * + * @return A string. + */ + makeUuid(): string; + + + /** + * Create a ChocolateChip collection object by creating elements from an HTML string. + * + * @param selector + * @return any + */ + make(selector: string): ChocolateChipElementArray; + + /** + * Create a ChocolateChip collection object by creating elements from an HTML string. This is an alias for $.make. + * + * @param selector + * @return any + */ + html(selector: string): ChocolateChipElementArray; + + /** + * Replace one element with another. + * + * @param new HTMLElement + * @param old HTMLElement + * @return HTMLElement[] + */ + replace(newElement: ChocolateChipElementArray, oldElement: ChocolateChipElementArray): void; + + /** + * Load a JavaScript file from a url, then execute it. + * + * @param url A string containing the URL where the script resides. + * @param callback A callback function that is executed after the script loads. + * @return void + */ + require(url: string, callback: Function): Function; + + /** + * Process JavaScript returned by Ajax request. An optional name can be used to create a custom variable name by which the data is exposed, otherwise it is exposed with the variable "data". + * + * @param url A string containing the URL where the script resides. + * @param callback A callback function that is executed after the script loads. + * @return Function + */ + processJSON(json: string, name?: string): any; + + /** + * This method takes a referenced form and serializes its element names and values, which it returns as a string. This is required if you want to send form data. + * + * @param element A string, HTML element or ChocolateChipElementArray containing a reference to a from. + * @return An encode string form element names and values. + */ + serialize(element: any): string; + + /** + * Parse the data in a Promise response as JSON. + * + * @param response The response from a Promise. + * @result + */ + json(reponse: Response): JSON; + /** + * This method will defer the execution of a function until the call stack is clear. + * + * @param callback A function to execute. + * @param duration The number of milliseconds to delay execution. + * @return any + */ + delay(callback: Function, duration?: number): any; + + /** + * The method will defer the execution of its callback until the call stack is clear. + * + * @param callback A callback to execute after a delay. + * @return Function. + */ + defer(callback: Function): Function; + + /** + * This method makes sure a method always returns an array. If no values are available to return, it returns and empty array. This is to make sure that methods that expect a chainable array will not throw and exception. + * + * @param result The result of a method to test if it can be returned in an array. + * @return An array hold the results of a method, otherwise an empty array. + */ + returnResult(result: HTMLElement[]): any[]; + + /** + * This method allows you to execute a callback on each item in an array of elements. + * + * @param array An array of elements. + * @param callback A callback to execute on each element. This has two parameters: the context, followed by the index of the current iteration. + */ + each(array: any[], callback: (ctx: any, idx?: number) => any): any[]; + + /** + * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. + * + * @param string or number A comma separated series of strings to concatenate. + * @return string + */ + concat(...string: string[]): string; + + /** + * This method takes a space-delimited string of words and returns it as an array where the individual words are indices. + * + * @param string Any string with values separated by spaces. + * @return string[] + */ + w(string: string): string[]; + + /** + * This method converts a string of hyphenated tokens into a camel cased string. + * + * @param string A string of hyphenated tokens. + * @return string + */ + camelize(string: string): string; + + /** + * This method converts a camel case string into lowercase with hyphens. + * + * @param string A camel case string. + * @return string + */ + deCamelize(string: string): string; + + /** + * This method capitalizes the first letter of a string. + * + * @param string A string. + * @param boolean A boolean value. + * @return string + */ + capitalize(string: string, boolean?: boolean): string; + + /** + * Determine whether the argument is a string. + * + * @param obj Object to test whether or not it is a string. + * @return boolean + */ + isString(obj: any): boolean; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + * @return boolean + */ + isArray(obj: any): boolean; + + /** + * Determine whether the argument is a function. + * + * @param obj Object to test whether or not it is an function. + * @return boolean + */ + isFunction(obj: any): boolean; + + /** + * Determine whether the argument is an object. + * + * @param obj Object to test whether or not it is an object. + * @return boolean + */ + isObject(obj: any): boolean; + + /** + * Determine whether the argument is an empty object. + * + * @param obj Object to test whether or not it is an empty object. + * @return boolean + */ + isEmptyObject(obj: any): boolean; + + /** + * Determine whether the argument is an empty object. + * + * @param obj Object to test whether or not it is an empty object. + * @return boolean + */ + isEmptyObject(obj: any): boolean; + + /** + * Determine whether the argument is a number. + * + * @param obj Object to test whether or not it is a number. + * @return boolean + */ + isNumber(obj: any): boolean; + + /** + * Determine whether the argument is an integer. + * + * @param obj Object to test whether or not it is an integer. + * @return boolean + */ + isInteger(obj: any): boolean; + + /** + * Determine whether the argument is a float. + * + * @param obj Object to test whether or not it is a float. + * @return boolean + */ + isFloat(obj: any): boolean; + + /** + * Whether device is iPhone. + */ + isiPhone: boolean; + + /** + * Whether device is iPad. + */ + isiPad: boolean; + + /** + * Whether device is iPod. + */ + isiPod: boolean; + + /** + * Whether OS is iOS. + */ + isiOS: boolean; + + /** + * Whether OS is Android + */ + isAndroid: boolean; + + /** + * Whether OS is WebOS. + */ + isWebOS: boolean; + + /** + * Whether OS is Blackberry. + */ + isBlackberry: boolean; + + /** + * Whether OS supports touch events. + */ + isTouchEnabled: boolean; + + /** + * Whether there is a network connection. + */ + isOnline: boolean; + + /** + * Whether app is running in stanalone mode. + */ + isStandalone: boolean; + + /** + * Whether OS is iOS 6. + */ + isiOS6: boolean; + + /** + * Whether OS i iOS 7. + */ + isiOS7: boolean; + + /** + * Whether OS is Windows. + */ + isWin: boolean; + + /** + * Whether device is Windows Phone. + */ + isWinPhone: boolean; + + /** + * Whether browser is IE10. + */ + isIE10: boolean; + + /** + * Whether browser is IE11. + */ + isIE11: boolean; + + /** + * Whether browser is Webkit based. + */ + isWebkit: boolean; + + /** + * Whether browser is running on mobile device. + */ + isMobile: boolean; + + /** + * Whether browser is running on desktop. + */ + isDesktop: boolean; + + /** + * Whether browser is Safari. + */ + isSafari: boolean; + + /** + * Whether browser is Chrome. + */ + isChrome: boolean; + + /** + * Is native Android browser (not mobile Chrome). + */ + isNativeAndroid: boolean; + + JSONPCallbacks: string[]; + /** + * Load JSON from a remote server using the JSONP technique. + * + * @param url A string + * @return Promise + */ + jsonp( + options: { + timeout?: number; + callbackName?: string; + clear?: boolean; + } + ): Promise; + + /** + * Serialize + */ + serialize(form: HTMLFormElement | ChocolateChipElementArray): string; + + /** + * Grabs values from a form and converts them into a JSON object. + * + * @param rootNode: string | HTMLElement A form whose values you want to convert to JSON. + * @param delimiter string A delimiter to namespace your form values. The default is "." + * You use the form input's name to set up the namespace structure for your JSON, e.g. name="newUser.name.first". + */ + form2JSON(rootNode: string | HTMLElement, delimiter: string): Object; + + /** + * Subscribe to a publication. You provide the topic you want to subscribe to, as well as a callback to execute when a publication occurs. + * Any data passed by the publisher is exposed to the callback as its second parameter. The callback's first parameter is the published topic. + * + * @param topic string A topic to subscribe to. This can be a single term, or any type of namespaced term with delimiters. + * @data any You can receive any type: string, number, array, object, etc. + * @return any + */ + subscribe(topic: string, callback: (topic: string, data: any) => boolean): boolean; + + /** + * Unsubscribe from a topic. Pass this the topic you wish to unsubscribe from. The subscription will be terminated immediately. + * + * @param topic string The name of the topic to unsubscribe from. + * @return void + */ + unsubscribe(topic: string): void; + + /** + * Publish a topic with data for the topic's subscribers to receive. + * + * @param topic string The topic you wish to publish. + * @param data The data to send with the publication. This can be of any type: string, number, array, object, etc. + * @return void + */ + publish(topic: string, data: any): string; + + /** + * Object used to store string templates and parsed templates. + * + * @param string A string defining the template. + * @param string A label used to access an object's properties in the template. If none is provided it defaults to "data": [[= data.name]]. + * @return void + */ + templates: Object; + + /** + * This method returns a parsed template. + * + */ + template: { -interface ChocolateChipTemplate { /** * This method parses a string and an optoinal variable name and returns a parsed template in the form of a function. You can then pass this function data to get rendered nodes. * @@ -539,855 +515,884 @@ interface ChocolateChipTemplate { * @return void. */ repeater: (element: ChocolateChipElementArray, template: string, data: any) => void; + }; + +} + + +/** + * Interface for ChocolateChipJS Element Collections. + */ + +interface ChocolateChipElementArray extends Array { + + /** + * Iterate over an Array object, executing a function for each matched element. + * + * @param Function + * @return void + */ + each(func: (ctx: any, idx: number) => any): void; + + /** + * Sorts an array and removes duplicates before returning it. + * + * @return Array + */ + unique(): ChocolateChipElementArray; + + /** + * This method returns the element at the position in the array indicated by the argument. This is a zero-based number. + * When dealing with document nodes, this allows you to cherry pick a node from its collection based on its + * position amongst its siblings. + * + * @param number Index value indicating the node you wish to access from a collection. This is zero-based. + * @return HTMLElement + */ + eq(index: number): ChocolateChipElementArray; + + /** + * Search for a given element from among the matched elements on a collection. + * This method returns the index value as an integer. + * + * @return number + */ + index(): number; + + /** + * Search for a given element from among the matched elements on a collection. + * This method returns the index value as an integer. + * + * @param selector A selector representing an element to look for in a collection of elements. + * @return number + */ + index(selector: string | HTMLElement[]): number; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + is(selector: string): ChocolateChipElementArray; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + * @ return HTMLElement[] + */ + is(element: any): ChocolateChipElementArray; + + + /** + * Check the current matched set of elements against a selector or element and return it + * if it does not match the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + isnt(selector: string): ChocolateChipElementArray; + + /** + * Check the current matched set of elements against a selector or element and return it + * if it does not match the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + * @ return HTMLElement[] + */ + isnt(element: any): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + has(selector: string): ChocolateChipElementArray; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + * @ return HTMLElement[] + */ + has(contained: HTMLElement): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + hasnt(selector: string): ChocolateChipElementArray; + /** + * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. + * + * @param contained A DOM element to match elements against. + * @ return HTMLElement[] + */ + hasnt(contained: HTMLElement): ChocolateChipElementArray; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. + * + * @param selector A string containing a selector expression to match elements against. + * @ return HTMLElement[] + */ + find(selector: string): ChocolateChipElementArray; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. + * + * @param element An element to match elements against. + * @ return HTMLElement[] + */ + find(element: HTMLElement): ChocolateChipElementArray; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements. + * + * @ return HTMLElement[] + */ + prev(): ChocolateChipElementArray; + + /** + * Get the immediately following sibling of each element in the set of matched elements. + * + * @ return HTMLElement[] + */ + next(): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): ChocolateChipElementArray; + + /** + * Reduce the set of matched elements to the last in the set. + * + * @return HTMLElement[] + */ + last(): ChocolateChipElementArray; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + children(selector?: string): ChocolateChipElementArray; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * If multiple elements have the same parent, only one instance of the parent is returned. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + parent(selector?: string): ChocolateChipElementArray; + + /** + * For each element in the set, get the first element that matches the selector by testing the element + * itself and traversing up through its ancestors in the DOM tree, or, if a number is provided, + * retrieving that ancestor based on its distance from the element. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + ancestor(selector: string | number): ChocolateChipElementArray; + + /** + * For each element in the set, get the first element that matches the selector by testing the element + * itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + closest(selector: string | number): ChocolateChipElementArray; + + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] + */ + siblings(selector?: string): ChocolateChipElementArray; + + /** + * Get the HTML contents of the first element in the set of matched elements. + * + * @return HTMLElement[] + */ + html(): ChocolateChipElementArray; + + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + * @return HTMLElement[] + */ + html(htmlString: string): ChocolateChipElementArray; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + * @return string + */ + css(propertyName: string): string; + + /** + * Set one or more CSS properties for the set of matched elements using a quoted string. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + * @return HTMLElement[] + */ + css(propertyName: string, value: string): ChocolateChipElementArray; + + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + * @return HTMLElement[] + */ + css(properties: Object): ChocolateChipElementArray; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + * @return string + */ + attr(attributeName: string): string; + + /** + * Set an attribute for the set of matched elements. + * + * @param attributeName A string indicating the attribute to set. + * @param value A string indicating the value to set the attribute to. + * @return HTMLElement[] + */ + attr(attributeName: string, value: string): ChocolateChipElementArray; + + /** + * Remove an attribute from a node. + * + * @param attributeName A string indicating the attribute to remove. + * @return HTMLElement[] + */ + removeAttr(attributeName: string): ChocolateChipElementArray; + + /** + * Return any of the matched elements that have the given attribute. + * + * @param className The class name to search for. + * @return HTMLElement[] + */ + hasAttr(attributeName: string): ChocolateChipElementArray; + + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + * @return string + */ + prop(attributeName: string): string; + + /** + * Set an property for the set of matched elements. + * + * @param propertyName A string indicating the property to set. + * @param value A string indicating the value to set the property to. + * @return HTMLElement[] + */ + prop(propertyName: string, value: string): ChocolateChipElementArray; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + * @return HTMLElement[] + */ + addClass(className: string): ChocolateChipElementArray; + + /** + * Remove a single class or multiple classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + * @return HTMLElement[] + */ + removeClass(className?: string): ChocolateChipElementArray; + + /** + * Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @return HTMLElement[] + */ + toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray; + + /** + * Return any of the matched elements that have the given class. + * + * @param className The class name to search for. + * @return HTMLElement[] + */ + hasClass(className: string): ChocolateChipElementArray; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + * @return HTMLElement[] + */ + data(key: string, value: any): ChocolateChipElementArray; + + /** + * Return the value at the named data store for the first element in the element collection, as set by + * data(name). + * + * @param key Name of the data stored. + * @return any + */ + data(key: string): any; + + /** + * Remove the value at the named data store for the first element in the element collection, as set by data(name, value). + * + * @param key Name of the data stored. + * @return any + */ + removeData(key: string): any; + + /** + * Store string data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it must be a string. You can convert JSON into a string to use with this. + * @return HTMLElement[] + */ + dataset(key: string, value: any): ChocolateChipElementArray; + + /** + * Retrieve a dataset key's value for the first element in the element collection. + * + * @param key A string naming the piece of data to set. + * @return HTMLElement[] + */ + dataset(key: string): ChocolateChipElementArray; + + /** + * Return the value at the named data store for the first element in the element collection, as set by data(name, value). + * + * @param key Name of the data stored. + * @return any + */ + data(key: string): any; + + /** + * Store arbitrary data associated with the matched element. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + * @return HTMLElement[] + */ + data(key: string, value?: any): ChocolateChipElementArray; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text or an array of strings corresponding to the value of each matched element + * to set as selected/checked. + * @return any + */ + val(value: string): ChocolateChipElementArray; + + /** + * Set the property of an element to enabled by removing the "disabled" attribute. + * + * @return HTMLElement[] + */ + enable(): ChocolateChipElementArray; + + /** + * Set the property of an element to "disabled". + * + * @return HTMLElement[] + */ + disable(): ChocolateChipElementArray; + + /** + * Display the matched elements. + * + * @param speed A string or number determining how long the animation will run. + * @param callback A function to call once the animation is complete. + * @return HTMLElement[] + */ + show(duration?: number | string, callback?: Function): ChocolateChipElementArray; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param callback A function to call once the animation is complete. + * @return HTMLElement[] + */ + hide(duration?: number | string, callback?: Function): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements. + * @return HTMLElement[] + */ + before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements. + * @return HTMLElement[] + */ + after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set + * of matched elements. + * @return HTMLElement[] + */ + append(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; + + /** + * Insert content, specified by the parameter, at the beginning of each element in the set of matched elements. + * + * @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements. + * @return HTMLElement[] + */ + prepend(content: ChocolateChipElementArray | HTMLElement | Text | string): ChocolateChipElementArray; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter. + * @return HTMLElement[] + */ + prependTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter. + * If no position value is provided it will simply append the content to the target. + * @return HTMLElement[] + */ + appendTo(target: any[] | HTMLElement | string): ChocolateChipElementArray; + + /** + * Insert element(s) into the target element. + * + * @return HTMLElement[] + */ + insert(content: string, position?: number | string): ChocolateChipElementArray; + + /** + * Create a copy of the set of matched elements. + * + * @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children. + * @return HTMLElement[] + */ + clone(value?: boolean): ChocolateChipElementArray; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements. + * @return HTMLElement[] + */ + wrap(wrappingElement: string): ChocolateChipElementArray; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + * + * @return HTMLElement[] + */ + unwrap(): ChocolateChipElementArray; + + /** + * Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + * @return HTMLElement[] + */ + remove(selector?: string): ChocolateChipElementArray; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + * + * @return HTMLElement[] + */ + empty(): ChocolateChipElementArray; + + /** + * Get an object of the current coordinates of the first element in the set of matched elements, relative to the document. + * These are: top, left, bottom and right. The values are numbers representing pixel values. + * @return Object + */ + offset(): { + top: number; + bottom: number; + left: number; + right: number; + }; + + /** + * Get the current computed width for the first element in the set of matched elements, + * including padding but excluding borders. + * + * @return number + */ + width(): number; + + /** + * Get the current computed height for the first element in the set of matched elements, + * including padding but excluding borders. + * + * @return number + */ + height(): number; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + * + * @return string + */ + text(): string; + + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number is supplied, it will be converted to a String representation. To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove(). + * @return HTMLElement + */ + text(text: string | number): HTMLElement; + + /** + * A method to animate DOM nodes using CSS. This uses CSS transitions. + * + * @param options And object of key value pairs define the CSS properties and values to animate. + * @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc. + * @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out". + * @return void + */ + animate(options: Object, duration?: string, easing?: string): void; + + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Remove a handler for an event from the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + unbind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a delegated event to listen for the provided event on the descendant elements. + * + * @param selector A string defining the descendant elements to listen on for the designated event. + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. The keyword "this" will refer + * to the element receiving the event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a delegated event to listen for the provided event on the descendant elements. + * + * @param selector A string defining the descendant elements are listening for the event. + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + undelegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + + /** + * Add a handler to an event for elements. If a selector is provided as the second argument, this implements a delegated event. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param selector A string defining the descendant elements are listening for the event. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + on(eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; + + /** + * Remove a handler for an event from the elements. If the second argument is a selector, it tries to undelegate the event. + * If no arugments are provided, it removes all events from the element(s). + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param selector A string defining the descendant elements are listening for the event. + * @param handler A function handler assigned to this event. + * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. + * @return ChocolateChipStatic + */ + off(eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; + + /** + * + */ + trigger(eventType: string): void; } /** * Represents the completion of an asynchronous operation */ interface Promise { - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @return Promise A Promise for the completion of which ever callback is executed. - * @return Promise A new Promise - */ - then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @return Promise A Promise for the completion of which ever callback is executed. + * @return Promise A new Promise + */ + then(onfulfilled?: (value: T) => TResult | Promise, onrejected?: (reason: any) => TResult | Promise): Promise; - /** - * Attaches a callback for only the rejection of the Promise. - * - * @param onrejected The callback to execute when the Promise is rejected. - * @return Promise A Promise for the completion of the callback. - * @return Promise A new Promise - */ - catch(onrejected?: (reason: any) => T | Promise): Promise; + /** + * Attaches a callback for only the rejection of the Promise. + * + * @param onrejected The callback to execute when the Promise is rejected. + * @return Promise A Promise for the completion of the callback. + * @return Promise A new Promise + */ + catch(onrejected?: (reason: any) => T | Promise): Promise; } interface PromiseConstructor { - /** - * A reference to the prototype. - */ - prototype: Promise; + /** + * A reference to the prototype. + */ + prototype: Promise; - /** - * Creates a new Promise. - * - * @param init A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error. - * @return Promise A new Proimise - */ - new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + /** + * Creates a new Promise. + * + * @param init A callback used to initialize the promise. This callback is passed two arguments: a resolve callback used resolve the promise with a value or the result of another promise, and a reject callback used to reject the promise with a provided reason or error. + * @return Promise A new Proimise + */ + new (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; - (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; + (init: (resolve: (value?: T | Promise) => void, reject: (reason?: any) => void) => void): Promise; - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. - * - * @param values An array of Promises. - * @return Promise A new Promise. - */ - all(values: (T | Promise)[]): Promise; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. + * + * @param values An array of Promises. + * @return Promise A new Promise. + */ + all(values: (T | Promise)[]): Promise; - /** - * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. - * - * @param values An array of values. - * @returns A new Promise. - */ - all(values: Promise[]): Promise; + /** + * Creates a Promise that is resolved with an array of results when all of the provided Promises resolve, or rejected when any Promise is rejected. + * + * @param values An array of values. + * @returns A new Promise. + */ + all(values: Promise[]): Promise; - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected. - * - * @param values An array of Promises. - * @return Promise A new Promise. - */ - race(values: (T | Promise)[]): Promise; + /** + * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected. + * + * @param values An array of Promises. + * @return Promise A new Promise. + */ + race(values: (T | Promise)[]): Promise; - /** - * Creates a new rejected promise for the provided reason. - * - * @param reason The reason the promise was rejected. - * @return Promise A new rejected Promise. - */ - reject(reason: any): Promise; + /** + * Creates a new rejected promise for the provided reason. + * + * @param reason The reason the promise was rejected. + * @return Promise A new rejected Promise. + */ + reject(reason: any): Promise; - /** - * Creates a new rejected promise for the provided reason. - * - * @param reason The reason the promise was rejected. - * @return void A Promise is rejected. - */ - reject(reason: any): Promise; + /** + * Creates a new rejected promise for the provided reason. + * + * @param reason The reason the promise was rejected. + * @return void A Promise is rejected. + */ + reject(reason: any): Promise; - /** - * Creates a new resolved promise for the provided value. - * - * @param value A promise. - * @return Promise A promise whose internal state matches the provided promise. - */ - resolve(value: T | Promise): Promise; + /** + * Creates a new resolved promise for the provided value. + * + * @param value A promise. + * @return Promise A promise whose internal state matches the provided promise. + */ + resolve(value: T | Promise): Promise; - /** - * Creates a new resolved promise. - * - * @return Promise A resolved promise. - */ - resolve(): Promise; + /** + * Creates a new resolved promise. + * + * @return Promise A resolved promise. + */ + resolve(): Promise; } declare var Promise: PromiseConstructor; +declare type ByteString = string; +declare type USVString = string; +declare type DOMString = string; +declare type OpenEndedDictionary = Object; /** - * Interface for the Ajax setting that will configure the Ajax request. + * Interface for fetch API. + * + * @param input A string representing a valid url. + * @param init An object literal of key value pairs to set method, headers, body, credentials or cache. + * @return Promise. */ -interface ChocolateChipAjaxSettings { - /** - * A string containing the URL to which the request is sent. - */ - url?: string; - /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - user?: string; - - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - - /** - * The type of data that you're expecting back from the server. If none is specified, ChocolateChipJS will - * infer it based on the MIME type of the response. - */ - dataType?: string; - - /** - * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, - * such as PUT and DELETE, can also be used here, but they are not supported by all browsers. - */ - type?: string; - - /** - * 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. - */ +interface fetch { + (input: string, + init?: { method?: string; + headers?: {}; + body?: any; + mode?: { + cors: string; + "no-cors": string; + "same-origin": string; + }; + credentials?: { + omit: string; + "same-origin": string; + include: string; + }; + cache?: { + default: string; + "no-store": string; + reload: string; + "no-cache": string; + "force-cache": string; + "only-if-cached": string; + } + }): Promise; +} - /** - * 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. - * @return void - */ - beforeSend?: (xhr: XMLHttpRequest, settings: ChocolateChipAjaxSettings) => void; +interface XMLHttpRequest { + responseURL: string; +} - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, - * formatted according to the dataType parameter; a string describing the status; and the XMLHttpRequest object. This is an Ajax Event. - * @return void - */ - success?: (data: any) => void; +interface Headers { + (headers?: any): void; + append(name: string, value: string): void; + delete(name: string): any; + get(name: string): any; + getAll(name: string): any; + has(name: string): any; + set(name: string, value: string): any; + forEach(callback: Function, thisArg: any): any; +} - /** - * A function to be called if the request fails. The function receives three arguments: The XMLHttpRequest object, a string describing - * the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) - * are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, - * such as "Not Found" or "Internal Server Error." This is an Ajax Event. - */ - error?: (error: Error) => void; +interface decode { + (body: any): FormData; +} - /** - * This object will be made the context of all Ajax-related callbacks. By default, the context is null. - */ - context?: any; +interface Request { + (input: { + url: string; + request: Request; + }, init: Object): Request; + clone(): Request; + arrayBuffer(): ArrayBuffer; + blob(): Blob; + formData(): FormData; + json(): JSON; + text(): string; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. - * Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the - * browser, disabling any actions while the request is active. - */ - async?: boolean; + method: string; + url: string; + heaers: Headers; + context: any; + referrer: any; + mode: string; + credentials: any; + cache: string; + bodyUsed: boolean; +} - /** - * Set a timeout (in milliseconds) for the request. The timeout period starts at the point the $.ajax call is made; if several other requests are in progress - * and the browser has no connections available, it is possible for a request to time out before it can be sent. - */ +interface URLSearchParams { + ():URLSearchParams; +} + +interface Response { + (body?: { + blob: Blob; + bormData: FormData; + urlParams: URLSearchParams; + url: string; + }, + init?: { + status?: string | number; + statusText?: string; + headers: Headers; + }): Response; + clone(): Response; + redirect(): Response; + arrayBuffer(): ArrayBuffer; + blob(): Blob; + formData(): FormData; + json(): JSON; + text(): string; + + type: string; + url: string; + useFinalURL: boolean; + ok: boolean; + statusText: string; + headers: Headers; + bodyUsed: boolean; +} +interface ChocolateChipStatic { + jsonp(url: string, options?: { timeout?: number; - - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, - * but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. - */ - headers?: Object; - - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. Object must be Key/Value pairs. - */ - data?: any; + callbackName?: string; + clear?: boolean; + }): any } -interface ChocolateChipXHR { - ajax: (settings: ChocolateChipAjaxSettings) => PromiseConstructor; -} -interface ChocolateChipJSONP { - url: string; - success?: (data: any) => Promise; - callbackType?: string; - timeout?: number; -} - -interface ChocolateChipElementArray extends Array { - /** - * Iterate over an Array object, executing a function for each matched element. - * - * @param Function - * @return void - */ - each(func: (ctx: any, idx: number) => any): void; - - /** - * Sorts an array and removes duplicates before returning it. - * - * @return Array - */ - unique(): T[]; - - /** - * This method returns the element at the position in the array indicated by the argument. This is a zero-based number. - * When dealing with document nodes, this allows you to cherry pick a node from its collection based on its - * position amongst its siblings. - * - * @param number Index value indicating the node you wish to access from a collection. This is zero-based. - * @return HTMLElement - */ - eq(index: number): ChocolateChipElementArray; - - /** - * Search for a given element from among the matched elements on a collection. - * This method returns the index value as an integer. - * - * @return number - */ - index(): number; - - /** - * Search for a given element from among the matched elements on a collection. - * This method returns the index value as an integer. - * - * @param selector A selector representing an element to look for in a collection of elements. - * @return number - */ - index(selector: string | HTMLElement[]): number; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - is(selector: string): ChocolateChipElementArray; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it matches the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] - */ - is(element: any): ChocolateChipElementArray; - - - /** - * Check the current matched set of elements against a selector or element and return it - * if it does not match the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - isnt(selector: string): ChocolateChipElementArray; - - /** - * Check the current matched set of elements against a selector or element and return it - * if it does not match the given arguments. - * - * @param elements One or more elements to match the current set of elements against. - * @ return HTMLElement[] - */ - isnt(element: any): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - has(selector: string): ChocolateChipElementArray; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param contained A DOM element to match elements against. - * @ return HTMLElement[] - */ - has(contained: HTMLElement): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - hasnt(selector: string): ChocolateChipElementArray; - /** - * Reduce the set of matched elements to those that have a descendant that does not match the selector or DOM element. - * - * @param contained A DOM element to match elements against. - * @ return HTMLElement[] - */ - hasnt(contained: HTMLElement): ChocolateChipElementArray; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. - * - * @param selector A string containing a selector expression to match elements against. - * @ return HTMLElement[] - */ - find(selector: string): ChocolateChipElementArray; - - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector or element. - * - * @param element An element to match elements against. - * @ return HTMLElement[] - */ - find(element: HTMLElement): ChocolateChipElementArray; - - /** - * Get the immediately preceding sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] - */ - prev(): ChocolateChipElementArray; - - /** - * Get the immediately following sibling of each element in the set of matched elements. - * - * @ return HTMLElement[] - */ - next(): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to the first in the set. - */ - first(): ChocolateChipElementArray; - - /** - * Reduce the set of matched elements to the last in the set. - * - * @return HTMLElement[] - */ - last(): ChocolateChipElementArray; - - /** - * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - children(selector?: string): ChocolateChipElementArray; - - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * If multiple elements have the same parent, only one instance of the parent is returned. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - parent(selector?: string): ChocolateChipElementArray; - - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree, or, if a number is provided, - * retrieving that ancestor based on its distance from the element. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - ancestor(selector: string | number): ChocolateChipElementArray; - - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - closest(selector: string | number): ChocolateChipElementArray; - - - /** - * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @return HTMLElement[] - */ - siblings(selector?: string): ChocolateChipElementArray; - - /** - * Get the HTML contents of the first element in the set of matched elements. - * - * @return HTMLElement[] - */ - html(): ChocolateChipElementArray; - - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - * @return HTMLElement[] - */ - html(htmlString: string): ChocolateChipElementArray; - - - /** - * Get the value of style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - * @return string - */ - css(propertyName: string): string; - - /** - * Set one or more CSS properties for the set of matched elements using a quoted string. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - * @return HTMLElement[] - */ - css(propertyName: string, value: string): ChocolateChipElementArray; - - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - * @return HTMLElement[] - */ - css(properties: Object): ChocolateChipElementArray; - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - * @return string - */ - attr(attributeName: string): string; - - /** - * Set an attribute for the set of matched elements. - * - * @param attributeName A string indicating the attribute to set. - * @param value A string indicating the value to set the attribute to. - * @return HTMLElement[] - */ - attr(attributeName: string, value: string): ChocolateChipElementArray; - - /** - * Remove an attribute from a node. - * - * @param attributeName A string indicating the attribute to remove. - * @return HTMLElement[] - */ - removeAttr(attributeName: string): ChocolateChipElementArray; - - /** - * Return any of the matched elements that have the given attribute. - * - * @param className The class name to search for. - * @return HTMLElement[] - */ - hasAttr(attributeName: string): ChocolateChipElementArray; - - - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - * @return string - */ - prop(attributeName: string): string; - - /** - * Set an property for the set of matched elements. - * - * @param propertyName A string indicating the property to set. - * @param value A string indicating the value to set the property to. - * @return HTMLElement[] - */ - prop(propertyName: string, value: string): ChocolateChipElementArray; - - /** - * Adds the specified class(es) to each of the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - * @return HTMLElement[] - */ - addClass(className: string): ChocolateChipElementArray; - - /** - * Remove a single class or multiple classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - * @return HTMLElement[] - */ - removeClass(className?: string): ChocolateChipElementArray; - - /** - * Add or remove a classe from each element in the set of matched elements, depending on whether the class is present or not. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * @return HTMLElement[] - */ - toggleClass(className: string, swtch?: boolean): ChocolateChipElementArray; - - /** - * Return any of the matched elements that have the given class. - * - * @param className The class name to search for. - * @return HTMLElement[] - */ - hasClass(className: string): ChocolateChipElementArray; - - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] - */ - data(key: string, value: any): ChocolateChipElementArray; - - /** - * Return the value at the named data store for the first element in the element collection, as set by - * data(name). - * - * @param key Name of the data stored. - * @return any - */ - data(key: string): any; - - /** - * Remove the value at the named data store for the first element in the element collection, as set by data(name, value). - * - * @param key Name of the data stored. - * @return any - */ - removeData(key: string): any; - - /** - * Store string data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it must be a string. You can convert JSON into a string to use with this. - * @return HTMLElement[] - */ - dataset(key: string, value: any): ChocolateChipElementArray; - - /** - * Retrieve a dataset key's value for the first element in the element collection. - * - * @param key A string naming the piece of data to set. - * @return HTMLElement[] - */ - dataset(key: string): ChocolateChipElementArray; - - /** - * Return the value at the named data store for the first element in the element collection, as set by data(name, value). - * - * @param key Name of the data stored. - * @return any - */ - data(key: string): any; - - /** - * Store arbitrary data associated with the matched element. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; it can be any Javascript type including Array or Object. - * @return HTMLElement[] - */ - data(key: string, value?: any): ChocolateChipElementArray; - - /** - * Get the current value of the first element in the set of matched elements. - */ - val(): any; - - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text or an array of strings corresponding to the value of each matched element - * to set as selected/checked. - * @return any - */ - val(value: string): ChocolateChipElementArray; - - /** - * Set the property of an element to enabled by removing the "disabled" attribute. - * - * @return HTMLElement[] - */ - enable(): ChocolateChipElementArray; - - /** - * Set the property of an element to "disabled". - * - * @return HTMLElement[] - */ - disable(): ChocolateChipElementArray; - - /** - * Display the matched elements. - * - * @param speed A string or number determining how long the animation will run. - * @param callback A function to call once the animation is complete. - * @return HTMLElement[] - */ - show(duration?: number | string, callback?: Function): ChocolateChipElementArray; - - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param callback A function to call once the animation is complete. - * @return HTMLElement[] - */ - hide(duration?: number | string, callback?: Function): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * @param content HTML string, DOM element, array of elements to insert before each element in the set of matched elements. - * @return HTMLElement[] - */ - before(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * @param content HTML string, DOM element, array of elements to insert after each element in the set of matched elements. - * @return HTMLElement[] - */ - after(content: ChocolateChipElementArray | HTMLElement | string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * @param content DOM element, array of elements, or HTML string to insert at the end of each element in the set - * of matched elements. - * @return HTMLElement[] - */ - append(content: ChocolateChipElementArray|HTMLElement|Text|string): ChocolateChipElementArray; - - /** - * Insert content, specified by the parameter, at the beginning of each element in the set of matched elements. - * - * @param content DOM element, array of elements, or HTML string to insert at the beginning of each element in the set of matched elements. - * @return HTMLElement[] - */ - prepend(content: ChocolateChipElementArray|HTMLElement|Text|string): ChocolateChipElementArray; - - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the beginning of the element specified by this parameter. - * @return HTMLElement[] - */ - prependTo(target: any[]|HTMLElement|string): ChocolateChipElementArray; - - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, or HTML string. The matched set of elements will be inserted at the end of the element specified by this parameter. - * If no position value is provided it will simply append the content to the target. - * @return HTMLElement[] - */ - appendTo(target: any[]|HTMLElement|string): ChocolateChipElementArray; - - /** - * Insert element(s) into the target element. - * - * @return HTMLElement[] - */ - insert(content: string, position?: number | string): ChocolateChipElementArray; - - /** - * Create a copy of the set of matched elements. - * - * @param value A Boolean indicating whether to copy the element(s) with their children. A true value copies the children. - * @return HTMLElement[] - */ - clone(value?: boolean): ChocolateChipElementArray; - - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector or HTML string specifying the structure to wrap around the matched elements. - * @return HTMLElement[] - */ - wrap(wrappingElement: string): ChocolateChipElementArray; - - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - * - * @return HTMLElement[] - */ - unwrap(): ChocolateChipElementArray; - - /** - * Remove the set of matched elements from the DOM. If there are any attached events, this will remove them to prevent memory leaks. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - * @return HTMLElement[] - */ - remove(selector?: string): ChocolateChipElementArray; - - /** - * Remove all child nodes of the set of matched elements from the DOM. - * - * @return HTMLElement[] - */ - empty(): ChocolateChipElementArray; - - /** - * Get an object of the current coordinates of the first element in the set of matched elements, relative to the document. - * These are: top, left, bottom and right. The values are numbers representing pixel values. - * @return Object - */ - offset(): ChocolateChipOffsetObject; - - /** - * Get the current computed width for the first element in the set of matched elements, - * including padding but excluding borders. - * - * @return number - */ - width(): number; - - /** - * Get the current computed height for the first element in the set of matched elements, - * including padding but excluding borders. - * - * @return number - */ - height(): number; - - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - * - * @return string - */ - text(): string; - - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number is supplied, it will be converted to a String representation. To delete text, use ChocolateChipElementArray.empty() or ChocolateChipElementArray.remove(). - * @return HTMLElement - */ - text(text: string | number): HTMLElement; - - /** - * Attach a handler to an event for the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - bind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Remove a handler for an event from the elements. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - unbind(eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a delegated event to listen for the provided event on the descendant elements. - * - * @param selector A string defining the descendant elements to listen on for the designated event. - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute each time the event is triggered. The keyword "this" will refer - * to the element receiving the event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - delegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a delegated event to listen for the provided event on the descendant elements. - * - * @param selector A string defining the descendant elements are listening for the event. - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - undelegate(selector: any, eventType: string, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; - - /** - * Add a handler to an event for elements. If a selector is provided as the second argument, this implements a delegated event. - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param selector A string defining the descendant elements are listening for the event. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - on( eventType: string, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; - - /** - * Remove a handler for an event from the elements. If the second argument is a selector, it tries to undelegate the event. - * If no arugments are provided, it removes all events from the element(s). - * - * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. - * @param selector A string defining the descendant elements are listening for the event. - * @param handler A function handler assigned to this event. - * @param useCapture Setting the third argument to true will trigger event bubbling. The default is false. - * @return ChocolateChipStatic - */ - off( eventType?: string, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; - - /** - * - */ - trigger(eventType: string): void; - - /** - * A method to animate DOM nodes using CSS. This uses CSS transitions. - * - * @param options And object of key value pairs define the CSS properties and values to animate. - * @param duration A string representing the time. Should have a time identifier: "200s", "200ms", etc. - * @param easing A string indicating the easing for the animation, such as "ease-out", "ease-in", "ease-in-out". - * @return void - */ - animate(options: Object, duration?: string, easing?: string ): void; -} - -/** - * Interface for offset object. - */ -interface ChocolateChipOffsetObject { - top: number; - left: number; - bottom: number; - right: number; -} +declare var $: ChocolateChipStatic; +declare var fetch: fetch; From f8e3b34ad9f40efd0ef8496158633569434106c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Musa=20Karaka=C5=9F?= Date: Thu, 6 Aug 2015 11:22:41 +0300 Subject: [PATCH 096/309] lodash #5244 join/pop/shift do not return wrappers _([1, 2]).join() // "1,2" _([1, 2]).pop() // 2 _([1, 2]).shift() // 1 --- lodash/lodash-tests.ts | 6 +++--- lodash/lodash.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 14efc9c008..aee658f4de 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -114,11 +114,11 @@ result = <_.LoDashObjectWrapper<_.Dictionary>>_(<{ [index: string]: stri //Wrapped array shortcut methods result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).concat(5, 6); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).join(','); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).pop(); +result = _([1, 2, 3, 4]).join(','); +result = _([1, 2, 3, 4]).pop(); _([1, 2, 3, 4]).push(5, 6, 7); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).reverse(); -result = <_.LoDashWrapper>_([1, 2, 3, 4]).shift(); +result = _([1, 2, 3, 4]).shift(); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(1, 2); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).slice(2); result = <_.LoDashArrayWrapper>_([1, 2, 3, 4]).sort((a, b) => 1); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ea93f2e70c..c5602884d4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -219,11 +219,11 @@ declare module _ { interface LoDashArrayWrapper extends LoDashWrapperBase> { concat(...items: T[]): LoDashArrayWrapper; - join(seperator?: string): LoDashWrapper; - pop(): LoDashWrapper; + join(seperator?: string): string; + pop(): T; push(...items: T[]): void; reverse(): LoDashArrayWrapper; - shift(): LoDashWrapper; + shift(): T; slice(start: number, end?: number): LoDashArrayWrapper; sort(compareFn?: (a: T, b: T) => number): LoDashArrayWrapper; splice(start: number): LoDashArrayWrapper; From 2a878aca464c06080dabe3b465d5253a28842067 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Osman=20Nuri=20Okumu=C5=9F?= Date: Thu, 6 Aug 2015 12:28:42 +0300 Subject: [PATCH 097/309] Create metismenu.d.ts On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed: new file: metismenu/metismenu-tests.ts new file: metismenu/metismenu.d.ts --- metismenu/metismenu-tests.ts | 13 +++++++++++++ metismenu/metismenu.d.ts | 4 ++++ 2 files changed, 17 insertions(+) create mode 100644 metismenu/metismenu-tests.ts create mode 100644 metismenu/metismenu.d.ts diff --git a/metismenu/metismenu-tests.ts b/metismenu/metismenu-tests.ts new file mode 100644 index 0000000000..824beecbb1 --- /dev/null +++ b/metismenu/metismenu-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +$('#menu').metisMenu(); +$('.metismenu').metisMenu({toggle: false}); +$('.test').metisMenu({ + toggle: false, + doubleTapToGo: true, + activeClass: 'active', + collapseClass: 'collapse', + collapseInClass: 'in', + collapsingClass: 'collapsing' +}); diff --git a/metismenu/metismenu.d.ts b/metismenu/metismenu.d.ts new file mode 100644 index 0000000000..be27ac9bcb --- /dev/null +++ b/metismenu/metismenu.d.ts @@ -0,0 +1,4 @@ +// Type definitions for metisMenu 2.0.3 // Project: http://github.com/onokumus/metisMenu/ // Definitions by: Osman Nuri Okumuş // Definitions: https://github.com/borisyankov/DefinitelyTyped + /// +interface MetisMenuOptions { toggle?: boolean; doubleTapToGo?: boolean; activeClass?: string; collapseClass?: string; collapseInClass?: string; collapsingClass?: string; } +interface JQuery { metisMenu(options?: MetisMenuOptions): JQuery; } \ No newline at end of file From 4e59a0f2b53e901083fe10ec1341b4ef60e57185 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Osman=20Nuri=20Okumu=C5=9F?= Date: Thu, 6 Aug 2015 13:36:04 +0300 Subject: [PATCH 098/309] update metismenu/metismenu.d.ts file --- metismenu/metismenu.d.ts | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/metismenu/metismenu.d.ts b/metismenu/metismenu.d.ts index be27ac9bcb..a4dbdc0fd6 100644 --- a/metismenu/metismenu.d.ts +++ b/metismenu/metismenu.d.ts @@ -1,4 +1,19 @@ -// Type definitions for metisMenu 2.0.3 // Project: http://github.com/onokumus/metisMenu/ // Definitions by: Osman Nuri Okumuş // Definitions: https://github.com/borisyankov/DefinitelyTyped - /// -interface MetisMenuOptions { toggle?: boolean; doubleTapToGo?: boolean; activeClass?: string; collapseClass?: string; collapseInClass?: string; collapsingClass?: string; } -interface JQuery { metisMenu(options?: MetisMenuOptions): JQuery; } \ No newline at end of file +// Type definitions for metisMenu 2.0.3 +// Project: http://github.com/onokumus/metisMenu +// Definitions by: onokums +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface MetisMenuOptions { + toggle?: boolean; + doubleTapToGo?: boolean; + activeClass?: string; + collapseClass?: string; + collapseInClass?: string; + collapsingClass?: string; +} + +interface JQuery { + metisMenu(options?: MetisMenuOptions): JQuery; +} From a4a2aaf62a8b148ec3f73d3b6978dd2802a820c8 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:18:30 +0200 Subject: [PATCH 099/309] changed definition of Vex.Flow.Renderer - changed type of enums to const --- 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 5786f1dbe8..7c795c4d0c 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -721,8 +721,8 @@ declare module Vex { } export module Renderer { - enum Backends {CANVAS, RAPHAEL, SVG, VML} - enum LineEndType {NONE, UP, DOWN} + const enum Backends {CANVAS, RAPHAEL, SVG, VML} + const enum LineEndType {NONE, UP, DOWN} } class Renderer { From b37a49c0049761f9ee242215119f7a998a8b459a Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:20:20 +0200 Subject: [PATCH 100/309] changed definition of Vex.Flow.Repetition - changed type enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 7c795c4d0c..5c5a597a03 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -739,7 +739,7 @@ declare module Vex { } 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} + const 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 { From 531a057c380bbcbd6c21e1817594097333b6e3df Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:28:44 +0200 Subject: [PATCH 101/309] changed definition of Vex.Flow.Stave - removed static THICKNESS as it is set by Vex.Flow.STAVE_LINE_THICKNESS --- vexflow/vexflow.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 5c5a597a03..e25ff70ea0 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -755,7 +755,6 @@ declare module Vex { 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; From dbb9d1cbde8c2461ec6e679a991ba9ed16279f8b Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:32:38 +0200 Subject: [PATCH 102/309] fixed definition of Vex.Flow.StaveConnector - changed type enum to const - fixed type of setFont() --- 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 e25ff70ea0..8176980860 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -808,7 +808,7 @@ declare module Vex { } export module StaveConnector { - enum type {SINGLE_RIGHT, SINGLE_LEFT, SINGLE, DOUBLE, BRACE, BRACKET, BOLD_DOUBLE_LEFT, BOLD_DOUBLE_RIGHT, THIN_DOUBLE} + const enum type {SINGLE_RIGHT, SINGLE_LEFT, SINGLE, DOUBLE, BRACE, BRACKET, BOLD_DOUBLE_LEFT, BOLD_DOUBLE_RIGHT, THIN_DOUBLE} } class StaveConnector { @@ -816,7 +816,7 @@ declare module Vex { 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; + setFont(font : {family? : string, size? : number, weight? : string}) : void; //inconsistent type: void -> StaveConnector setXShift(x_shift : number) : StaveConnector; draw() : void; drawBoldDoubleLine(ctx : Object, type : StaveConnector.type, topX : number, topY : number, botY : number) : void; From b067174872ea5188affd2a2bbf7c478276dd5e45 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:39:50 +0200 Subject: [PATCH 103/309] fixed definition of Vex.Flow.StaveHairpin - changed type enum to const - fixed arguments of FormatByTicksAndDraw() - added missing declaration of renderHairpin() --- vexflow/vexflow.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 8176980860..c9269a635a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -823,16 +823,17 @@ declare module Vex { } export module StaveHairpin { - enum type {CRESC, DECRESC} + const 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; + static FormatByTicksAndDraw(ctx : IRenderContext, formatter : Formatter, notes : {first_note : Note, last_note : Note}, type : StaveHairpin.type, position : Modifier.Position, options? : {height : number, y_shift : number, left_shift_ticks : number, right_shift_ticks : 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; + renderHairpin(params : {first_x : number, last_x : number, first_y : number, last_y : number, staff_height : number}) : void; draw() : boolean; } From 0936292468ff3aef9b52e63bce45ac5941e6b6c8 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:45:22 +0200 Subject: [PATCH 104/309] changed definition of Vex.Flow.StaveLine - changed enums to const --- 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 c9269a635a..3d0b5c67ad 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -838,8 +838,8 @@ declare module Vex { } export module StaveLine { - enum TextVerticalPosition {TOP, BOTTOM} - enum TextJustification {LEFT, CENTER, RIGHT} + const enum TextVerticalPosition {TOP, BOTTOM} + const enum TextJustification {LEFT, CENTER, RIGHT} } class StaveLine { From 6add88934ffee7a1c2b336434fec5d0c986593a4 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:51:39 +0200 Subject: [PATCH 105/309] fixed definition of Vex.Flow.StaveTempo - fixed arguments of setTempo() --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 3d0b5c67ad..8d2e7193fe 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -945,7 +945,7 @@ declare module Vex { 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; + 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; From 41a8267383f2f381f5926e088ac52b3778d74fab Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 16:56:26 +0200 Subject: [PATCH 106/309] fixed definition of Vex.Flow.StaveTie --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 8d2e7193fe..92fc436549 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -966,7 +966,7 @@ declare module Vex { } class StaveTie { - constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, text : string); + 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; From 8c097669b0c71b7abb81df264a895e808305cd66 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:03:31 +0200 Subject: [PATCH 107/309] changed definition of Vex.Flow.Stem - changed constants UP and DOWN from static to const - removed constants WIDTH and HEIGHT as they are set by Vex.Flow.STEM_WIDTH and Vex.Flow.STEM_HEIGHT - added hide property --- vexflow/vexflow.d.ts | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 92fc436549..e48416250f 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -976,13 +976,14 @@ declare module Vex { draw() : boolean; } + module Stem { + const UP : number; + const DOWN : number; + } + 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; @@ -996,6 +997,9 @@ declare module Vex { getStyle() : {shadowColor? : string, shadowBlur? : string, fillStyle? : string, strokeStyle? : string}; applyStyle(context : IRenderContext) : Stem; draw() : void; + + //inconsistent API: this should be set via the options object in the constructor + hide : boolean; } class StemmableNote extends Note { From 57bd0ee3d5f77aa5582d24ff3f71bd35320c18f3 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:10:00 +0200 Subject: [PATCH 108/309] fixed definition of Vex.Flow.StringNumber - fixed arguments of setNote() and setLastNote() --- 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 e48416250f..4c792d77c5 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1036,7 +1036,7 @@ declare module Vex { static CATEGORY : string; static format(nums : StringNumber[], state : {left_shift : number, right_shift : number, text_line : number}) : boolean; getNote() : Note; - setNote(note : StaveNote) : StringNumber; + setNote(note : StemmableNote) : StringNumber; getIndex() : number; setIndex(index : number) : StringNumber; setLineEndType(leg : Renderer.LineEndType) : StringNumber; @@ -1045,7 +1045,7 @@ declare module Vex { setStringNumber(number : number) : StringNumber; setOffsetX(x : number) : StringNumber; setOffsetY(y : number) : StringNumber; - setLastNote(note : StaveNote) : StringNumber; + setLastNote(note : StemmableNote) : StringNumber; setDashed(dashed : boolean) : StringNumber; draw() : void; } From 41f25f3c763296a867cd484942c2d122b9c1e913 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:12:31 +0200 Subject: [PATCH 109/309] changed definition of Vex.Flow.Stroke - changed Type enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 4c792d77c5..3a66c318ac 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1051,7 +1051,7 @@ declare module Vex { } export module Stroke { - enum Type {BRUSH_DOWN, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP} + const enum Type {BRUSH_DOWN, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP} } class Stroke extends Modifier { From 45599bb3cfd07e86e7fe778a2a906b1843f45771 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:18:08 +0200 Subject: [PATCH 110/309] fixed definition of Vex.Flow.TabNote --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 3a66c318ac..10f25f3698 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1105,7 +1105,7 @@ declare module Vex { 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); + constructor(tab_struct : {positions : {str : number, fret : number}[], type? : string, dots? : number, duration : string, stem_direction? : boolean}, draw_stem : boolean); getCategory() : string; setGhost(ghost : boolean) : TabNote; hasStem() : boolean; From 8eb312c09afc94d219873b8e26ba39be45f7483d Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:20:53 +0200 Subject: [PATCH 111/309] fixed definition of Vex.Flow.TabSlide - changed constants SLIDE_UP and SLIDE_DOWN from static to const - fixed constructor arguments --- vexflow/vexflow.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 10f25f3698..e2b63cda5b 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1129,10 +1129,13 @@ declare module Vex { draw() : void; } + module TabSlide { + const SLIDE_UP : number; + const SLIDE_DOWN : number; + } + 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; + constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, direction? : 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; From 0cf5c332311197eba7086e319ea6fb5fd829fc29 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:23:04 +0200 Subject: [PATCH 112/309] fixed definition of Vex.Flow.TabTie --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index e2b63cda5b..5280eb5d5d 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1148,7 +1148,7 @@ declare module Vex { } class TabTie extends StaveTie { - constructor(notes : {first_note: Note, last_note: Note, first_indices : number[], last_indices : number[]}, text : string); + 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; From c377f8452fc31a691c8fd19d10c22624412e8cc8 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:25:51 +0200 Subject: [PATCH 113/309] fixed definition of Vex.Flow.TextBracket - changed Positions enum to const - fixed setFont() - fixed constructor argument --- vexflow/vexflow.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 5280eb5d5d..01e3e7fdf5 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1155,15 +1155,15 @@ declare module Vex { } export module TextBracket { - enum Position {TOP, BOTTOM} + const enum Positions {TOP, BOTTOM} } class TextBracket { - constructor(bracket_data : {start : Note, stop : Note, text? : string, superscript? : string, position : TextBracket.Position}); + constructor(bracket_data : {start : Note, stop : Note, text? : string, superscript? : string, position? : TextBracket.Positions}); static DEBUG : boolean; applyStyle(context : IRenderContext) : TextBracket; setDashed(dashed : boolean, dash? : number[]) : TextBracket; - setFont(family : string, size : number, weight? : number) : TextBracket; + setFont({family : string, size : number, weight : string}) : TextBracket; setContext(context : IRenderContext) : TextBracket; setLine(line : number) : TextBracket; draw() : void; From b3f154c5c33d4c5f5da3abbb3b8dc764e4437a4d Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:36:22 +0200 Subject: [PATCH 114/309] fixed definition of Vex.Flow.TextNote - changed Justification enum to const - added GLYPHS const - fixed constructor arguments --- vexflow/vexflow.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 01e3e7fdf5..46d1d63226 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1178,11 +1178,12 @@ declare module Vex { } export module TextNote { - enum Justification {LEFT, CENTER, RIGHT} + const enum Justification {LEFT, CENTER, RIGHT} + const GLYPHS : {[name : string] : {code : string, point : number, x_shift : number, y_shift : number}} } 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}); + 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; From 13650983044cd260606b05d9e59363e57dc772f3 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:40:50 +0200 Subject: [PATCH 115/309] changed definition of Vex.Flow.TimeSignature - added constant glyphs --- vexflow/vexflow.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 46d1d63226..113e108e36 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1240,6 +1240,10 @@ declare module Vex { static getNextContext(tContext : TickContext) : TickContext; } + module TimeSignature { + const glyphs : {[name : string] : {code : string, point : number, line : number}}; + } + class TimeSignature extends StaveModifier { //TODO remove the following lines once TypeScript allows subclass overrides with type changes addModifier() : void; From 6970bb6f7889d63bf1df26914bbf787904b44db0 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:44:46 +0200 Subject: [PATCH 116/309] changed definition of Vex.Flow.Tuning - added names constant --- vexflow/vexflow.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 113e108e36..7640d4a90f 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1275,6 +1275,10 @@ declare module Vex { draw() : void; } + module Tuning { + const names : {[name : string] : string}; + } + class Tuning { constructor(tuningString? : string); noteToInteger(noteString : string) : number; From dcef9183ea4304eb23bbc924ba64665cecd19fc3 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:47:21 +0200 Subject: [PATCH 117/309] changed definition of Vex.Flow.Tuplet - changed LOCATION_TOP and LOCATION_BOTTOM from static to const --- vexflow/vexflow.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 7640d4a90f..bb920c7581 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1288,10 +1288,13 @@ declare module Vex { getNoteForFret(fretNum : string, stringNum : string) : string; } + module Tuplet { + const LOCATION_TOP : number; + const LOCATION_BOTTOM : number; + } + 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; From 25f06dbb005bcc755789c6e465e1f2010cf21e41 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:50:22 +0200 Subject: [PATCH 118/309] fixed definition of Vex.Flow.Voice - changed enum Mode to const - fixed constructor arguments --- 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 bb920c7581..1cc54fa8a8 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1318,11 +1318,11 @@ declare module Vex { } export module Voice { - enum Mode {STRICT, SOFT, FULL} + const enum Mode {STRICT, SOFT, FULL} } class Voice { - constructor(time : {num_beats : number, beat_value : number, resolution : number}); + constructor(time : {num_beats? : number, beat_value? : number, resolution? : number}); getTotalTicks() : Fraction; getTicksUsed() : Fraction; getLargestTickWidth() : number; From f6c8562355d2c89f09a70e68d2d6ba37b8630594 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:53:41 +0200 Subject: [PATCH 119/309] changed definition of Vex.Flow.Volta - changed type enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 1cc54fa8a8..c17c4f710d 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1351,7 +1351,7 @@ declare module Vex { } export module Volta { - enum type {NONE, BEGIN, MID, END, BEGIN_END} + const enum type {NONE, BEGIN, MID, END, BEGIN_END} } class Volta extends StaveModifier { From bc8e29fcd034903a9fc80d73942915fea2b48f70 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 17:57:07 +0200 Subject: [PATCH 120/309] fixed definition of Vex.Flow.Glyph - fixed argument of setOptions() --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index c17c4f710d..0707282127 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -452,7 +452,7 @@ declare module Vex { class Glyph { constructor(code : string, point : number, options? : {cache? : boolean, font? : IFont}); - setOptions(options? : {cache? : boolean, font? : IFont}) : void; + setOptions(options : {cache? : boolean, font? : IFont}) : void; setStave(stave : Stave) : Glyph; setXShift(x_shift : number) : Glyph; setYShift(y_shift : number) : Glyph; From 66440e6fb3738bea65937863148483360988ba0e Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:00:10 +0200 Subject: [PATCH 121/309] fixed definition of Vex.Flow.TabStave --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 0707282127..815c8c9313 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1142,7 +1142,7 @@ declare module Vex { } 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}); + 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; } From 59dd256bf26ee9c8718848c44b01ce6ee47f4d7b Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:02:33 +0200 Subject: [PATCH 122/309] fixed definition of Vex.Flow.Formatter - fixed arguments of FormatAndDraw - fixed arguments of FormatAndDrawTab --- vexflow/vexflow.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 815c8c9313..9a2e87a57a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -372,10 +372,10 @@ declare module Vex { 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 FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params : {auto_beam : boolean, align_rests : boolean}) : BoundingBox; + static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params : boolean) : BoundingBox; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], autobeam : boolean, params : {auto_beam : boolean, align_rests : boolean}) : void; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], 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; From 15ccac22d6d9550bfd2a0751d10eb7b89a9397bb Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:07:13 +0200 Subject: [PATCH 123/309] changed Vex.Flow.Tickable from class to interface - added respective methods to Vex.Flow.Note --- vexflow/vexflow.d.ts | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 9a2e87a57a..dd33c133ed 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -582,7 +582,23 @@ declare module Vex { createScaleMap(keySignature : string) : {[rootName : string] : string}; } - class Note extends Tickable { + class Note implements Tickable { + //from tickable interface: + getTicks() : Fraction; + getCenterXShift() : number; + isCenterAligned() : boolean; + setCenterAlignment(align_center : boolean) : Note; + getTuplet() : Tuplet; + setTuplet(tuplet : Tuplet) : Note; + addToModifierContext(mc : ModifierContext) : void; + preFormat() : void; + postFormat() : Note; + getIntrinsicTicks() : Fraction; + setIntrinsicTicks(intrinsicTicks : Fraction) : void; + getTickMultiplier() : Fraction; + applyTickMultiplier(numerator : number, denominator : number) : void; + setDuration(duration : Fraction) : void; + constructor(note_struct : {type? : string, dots? : number, duration : string}); static CATEGORY : string; getPlayNote() : any; @@ -1190,7 +1206,7 @@ declare module Vex { draw() : void; } - class Tickable { + interface Tickable { setContext(context : IRenderContext) : void; getBoundingBox() : BoundingBox; getTicks() : Fraction; From 727502c429e50b3ee994541d270c588458c1398d Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:10:46 +0200 Subject: [PATCH 124/309] fixed definition of Vex.Flow.StaveNote - changed STEM_UP and STEM_DOWN from static to const - fixed constructor arguments --- vexflow/vexflow.d.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index dd33c133ed..19e0c68a31 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -883,6 +883,11 @@ declare module Vex { addEndModifier() : void; } + module StaveNote { + const STEM_UP : number; + const STEM_DOWN : number; + } + 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; @@ -891,11 +896,9 @@ 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, auto_stem? : boolean, stem_direction? : 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; From f5ec5ac8f0248e112ce4a27aee4cb8ae9005bac8 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:13:33 +0200 Subject: [PATCH 125/309] changed Vex.Flow.Annotation - changed enums to const --- 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 19e0c68a31..b1911eb6d1 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -152,8 +152,8 @@ declare module Vex { } export module Annotation { - enum Justify {LEFT, CENTER, RIGHT, CENTER_STEM} - enum VerticalJustify {TOP, CENTER, BOTTOM, CENTER_STEM} + const enum Justify {LEFT, CENTER, RIGHT, CENTER_STEM} + const enum VerticalJustify {TOP, CENTER, BOTTOM, CENTER_STEM} } class Annotation extends Modifier { From 73c743248960acbbb8b1bf834031738f7624ea31 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:14:24 +0200 Subject: [PATCH 126/309] changed Vex.Flow.Barline - changed type enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index b1911eb6d1..5f450190a3 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -188,7 +188,7 @@ declare module Vex { } export module Barline { - enum type {SINGLE, DOUBLE, END, REPEAT_BEGIN, REPEAT_END, REPEAT_BOTH, NONE} + const enum type {SINGLE, DOUBLE, END, REPEAT_BEGIN, REPEAT_END, REPEAT_BOTH, NONE} } class Barline extends StaveModifier { From af4b4626fa2d6123c486c7f2216340efd8728e3d Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:15:08 +0200 Subject: [PATCH 127/309] changed definition of Vex.Flow.Curve - changed Position enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 5f450190a3..f44fb7868a 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -346,7 +346,7 @@ declare module Vex { } export module Curve { - enum Position {NEAR_HEAD, NEAR_TOP} + const enum Position {NEAR_HEAD, NEAR_TOP} } class Curve { From f8fb63d8cc58cf310f04eac958a515158bed9532 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:15:50 +0200 Subject: [PATCH 128/309] changed definition of Vex.Flow.Modifier - changed Position enum to const --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index f44fb7868a..2f9b94ac0d 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -514,7 +514,7 @@ declare module Vex { } export module Modifier { - enum Position {LEFT, RIGHT, ABOVE, BELOW} + const enum Position {LEFT, RIGHT, ABOVE, BELOW} } class Modifier { From 77445160adfcdcc1b1ebf20fa27fdedf17b17bc1 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:19:54 +0200 Subject: [PATCH 129/309] changed CATEGORY property of several classes from static to const --- vexflow/vexflow.d.ts | 58 +++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index 2f9b94ac0d..a2666bae94 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -137,12 +137,15 @@ declare module Vex { 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 Accidental { + const CATEGORY : string; + } + 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; @@ -154,11 +157,11 @@ declare module Vex { export module Annotation { const enum Justify {LEFT, CENTER, RIGHT, CENTER_STEM} const enum VerticalJustify {TOP, CENTER, BOTTOM, CENTER_STEM} + const CATEGORY : string; } 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; @@ -169,9 +172,12 @@ declare module Vex { draw() : void; } + module Articulation { + const CATEGORY : string; + } + 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; @@ -222,9 +228,12 @@ declare module Vex { 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[]; } + module Bend { + const CATEGORY : string; + } + class Bend extends Modifier { 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; @@ -359,11 +368,14 @@ declare module Vex { draw() : boolean; } + module Dot { + const CATEGORY : string; + } + 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; @@ -421,9 +433,12 @@ declare module Vex { parse(str : string) : Fraction; } + module FretHandFinger { + const CATEGORY : string; + } + 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; @@ -474,13 +489,16 @@ declare module Vex { draw() : void; } + module GraceNoteGroup { + const CATEGORY : string; + } + class GraceNoteGroup extends Modifier { //TODO remove the following lines once TypeScript allows subclass overrides with type changes or type inconsistencies mentioned below are fixed setWidth(width : number) : Modifier; setNote(note : StaveNote) : Modifier; 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; @@ -515,10 +533,10 @@ declare module Vex { export module Modifier { const enum Position {LEFT, RIGHT, ABOVE, BELOW} + const CATEGORY : string } class Modifier { - static CATEGORY : string; static DEBUG : boolean; getCategory() : string; getWidth() : number; @@ -582,6 +600,10 @@ declare module Vex { createScaleMap(keySignature : string) : {[rootName : string] : string}; } + module Note { + const CATEGORY : string; + } + class Note implements Tickable { //from tickable interface: getTicks() : Fraction; @@ -600,7 +622,6 @@ declare module Vex { setDuration(duration : Fraction) : void; constructor(note_struct : {type? : string, dots? : number, duration : string}); - static CATEGORY : string; getPlayNote() : any; setPlayNote(note : any) : Note; isRest() : boolean; @@ -666,9 +687,12 @@ declare module Vex { draw() : void; } + module Ornament { + const CATEGORY : string; + } + 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; @@ -886,6 +910,7 @@ declare module Vex { module StaveNote { const STEM_UP : number; const STEM_DOWN : number; + const CATEGORY : string; } class StaveNote extends StemmableNote { @@ -897,7 +922,6 @@ declare module Vex { getDots() : number; constructor(note_struct : {type? : string, dots? : number, duration : string, clef? : string, keys : string[], octave_shift? : number, auto_stem? : boolean, stem_direction? : number}); - static CATEGORY : string; static DEBUG : boolean; 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; @@ -1047,12 +1071,15 @@ declare module Vex { 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; } + module StringNumber { + const CATEGORY : string; + } + 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 : StemmableNote) : StringNumber; @@ -1071,11 +1098,11 @@ declare module Vex { export module Stroke { const enum Type {BRUSH_DOWN, BRUSH_UP, ROLL_DOWN, ROLL_UP, RASQUEDO_DOWN, RASQUEDO_UP} + const CATEGORY : string; } 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; @@ -1328,8 +1355,11 @@ declare module Vex { draw() : void; } + module Vibrato { + const CATEGORY : string; + } + 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; From b330fede59a3c57cd42a931517f5403300bc6fac Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:47:42 +0200 Subject: [PATCH 130/309] fixed definition of Vex.Flow.TextBracket - fixed argument of setFont() --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index a2666bae94..ca0c901054 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1209,7 +1209,7 @@ declare module Vex { static DEBUG : boolean; applyStyle(context : IRenderContext) : TextBracket; setDashed(dashed : boolean, dash? : number[]) : TextBracket; - setFont({family : string, size : number, weight : string}) : TextBracket; + setFont(font : {family : string, size : number, weight : string}) : TextBracket; setContext(context : IRenderContext) : TextBracket; setLine(line : number) : TextBracket; draw() : void; From fea6bb785ab5c26b66704df5aa76eb55080d25e3 Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:49:37 +0200 Subject: [PATCH 131/309] fixed definition of Vex.Flow.TabNote --- vexflow/vexflow.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index ca0c901054..ca7cc41717 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -1151,7 +1151,7 @@ declare module Vex { setStave(stave : Stave) : Note; getModifierStartXY() : {x : number, y : number}; - constructor(tab_struct : {positions : {str : number, fret : number}[], type? : string, dots? : number, duration : string, stem_direction? : boolean}, draw_stem : boolean); + constructor(tab_struct : {positions : {str : number, fret : number}[], type? : string, dots? : number, duration : string, stem_direction? : boolean}, draw_stem? : boolean); getCategory() : string; setGhost(ghost : boolean) : TabNote; hasStem() : boolean; From b4b5855f86b6bbff66bf691ed4a48ee8755128aa Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 18:55:31 +0200 Subject: [PATCH 132/309] added vexflow-tests.ts --- vexflow/vexflow-tests.ts | 88 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 vexflow/vexflow-tests.ts diff --git a/vexflow/vexflow-tests.ts b/vexflow/vexflow-tests.ts new file mode 100644 index 0000000000..351ad2ee88 --- /dev/null +++ b/vexflow/vexflow-tests.ts @@ -0,0 +1,88 @@ +/// + +var canvas = document.getElementById("canvas"); +var renderer = new Vex.Flow.Renderer(canvas, Vex.Flow.Renderer.Backends.CANVAS); +var ctx = renderer.getContext(); + +// Add a treble clef and time signature +var stave = new Vex.Flow.Stave(10, 0, 550); +stave.setContext(ctx). + addClef("treble"). + addKeySignature("A"). + addTimeSignature("4/4"); + +// Dotted eighth E##, sixteenth Eb, half D, quarter Cm#5 +var notes1 = [ + new Vex.Flow.StaveNote({keys: ["e##/5"], duration: "8d"}). + addAccidental(0, new Vex.Flow.Accidental("##")). + addDotToAll(), + new Vex.Flow.StaveNote({keys: ["eb/5"], duration: "16"}). + addAccidental(0, new Vex.Flow.Accidental("b")), + new Vex.Flow.StaveNote({keys: ["d/5"], duration: "h"}), + new Vex.Flow.StaveNote({keys: ["c/5", "eb/5", "g#/5"], duration: "q"}). + addAccidental(1, new Vex.Flow.Accidental("b")). + addAccidental(2, new Vex.Flow.Accidental("#")) +]; + +// Create a beam for the first two notes +var beam = new Vex.Flow.Beam(notes1.slice(0, 2)); + +// Add a grace note to the half D +var gracenote = new Vex.Flow.GraceNote({keys: ["e/5"], duration: "16", slash: true}); +notes1[2].addModifier(0, new Vex.Flow.GraceNoteGroup([gracenote], true).beamNotes()); + +// Color the chord +notes1[3].setStyle({fillStyle: "blue", strokeStyle: "blue", stemStyle: "blue"}); + +// Create a voice in 4/4 and add notes +var voice1 = new Vex.Flow.Voice({ + num_beats: 4, + beat_value: 4, + resolution: Vex.Flow.RESOLUTION +}).addTickables(notes1); + +// Create a second voice with just one whole note +var voice2 = new Vex.Flow.Voice(Vex.Flow.TIME4_4). + addTickables([new Vex.Flow.StaveNote({keys: ["c/4"], duration: "w"})]); + +// Format and justify the notes to 550 pixels +var formatter = new Vex.Flow.Formatter(). + joinVoices([voice1, voice2]).format([voice1, voice2], 550); + +// Render stave +stave.draw(); + +// Render voices +voice1.draw(ctx, stave); +voice2.draw(ctx, stave); + +// Render beam +beam.setContext(ctx).draw(); + +// Create and draw a tablature stave +var tabstave = new Vex.Flow.TabStave(10, 200, 550); +tabstave.addTabGlyph(); +tabstave.setContext(ctx).draw(); + +// Create some TabNotes +var notes = [ + // A single note + new Vex.Flow.TabNote({ + positions: [{str: 3, fret: 7}], + duration: "q"}), + + // A chord with the note on the 3rd string bent + new Vex.Flow.TabNote({ + positions: [{str: 2, fret: 10}, {str: 3, fret: 9}], + duration: "q"}). + addModifier(new Vex.Flow.Bend("Full"), 1), + + // A single note with a harsh vibrato + new Vex.Flow.TabNote({ + positions: [{str: 2, fret: 5}], + duration: "h"}). + addModifier(new Vex.Flow.Vibrato().setHarsh(true).setVibratoWidth(70), 0) +]; + +// Format ad draw the notes +Vex.Flow.Formatter.FormatAndDraw(ctx, tabstave, notes); \ No newline at end of file From ab17e168530eef2166e42db66f9fa42e1615d74a Mon Sep 17 00:00:00 2001 From: Roman Quiring Date: Thu, 6 Aug 2015 19:04:38 +0200 Subject: [PATCH 133/309] fixed definition of Vex.Flow.Formatter - fixed arguments of FormatAndDraw() - fixed arguments of FormatAndDrawTab() --- vexflow/vexflow.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/vexflow/vexflow.d.ts b/vexflow/vexflow.d.ts index ca7cc41717..1822c0c67e 100644 --- a/vexflow/vexflow.d.ts +++ b/vexflow/vexflow.d.ts @@ -384,10 +384,10 @@ declare module Vex { class Formatter { static DEBUG : boolean; - static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params : {auto_beam : boolean, align_rests : boolean}) : BoundingBox; - static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params : boolean) : BoundingBox; - static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], autobeam : boolean, params : {auto_beam : boolean, align_rests : boolean}) : void; - static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], autobeam : boolean, params : boolean) : void; + static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params? : {auto_beam : boolean, align_rests : boolean}) : BoundingBox; + static FormatAndDraw(ctx : IRenderContext, stave : Stave, notes : Note[], params? : boolean) : BoundingBox; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], autobeam? : boolean, params? : {auto_beam : boolean, align_rests : boolean}) : void; + static FormatAndDrawTab(ctx : IRenderContext, tabstave : TabStave, stave : Stave, tabnotes : TabNote[], notes : Note[], 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; From b05ea8139c03b72773b6d0e6c74cbe5a7fc89b08 Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Thu, 6 Aug 2015 15:14:39 -0400 Subject: [PATCH 134/309] KaTeX definitions --- katex/katex-tests.ts | 18 ++++++++++++++++++ katex/katex.d.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 katex/katex-tests.ts create mode 100644 katex/katex.d.ts diff --git a/katex/katex-tests.ts b/katex/katex-tests.ts new file mode 100644 index 0000000000..9829fcddf7 --- /dev/null +++ b/katex/katex-tests.ts @@ -0,0 +1,18 @@ +/// + +import katexLib = require('katex'); + +class KatexTest { + constructor() { + katexLib.render('My Latex String', document.createElement('div')); + + try { + let options: katexLib.KatexOptions = { breakOnUnsupportedCmds: true }; + let value: string = katexLib.renderToString('My Latex String', options); + } catch (error) { + if (error instanceof katexLib.ParseError) { + //do something with this error + } + } + } +} \ No newline at end of file diff --git a/katex/katex.d.ts b/katex/katex.d.ts new file mode 100644 index 0000000000..6d139ded13 --- /dev/null +++ b/katex/katex.d.ts @@ -0,0 +1,33 @@ +// Type definitions for KaTeX v.0.5.0 +// Project: http://khan.github.io/KaTeX/ +// Definitions by: Michael Randolph +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "katex" { + interface KatexOptions { + displayMode?: boolean; + breakOnUnsupportedCmds?: boolean; + errorColor?: string; + } + + class ParseError implements Error { + constructor(message: string, lexer: any, position: number); + name: string; + message: string; + position: number; + } + + /** + * Renders a TeX expression into the specified DOM element + * @param tex A TeX expression + * @param element The DOM element to render into + * @param options KaTeX options + */ + function render(tex: string, element: HTMLElement, options?:KatexOptions): void; + /** + * Renders a TeX expression into an HTML string + * @param tex A TeX expression + * @param options KaTeX options + */ + function renderToString(tex: string, options?:KatexOptions): string; +} \ No newline at end of file From c642fb841b8c36fe18786214da62710aa74a967c Mon Sep 17 00:00:00 2001 From: Michael Nahkies Date: Fri, 7 Aug 2015 09:51:39 +1200 Subject: [PATCH 135/309] Added definitions for amqplib (https://github.com/squaremo/amqp.node) --- amqplib/amqplib-tests.ts | 21 ++++++ amqplib/amqplib.d.ts | 144 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 165 insertions(+) create mode 100644 amqplib/amqplib-tests.ts create mode 100644 amqplib/amqplib.d.ts diff --git a/amqplib/amqplib-tests.ts b/amqplib/amqplib-tests.ts new file mode 100644 index 0000000000..7a1f512002 --- /dev/null +++ b/amqplib/amqplib-tests.ts @@ -0,0 +1,21 @@ +/// + +import amqp = require("amqplib"); + +var msg = "Hello World"; + +amqp.connect("amqp://localhost") + .then(connection => { + return connection.createChannel() + .tap(channel => channel.checkQueue("myQueue")) + .then(channel => channel.sendToQueue("myQueue", new Buffer(msg))) + .ensure(() => connection.close()); + }); + +amqp.connect("amqp://localhost") + .then(connection => { + return connection.createChannel() + .tap(channel => channel.checkQueue("myQueue")) + .then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString()))) + .ensure(() => connection.close()); + }); diff --git a/amqplib/amqplib.d.ts b/amqplib/amqplib.d.ts new file mode 100644 index 0000000000..0c7f0720a6 --- /dev/null +++ b/amqplib/amqplib.d.ts @@ -0,0 +1,144 @@ +// Type definitions for amqplib 0.3.x +// Project: https://github.com/squaremo/amqp.node +// Definitions by: Michael Nahkies +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "amqplib" { + + import events = require("events"); + import when = require("when"); + + interface Connection extends events.EventEmitter { + close(): when.Promise; + createChannel(): when.Promise; + createConfirmChannel(): when.Promise; + } + + module Replies { + interface Empty { + } + interface AssertQueue { + queue: string; + messageCount: number; + consumerCount: number; + } + interface DeleteQueue { + messageCount: number; + } + interface AssertExchange { + exchange: string; + } + interface Consume { + consumerTag: string; + } + } + + module Options { + interface AssertQueue { + exclusive?: boolean; + durable?: boolean; + autoDelete?: boolean; + arguments?: any; + messageTtl?: number; + expires?: number; + deadLetterExchange?: string; + maxLength?: number; + } + interface DeleteQueue { + ifUnused?: boolean; + ifEmpty?: boolean; + } + interface AssertExchange { + durable?: boolean; + internal?: boolean; + autoDelete?: boolean; + alternateExchange?: string; + arguments?: any; + } + interface DeleteExchange { + ifUnused?: boolean; + } + interface Publish { + expiration?: string; + userId?: string; + CC?: string | string[]; + + mandatory?: boolean; + persistent?: boolean; + deliveryMode?: boolean | number; + BCC?: string | string[]; + + contentType?: string; + contentEncoding?: string; + headers?: Object; + priority?: number; + correlationId?: string; + replyTo?: string; + messageId?: string; + timestamp?: number; + type?: string; + appId?: string; + } + interface Consume { + consumerTag?: string; + noLocal?: boolean; + noAck?: boolean; + exclusive?: boolean; + priority?: number; + arguments?: Object; + } + interface Get { + noAck?: boolean; + } + } + + interface Message { + content: Buffer; + fields: Object; + properties: Object; + } + + interface Channel extends events.EventEmitter { + close(): when.Promise; + + assertQueue(queue: string, options?: Options.AssertQueue): when.Promise; + checkQueue(queue: string): when.Promise; + + deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise; + purgeQueue(queue: string): when.Promise; + + bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise; + + assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise; + checkExchange(exchange: string): when.Promise; + + deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise; + + bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise; + + publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; + sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; + + consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise; + + cancel(consumerTag: string): when.Promise; + get(queue: string, options?: Options.Get): when.Promise; + + ack(message: Message, allUpTo?: boolean): void; + ackAll(): void; + + nack(message: Message, allUpTo?: boolean, requeue?: boolean): void; + nackAll(requeue?: boolean): void; + reject(message: Message, requeue?: boolean): void; + + prefetch(count: number, global?: boolean): when.Promise; + recover(): when.Promise; + } + + function connect(url: string, socketOptions?: any): when.Promise; +} From 00c2478e989faab63b7f862ce385ec1989895d3e Mon Sep 17 00:00:00 2001 From: Matthias Hild Date: Thu, 6 Aug 2015 19:02:28 -0400 Subject: [PATCH 136/309] Transition.styleTween has incorrect signature The signature of Transition.styleTween is currently: styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => Primitive, priority?: string): Transition; (line 833) Note that the tween is said to return a Primitive. This seems incorrect, both in terms of D3 intent and implementation. The *correct* version appears to be: styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive, priority?: string): Transition; (This is similar to similar to Transition.attrTween.) First, the documentation states: >>> The return value of tween must be an interpolator: a function that maps a parametric value t in the domain [0,1] >>> to a color, number or arbitrary value. Second, the source code of d3 3.5.5 has: d3_transitionPrototype.styleTween = function(name, tween, priority) { if (arguments.length < 3) priority = ""; function styleTween(d, i) { var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name)); return f && function(t) { this.style.setProperty(name, f(t), priority); }; } return this.tween("style." + name, styleTween); }; Note the line "this.style.setProperty(name, f(t), priority);" where the result f of applying the tween is passed a parameter t. The only point of discussion might be the type of the return value of the tween's interpolator output. Is it Primitive or any? The documentation quoted above (incidentally the same for attrTween and styleTween) explicitly allows for an arbitrary value. I don't have enough D3 experience to know if this is a practically relevant possibility. Many thanks for your great work on d3.d.ts!!! Especially the use of tweens and interpolators perfectly illustrates the benefits of Typescript. Best wishes, Matthias --- d3/d3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 2b6caeddfb..ef3909e9fc 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -830,7 +830,7 @@ declare module d3 { style(name: string, value: (datum: Datum, index: number, outerIndex: number) => Primitive, priority?: string): Transition; style(obj: { [key: string]: Primitive | ((datum: Datum, index: number, outerIndex: number) => Primitive) }, priority?: string): Transition; - styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => Primitive, priority?: string): Transition; + styleTween(name: string, tween: (datum: Datum, index: number, attr: string) => (t: number) => Primitive, priority?: string): Transition; text(value: Primitive): Transition; text(value: (datum: Datum, index: number, outerIndex: number) => Primitive): Transition; From 5dafa21e89ee5beb8fec49643549b5c9a2b0a630 Mon Sep 17 00:00:00 2001 From: Eric Pelz Date: Wed, 5 Aug 2015 21:20:31 -0700 Subject: [PATCH 137/309] Add the TestBackend module to React DnD This allows unit testing with React DnD. --- react-dnd/react-dnd-tests.ts | 13 +++++++++---- react-dnd/react-dnd.d.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/react-dnd/react-dnd-tests.ts b/react-dnd/react-dnd-tests.ts index 244144029c..d270a041de 100644 --- a/react-dnd/react-dnd-tests.ts +++ b/react-dnd/react-dnd-tests.ts @@ -13,6 +13,7 @@ import DragSource = ReactDnd.DragSource; import DropTarget = ReactDnd.DropTarget; import DragDropContext = ReactDnd.DragDropContext; import HTML5Backend = require('react-dnd/modules/backends/HTML5'); +import TestBackend = require('react-dnd/modules/backends/Test'); // Game Component // ---------------------------------------------------------------------- @@ -247,14 +248,18 @@ module Board { } } - var DndBoard = DragDropContext(HTML5Backend)(Board); - export var create = React.createFactory(DndBoard); + export var createWithHTMLBackend = React.createFactory(DragDropContext(HTML5Backend)(Board)); + export var createWithTestBackend = React.createFactory(DragDropContext(TestBackend)(Board)); } - // Render the Board Component // ---------------------------------------------------------------------- -Board.create({ +Board.createWithHTMLBackend({ + knightPosition: [0, 0] +}); + + +Board.createWithTestBackend({ knightPosition: [0, 0] }); diff --git a/react-dnd/react-dnd.d.ts b/react-dnd/react-dnd.d.ts index 86eab01cdb..d86af3b8b7 100644 --- a/react-dnd/react-dnd.d.ts +++ b/react-dnd/react-dnd.d.ts @@ -170,3 +170,19 @@ declare module "react-dnd/modules/backends/HTML5" { export = HTML5Backend; } + +declare module "react-dnd/modules/backends/Test" { + class TestBackend { + setup(): void; + teardown(): void; + connectDragSource(): void; + connectDropTarget(): void; + simulateBeginDrag(sourceIds: __ReactDnd.Identifier[], options?: {}): void; + simulatePublishDragSource(): void; + simulateHover(targetIds: __ReactDnd.Identifier[], options?: {}): void; + simulateDrop(): void; + simulateEndDrag(): void; + } + + export = TestBackend; +} From 98105f1e610ca52c6a3e636ca85be04e8d586e91 Mon Sep 17 00:00:00 2001 From: Stefan Profanter Date: Fri, 7 Aug 2015 09:23:58 +0200 Subject: [PATCH 138/309] Changed BoundingBoxHelper constructor --- threejs/three.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 993a228c36..826d6332fd 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -5672,8 +5672,7 @@ declare module THREE { } export class BoundingBoxHelper extends Mesh { - constructor(object: Object3D, hex?: number); - constructor(); + constructor(object?: Object3D, hex?: number); object: Object3D; box: Box3; @@ -5792,8 +5791,6 @@ declare module THREE { export class WireframeHelper extends Line { constructor(object: Object3D, hex?: number); - object: Object3D; - } // Extras / Objects ///////////////////////////////////////////////////////////////////// From 6ca9fa0d5eca1ad16dac85fd9558c6f48aec9a90 Mon Sep 17 00:00:00 2001 From: Allan Hvam Petersen Date: Fri, 7 Aug 2015 12:35:54 +0200 Subject: [PATCH 139/309] Removed TaxonomySession.getTerms(string, boolean) There is no overload for getTerms on TaxonomySession that takes string and boolean. There is only a function that takes match information, see: https://msdn.microsoft.com/en-us/library/office/dn312597.aspx --- sharepoint/SharePoint.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/sharepoint/SharePoint.d.ts b/sharepoint/SharePoint.d.ts index fef652dd30..24bea641a5 100644 --- a/sharepoint/SharePoint.d.ts +++ b/sharepoint/SharePoint.d.ts @@ -6507,7 +6507,6 @@ declare module SP { static getTaxonomySession(context: SP.ClientContext): TaxonomySession; get_offlineTermStoreNames(): string[]; get_termStores(): TermStoreCollection; - getTerms(termLabel: string, trimUnavailable: boolean): TermCollection; getTerms(labelMatchInformation: LabelMatchInformation): TermCollection; updateCache(): void; getTerm(guid: SP.Guid): Term; From 62000d5e40fad11d164035a3ec54d53c78c9622f Mon Sep 17 00:00:00 2001 From: Adam Santaniello Date: Fri, 7 Aug 2015 10:21:27 -0400 Subject: [PATCH 140/309] Added angular-signalr-hub definition and test. --- .../angular-signalr-hub-tests.ts | 77 +++++++++++++++++++ angular-signalr-hub/angular-signalr-hub.d.ts | 73 ++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 angular-signalr-hub/angular-signalr-hub-tests.ts create mode 100644 angular-signalr-hub/angular-signalr-hub.d.ts diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts new file mode 100644 index 0000000000..e2644bd1d0 --- /dev/null +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -0,0 +1,77 @@ +/// +/// + +angular + .module('app', ['SignalR']) + .factory('Employees', ngSignalrTest.EmployeesFactory); + +module ngSignalrTest { + export class EmployeesFactory { + static $inject = ['$rootScope', 'Hub', '$timeout']; + private hub: ngSignalr.Hub; + public all: Array; + + constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) { + // declaring the hub connection + this.hub = new Hub('employee', { + // client-side methods + listeners: { + 'lockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = true; + $rootScope.$apply(); + }, + 'unlockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = false; + $rootScope.$apply(); + } + }, + + // server-side methods + methods: ['lock', 'unlock'], + + // query params sent on initial connection + queryParams:{ + 'token': 'exampletoken' + }, + + // handle connection error + errorHandler: (message: string) => { + console.error(message); + }, + + stateChanged: (state: SignalRStateChange) => { + // your code here + } + }); + } + + private find(id: number) { + for (var i = 0; i < this.all.length; i++) { + if (this.all[i].Id === id) return this.all[i]; + } + + return null; + } + + public edit = (employee: Employee) => { + employee.Edit = true; + this.hub.invoke('lock', employee.Id); + }; + + public done = (employee: Employee) => { + employee.Edit = false; + this.hub.invoke('unlock', employee.Id); + } + } + + interface Employee { + Id: number; + Name: string; + Email: string; + Salary: number; + Edit: boolean; + Locked: boolean; + } +} \ No newline at end of file diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts new file mode 100644 index 0000000000..6fc956b342 --- /dev/null +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -0,0 +1,73 @@ +// Type definitions for angular-signalr-hub v1.5.0 +// Project: https://github.com/JustMaier/angular-signalr-hub +// Definitions by: Adam Santaniello +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module ngSignalr { + interface HubFactory { + /** + * Creates a new Hub connection + */ + new(hubName: string, options: HubOptions) : Hub + } + + class Hub { + hubName: string; + connection: SignalR; + proxy: HubProxy; + + on(event: string, fn: ((...args: any[]) => void)): void; + invoke(method: string, ...args: any[]): JQueryDeferred; + disconnect(): void; + connect(): JQueryPromise; + } + + interface HubOptions { + /** + * Collection of client side callbacks + */ + listeners?: { [index: string] : (...args: any[]) => void }; + + /** + * String array of server side methods which the client can call + */ + methods?: Array; + + /** + * Sets the root path for the SignalR web service + */ + rootPath?: string; + + /** + * Object representing additional query params to be sent on connection + */ + queryParams?: { [index: string] : string }; + + /** + * Function to handle hub connection errors + */ + errorHandler?: (error: string) => void; + + /** + * Enable/disable logging + */ + logging?: boolean; + + /** + * Use a shared global connection or create a new one just for this hub, defaults to true + */ + useSharedConnection?: boolean; + + /** + * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) + */ + transport?: any; + + /** + * Function to handle hub connection state changed event + */ + stateChanged?: (state: SignalRStateChange) => void; + } +} \ No newline at end of file From 8aeb330d26eb2e34dc8a0891d8587b1754ee15aa Mon Sep 17 00:00:00 2001 From: Adam Santaniello Date: Fri, 7 Aug 2015 11:02:31 -0400 Subject: [PATCH 141/309] Fixed tabbing issues. --- angular-signalr-hub/angular-signalr-hub-tests.ts | 6 +++--- angular-signalr-hub/angular-signalr-hub.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index e2644bd1d0..db1b19b7eb 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -32,9 +32,9 @@ module ngSignalrTest { methods: ['lock', 'unlock'], // query params sent on initial connection - queryParams:{ - 'token': 'exampletoken' - }, + queryParams:{ + 'token': 'exampletoken' + }, // handle connection error errorHandler: (message: string) => { diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts index 6fc956b342..cdd97299cd 100644 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -28,7 +28,7 @@ declare module ngSignalr { /** * Collection of client side callbacks */ - listeners?: { [index: string] : (...args: any[]) => void }; + listeners?: { [index: string] : (...args: any[]) => void }; /** * String array of server side methods which the client can call From 1fa1d659c75c18349e60c2eebdafd2eba4a6f976 Mon Sep 17 00:00:00 2001 From: Adam Santaniello Date: Fri, 7 Aug 2015 11:08:42 -0400 Subject: [PATCH 142/309] Changed tabs to spaces --- .../angular-signalr-hub-tests.ts | 140 +++++++++--------- angular-signalr-hub/angular-signalr-hub.d.ts | 128 ++++++++-------- 2 files changed, 134 insertions(+), 134 deletions(-) diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index db1b19b7eb..61b9a7fb9d 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -2,76 +2,76 @@ /// angular - .module('app', ['SignalR']) - .factory('Employees', ngSignalrTest.EmployeesFactory); + .module('app', ['SignalR']) + .factory('Employees', ngSignalrTest.EmployeesFactory); module ngSignalrTest { - export class EmployeesFactory { - static $inject = ['$rootScope', 'Hub', '$timeout']; - private hub: ngSignalr.Hub; - public all: Array; - - constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) { - // declaring the hub connection - this.hub = new Hub('employee', { - // client-side methods - listeners: { - 'lockEmployee': (id: number) => { - var employee = this.find(id); - employee.Locked = true; - $rootScope.$apply(); - }, - 'unlockEmployee': (id: number) => { - var employee = this.find(id); - employee.Locked = false; - $rootScope.$apply(); - } - }, - - // server-side methods - methods: ['lock', 'unlock'], - - // query params sent on initial connection - queryParams:{ - 'token': 'exampletoken' - }, - - // handle connection error - errorHandler: (message: string) => { - console.error(message); - }, - - stateChanged: (state: SignalRStateChange) => { - // your code here - } - }); - } - - private find(id: number) { - for (var i = 0; i < this.all.length; i++) { - if (this.all[i].Id === id) return this.all[i]; - } - - return null; - } - - public edit = (employee: Employee) => { - employee.Edit = true; - this.hub.invoke('lock', employee.Id); - }; - - public done = (employee: Employee) => { - employee.Edit = false; - this.hub.invoke('unlock', employee.Id); - } - } - - interface Employee { - Id: number; - Name: string; - Email: string; - Salary: number; - Edit: boolean; - Locked: boolean; - } + export class EmployeesFactory { + static $inject = ['$rootScope', 'Hub', '$timeout']; + private hub: ngSignalr.Hub; + public all: Array; + + constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) { + // declaring the hub connection + this.hub = new Hub('employee', { + // client-side methods + listeners: { + 'lockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = true; + $rootScope.$apply(); + }, + 'unlockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = false; + $rootScope.$apply(); + } + }, + + // server-side methods + methods: ['lock', 'unlock'], + + // query params sent on initial connection + queryParams:{ + 'token': 'exampletoken' + }, + + // handle connection error + errorHandler: (message: string) => { + console.error(message); + }, + + stateChanged: (state: SignalRStateChange) => { + // your code here + } + }); + } + + private find(id: number) { + for (var i = 0; i < this.all.length; i++) { + if (this.all[i].Id === id) return this.all[i]; + } + + return null; + } + + public edit = (employee: Employee) => { + employee.Edit = true; + this.hub.invoke('lock', employee.Id); + }; + + public done = (employee: Employee) => { + employee.Edit = false; + this.hub.invoke('unlock', employee.Id); + } + } + + interface Employee { + Id: number; + Name: string; + Email: string; + Salary: number; + Edit: boolean; + Locked: boolean; + } } \ No newline at end of file diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts index cdd97299cd..d1213cdf6a 100644 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -6,68 +6,68 @@ /// declare module ngSignalr { - interface HubFactory { - /** - * Creates a new Hub connection - */ - new(hubName: string, options: HubOptions) : Hub - } - - class Hub { - hubName: string; - connection: SignalR; - proxy: HubProxy; - - on(event: string, fn: ((...args: any[]) => void)): void; - invoke(method: string, ...args: any[]): JQueryDeferred; - disconnect(): void; - connect(): JQueryPromise; - } - - interface HubOptions { - /** - * Collection of client side callbacks - */ - listeners?: { [index: string] : (...args: any[]) => void }; - - /** - * String array of server side methods which the client can call - */ - methods?: Array; - - /** - * Sets the root path for the SignalR web service - */ - rootPath?: string; - - /** - * Object representing additional query params to be sent on connection - */ - queryParams?: { [index: string] : string }; - - /** - * Function to handle hub connection errors - */ - errorHandler?: (error: string) => void; - - /** - * Enable/disable logging - */ - logging?: boolean; - - /** - * Use a shared global connection or create a new one just for this hub, defaults to true - */ - useSharedConnection?: boolean; - - /** - * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) - */ - transport?: any; - - /** - * Function to handle hub connection state changed event - */ - stateChanged?: (state: SignalRStateChange) => void; - } + interface HubFactory { + /** + * Creates a new Hub connection + */ + new(hubName: string, options: HubOptions) : Hub + } + + class Hub { + hubName: string; + connection: SignalR; + proxy: HubProxy; + + on(event: string, fn: ((...args: any[]) => void)): void; + invoke(method: string, ...args: any[]): JQueryDeferred; + disconnect(): void; + connect(): JQueryPromise; + } + + interface HubOptions { + /** + * Collection of client side callbacks + */ + listeners?: { [index: string] : (...args: any[]) => void }; + + /** + * String array of server side methods which the client can call + */ + methods?: Array; + + /** + * Sets the root path for the SignalR web service + */ + rootPath?: string; + + /** + * Object representing additional query params to be sent on connection + */ + queryParams?: { [index: string] : string }; + + /** + * Function to handle hub connection errors + */ + errorHandler?: (error: string) => void; + + /** + * Enable/disable logging + */ + logging?: boolean; + + /** + * Use a shared global connection or create a new one just for this hub, defaults to true + */ + useSharedConnection?: boolean; + + /** + * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) + */ + transport?: any; + + /** + * Function to handle hub connection state changed event + */ + stateChanged?: (state: SignalRStateChange) => void; + } } \ No newline at end of file From 5ecb5253815b7917e62cab4eee3a7b8f16372d7c Mon Sep 17 00:00:00 2001 From: Adam Santaniello Date: Fri, 7 Aug 2015 11:17:18 -0400 Subject: [PATCH 143/309] Updated to 4-space indentation per contribution guidelines --- .../angular-signalr-hub-tests.ts | 130 +++++++++--------- angular-signalr-hub/angular-signalr-hub.d.ts | 124 ++++++++--------- 2 files changed, 127 insertions(+), 127 deletions(-) diff --git a/angular-signalr-hub/angular-signalr-hub-tests.ts b/angular-signalr-hub/angular-signalr-hub-tests.ts index 61b9a7fb9d..b46ff63ac7 100644 --- a/angular-signalr-hub/angular-signalr-hub-tests.ts +++ b/angular-signalr-hub/angular-signalr-hub-tests.ts @@ -2,76 +2,76 @@ /// angular - .module('app', ['SignalR']) - .factory('Employees', ngSignalrTest.EmployeesFactory); + .module('app', ['SignalR']) + .factory('Employees', ngSignalrTest.EmployeesFactory); module ngSignalrTest { - export class EmployeesFactory { - static $inject = ['$rootScope', 'Hub', '$timeout']; - private hub: ngSignalr.Hub; - public all: Array; - - constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) { - // declaring the hub connection - this.hub = new Hub('employee', { - // client-side methods - listeners: { - 'lockEmployee': (id: number) => { - var employee = this.find(id); - employee.Locked = true; - $rootScope.$apply(); - }, - 'unlockEmployee': (id: number) => { - var employee = this.find(id); - employee.Locked = false; - $rootScope.$apply(); - } - }, + export class EmployeesFactory { + static $inject = ['$rootScope', 'Hub', '$timeout']; + private hub: ngSignalr.Hub; + public all: Array; - // server-side methods - methods: ['lock', 'unlock'], - - // query params sent on initial connection - queryParams:{ - 'token': 'exampletoken' - }, - - // handle connection error - errorHandler: (message: string) => { - console.error(message); - }, - - stateChanged: (state: SignalRStateChange) => { - // your code here + constructor($rootScope: ng.IRootScopeService, Hub: ngSignalr.HubFactory, $timeout: ng.ITimeoutService) { + // declaring the hub connection + this.hub = new Hub('employee', { + // client-side methods + listeners: { + 'lockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = true; + $rootScope.$apply(); + }, + 'unlockEmployee': (id: number) => { + var employee = this.find(id); + employee.Locked = false; + $rootScope.$apply(); + } + }, + + // server-side methods + methods: ['lock', 'unlock'], + + // query params sent on initial connection + queryParams:{ + 'token': 'exampletoken' + }, + + // handle connection error + errorHandler: (message: string) => { + console.error(message); + }, + + stateChanged: (state: SignalRStateChange) => { + // your code here + } + }); + } + + private find(id: number) { + for (var i = 0; i < this.all.length; i++) { + if (this.all[i].Id === id) return this.all[i]; + } + + return null; + } + + public edit = (employee: Employee) => { + employee.Edit = true; + this.hub.invoke('lock', employee.Id); + }; + + public done = (employee: Employee) => { + employee.Edit = false; + this.hub.invoke('unlock', employee.Id); } - }); } - private find(id: number) { - for (var i = 0; i < this.all.length; i++) { - if (this.all[i].Id === id) return this.all[i]; - } - - return null; + interface Employee { + Id: number; + Name: string; + Email: string; + Salary: number; + Edit: boolean; + Locked: boolean; } - - public edit = (employee: Employee) => { - employee.Edit = true; - this.hub.invoke('lock', employee.Id); - }; - - public done = (employee: Employee) => { - employee.Edit = false; - this.hub.invoke('unlock', employee.Id); - } - } - - interface Employee { - Id: number; - Name: string; - Email: string; - Salary: number; - Edit: boolean; - Locked: boolean; - } } \ No newline at end of file diff --git a/angular-signalr-hub/angular-signalr-hub.d.ts b/angular-signalr-hub/angular-signalr-hub.d.ts index d1213cdf6a..1edae69c7a 100644 --- a/angular-signalr-hub/angular-signalr-hub.d.ts +++ b/angular-signalr-hub/angular-signalr-hub.d.ts @@ -6,68 +6,68 @@ /// declare module ngSignalr { - interface HubFactory { - /** - * Creates a new Hub connection - */ - new(hubName: string, options: HubOptions) : Hub - } - - class Hub { - hubName: string; - connection: SignalR; - proxy: HubProxy; + interface HubFactory { + /** + * Creates a new Hub connection + */ + new(hubName: string, options: HubOptions) : Hub + } - on(event: string, fn: ((...args: any[]) => void)): void; - invoke(method: string, ...args: any[]): JQueryDeferred; - disconnect(): void; - connect(): JQueryPromise; - } - - interface HubOptions { - /** - * Collection of client side callbacks - */ - listeners?: { [index: string] : (...args: any[]) => void }; + class Hub { + hubName: string; + connection: SignalR; + proxy: HubProxy; + + on(event: string, fn: ((...args: any[]) => void)): void; + invoke(method: string, ...args: any[]): JQueryDeferred; + disconnect(): void; + connect(): JQueryPromise; + } - /** - * String array of server side methods which the client can call - */ - methods?: Array; - - /** - * Sets the root path for the SignalR web service - */ - rootPath?: string; - - /** - * Object representing additional query params to be sent on connection - */ - queryParams?: { [index: string] : string }; - - /** - * Function to handle hub connection errors - */ - errorHandler?: (error: string) => void; - - /** - * Enable/disable logging - */ - logging?: boolean; - - /** - * Use a shared global connection or create a new one just for this hub, defaults to true - */ - useSharedConnection?: boolean; - - /** - * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) - */ - transport?: any; - - /** - * Function to handle hub connection state changed event - */ - stateChanged?: (state: SignalRStateChange) => void; - } + interface HubOptions { + /** + * Collection of client side callbacks + */ + listeners?: { [index: string] : (...args: any[]) => void }; + + /** + * String array of server side methods which the client can call + */ + methods?: Array; + + /** + * Sets the root path for the SignalR web service + */ + rootPath?: string; + + /** + * Object representing additional query params to be sent on connection + */ + queryParams?: { [index: string] : string }; + + /** + * Function to handle hub connection errors + */ + errorHandler?: (error: string) => void; + + /** + * Enable/disable logging + */ + logging?: boolean; + + /** + * Use a shared global connection or create a new one just for this hub, defaults to true + */ + useSharedConnection?: boolean; + + /** + * Sets transport method (e.g 'longPolling' or ['webSockets', 'longPolling'] ) + */ + transport?: any; + + /** + * Function to handle hub connection state changed event + */ + stateChanged?: (state: SignalRStateChange) => void; + } } \ No newline at end of file From bfa960ba203e50b5f58ae9606c20905d5e419994 Mon Sep 17 00:00:00 2001 From: Deryl Rodrigues Date: Fri, 7 Aug 2015 11:35:31 -0400 Subject: [PATCH 144/309] Changed the value type to any in order to support Nested Objects --- 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 ab4c1db5f5..e4f69c688b 100644 --- a/angular-translate/angular-translate.d.ts +++ b/angular-translate/angular-translate.d.ts @@ -13,7 +13,7 @@ declare module "angular-translate" { declare module angular.translate { interface ITranslationTable { - [key: string]: string; + [key: string]: any; } interface ILanguageKeyAlias { From a95ee80de0d4a56b7c5fc82ca19145fc239e76f4 Mon Sep 17 00:00:00 2001 From: Jeremy Elbourn Date: Fri, 7 Aug 2015 10:11:46 -0700 Subject: [PATCH 145/309] Update angular2 d.ts to alpha34 --- angular2/angular2-2.0.0-alpha.34.d.ts | 6564 +++++++++++++++++++++++++ angular2/angular2.d.ts | 568 ++- angular2/router-2.0.0-alpha.34.d.ts | 469 ++ angular2/router.d.ts | 372 +- 4 files changed, 7635 insertions(+), 338 deletions(-) create mode 100644 angular2/angular2-2.0.0-alpha.34.d.ts create mode 100644 angular2/router-2.0.0-alpha.34.d.ts diff --git a/angular2/angular2-2.0.0-alpha.34.d.ts b/angular2/angular2-2.0.0-alpha.34.d.ts new file mode 100644 index 0000000000..aa3b6b6f4a --- /dev/null +++ b/angular2/angular2-2.0.0-alpha.34.d.ts @@ -0,0 +1,6564 @@ +// Type definitions for Angular v2.0.0-alpha.34 +// 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 { + // 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 `bindings` and `viewBindings`. + * + * 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', + * viewBindings: [ + * Greeter + * ] + * }) + * @View({ + * template: ``, + * directives: [NeedsGreeter] + * }) + * class HelloWorld { + * } + * + * ``` + */ + viewBindings: 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 + * - `@Host() directive:DirectiveType`: any directive that matches the type between the current + * element and the + * Shadow DOM root. + * - `@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 current element, the + * parent element, or its parents. + * ``` + * @Directive({ selector: '[my-directive]' }) + * class MyDirective { + * constructor(@Host() dependency: Dependency) { + * expect(dependency.id).toEqual(2); + * } + * } + * ``` + * + * `@Host` checks the current element, 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 `