From ee872c633411d2524cafc68d339f016acbfa1fd6 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Sun, 14 Sep 2014 00:08:00 +0300 Subject: [PATCH 01/53] 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 02/53] 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 03/53] 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 04/53] 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 6befcf5e84a99dcee756f5f304c3e003683e7f8e Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:51:07 -0400 Subject: [PATCH 05/53] MediaStream typings --- webrtc/MediaStream.d.ts | 308 +++++++++++++++++++++------------------- 1 file changed, 165 insertions(+), 143 deletions(-) diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 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 ConstrainBooleanParameters { + exact: boolean; + ideal: boolean; +} + +interface NumberRange { + max: number; + min: number; +} + +interface ConstrainNumberRange extends NumberRange { + exact: number; + ideal: number; +} + +interface ConstrainStringParameters { + exact: string | string[]; + ideal: string | string[]; +} + interface MediaStreamConstraints { - audio: any; - video: any; + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; } -declare var MediaStreamConstraints: { - prototype: MediaStreamConstraints; - new (): MediaStreamConstraints; -}; interface MediaTrackConstraints { - mandatory: MediaTrackConstraintSet; - optional: MediaTrackConstraint[]; + advanced: MediaTrackConstraintSet[]; +} + +declare module W3C { + type LongRange = NumberRange; + type DoubleRange = NumberRange; + type ConstrainBoolean = boolean | ConstrainBooleanParameters; + type ConstrainNumber = number | ConstrainNumberRange; + type ConstrainLong = ConstrainNumber; + type ConstrainDouble = ConstrainNumber; + type ConstrainString = string | string[] | ConstrainStringParameters; } -declare var MediaTrackConstraints: { - prototype: MediaTrackConstraints; - new (): MediaTrackConstraints; -}; -// ks - Not defined in the source doc. interface MediaTrackConstraintSet { + width: W3C.ConstrainLong; + height: W3C.ConstrainLong; + aspectRatio: W3C.ConstrainDouble; + frameRate: W3C.ConstrainDouble; + facingMode: W3C.ConstrainString; + volume: W3C.ConstrainDouble; + sampleRate: W3C.ConstrainLong; + sampleSize: W3C.ConstrainLong; + echoCancellation: W3C.ConstrainBoolean; + latency: W3C.ConstrainDouble; + deviceId: W3C.ConstrainString; + groupId: W3C.ConstrainString; } -declare var MediaTrackConstraintSet: { - prototype: MediaTrackConstraintSet; - new (): MediaTrackConstraintSet; -}; -// ks - Not defined in the source doc. -interface MediaTrackConstraint { +interface MediaTrackSupportedConstraints { + width: boolean; + height: boolean; + aspectRatio: boolean; + frameRate: boolean; + facingMode: boolean; + volume: boolean; + sampleRate: boolean; + sampleSize: boolean; + echoCancellation: boolean; + latency: boolean; + deviceId: boolean; + groupId: boolean; +} + +interface MediaStream extends EventTarget { + id: string; + active: boolean; + + onactive: EventListener; + oninactive: EventListener; + onaddtrack: (event: MediaStreamTrackEvent) => any; + onremovetrack: (event: MediaStreamTrackEvent) => any; + + clone(): MediaStream; + stop(): void; + + getAudioTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + getTracks(): MediaStreamTrack[]; + + getTrackById(trackId: string): MediaStreamTrack; + + addTrack(track: MediaStreamTrack): void; + removeTrack(track: MediaStreamTrack): void; +} + +interface MediaStreamTrackEvent extends Event { + track: MediaStreamTrack; +} + +interface MediaStreamTrack extends EventTarget { + id: string; + kind: string; + label: string; + enabled: boolean; + muted: boolean; + remote: boolean; + readyState: string; + + onmute: EventListener; + onunmute: EventListener; + onended: EventListener; + onoverconstrained: EventListener; + + clone(): MediaStreamTrack; + + stop(): void; + + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + applyConstraints(constraints: MediaTrackConstraints): Promise; +} + +interface MediaTrackCapabilities { + width: number | W3C.LongRange; + height: number | W3C.LongRange; + aspectRatio: number | W3C.DoubleRange; + frameRate: number | W3C.DoubleRange; + facingMode: string; + volume: number | W3C.DoubleRange; + sampleRate: number | W3C.LongRange; + sampleSize: number | W3C.LongRange; + echoCancellation: boolean[]; + latency: number | W3C.DoubleRange; + deviceId: string; + groupId: string; +} + +interface MediaTrackSettings { + width: number; + height: number; + aspectRatio: number; + frameRate: number; + facingMode: string; + volume: number; + sampleRate: number; + sampleSize: number; + echoCancellation: boolean; + latency: number; + deviceId: string; + groupId: string; +} + +interface MediaStreamError { + name: string; + message: string; + constraintName: string; +} + +interface NavigatorGetUserMedia { + (constraints: MediaStreamConstraints, + successCallback: (stream: MediaStream) => void, + errorCallback: (error: MediaStreamError) => void): void; } -declare var MediaTrackConstraint: { - prototype: MediaTrackConstraint; - new (): MediaTrackConstraints; -}; interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void) : void; - webkitGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; - mozGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; + getUserMedia: NavigatorGetUserMedia; + + webkitGetUserMedia: NavigatorGetUserMedia; + + mozGetUserMedia: NavigatorGetUserMedia; + + msGetUserMedia: NavigatorGetUserMedia; + + mediaDevices: MediaDevices; } -interface EventHandler { (event: Event): void; } - -interface NavigatorUserMediaSuccessCallback { - (stream: LocalMediaStream): void; +interface MediaDevices { + getSupportedConstraints(): MediaTrackSupportedConstraints; + + getUserMedia(constraints: MediaStreamConstraints): Promise; } - -interface NavigatorUserMediaError { - PERMISSION_DENIED: number; // = 1; - code: number; -} -declare var NavigatorUserMediaError: { - prototype: NavigatorUserMediaError; - new (): NavigatorUserMediaError; - PERMISSION_DENIED: number; // = 1; -}; - -interface NavigatorUserMediaErrorCallback { - (error: NavigatorUserMediaError): void; -} - -interface MediaStreamTrackList { - length: number; - item: MediaStreamTrack; - add(track: MediaStreamTrack): void; - remove(track: MediaStreamTrack): void; - onaddtrack: (event: Event) => void; - onremovetrack: (event: Event) => void; -} -declare var MediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; -declare var webkitMediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; - -interface MediaStream extends EventTarget{ - label: string; - id: string; - getAudioTracks(): MediaStreamTrackList; - getVideoTracks(): MediaStreamTrackList; - ended: boolean; - onended: (event: Event) => void; -} -declare var MediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; -declare var webkitMediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; - -// an - not defined in source doc. -interface SourceInfo { - label: string; - id: string; - kind: string; - facing: string; -} -declare var SourceInfo: { - prototype: SourceInfo; -}; - -interface LocalMediaStream extends MediaStream { - stop(): void; -} - -interface MediaStreamTrack extends EventTarget{ - kind: string; - label: string; - enabled: boolean; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - readyState: number; - onmute: (event: Event) => void; - onunmute: (event: Event) => void; - onended: (event: Event) => void; -} -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new (): MediaStreamTrack; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - getSources: (callback: (sources: SourceInfo[]) => void) => void; -}; - -interface streamURL extends URL { - createObjectURL(stream: MediaStream): string; -} -//declare var URL: { -// prototype: MediaStreamTrack; -// new (): URL; -// createObjectURL(stream: MediaStream): string; -//} - -interface WebkitURL extends streamURL { -} -declare var webkitURL: { - prototype: WebkitURL; - new (): streamURL; - createObjectURL(stream: MediaStream): string; -}; From 35e40c5d8500681f7d05c9aef81ad50f9e043c85 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:52:58 -0400 Subject: [PATCH 06/53] 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 07/53] 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 08/53] 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 09/53] 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 b8130a65bc3284dd1ac1cde827370771b35dc6ee Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 11:52:32 +0200 Subject: [PATCH 10/53] 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 11/53] 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 12/53] 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 13/53] 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 2ee0d57fae6bb5a7a298a563da13233bb59f5fdf Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Fri, 31 Jul 2015 14:46:55 -0600 Subject: [PATCH 14/53] 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 f4442b0842860cc6eec384b5e21e5cc478aac554 Mon Sep 17 00:00:00 2001 From: Matija Grcic Date: Tue, 4 Aug 2015 16:16:58 +0100 Subject: [PATCH 15/53] 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 9522b37f7e4f5625f31db4006e4c54efc449041a Mon Sep 17 00:00:00 2001 From: Austen Talbot Date: Wed, 5 Aug 2015 12:21:02 -0700 Subject: [PATCH 16/53] 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 17/53] 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 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 18/53] 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 00c2478e989faab63b7f862ce385ec1989895d3e Mon Sep 17 00:00:00 2001 From: Matthias Hild Date: Thu, 6 Aug 2015 19:02:28 -0400 Subject: [PATCH 19/53] 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 78313e98077d742a6a441b609f148546e17b210a Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 8 Aug 2015 17:32:20 +0300 Subject: [PATCH 20/53] Updated iso8601-localizer type definitions to suit v1.2.0 --- iso8601-localizer/iso8601-localizer-tests.ts | 2 ++ iso8601-localizer/iso8601-localizer.d.ts | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/iso8601-localizer/iso8601-localizer-tests.ts b/iso8601-localizer/iso8601-localizer-tests.ts index 592799388d..d532d7af01 100644 --- a/iso8601-localizer/iso8601-localizer-tests.ts +++ b/iso8601-localizer/iso8601-localizer-tests.ts @@ -3,3 +3,5 @@ new ISO8601Localizer('2015-06-02T14:13:12').localize(); new ISO8601Localizer('2015-06-02T14:13:12').to(-5).localize(); + +new ISO8601Localizer('2015-06-02T14:13:12').to(-5).returnAs('object').localize(); diff --git a/iso8601-localizer/iso8601-localizer.d.ts b/iso8601-localizer/iso8601-localizer.d.ts index 0fdc1b4cb6..7d7c526261 100644 --- a/iso8601-localizer/iso8601-localizer.d.ts +++ b/iso8601-localizer/iso8601-localizer.d.ts @@ -1,15 +1,17 @@ -// Type definitions for ISO8601-Localizer v1.0.5 +// Type definitions for ISO8601-Localizer v1.2.0 // Project: https://github.com/avielfedida/ISO8601-Localizer // Definitions by: Aviel Fedida // Definitions: https://github.com/borisyankov/DefinitelyTyped interface localizer { to(offset: number): localizer, + returnAs(as: string): localizer; localize(): string; } declare class ISO8601Localizer implements localizer { constructor(userISO8601: string); to(offset: number): localizer; + returnAs(as: string): localizer; localize(): string; } From 2657762049b5ed25162db0ac0b08018deacb7d31 Mon Sep 17 00:00:00 2001 From: sourcebits-robertbiggs Date: Sat, 8 Aug 2015 08:08:39 -0700 Subject: [PATCH 21/53] Updated ChUI to version 3.9.0 types. --- chui/chui-tests.ts | 10 +- chui/chui.d.ts | 1649 +++++++++++++++++++++++++------------------- 2 files changed, 938 insertions(+), 721 deletions(-) diff --git a/chui/chui-tests.ts b/chui/chui-tests.ts index ce24f36815..98070b4333 100644 --- a/chui/chui-tests.ts +++ b/chui/chui-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// $(function() { @@ -7,10 +7,10 @@ $(function() { * Test static methods: */ var concatenatedText = $.concat("This", "is", "text", "to", "contatenate."); - $.forEach([1,2,3], function(ctx) { + $.forEach([1,2,3], function(ctx: number) { return ctx; }); - $.forEach([1,2,3], function(ctx, idx) { + $.forEach([1,2,3], function(ctx: number, idx: number) { return idx; }); @@ -53,13 +53,13 @@ $(function() { $.UISheet({id: "mySheet", listClass: "specialList", background: 'red', handle: false}); $.UIShowSheet("#mySheet"); $.UIHideSheet(); - $.UISlideout({position: "right", dynamic: false, callback: $.noop}); + $.UISlideout({dynamic: false, callback: $.noop}); var myStepper = $('#myStepper'); $.UIResetStepper(myStepper); $.UICreateSwitch({id: "mySwitch", value: 5, checked: "true", callback: $.noop}); $.UITabbar({ tabs: 3, labels: ["one", "two", "three"], selected: 2 }); $.UISearch({ articleId: "#main", placeholder: "Looking?", results: 10 }); - var carouselPanels = $('li'); + var carouselPanels = $("
  • 1
  • 2
  • 3
  • "); $.UISetupCarousel({target: "#carousel", panels: carouselPanels}); $.UIBindData(); $.UIBindData("#myBoundData"); diff --git a/chui/chui.d.ts b/chui/chui.d.ts index 614b9bb8bb..2f68ae4540 100644 --- a/chui/chui.d.ts +++ b/chui/chui.d.ts @@ -1,14 +1,16 @@ -// Type definitions for chui v3.8.10 +// Type definitions for chui v3.9.0 // Project: https://github.com/chocolatechipui/chocolatechip-ui // Definitions by: Robert Biggs // Definitions: https://github.com/borisyankov/DefinitelyTyped +// ChocolateChip-UI 3.9.0 /** - These TypeScript delcarations for ChocolateChip-UI contain interfaces for both jQuery and ChocolateChipJS. Depending on which library you are using, you will get the type interfaces appropriate for it. + These TypeScript delcarations for ChocolateChip-UI contain interfaces for both ChocolateChipJS and jQuery. Depending on which library you are using, you will get the type interfaces appropriate for it. */ + /** * Interface for ChocolateChipJS. */ -interface ChocolateChipStatic extends ChuiDetectors { +interface ChocolateChipStatic { /** * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. * @@ -16,18 +18,15 @@ interface ChocolateChipStatic extends ChuiDetectors { * @return string */ concat(...string: string[]): string; - - + /** - * This function replicates normal array iteration with the context first, followed by the index. - * Usage: $.forEach([1,2,3], function(ctx, idx) { console.log(ctx + "is: " + (idx + 1)) }); - * - * @param obj An array-like object. This will usually be an array of HTML elements. - * @param callback A callback to execute with each iteration of the object. - * @param args Any extra arguments you wish to pass. - * @return void + * The method will iterate over an array. + * + * @param obj An iterable object. + * @param callback A callback to execute on each loop. + * @param args Any arguments you need to pass to the callback. */ - forEach(obj: T[], callback: (ctx: T, idx?: number) => any, args?: any): any; + forEach(obj: Array, callback: Function, args?: any): any; /** * Alias for cross-platform events: pointerdown, MSPointerDown, touchstart and mousedown. @@ -49,21 +48,39 @@ interface ChocolateChipStatic extends ChuiDetectors { */ eventCancel: ChUIEventInterface; + /** + * Whether browser is Microsoft Edge or not. + */ + isIEEdge: boolean; + + /** + * Whether screen is at least 960 pixels wide. + */ + isWideScreen: boolean; + + /** + * Whether screen is at least 960 pixels wide and in portrait orientation. + */ + isWideScreenPortrait: boolean; /** * Return the version of the current browser. * - * @return string The current browser version. + * @return number Returns the current browser's version. */ browserVersion(): number; /** * Hide the navigation bar, raising up the content below it. + * + * @return void */ UIHideNavBar(): void; /** * If the navigation bar is hidden, show it, pushing down the content to make room. + * + * @return void */ UIShowNavBar(): void; @@ -76,11 +93,14 @@ interface ChocolateChipStatic extends ChuiDetectors { * Navigate to the article indicated by the provided destination ID. This enters the destination into the navigation history array. * * param destination An id for the article to navigate to. + * @return void */ UIGoToArticle(destination: string): void; /** * Go back to the previous article from whence you came. This resets the navigation history array. + * + * @return void */ UIGoBack(): void; @@ -90,14 +110,17 @@ interface ChocolateChipStatic extends ChuiDetectors { UIGoBackToArticle(articleID: string): void; /** - * Display a transparent screen over the UI. This takes an optional, decimal-based number for opacity: .5 for 50%. + * Display a transparent screen over the UI. * * @param opacity The percentage of opacity for the screen. + * @return void */ UIBlock(opacity?: number): void; /** * Remove the transparent screen covering the UI. + * + * @return void */ UIUnblock(): void; @@ -107,17 +130,32 @@ interface ChocolateChipStatic extends ChuiDetectors { * * param options UIPopupOptions */ - UIPopup(options: UIPopupOptions): void; + UIPopup(options?: { + id?: string; + title?: string; + message?: string; + cancelButton?: string; + continueButton?: string; + callback?: Function; + empty?: boolean; + }): void; /** * Create and show a Popover. Options: {id: "#myPopover", title: "Whatever", callback: function() {console.log('Blah!');}}. * * param options UIPopoverOptions + * @return void */ - UIPopover(options: UIPopoverOptions): void; + UIPopover(options?: { + id?: string; + callback?: Function; + title?: string; + }): void; /** * Close any currently visible popovers. + * + * @return void */ UIPopoverClose(): void; @@ -126,26 +164,44 @@ interface ChocolateChipStatic extends ChuiDetectors { * * param: options UICreateSegmentedOptions */ - UICreateSegmented(options: UICreateSegmentedOptions): ChocolateChipElementArray; + UICreateSegmented(options?: { + id?: string; + className?: string; + labels?: string[]; + selected?: number + }): ChocolateChipElementArray; /** * Initialize a horiontal or vertical paging control. This uses a segmented control in the navigation bar with a class * like "segmented paging horizontal" or "segmented paging vertical". It uses a single article with multiple sections to paginate. + * + * @return void */ UIPaging(): void; /** * Creates a sheet. Minimum option is an id: {id : 'starTrek', listClass :'enterprise', background: 'transparent', handle: false } + * + * @return void */ - UISheet(options: UISheetOptions): void; + UISheet(options: { + id: string; + listClass?: string; + background?: string; + handle?: boolean; + }): void; /** * Show a sheet by passing this its ID. + * + * @return void */ - UIShowSheet(id?: string): void; + UIShowSheet(id: string): void; /** * Hide any currently displayed sheets. + * + * @return void */ UIHideSheet(): void; @@ -162,41 +218,91 @@ interface ChocolateChipStatic extends ChuiDetectors { /** * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} */ - UISlideout: UISlideoutInterface; + UISlideout: { + /** + * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} + * + * @return void + */ + (options?: { + dynamic?: boolean; + callback?: (args?: any) => any; + }): any; + + /** + * Populates a slideout menu. + * + * @return void + */ + populate(array: Object[]): void; + }; /** - * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. It takes a stepper element: $("#myStepper"). - * - * @param stepper A stepper to reset. + * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. + * + * @return void */ - UIResetStepper(stepper: ChocolateChipElementArray): void; + UIResetStepper(stepper: HTMLElement[]): void; /** * Create a switch control. Possible options: { id: '#myId', name: 'fruit.mango', state: 'on', value: 'Mango', checked: 'on', style: 'traditional', callback: function() { alert('hi');}} + * + * @return void */ - UICreateSwitch(options: UICreateSwitchOptions): void; + UICreateSwitch(options?: { + id?: string; + name?: string; + state?: string; + value?: string | number; + checked?: string; + style?: string; + callback?: () => any; + }): void; /** * Creates a tabbar. On iOS this is at the bottom of the screen. On Android and Windows, it is at the top. * Options: {id: 'mySpecialTabbar', tabs: 4, labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"], icons: ["refresh", "add", "info", "downloads", "favorite"], selected: 2 } + * + * @return void */ - UITabbar(options: UITabbarOptions): void; + UITabbar(options?: { + id?: string; + tabs: number; + labels: string[]; + icons?: string[]; + selected?: number; + }): void; /** * Create a search bar for an article. Options: { articleId: '#products', id: 'productSearch', placeholder: 'Find a product', results: 5 } + * + * @return void */ - UISearch(options: UISearchOptions): void; + UISearch(options?: { + articleId?: any; + id?: string; + placeholder?: string; + results?: number; + }): void; /** * Create and initialize a swipable carousel. Options: {target : '#myCarousel', panels: ['

    stuff

    ','

    more

    '], loop: true, pagination: true } + * + * @return void */ - UISetupCarousel(options: UISetupCarouselOptions): void; + UISetupCarousel(options: { + target: any; + panels: ChocolateChipElementArray; + loop?: boolean; + pagination?: boolean; + }): void; /** * Bind the values of data-models to elements with data-controllers:

    . * You can bind a single model to its controller by providing its name as the argument: $.UIBindData('input-value'); * * @param controller A string indicating the controller whose value a model is bound to. + * @return void */ UIBindData(controller?: string): void; @@ -205,18 +311,21 @@ interface ChocolateChipStatic extends ChuiDetectors { * If you provide a controller name as the argument, only that controller will be unbound. * * @param controller A controller to unbind. + * @return void */ UIUnBindData(controller?: string): void; } /** - * Interface for ChocolateChipJS Element Array. + * Interface for ChocolateChipJS HTMLElement Array. */ interface ChocolateChipElementArray { /** * Iterate over an Array object, executing a function for each matched element. + * + * @return void */ forEach(func: (ctx: any, idx: number) => void): void; @@ -226,6 +335,7 @@ interface ChocolateChipElementArray { * if it matches the given arguments. * * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] */ iz(selector: string): ChocolateChipElementArray; @@ -234,6 +344,7 @@ interface ChocolateChipElementArray { * if it matches the given arguments. * * @param elements One or more elements to match the current set of elements against. + * @return HTMLElement[] */ iz(element: any): ChocolateChipElementArray; @@ -242,6 +353,7 @@ interface ChocolateChipElementArray { * if it does not match the given arguments. * * @param selector A string containing a selector expression to match elements against. + * @return HTMLElement[] */ iznt(selector: string): ChocolateChipElementArray; @@ -250,6 +362,7 @@ interface ChocolateChipElementArray { * if it does not match the given arguments. * * @param elements One or more elements to match the current set of elements against. + * @return HTMLElement[] */ iznt(element: any): ChocolateChipElementArray; @@ -257,32 +370,37 @@ interface 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[] */ haz(selector: string): ChocolateChipElementArray; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. * - * @param element A DOM element to match elements against. + * @param contained A DOM element to match elements against. + * @return HTMLElement[] */ - haz(element: Element): ChocolateChipElementArray; + haz(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[] */ haznt(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 element A DOM element to match elements against. + * @param contained A DOM element to match elements against. + * @return HTMLElement[] */ - haznt(element: Element): ChocolateChipElementArray; + haznt(contained: HTMLElement): ChocolateChipElementArray; /** * Return any of the matched elements that have the given class. * * @param className The class name to search for. + * @return HTMLElement[] */ hazClass(className: string): ChocolateChipElementArray; @@ -290,6 +408,7 @@ interface ChocolateChipElementArray { * Return any of the matched elements that do not have the given class. * * @param className The class name to search for. + * @return HTMLElement[] */ hazntClass(className: string): ChocolateChipElementArray; @@ -298,6 +417,7 @@ interface ChocolateChipElementArray { * Return any of the matched elements that have the given attribute. * * @param className The class name to search for. + * @return HTMLElement[] */ hazAttr(attributeName: string): ChocolateChipElementArray; @@ -305,6 +425,7 @@ interface ChocolateChipElementArray { * Return any of the matched elements that do not have the given attribute. * * @param className The class name to search for. + * @return HTMLElement[] */ hazntAttr(attributeName: string): ChocolateChipElementArray; @@ -314,6 +435,7 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -323,8 +445,9 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, handler?: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; + unbind(eventType: string | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; /** * Add a delegated event to listen for the provided event on the descendant elements. @@ -334,6 +457,7 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -344,6 +468,7 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, handler: (eventObject: Event) => any, useCapture?: boolean): ChocolateChipStatic; @@ -354,6 +479,7 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, selector: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; @@ -365,6 +491,7 @@ interface ChocolateChipElementArray { * @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 | ChUIEventInterface, selector?: any, handler?: (eventObject: Event) => any, capturePhase?: boolean): ChocolateChipStatic; @@ -385,49 +512,89 @@ interface ChocolateChipElementArray { * @param color The color for the busy indicator: "#ff0000". * @param position Optional positioning, such as "align-flush". * @param duration The time for the busy indicator to display: "500ms". + * @return void */ - UIBusy(options: UIBusyOptions): void; + UIBusy(options?: { + size?: string; + color?: string; + position?: string | boolean; + duration?: string; + }): void; /** * Close the currently displayed Popup. This is executed on the popup: $('#myPopup').UIPopupClose(). + * + * @return void */ UIPopupClose(): void; /** * Initialize a segmented control. Options: {selected: 2, callback: function() {console.log('Blah');}} + * + * @return void */ - UISegmented(options: UISegmentedOptions): void; + UISegmented(options?: { + selected?: number; + callback?: Function; + }): void; /** * This method allows the user to use a segmented control to toggle a set of panels. It is executed on the segmented control. * The options id is the contain of the panels. The options callback is to execute when the user toggles a panel. + * + * @return void */ UIPanelToggle(panelsContainer: string, callback: () => any): void; /** * Make a list editable. This can be enabling changing the order of list items, or deleting them, or both. Options: {editLabel: "Edit", doneLabel: "Done", * deleteLabel: "Delete", callback: function() {alert('Bye bye!');}, deletable: true, movable: true}. + * + * @return void */ - UIEditList(options: UIEditListOptions): void; + UIEditList(options?: { + editLabel?: string; + doneLabel?: string; + deleteLabel?: string; + callback?: Function; + deletable?: boolean; + movable?: boolean; + }): void; /** * Convert a simple list into a selection list. This converts the list into a radio button group, meaning only one can be selected at any time. * You can name the radios buttons using the options name. Options: {name: "selectedNamesGroup", selected: 2, callback: function() {alert('hi');}} + * + * @return void */ - UISelectList(): void; + UISelectList(options?: { + name?: string; + selected?: number; + callback?: Function; + }): void; /** * Create a stepper control by executing it on a span with the class "stepper". Possible options: {start: 0, end: 10, defaultValue: 3}. + * + * @return void */ - UIStepper(options: UIStepperOptions): void; + UIStepper(options: { + start: number; + end: number; + defaultValue: number; + }): void; /** * Initialize any existing switch controls: $('.switch').UISwitch(); + * + * @return void */ UISwitch(): void; /** * Execute this on a range control to initialize it. + * + * @return void */ UIRange(): void; } @@ -435,8 +602,7 @@ interface ChocolateChipElementArray { /** * Interface for jQuery */ - -interface JQueryStatic extends ChuiDetectors { +interface JQueryStatic { /** * This method will concatenate strings or values as a cleaner alternative to using the '+' operator. * @@ -444,17 +610,15 @@ interface JQueryStatic extends ChuiDetectors { * @return string */ concat(...string: string[]): string; - + /** - * This function replicates normal array iteration with the context first, followed by the index. - * Usage: $.forEach([1,2,3], function(ctx, idx) { console.log(ctx + "is: " + (idx + 1)) }); - * - * @param obj An array-like object. This will usually be an array of HTML elements. - * @param callback A callback to execute with each iteration of the object. - * @param args Any extra arguments you wish to pass. - * @return void + * The method will iterate over an array. + * + * @param obj An iterable object. + * @param callback A callback to execute on each loop. + * @param args Any arguments you need to pass to the callback. */ - forEach(obj: T[], callback: (ctx: T, idx?: number) => any, args?: any): any; + forEach(obj: Array, callback: Function, args?: any): any; /** * Alias for cross-platform events: pointerdown, MSPointerDown, touchstart and mousedown. @@ -476,660 +640,6 @@ interface JQueryStatic extends ChuiDetectors { */ eventCancel: ChUIEventInterface; - /** - * Return the version of the current browser. - */ - browserVersion(): number; - - /** - * Hide the navigation bar, raising up the content below it. - */ - UIHideNavBar(): void; - - /** - * If the navigation bar is hidden, show it, pushing down the content to make room. - */ - UIShowNavBar(): void; - - /** - * Determine whether navigation is in progress or not. - */ - isNavigating: boolean; - - /** - * Navigate to the article indicated by the provided destination ID. This enters the destination into the navigation history array. - * - * param destination An id for the article to navigate to. - */ - UIGoToArticle(destination: string): void; - - /** - * Go back to the previous article from whence you came. This resets the navigation history array. - */ - UIGoBack(): void; - - /** - * Go back to the article indicated by the provided ID. This is for non-linear back navigation. This will reset the navigation history array to match the current state. - */ - UIGoBackToArticle(articleID: string): void; - - /** - * Display a transparent screen over the UI. This takes an optional, decimal-based number for opacity: .5 for 50%. - * - * @param opacity The percentage of opacity for the screen. - */ - UIBlock(opacity?: number): void; - - /** - * Remove the transparent screen covering the UI. - */ - UIUnblock(): void; - - /** - * Create and show a Popup with title and message. Possible options: {id: "#myPopup", title: "My Popup", - * message: "Woohoo!", cancelButton: "Forget It!", contiueButton: "Whatever", callback: function() {console.log('Blah!');}, empty: false }. - * - * param options UIPopupOptions - */ - UIPopup(options: UIPopupOptions): void; - - /** - * Create and show a Popover. Options: {id: "#myPopover", title: "Whatever", callback: function() {console.log('Blah!');}}. - * - * param options UIPopoverOptions - */ - UIPopover(options: UIPopoverOptions): void; - - /** - * Close any currently visible popovers. - */ - UIPopoverClose(): void; - - /** - * Create a segmented control: {id: "mySegments", className: "seggie", labels: ["one", "two","three"], selected: 1} - * - * param: options UICreateSegmentedOptions - */ - UICreateSegmented(options: UICreateSegmentedOptions): JQuery; - - /** - * Initialize a horiontal or vertical paging control. This uses a segmented control in the navigation bar with a class - * like "segmented paging horizontal" or "segmented paging vertical". It uses a single article with multiple sections to paginate. - */ - UIPaging(): void; - - /** - * Creates a sheet. Minimum option is an id: {id : 'starTrek', listClass :'enterprise', background: 'transparent', handle: false } - */ - UISheet(options: UISheetOptions): void; - - /** - * Show a sheet by passing this its ID. - */ - UIShowSheet(id: string): void; - - /** - * Hide any currently displayed sheets. - */ - UIHideSheet(): void; - - /** - * The body tag wrapped and ready to use: $.body.css('background-color','orange') - */ - body: JQuery; - - /** - * An array of the navigation history. Do not manipulate this. For examination only. This is used by navigation lists, etc. - */ - UINavigationHistory: string[]; - - /** - * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} - */ - UISlideout: UISlideoutInterface; - - /** - * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. - */ - UIResetStepper(stepper: JQuery): void; - - /** - * Create a switch control. Possible options: { id: '#myId', name: 'fruit.mango', state: 'on', value: 'Mango', checked: 'on', style: 'traditional', callback: function() { alert('hi');}} - */ - UICreateSwitch(options: UICreateSwitchOptions): void; - - /** - * Creates a tabbar. On iOS this is at the bottom of the screen. On Android and Windows, it is at the top. - * Options: {id: 'mySpecialTabbar', tabs: 4, labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"], icons: ["refresh", "add", "info", "downloads", "favorite"], selected: 2 } - */ - UITabbar(options: UITabbarOptions): void; - - /** - * Create a search bar for an article. Options: { articleId: '#products', id: 'productSearch', placeholder: 'Find a product', results: 5 } - */ - UISearch(options: UISearchOptions): void; - - /** - * Create and initialize a swipable carousel. Options: {target : '#myCarousel', panels: ['

    stuff

    ','

    more

    '], loop: true, pagination: true } - */ - UISetupCarousel(options: UISetupCarouselOptions): void; - - /** - * Bind the values of data-models to elements with data-controllers:

    . - * You can bind a single model to its controller by providing its name as the argument: $.UIBindData('input-value'); - * - * @param controller A string indicating the controller whose value a model is bound to. - */ - UIBindData(controller?: string): void; - - /** - * Unbind the values of data-models from their data-controllers. - * If you provide a controller name as the argument, only that controller will be unbound. - * - * @param controller A controller to unbind. - */ - UIUnBindData(controller?: string): void; - -} - -/** - * Interface for jQuery - */ -interface JQuery { - - /** - * Iterate over an Array object, executing a function for each matched element. - */ - //forEach(func: (ctx: any, idx: number) => void, JQuery: any): void; - forEach(callback: (ctx: Element, idx: number) => any): JQuery; - - /** - * 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. - */ - iz(selector: string): JQuery; - - /** - * 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. - */ - iz(element: any): JQuery; - - /** - * 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. - */ - iznt(selector: string): JQuery; - - /** - * 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. - */ - iznt(element: any): JQuery; - - /** - * 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. - */ - haz(selector: string): JQuery; - /** - * 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. - */ - haz(contained: Element): JQuery; - - /** - * 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. - */ - haznt(selector: string): JQuery; - /** - * 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. - */ - haznt(contained: Element): JQuery; - - /** - * Return any of the matched elements that have the given class. - * - * @param className The class name to search for. - */ - hazClass(className: string): JQuery; - - /** - * Return any of the matched elements that do not have the given class. - * - * @param className The class name to search for. - */ - hazntClass(className: string): JQuery; - - - /** - * Return any of the matched elements that have the given attribute. - * - * @param className The class name to search for. - */ - hazAttr(attributeName: string): JQuery; - - /** - * Return any of the matched elements that do not have the given attribute. - * - * @param className The class name to search for. - */ - hazntAttr(attributeName: string): JQuery; - - /** - * Center an element to the screen. - */ - UICenter(): void; - - /** - * Display a busy indicator. Posible options: {size: "100px", color: "#ff0000", position: "align-flush", duration: "2s"}. - * - * @param size The size as a string with length identifier: "40px". - * @param color The color for the busy indicator: "#ff0000". - * @param position Optional positioning, such as "align-flush". - * @param duration The time for the busy indicator to display: "500ms". - */ - UIBusy(options: UIBusyOptions): void; - - /** - * Close the currently displayed Popup. This is executed on the popup: $('#myPopup').UIPopupClose(). - */ - UIPopupClose(): void; - - /** - * Initialize a segmented control. Options: {selected: 2, callback: function() {console.log('Blah');}} - */ - UISegmented(options: UISegmentedOptions): void; - - /** - * This method allows the user to use a segmented control to toggle a set of panels. It is executed on the segmented control. - * The options id is the contain of the panels. The options callback is to execute when the user toggles a panel. - */ - UIPanelToggle(panelsContainer: string, callback: () => any): void; - - /** - * Make a list editable. This can be enabling changing the order of list items, or deleting them, or both. Options: {editLabel: "Edit", doneLabel: "Done", - * deleteLabel: "Delete", callback: function() {alert('Bye bye!');}, deletable: true, movable: true}. - */ - UIEditList(options: UIEditListOptions): void; - - /** - * Convert a simple list into a selection list. This converts the list into a radio button group, meaning only one can be selected at any time. - * You can name the radios buttons using the options name. Options: {name: "selectedNamesGroup", selected: 2, callback: function() {alert('hi');}} - */ - UISelectList(): void; - - /** - * Create a stepper control by executing it on a span with the class "stepper". Possible options: {start: 0, end: 10, defaultValue: 3}. - */ - UIStepper(options: UIStepperOptions): void; - - /** - * Initialize any existing switch controls: $('.switch').UISwitch(); - */ - UISwitch(): void; - - /** - * Execute this on a range control to initialize it. - */ - UIRange(): 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 eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - */ - bind(eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * 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. - */ - bind(eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * 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 eventData An object containing data that will be passed to the event handler. - * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string | ChUIEventInterface, eventData: any, preventBubble: boolean): JQuery; - /** - * 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 preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. - */ - bind(eventType: string | ChUIEventInterface, preventBubble: boolean): JQuery; - - - delegate(selector: any, eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; - delegate(selector: any, eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string | ChUIEventInterface, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". - * @param handler A handler function previously attached for the event(s), or the special value false. - */ - off(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). - */ - on(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string | ChUIEventInterface, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - /** - * Attach an event handler function for one or more events to the selected elements. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - on(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. - * @param data An object containing data that will be passed to the event handler. - * @param handler A function to execute at the time the event is triggered. - */ - one(events: string | ChUIEventInterface, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. - * - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. - */ - one(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; - - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters Additional parameters to pass along to the event handler. - */ - trigger(eventType: string | ChUIEventInterface, extraParameters?: any[]|Object): JQuery; - - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param extraParameters An array of additional parameters to pass along to the event handler. - */ - triggerHandler(eventType: string | ChUIEventInterface, ...extraParameters: any[]): Object; - - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param handler The function that is to be no longer executed. - */ - unbind(eventType?: string | ChUIEventInterface, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a previously-attached event handler from the elements. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). - */ - unbind(eventType: string | ChUIEventInterface, fls: boolean): JQuery; - - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute at the time the event is triggered. - */ - undelegate(selector: string | ChUIEventInterface, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; - /** - * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * - * @param selector A selector which will be used to filter the event results. - * @param events An object of one or more event types and previously bound functions to unbind from them. - */ - undelegate(selector: string | ChUIEventInterface, events: Object): JQuery; -} - -interface UISetupCarouselOptions { - target: string; - panels: HTMLElement[] | JQuery; - loop?: boolean; - pagination?: boolean; -} - -interface UISearchOptions { - articleId?: string; - id?: string; - placeholder?: string; - results?: number; -} - -interface UITabbarOptions { - id?: string; - tabs: number; - labels: string[]; - icons?: string[]; - selected?: number; -} - -interface UICreateSwitchOptions { - id?: string; - name?: string; - state?: string; - value?: string | number; - checked?: string; - style?: string; - callback?: () => any; -} - -/** - * Interface for UISlideout. - */ -interface UISlideoutInterface { - /** - * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} - */ - (options: UISlideoutOptions): void; - - /** - * Populates a slideout menu. - */ - populate(array: Object[]): void; -} - -interface UIStepperOptions { - start: number; - end: number; - defaultValue?: number; -} - -interface ChUIEventInterface { - eventStart: string; - eventEnd: string; - eventMove: string; - eventCancel: string; -} - -interface UIBusyOptions { - size?: string; - color?: string; - position?: string | boolean; - duration?: string; -} - -interface UIPopupOptions { - id?: string; - title?: string; - message?: string; - cancelButton?: string; - continueButton?: string; - callback?: Function; - empty?: boolean; -} - -interface UIPopoverOptions { - id?: string; - callback?: Function; - title?: string; -} - -interface UICreateSegmentedOptions { - id?: string; - className?: string; - labels?: string[]; - selected?: number -} - -interface UISegmentedOptions { - selected?: number; - callback?: Function; -} - -interface UIEditListOptions { - editLabel?: string; - doneLabel?: string; - deleteLabel?: string; - callback?: Function; - deletable?: boolean; - movable?: boolean; -} - -interface UISelectListOptions { - name?: string; - selected?: number; - callback?: Function; -} - -interface UISheetOptions { - id?: string; - listClass?: string; - background?: string; - handle?: boolean; -} - -interface UISlideoutOptions { - dynamic?: boolean; - callback?: Function; - position?: string; -} - - -/** - * The interface used to construct jQuery events (with $.Event). It is - * defined separately instead of inline in JQueryStatic to allow - * overriding the construction function with specific strings - * returning specific event objects. - */ -interface JQueryEventConstructor { - (name: string, eventProperties?: any): JQueryEventObject; - new (name: string, eventProperties?: any): JQueryEventObject; -} - -interface JQueryEventInterface { - Event: JQueryEventConstructor; -} - -/** - * Interface of the JQuery extension of the W3C event object - */ -interface BaseJQueryEventObject extends Event { - -} -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { -} - -/** - * Interface of the JQuery extension of the W3C event object - */ -interface BaseJQueryEventObject extends Event { - -} - -interface JQueryInputEventObject extends BaseJQueryEventObject { - -} - -interface JQueryMouseEventObject extends JQueryInputEventObject { - -} - -interface JQueryKeyEventObject extends JQueryInputEventObject { - -} - -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { -} - -/** - * Interface for detectors. - */ - interface ChuiDetectors { - /** * Whether device is iPhone. */ @@ -1180,21 +690,16 @@ interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObjec */ isStandalone: boolean; + /** + * Whether OS is iOS 6. + */ + isiOS6: boolean; + /** * Whether OS i iOS 7. */ isiOS7: boolean; - /** - * Whether OS i iOS 7. - */ - isiOS8: boolean; - - /** - * Whether OS i iOS 7. - */ - isiOS9: boolean; - /** * Whether OS is Windows. */ @@ -1258,4 +763,716 @@ interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObjec * Whether screen is at least 960 pixels wide and in portrait orientation. */ isWideScreenPortrait: boolean; - } \ No newline at end of file + + /** + * Return the version of the current browser. + */ + browserVersion(): number; + + /** + * Hide the navigation bar, raising up the content below it. + */ + UIHideNavBar(): void; + + /** + * If the navigation bar is hidden, show it, pushing down the content to make room. + */ + UIShowNavBar(): void; + + /** + * Determine whether navigation is in progress or not. + */ + isNavigating: boolean; + + /** + * Navigate to the article indicated by the provided destination ID. This enters the destination into the navigation history array. + * + * @param destination An id for the article to navigate to. + * @return void + */ + UIGoToArticle(destination: string): void; + + /** + * Go back to the previous article from whence you came. This resets the navigation history array. + * + * @return void + */ + UIGoBack(): void; + + /** + * Go back to the article indicated by the provided ID. This is for non-linear back navigation. This will reset the navigation history array to match the current state. + * + * @return void + */ + UIGoBackToArticle(articleID: string): void; + + /** + * Display a transparent screen over the UI. + * + * @param opacity The percentage of opacity for the screen. + * @return void + */ + UIBlock(opacity?: number): void; + + /** + * Remove the transparent screen covering the UI. + * + * @return void + */ + UIUnblock(): void; + + /** + * Create and show a Popup with title and message. Possible options: {id: "#myPopup", title: "My Popup", + * message: "Woohoo!", cancelButton: "Forget It!", contiueButton: "Whatever", callback: function() {console.log('Blah!');}, empty: false }. + * + * @param options UIPopupOptions + * @return void + */ + UIPopup(options?: { + id?: string; + title?: string; + message?: string; + cancelButton?: string; + continueButton?: string; + callback?: Function; + empty?: boolean; + }): void; + + /** + * Create and show a Popover. Options: {id: "#myPopover", title: "Whatever", callback: function() {console.log('Blah!');}}. + * + * @param options UIPopoverOptions + * @return void + */ + UIPopover(options?: { + id?: string; + callback?: Function; + title?: string; + }): void; + + /** + * Close any currently visible popovers. + * + * @return void + */ + UIPopoverClose(): void; + + /** + * Create a segmented control: {id: "mySegments", className: "seggie", labels: ["one", "two","three"], selected: 1} + * + * @param: options UICreateSegmentedOptions + * @return JQuery + */ + UICreateSegmented(options: { + id?: string; + className?: string; + labels?: string[]; + selected?: number + }): JQuery; + + /** + * Initialize a horiontal or vertical paging control. This uses a segmented control in the navigation bar with a class + * like "segmented paging horizontal" or "segmented paging vertical". It uses a single article with multiple sections to paginate. + * + * @return void + */ + UIPaging(): void; + + /** + * Creates a sheet. Minimum option is an id: {id : 'starTrek', listClass :'enterprise', background: 'transparent', handle: false } + * + * @return void + */ + UISheet(options: { + id: string; + listClass?: string; + background?: string; + handle?: boolean; + }): void; + + /** + * Show a sheet by passing this its ID. + * + * @return void + */ + UIShowSheet(id: string): void; + + /** + * Hide any currently displayed sheets. + * + * @return void + */ + UIHideSheet(): void; + + /** + * The body tag wrapped and ready to use: $.body.css('background-color','orange') + */ + body: JQuery; + + /** + * An array of the navigation history. Do not manipulate this. For examination only. This is used by navigation lists, etc. + */ + UINavigationHistory: string[]; + + /** + * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} + */ + UISlideout: { + /** + * Creates and initializes a slide out menu. Possible options: {dynamic: true, callback: function() { alert("Woohoo!");}} + * + * @return void + */ + (options?: { + dynamic?: boolean; + callback?: (args?: any) => any; + }): any; + + /** + * Populates a slideout menu. + * + * @return void + */ + populate(array: Object[]): void; + }; + + /** + * Reset the value of the stepper to its defaults at initialization. Pass it a reference to the stepper to reset. + * + * @return void + */ + UIResetStepper(stepper: JQuery): void; + + /** + * Create a switch control. Possible options: { id: '#myId', name: 'fruit.mango', state: 'on', value: 'Mango', checked: 'on', style: 'traditional', callback: function() { alert('hi');}} + * + * @return void + */ + UICreateSwitch(options?: { + id?: string; + name?: string; + state?: string; + value?: string | number; + checked?: string; + style?: string; + callback?: () => any; + }): void; + + /** + * Creates a tabbar. On iOS this is at the bottom of the screen. On Android and Windows, it is at the top. + * Options: {id: 'mySpecialTabbar', tabs: 4, labels: ["Refresh", "Add", "Info", "Downloads", "Favorite"], icons: ["refresh", "add", "info", "downloads", "favorite"], selected: 2 } + * + * @return void + */ + UITabbar(options?: { + id?: string; + tabs: number; + labels: string[]; + icons?: string[]; + selected?: number; + }): void; + + /** + * Create a search bar for an article. Options: { articleId: '#products', id: 'productSearch', placeholder: 'Find a product', results: 5 } + * + * @return void + */ + UISearch(options?: { + articleId?: any; + id?: string; + placeholder?: string; + results?: number; + }): void; + + /** + * Create and initialize a swipable carousel. Options: {target : '#myCarousel', panels: ['

    stuff

    ','

    more

    '], loop: true, pagination: true } + * + * @return void + */ + UISetupCarousel(options: { + target: any; + panels: JQuery; + loop?: boolean; + pagination?: boolean; + }): void; + + /** + * Bind the values of data-models to elements with data-controllers:

    . + * You can bind a single model to its controller by providing its name as the argument: $.UIBindData('input-value'); + * + * @param controller A string indicating the controller whose value a model is bound to. + * @return void + */ + UIBindData(controller?: string): void; + + /** + * Unbind the values of data-models from their data-controllers. + * If you provide a controller name as the argument, only that controller will be unbound. + * + * @param controller A controller to unbind. + * @return void + */ + UIUnBindData(controller?: string): void; + +} + +/** + * Interface for jQuery + */ +interface JQuery { + + /** + * Iterate over an Array object, executing a function for each matched element. + * + * @param callback A function to execute while looping over an interable. This takes to arguments: ctx: HTMLElement and idx: number. + * @return JQuery + */ + forEach(callback: (ctx: HTMLElement, idx: number) => any): JQuery; + + /** + * 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 JQuery + */ + iz(selector: string): JQuery; + + /** + * 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 JQuery + */ + iz(element: any): JQuery; + + /** + * 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 JQuery + */ + iznt(selector: string): JQuery; + + /** + * 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 JQuery + */ + iznt(element: any): JQuery; + + /** + * 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 JQuery + */ + haz(selector: string): JQuery; + /** + * 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 JQuery + */ + haz(contained: HTMLElement): JQuery; + + /** + * 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 JQuery + */ + haznt(selector: string): JQuery; + /** + * 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 JQuery + */ + haznt(contained: HTMLElement): JQuery; + + /** + * Return any of the matched elements that have the given class. + * + * @param className The class name to search for. + * @return JQuery + */ + hazClass(className: string): JQuery; + + /** + * Return any of the matched elements that do not have the given class. + * + * @param className The class name to search for. + * @return JQuery + */ + hazntClass(className: string): JQuery; + + + /** + * Return any of the matched elements that have the given attribute. + * + * @param className The class name to search for. + * @return JQuery + */ + hazAttr(attributeName: string): JQuery; + + /** + * Return any of the matched elements that do not have the given attribute. + * + * @param className The class name to search for. + * @return JQuery + */ + hazntAttr(attributeName: string): JQuery; + + /** + * Center an element to the screen. + * + * @return void + */ + UICenter(): void; + + /** + * Display a busy indicator. Posible options: {size: "100px", color: "#ff0000", position: "align-flush", duration: "2s"}. + * + * @param size The size as a string with length identifier: "40px". + * @param color The color for the busy indicator: "#ff0000". + * @param position Optional positioning, such as "align-flush". + * @param duration The time for the busy indicator to display: "500ms". + * @return void + */ + UIBusy(options?: { + size?: string; + color?: string; + position?: string | boolean; + duration?: string; + }): void; + + /** + * Close the currently displayed Popup. This is executed on the popup: $('#myPopup').UIPopupClose(). + * + * @return void + */ + UIPopupClose(): void; + + /** + * Initialize a segmented control. Options: {selected: 2, callback: function() {console.log('Blah');}} + * + * @return void + */ + UISegmented(options?: { + selected?: number; + callback?: Function; + }): void; + + /** + * This method allows the user to use a segmented control to toggle a set of panels. It is executed on the segmented control. + * The options id is the contain of the panels. The options callback is to execute when the user toggles a panel. + * + * @return void + */ + UIPanelToggle(panelsContainer: string, callback: () => any): void; + + /** + * Make a list editable. This can be enabling changing the order of list items, or deleting them, or both. Options: {editLabel: "Edit", doneLabel: "Done", + * deleteLabel: "Delete", callback: function() {alert('Bye bye!');}, deletable: true, movable: true}. + * + * @return void + */ + UIEditList(options?: { + editLabel?: string; + doneLabel?: string; + deleteLabel?: string; + callback?: Function; + deletable?: boolean; + movable?: boolean; + }): void; + + /** + * Convert a simple list into a selection list. This converts the list into a radio button group, meaning only one can be selected at any time. + * You can name the radios buttons using the options name. Options: {name: "selectedNamesGroup", selected: 2, callback: function() {alert('hi');}} + * + * @return void + */ + UISelectList(options?: { + name?: string; + selected?: number; + callback?: Function; + }): void; + + /** + * Create a stepper control by executing it on a span with the class "stepper". Possible options: {start: 0, end: 10, defaultValue: 3}. + * + * @return void + */ + UIStepper(options: { + start: number; + end: number; + defaultValue: number; + }): void; + + /** + * Initialize any existing switch controls: $('.switch').UISwitch(); + * + * @return void + */ + UISwitch(): void; + + /** + * Execute this on a range control to initialize it. + * + * @return void + */ + UIRange(): 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 eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * 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. + * @return JQuery + */ + bind(eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * 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 eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + * @return JQuery + */ + bind(eventType: string | ChUIEventInterface, eventData: any, preventBubble: boolean): JQuery; + /** + * 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 preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + * @return JQuery + */ + bind(eventType: string | ChUIEventInterface, preventBubble: boolean): JQuery; + + + delegate(selector: any, eventType: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string | ChUIEventInterface, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + * @return JQuery + */ + off(events: string | ChUIEventInterface, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + * @return JQuery + */ + off(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + * @return JQuery + */ + on(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + * @return JQuery + */ + on(events: string | ChUIEventInterface, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + * @return JQuery + */ + on(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + * @return JQuery + */ + on(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + * @return JQuery + */ + one(events: string | ChUIEventInterface, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + * @return JQuery + */ + one(events: string | ChUIEventInterface, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + * @return JQuery + */ + one(events: string | ChUIEventInterface, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + * @return JQuery + */ + one(events: string | ChUIEventInterface, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + * @return JQuery + */ + trigger(eventType: string | ChUIEventInterface, extraParameters?: any[]|Object): JQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + * @return Object + */ + triggerHandler(eventType: string | ChUIEventInterface, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + * @return JQuery + */ + unbind(eventType?: string | ChUIEventInterface, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + * @return JQuery + */ + unbind(eventType: string | ChUIEventInterface, fls: boolean): JQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + * @return JQuery + */ + undelegate(selector: string | ChUIEventInterface, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + * @return JQuery + */ + undelegate(selector: string | ChUIEventInterface, events: Object): JQuery; +} + +interface ChUIEventInterface { + eventStart: string; + eventEnd: string; + eventMove: string; + eventCancel: string; + tap: string; + singletap: string; + doubletap: string; + longtap: string; + swipe: string; + swipeleft: string; + swiperight: string; + swipeup: string; + swipedown: string; +} + + +/** + * The interface used to construct jQuery events (with $.Event). It is + * defined separately instead of inline in JQueryStatic to allow + * overriding the construction function with specific strings + * returning specific event objects. + */ +interface JQueryEventConstructor { + (name: string, eventProperties?: any): JQueryEventObject; + new (name: string, eventProperties?: any): JQueryEventObject; +} + +interface JQueryEventInterface { + Event: JQueryEventConstructor; +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + +} +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + +} + +interface JQueryInputEventObject extends BaseJQueryEventObject { + +} + +interface JQueryMouseEventObject extends JQueryInputEventObject { + +} + +interface JQueryKeyEventObject extends JQueryInputEventObject { + +} + +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { +} \ No newline at end of file From a71b9f23966dd988ee3d9252fa7993e968f4d26f Mon Sep 17 00:00:00 2001 From: Pascal Vomhoff Date: Sat, 8 Aug 2015 17:35:36 +0200 Subject: [PATCH 22/53] Add typings for module usage --- usage/usage-tests.ts | 19 +++++++++++++++++++ usage/usage.d.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 usage/usage-tests.ts create mode 100644 usage/usage.d.ts diff --git a/usage/usage-tests.ts b/usage/usage-tests.ts new file mode 100644 index 0000000000..af8a3b2751 --- /dev/null +++ b/usage/usage-tests.ts @@ -0,0 +1,19 @@ +/// +/// + +import usage = require('usage'); + +var pid = process.pid; +var options = { keepHistory: true }; + +usage.lookup(pid, function(err, result) { + console.log("Usage infos", result); +}); + +usage.lookup(pid, options, function (err, result) { + console.log("Usage infos with history", result); +}); + +usage.clearHistory(pid); +usage.clearHistory(); + diff --git a/usage/usage.d.ts b/usage/usage.d.ts new file mode 100644 index 0000000000..194bfcd7d8 --- /dev/null +++ b/usage/usage.d.ts @@ -0,0 +1,28 @@ +// Type definitions for usage +// Project: https://github.com/arunoda/node-usage +// Definitions by: Pascal Vomhoff +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "usage" { + + export interface ResultObject { + memory:number; + memoryInfo: { + rss:number; + vsize:number; + } + cpu:number; + } + + export interface Options { + keepHistory:boolean; + } + + export function lookup(pid:number, callback:(err:Error, result:ResultObject) => void); + export function lookup(pid:number, options:Options, callback:(err:Error, result:ResultObject) => void); + + //Only availible on linux + export function clearHistory(pid?:number); + + +} \ No newline at end of file From 6898cb77dc1fdebd16478786035a85a0bfacd68c Mon Sep 17 00:00:00 2001 From: Pascal Vomhoff Date: Sat, 8 Aug 2015 17:42:55 +0200 Subject: [PATCH 23/53] Fix return type of all functions --- usage/usage.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/usage/usage.d.ts b/usage/usage.d.ts index 194bfcd7d8..44d8c41836 100644 --- a/usage/usage.d.ts +++ b/usage/usage.d.ts @@ -18,11 +18,11 @@ declare module "usage" { keepHistory:boolean; } - export function lookup(pid:number, callback:(err:Error, result:ResultObject) => void); - export function lookup(pid:number, options:Options, callback:(err:Error, result:ResultObject) => void); + export function lookup(pid:number, callback:(err:Error, result:ResultObject) => void):void; + export function lookup(pid:number, options:Options, callback:(err:Error, result:ResultObject) => void):void; //Only availible on linux - export function clearHistory(pid?:number); + export function clearHistory(pid?:number):void; } \ No newline at end of file From a0996d4266c0cf03b65e6b63ba80cac549f3063b Mon Sep 17 00:00:00 2001 From: Sam Saint-Pettersen Date: Sat, 8 Aug 2015 17:32:33 +0100 Subject: [PATCH 24/53] Type definitions and tests for swap-case --- swap-case/swap-case-tests.ts | 10 ++++++++++ swap-case/swap-case.d.ts | 9 +++++++++ 2 files changed, 19 insertions(+) create mode 100644 swap-case/swap-case-tests.ts create mode 100644 swap-case/swap-case.d.ts diff --git a/swap-case/swap-case-tests.ts b/swap-case/swap-case-tests.ts new file mode 100644 index 0000000000..2a5e987efe --- /dev/null +++ b/swap-case/swap-case-tests.ts @@ -0,0 +1,10 @@ +/// + +import swapCase = require('swap-case'); + +console.log(swapCase(null)); // => "" +console.log(swapCase('string')); // => "STRING" +console.log(swapCase('PascalCase')); // => "pASCALcASE" +console.log(swapCase('Iñtërnâtiônàlizætiøn')); //=> "iÑTËRNÂTIÔNÀLIZÆTIØN" + +console.log(swapCase('My String', 'tr')); // => "mY sTRİNG" diff --git a/swap-case/swap-case.d.ts b/swap-case/swap-case.d.ts new file mode 100644 index 0000000000..a45aaf6503 --- /dev/null +++ b/swap-case/swap-case.d.ts @@ -0,0 +1,9 @@ +// Type definitions for swap-case +// Project: https://github.com/blakeembrey/swap-case +// Definitions by: Sam Saint-Pettersen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "swap-case" { + function swapCase(string: string, locale?: string): string; + export = swapCase; +} From e514901e942ceb125f9a80051b7bba7ca0e6bd47 Mon Sep 17 00:00:00 2001 From: Guillaume Mouron Date: Sat, 8 Aug 2015 19:55:35 +0200 Subject: [PATCH 25/53] Cheerio: Missing function definition "contents()" See api documentation : https://github.com/cheeriojs/cheerio#contents --- cheerio/cheerio.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cheerio/cheerio.d.ts b/cheerio/cheerio.d.ts index af708cf0a4..fc8e5a70ff 100644 --- a/cheerio/cheerio.d.ts +++ b/cheerio/cheerio.d.ts @@ -74,6 +74,8 @@ interface Cheerio { children(selector?: string): Cheerio; + contents(): Cheerio; + each(func: (index: number, element: CheerioElement) => any): Cheerio; map(func: (index: number, element: CheerioElement) => any): Cheerio; From 17146c4455e73a38d2564279c78a66bbaf59d12a Mon Sep 17 00:00:00 2001 From: Alex Wilson Date: Sat, 8 Aug 2015 12:54:49 -0600 Subject: [PATCH 26/53] Update node's ReadLine.setPrompt to match new API Fixes #5224 --- node/node-0.11-tests.ts | 28 +++++++++++++++++++++++----- node/node-0.11.d.ts | 2 +- node/node-tests.ts | 30 ++++++++++++++++++++++++------ node/node.d.ts | 2 +- 4 files changed, 49 insertions(+), 13 deletions(-) diff --git a/node/node-0.11-tests.ts b/node/node-0.11-tests.ts index 38bae0d572..92ce84a9d8 100644 --- a/node/node-0.11-tests.ts +++ b/node/node-0.11-tests.ts @@ -1,4 +1,4 @@ -/// +/// import assert = require("assert"); import fs = require("fs"); @@ -11,6 +11,7 @@ import http = require("http"); import net = require("net"); import dgram = require("dgram"); import querystring = require('querystring'); +import readline = require('readline'); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -71,9 +72,9 @@ url.format(url.parse('http://www.example.com/xyz')); // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', + protocol: 'https', + host: "google.com", + pathname: 'search', query: { q: "you're a lizard, gary" } }); @@ -139,5 +140,22 @@ var escaped: string = querystring.escape(original); console.log(escaped); // http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html var unescaped: string = querystring.unescape(escaped); -console.log(unescaped); +console.log(unescaped); // http://example.com/product/abcde.html + +//////////////////////////////////////////////////// +///ReadLine tests : https://nodejs.org/docs/v0.11.0/api/readline.html +//////////////////////////////////////////////////// + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +rl.setPrompt("$>"); +rl.prompt(); +rl.prompt(true); + +rl.question("do you like typescript?", function(answer: string) { + rl.close(); +}); diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index b45ba637c6..cd55bdfb1c 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -570,7 +570,7 @@ declare module "readline" { import stream = require("stream"); export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: Function): void; pause(): void; diff --git a/node/node-tests.ts b/node/node-tests.ts index 7978766eb6..19f686ef54 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -12,6 +12,7 @@ import * as net from "net"; import * as dgram from "dgram"; import * as querystring from "querystring"; import * as path from "path"; +import * as readline from "readline"; assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -95,9 +96,9 @@ url.format(url.parse('http://www.example.com/xyz')); // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ - protocol: 'https', - host: "google.com", - pathname: 'search', + protocol: 'https', + host: "google.com", + pathname: 'search', query: { q: "you're a lizard, gary" } }); @@ -191,14 +192,14 @@ module http_tests { var code = 100; var codeMessage = http.STATUS_CODES['400']; var codeMessage = http.STATUS_CODES[400]; - + var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, maxSockets: Infinity, maxFreeSockets: 256 }); - + var agent: http.Agent = http.globalAgent; } @@ -221,7 +222,7 @@ var escaped: string = querystring.escape(original); console.log(escaped); // http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html var unescaped: string = querystring.unescape(escaped); -console.log(unescaped); +console.log(unescaped); // http://example.com/product/abcde.html //////////////////////////////////////////////////// @@ -362,3 +363,20 @@ module path_tests { // returns // '/home/user/dir/file.txt' } + +//////////////////////////////////////////////////// +///ReadLine tests : https://nodejs.org/api/readline.html +//////////////////////////////////////////////////// + +var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout, +}); + +rl.setPrompt("$>"); +rl.prompt(); +rl.prompt(true); + +rl.question("do you like typescript?", function(answer: string) { + rl.close(); +}); diff --git a/node/node.d.ts b/node/node.d.ts index 1b661d8fad..aca3cbee15 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -781,7 +781,7 @@ declare module "readline" { import * as stream from "stream"; export interface ReadLine extends events.EventEmitter { - setPrompt(prompt: string, length: number): void; + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: Function): void; pause(): void; From e40d4a62f50fd21ef924c1f4bde4f43d2e096a44 Mon Sep 17 00:00:00 2001 From: Adam Babcock Date: Sat, 8 Aug 2015 15:40:29 -0500 Subject: [PATCH 27/53] Add empty send() method for superagent --- superagent/superagent-tests.ts | 5 +++++ superagent/superagent.d.ts | 1 + 2 files changed, 6 insertions(+) diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index eaefbf473d..466fc33a12 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -56,6 +56,11 @@ request .delete('/user/1') .end(callback); +request + .delete('/user/1') + .send() + .end(callback); + request('/search') .end(callback); diff --git a/superagent/superagent.d.ts b/superagent/superagent.d.ts index 6944fcceba..a5118a7645 100644 --- a/superagent/superagent.d.ts +++ b/superagent/superagent.d.ts @@ -97,6 +97,7 @@ declare module "superagent" { redirects(n: number): Req; send(data: string): Req; send(data: Object): Req; + send(): Req; set(field: string, val: string): Req; set(field: Object): Req; timeout(ms: number): Req; From fc806e7e1ddb7945f9877e38feb65cece7960978 Mon Sep 17 00:00:00 2001 From: Mike Morton Date: Sat, 8 Aug 2015 18:54:05 -0400 Subject: [PATCH 28/53] normal() should return a number, not a string Small change to ensure the normal() function declares that it returns a number and not a string. --- chance/chance.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 2af960efec..e79304c8d5 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -127,7 +127,7 @@ declare module Chance { guid(): string; hash(opts?: Options): string; n(generator: () => T, count: number, opts?: Options): T[]; - normal(opts?: Options): string; + normal(opts?: Options): number; radio(opts?: Options): string; rpg(dice: string): number[]; rpg(dice: string, opts?: Options): number[]|number; From 9adacf679010c3cedc50409c1bd280fa8582a021 Mon Sep 17 00:00:00 2001 From: Brian Surowiec Date: Mon, 10 Aug 2015 04:06:13 -0400 Subject: [PATCH 29/53] Update to angular ui bootstrap v0.13.3 --- .../angular-ui-bootstrap-tests.ts | 32 +++-- .../angular-ui-bootstrap.d.ts | 126 ++++++++++-------- 2 files changed, 97 insertions(+), 61 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts index 9a5c1cd7c4..efb63d006f 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap-tests.ts @@ -31,18 +31,23 @@ testApp.config(( /** * $datepickerConfig tests */ - $datepickerConfig.dayFormat = 'd'; - $datepickerConfig.dayHeaderFormat = 'E'; - $datepickerConfig.dayTitleFormat = 'dd-MM-yyyy'; + $datepickerConfig.datepickerMode = 'month'; + $datepickerConfig.formatDay = 'd'; + $datepickerConfig.formatDayHeader = 'E'; + $datepickerConfig.formatDayTitle = 'dd-MM-yyyy'; + $datepickerConfig.formatMonth = 'M'; + $datepickerConfig.formatMonthTitle = 'yy'; + $datepickerConfig.formatYear = 'y'; $datepickerConfig.maxDate = '1389586124979'; + $datepickerConfig.maxMode = 'month'; $datepickerConfig.minDate = '1389586124979'; - $datepickerConfig.monthFormat = 'M'; - $datepickerConfig.monthTitleFormat = 'yy'; + $datepickerConfig.minMode = 'month'; + $datepickerConfig.shortcutPropagation = true; $datepickerConfig.showWeeks = false; $datepickerConfig.startingDay = 1; - $datepickerConfig.yearFormat = 'y'; $datepickerConfig.yearRange = 10; - $datepickerConfig.shortcutPropagation = true; + + /** @@ -53,9 +58,12 @@ testApp.config(( $datepickerPopupConfig.clearText = 'Reset Selection'; $datepickerPopupConfig.closeOnDateSelection = false; $datepickerPopupConfig.closeText = 'Finished'; - $datepickerPopupConfig.dateFormat = 'dd-MM-yyyy'; + $datepickerPopupConfig.datepickerPopup = 'dd-MM-yyyy'; + $datepickerPopupConfig.datepickerPopupTemplateUrl = 'template.html'; + $datepickerPopupConfig.datepickerTemplateUrl = 'template.html'; + $datepickerPopupConfig.html5Types.date = 'MM-dd-yyyy'; + $datepickerPopupConfig.onOpenFocus = false; $datepickerPopupConfig.showButtonBar = false; - $datepickerPopupConfig.toggleWeeksText = 'Show Weeks'; /** @@ -72,9 +80,13 @@ testApp.config(( $paginationConfig.firstText = 'First Page'; $paginationConfig.itemsPerPage = 25; $paginationConfig.lastText = 'Last Page'; + $paginationConfig.maxSize = 13; + $paginationConfig.numPages = 13; $paginationConfig.nextText = 'Next Page'; $paginationConfig.previousText = 'Previous Page'; $paginationConfig.rotate = false; + $paginationConfig.templateUrl = 'template.html'; + $paginationConfig.totalItems = 13; /** @@ -122,6 +134,7 @@ testApp.config(( animation: false, popupDelay: 1000, appendToBody: true, + trigger: 'mouseenter hover', useContentExp: true }); $tooltipProvider.setTriggers({ @@ -148,6 +161,7 @@ testApp.controller('TestCtrl', ( controller: 'ModalTestCtrl', controllerAs: 'vm', keyboard: true, + openedClass: 'modal-open my-modal', resolve: { items: ()=> { return [1, 2, 3, 4, 5]; diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 6ed8be8e3e..1a36d21a2d 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular UI Bootstrap 0.13.2 +// Type definitions for Angular UI Bootstrap 0.13.3 // Project: https://github.com/angular-ui/bootstrap // Definitions by: Brian Surowiec // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -36,42 +36,63 @@ declare module angular.ui.bootstrap { * * @default 'dd' */ - dayFormat?: string; + formatDay?: string; /** * Format of month in year. * * @default 'MMM' */ - monthFormat?: string; + formatMonth?: string; /** * Format of year in year range. * * @default 'yyyy' */ - yearFormat?: string; + formatYear?: string; /** * Format of day in week header. * * @default 'EEE' */ - dayHeaderFormat?: string; + formatDayHeader?: string; /** * Format of title when selecting day. * * @default 'MMM yyyy' */ - dayTitleFormat?: string; + formatDayTitle?: string; /** * Format of title when selecting month. * * @default 'yyyy' */ - monthTitleFormat?: string; + formatMonthTitle?: string; + + /** + * Current mode of the datepicker (day|month|year). Can be used to initialize datepicker to specific mode. + * + * @default 'day' + */ + datepickerMode?: string; + + /** + * Set a lower limit for mode. + * + * @default 'day' + */ + minMode?: string; + + /** + * Set an upper limit for mode. + * + * @default 'year' + */ + maxMode?: string; /** * Whether to display week numbers. @@ -122,7 +143,30 @@ declare module angular.ui.bootstrap { * * @default 'yyyy-MM-dd' */ - dateFormat?: string; + datepickerPopup?: string; + + /** + * Allows overriding of default template of the popup. + * + * @default 'template/datepicker/popup.html' + */ + datepickerPopupTemplateUrl?: string; + + /** + * Allows overriding of default template of the datepicker used in popup. + * + * @default 'template/datepicker/popup.html' + */ + datepickerTemplateUrl?: string; + + /** + * Allows overriding of the default format for html5 date inputs. + */ + html5Types?: { + date?: string; + 'datetime-local'?: string; + month?: string; + }; /** * The text to display for the current day button. @@ -131,13 +175,6 @@ declare module angular.ui.bootstrap { */ currentText?: string; - /** - * The text to display for the toggling week numbers button. - * - * @default 'Weeks' - */ - toggleWeeksText?: string; - /** * The text to display for the clear button. * @@ -172,6 +209,13 @@ declare module angular.ui.bootstrap { * @default true */ showButtonBar?: boolean; + + /** + * Whether to focus the datepicker popup upon opening. + * + * @default true + */ + onOpenFocus?: boolean; } @@ -318,6 +362,13 @@ declare module angular.ui.bootstrap { * a path to a template overriding modal's window template */ windowTemplateUrl?: string; + + /** + * The class added to the body element when the modal is opened. + * + * @default 'model-open' + */ + openedClass?: string; } interface IModalStackService { @@ -354,11 +405,6 @@ declare module angular.ui.bootstrap { interface IPaginationConfig { - /** - * Current page number. First page is 1. - */ - page?: number; - /** * Total number of items in all pages. */ @@ -392,13 +438,6 @@ declare module angular.ui.bootstrap { */ rotate?: boolean; - /** - * An optional expression called when a page is selected having the page number as argument. - * - * @default null - */ - onSelectPage?(page: number): void; - /** * Whether to display Previous / Next buttons. * @@ -440,6 +479,13 @@ declare module angular.ui.bootstrap { * @default 'Last' */ lastText?: string; + + /** + * Override the template for the component with a custom provided template. + * + * @default 'template/pagination/pagination.html' + */ + templateUrl?: string; } interface IPagerConfig { @@ -450,16 +496,6 @@ declare module angular.ui.bootstrap { */ align?: boolean; - /** - * Current page number. First page is 1. - */ - page?: number; - - /** - * Total number of items in all pages. - */ - totalItems?: number; - /** * Maximum number of items per page. A value less than one indicates all items on one page. * @@ -467,20 +503,6 @@ declare module angular.ui.bootstrap { */ itemsPerPage?: number; - /** - * An optional expression assigned the total number of pages to display. - * - * @default angular.noop - */ - numPages?: number; - - /** - * An optional expression called when a page is selected having the page number as argument. - * - * @default null - */ - onSelectPage?(page: number): void; - /** * Text for Previous button. * @@ -654,7 +676,7 @@ declare module angular.ui.bootstrap { appendToBody?: boolean; /** - * Determines the default open triggers for tooltips and popovers + * What should trigger a show of the tooltip? Supports a space separated list of event names. * * @default 'mouseenter' for tooltip, 'click' for popover */ From 32dc65363f87983e63608466335adcd2b72f0385 Mon Sep 17 00:00:00 2001 From: Andrew Breen Date: Mon, 10 Aug 2015 22:23:13 +1000 Subject: [PATCH 30/53] Added firebase-client typescript definition file --- firebase-client/firebase-client-tests.ts | 50 ++++++++++++++++ firebase-client/firebase-client.d.ts | 75 ++++++++++++++++++++++++ 2 files changed, 125 insertions(+) create mode 100644 firebase-client/firebase-client-tests.ts create mode 100644 firebase-client/firebase-client.d.ts diff --git a/firebase-client/firebase-client-tests.ts b/firebase-client/firebase-client-tests.ts new file mode 100644 index 0000000000..bc4ef06a8e --- /dev/null +++ b/firebase-client/firebase-client-tests.ts @@ -0,0 +1,50 @@ +/// + +//Class definitions for type safety +class Name{ + first:string; + last:string; +} + +class User{ + name:Name; +} + +//Connect to service +var client = new FirebaseClient({ + url : "https://fb-client-test.firebaseio.com/", + auth : null +}); + +var newUser:User = new User(); +newUser.name = { + first: "Fred", + last: "Flinstone" +}; + +client.push("users", newUser) + .then(function (result){ + console.log(result.name); + var newUser2:User = new User(); + newUser2.name = { + first: "Fred", + last: "Rockington" + } + return client.update("users/" + result.name, newUser2); + }).then(function (result){ + console.log(result.name.last); + var newUser3:User = new User(); + newUser3.name = { + first: "Axe", + last: "Steel" + }; + return client.set("users/AXESTEEL", newUser3); + }).then(function (result){ + console.log(result.name.first); + return client.get(); + }).then(function (result){ + console.log(result); + return client.get("users/AXESTEEL") + }).then(function (result){ + console.log(result.name.first); + }); \ No newline at end of file diff --git a/firebase-client/firebase-client.d.ts b/firebase-client/firebase-client.d.ts new file mode 100644 index 0000000000..15839deee4 --- /dev/null +++ b/firebase-client/firebase-client.d.ts @@ -0,0 +1,75 @@ +// Type definitions for Firebase Client 0.1.0 +// Project: https://www.github.com/jpstevens/firebase-client +// Definitions by: Andrew Breen +// Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + +interface PushResponse { + /** + * Name ref (key) of the child resource + */ + name : string; +} + +interface FirebaseConfig { + /** + * path for the Firebase instance + */ + url : string; + + /** + * Token for authorisation + */ + auth: string; +} + +interface FirebaseClient { + /** + * Creates a new FirebaseClient given the provided configuration + */ + new (config : FirebaseConfig) : FirebaseClient; + + /** + * Retrieves all objects at the base path + */ + get() : Q.Promise; + + /** + * Retrieves an object + * @param path Relative path from the base for the resource + */ + get(path : string) : Q.Promise; + + /** + * Returns a promise of the HTTP response from setting the value at the given path + * @param path Relative path from the base for the resource + * @param data Data to be set as the value for the given path + */ + set(path : string, data : T) : Q.Promise; + + /** + * Update a node at a given path + * @param path Relative path from the base for the resource + * @param value Value of the response + */ + update(path : string, value : T) : Q.Promise; + + /** + * Deletes the resource at a given path + * @param path Relative path from the base for the resource + */ + delete(path : string) : Q.Promise; + + /** + * @param path Relative path from the base for the resource + * @param value Object to push to the path + */ + push(path : string, value : T) : Q.Promise; +} + +declare var FirebaseClient: FirebaseClient; + +declare module 'firebase-client' { + export = FirebaseClient; +} + From b090bcf9ba9f756ec8ff53e7707269729172a325 Mon Sep 17 00:00:00 2001 From: Matt Brooks Date: Mon, 10 Aug 2015 15:00:21 +0100 Subject: [PATCH 31/53] Add prototype accessor `moment.fn` The `Moment` prototype is exposed through `moment.fn`. --- moment/moment-external-tests.ts | 4 ++++ moment/moment-node.d.ts | 3 ++- moment/moment.d.ts | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/moment/moment-external-tests.ts b/moment/moment-external-tests.ts index b76752b118..ed3e1e2a82 100644 --- a/moment/moment-external-tests.ts +++ b/moment/moment-external-tests.ts @@ -456,4 +456,8 @@ moment.locale('en', { } }); +moment.fn.toJSON = function() { + return this.format(); +}; + console.log(moment.version); diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 3728f898f7..1c7267638c 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -1,6 +1,6 @@ // Type definitions for Moment.js 2.8.0 // Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya +// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya , Matt Brooks // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module moment { @@ -371,6 +371,7 @@ declare module moment { interface MomentStatic { version: string; + fn: Moment; (): Moment; (date: number): Moment; diff --git a/moment/moment.d.ts b/moment/moment.d.ts index 736956e5db..78b09016cb 100644 --- a/moment/moment.d.ts +++ b/moment/moment.d.ts @@ -1,6 +1,6 @@ // Type definitions for Moment.js 2.8.0 // Project: https://github.com/timrwood/moment -// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya +// Definitions by: Michael Lakerveld , Aaron King , Hiroki Horiuchi , Dick van den Brink , Adi Dahiya , Matt Brooks // Definitions: https://github.com/borisyankov/DefinitelyTyped /// From 348f3e62bd158ab75aeae74ac5e31496503549f5 Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Mon, 10 Aug 2015 09:17:57 -0600 Subject: [PATCH 32/53] Revert to previous tests --- yamljs/yamljs-tests.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/yamljs/yamljs-tests.ts b/yamljs/yamljs-tests.ts index d4e6376d68..9780c504d4 100644 --- a/yamljs/yamljs-tests.ts +++ b/yamljs/yamljs-tests.ts @@ -1,7 +1,13 @@ /// -var yamlObj = YAML.parse("test: some yaml"); +import yamljs = require('yamljs'); -YAML.stringify(yamlObj); +yamljs.load('yaml-testfile.yml'); -YAML.load("path/to/file.yaml"); \ No newline at end of file +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 From f66606b3863f0e3544e41736686e82f0dc514333 Mon Sep 17 00:00:00 2001 From: luckyllama Date: Mon, 10 Aug 2015 10:00:06 -0700 Subject: [PATCH 33/53] Update velocity-animate.d.ts Adding support for the "scroll" effect and related option parameters. See http://julian.com/research/velocity/#scroll --- velocity-animate/velocity-animate.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts index 6946da972a..b25a31408c 100644 --- a/velocity-animate/velocity-animate.d.ts +++ b/velocity-animate/velocity-animate.d.ts @@ -58,5 +58,7 @@ declare module jquery.velocity { delay?: any; mobileHA?: boolean; _cacheValues?: boolean; + container?: JQuery; + axis?: string; } } From 99ee1fcd9635335b2e8d870fe52fd401851a65e7 Mon Sep 17 00:00:00 2001 From: Austen Talbot Date: Mon, 10 Aug 2015 10:00:31 -0700 Subject: [PATCH 34/53] Converted Diff interfect object to type array --- diff-match-patch/diff-match-patch.d.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 3a55b77692..b92f24411e 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -4,10 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "diff-match-patch" { - interface Diff { - 0: number; - 1: string; - } + type Diff = [number, string]; export class DiffMatchPatch { Diff_Timeout: number; From 69cd45617c10f0ecafd700c43cbc0211ce6620ef Mon Sep 17 00:00:00 2001 From: Ben Tesser Date: Mon, 10 Aug 2015 14:01:16 -0400 Subject: [PATCH 35/53] Ui-Grid: Fix Column Defs Fix invalid type for IGridOptions.columnDefs. --- ui-grid/ui-grid.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui-grid/ui-grid.d.ts b/ui-grid/ui-grid.d.ts index 896a2d60e2..981f363b21 100644 --- a/ui-grid/ui-grid.d.ts +++ b/ui-grid/ui-grid.d.ts @@ -192,7 +192,7 @@ declare module uiGrid { export interface IGridOptions { aggregationCalcThrottle?: number; appScopeProvider?: ng.IScope | Object; - columnDefs?: IColumnDef; + columnDefs?: Array; columnFooterHeight?: number; columnVirtualizationThreshold?: number; data?: Array | string; From 03ca6c61b929762fe9787ecd477f2c977a704a36 Mon Sep 17 00:00:00 2001 From: Kamil Biela Date: Mon, 10 Aug 2015 22:29:05 +0200 Subject: [PATCH 36/53] Fix bluebird constructor definitions --- bluebird/bluebird-1.0.d.ts | 3 +-- bluebird/bluebird.d.ts | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/bluebird/bluebird-1.0.d.ts b/bluebird/bluebird-1.0.d.ts index 210032f864..69a4f9152d 100644 --- a/bluebird/bluebird-1.0.d.ts +++ b/bluebird/bluebird-1.0.d.ts @@ -20,8 +20,7 @@ declare class Promise implements Promise.Thenable { /** * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. */ - constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); - constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable) => void, reject: (error: any) => void) => void); /** * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index cd21d77e92..8876f69817 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -20,8 +20,7 @@ declare class Promise implements Promise.Thenable, Promise.Inspection { /** * Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise. */ - constructor(callback: (resolve: (thenable: Promise.Thenable) => void, reject: (error: any) => void) => void); - constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void); + constructor(callback: (resolve: (thenableOrResult: R | Promise.Thenable) => void, reject: (error: any) => void) => void); /** * Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise. From b177c999720bd6cc97480b6ad61e072bdeb821f2 Mon Sep 17 00:00:00 2001 From: Austen Talbot Date: Mon, 10 Aug 2015 15:10:25 -0700 Subject: [PATCH 37/53] Updated formatting --- diff-match-patch/diff-match-patch.d.ts | 52 ++++++++++++-------------- 1 file changed, 24 insertions(+), 28 deletions(-) diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index b92f24411e..63bf7eaa07 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -1,43 +1,39 @@ // Type definitions for diff-match-patch v1.0.0 // Project: https://www.npmjs.com/package/diff-match-patch -// Definitions by: Austen Talbot +// Definitions by: Asana // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module "diff-match-patch" { type Diff = [number, 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; + export class diff_match_patch { + static new (): diff_match_patch; - 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[]; + Diff_Timeout: number; + Diff_EditCost: number; + Match_Threshold: number; + Match_Distance: number; + Patch_DeleteThreshold: number; + Patch_Margin: number; + Match_MaxBits: number; - new (): DiffMatchPatch; + 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[]; } export var DIFF_DELETE: number; export var DIFF_INSERT: number; export var DIFF_EQUAL: number; - - export var diff_match_patch: { - new (): DiffMatchPatch; - }; } From 4f62396fdf7899bdfd9458473a23c9eaf29d33fa Mon Sep 17 00:00:00 2001 From: Justin Unterreiner Date: Mon, 10 Aug 2015 20:16:00 -0700 Subject: [PATCH 38/53] Added definitions for the PayPal mobile SDK Cordova plugin --- .../PayPal-Cordova-Plugin-test.ts | 115 ++++ .../PayPal-Cordova-Plugin.d.ts | 615 ++++++++++++++++++ 2 files changed, 730 insertions(+) create mode 100644 PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-test.ts create mode 100644 PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts diff --git a/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-test.ts b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-test.ts new file mode 100644 index 0000000000..dca1f93120 --- /dev/null +++ b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin-test.ts @@ -0,0 +1,115 @@ + +/// + +var item: PayPalItem; +item = new PayPalItem("name", 10, "25.00", "USD"); +item = new PayPalItem("name", 10, "25.00", "USD", null); +item = new PayPalItem("name", 10, "25.00", "USD", "SKU_ID"); + +var item_name: string = item.name; +var item_quantity: number = item.quantity; +var item_price: string = item.price; +var item_currency: string = item.currency; +var item_sku: string = item.sku; + + + +var paymentDetails: PayPalPaymentDetails; +paymentDetails = new PayPalPaymentDetails("10.50", "2.50", "1.25"); + +var paymentDetails_subtotal: string = paymentDetails.subtotal; +var paymentDetails_shipping: string = paymentDetails.shipping; +var paymentDetails_tax: string = paymentDetails.tax; + + + +var shippingAddress: PayPalShippingAddress; +shippingAddress = new PayPalShippingAddress("name", "line1", "line2", "city", "state", "postalCode", "countryCode"); + +var shippingAddress_recipientName: string = shippingAddress.recipientName; +var shippingAddress_line1: string = shippingAddress.line1; +var shippingAddress_line2: string = shippingAddress.line2; +var shippingAddress_city: string = shippingAddress.city; +var shippingAddress_state: string = shippingAddress.state; +var shippingAddress_postalCode: string = shippingAddress.postalCode; +var shippingAddress_countryCode: string = shippingAddress.countryCode; + + + +var payment: PayPalPayment; +payment = new PayPalPayment("10.00", "USD", "description", "Auth"); +payment = new PayPalPayment("10.00", "USD", "description", "Auth", paymentDetails); + +var payment_amount: string = payment.amount; +var payment_currency: string = payment.currency; +var payment_shortDescription: string = payment.shortDescription; +var payment_intent: string = payment.intent; +var payment_details: PayPalPaymentDetails = payment.details; +var payment_invoiceNumber: string = payment.invoiceNumber; +var payment_custom: string = payment.custom; +var payment_softDescriptor: string = payment.softDescriptor; +var payment_bnCode: string = payment.bnCode; +var payment_items: PayPalItem[] = [item, item, item]; +var payment_shippingAddress: PayPalShippingAddress = shippingAddress; + + + +var configOptions: PayPalConfigurationOptions = { + defaultUserEmail: "email", + defaultUserPhoneCountryCode: "countryCode", + defaultUserPhoneNumber: "phoneNumber", + merchantName: "merchantName", + merchantPrivacyPolicyURL: "merchantPrivacyPolicyURL", + merchantUserAgreementURL: "merchantUserAgreementURL", + acceptCreditCards: true, + payPalShippingAddressOption: 10, + rememberUser: true, + languageOrLocale: "languageOrLocal", + disableBlurWhenBackgrounding: true, + presentingInPopover: true, + forceDefaultsInSandbox: true, + sandboxUserPassword: "sandboxUserPassword", + sandboxUserPin: "sandboxUserPin" +}; + + + +var config: PayPalConfiguration; +config = new PayPalConfiguration(); +config = new PayPalConfiguration(null); +config = new PayPalConfiguration(configOptions); + +var config_defaultUserEmail: string = config.defaultUserEmail; +var config_defaultUserPhoneCountryCode: string = config.defaultUserPhoneCountryCode; +var config_defaultUserPhoneNumber: string = config.defaultUserPhoneNumber; +var config_merchantName: string = config.merchantName; +var config_merchantPrivacyPolicyURL: string = config.merchantPrivacyPolicyURL; +var config_merchantUserAgreementURL: string = config.merchantUserAgreementURL; +var config_acceptCreditCards: boolean = config.acceptCreditCards; +var config_payPalShippingAddressOption: number = config.payPalShippingAddressOption; +var config_rememberUser: boolean = config.rememberUser; +var config_languageOrLocale: string = config.languageOrLocale; +var config_disableBlurWhenBackgrounding: boolean = config.disableBlurWhenBackgrounding; +var config_presentingInPopover: boolean = config.presentingInPopover; +var config_forceDefaultsInSandbox: boolean = config.forceDefaultsInSandbox; +var config_sandboxUserPasword: string = config.sandboxUserPassword; +var config_sandboxUserPin: string = config.sandboxUserPin; + + + +var clientIds: PayPalCordovaPlugin.PayPalClientIds = { + PayPalEnvironmentProduction: "", + PayPalEnvironmentSandbox: "" +}; + + + +var apiModule: PayPalCordovaPlugin.PayPalMobileStatic = PayPalMobile; +apiModule.version((result: string) => {}); +apiModule.init(clientIds, () => {}); +apiModule.prepareToRender("environment", config, () => {}); +apiModule.renderSinglePaymentUI(payment, (result: any) => {}, (cancelReason: string) => {}); +apiModule.applicationCorrelationIDForEnvironment("environment", (applicationCorrelationId: string) => {}); +apiModule.clientMetadataID((clientMetadataId: string) => {}); +apiModule.renderFuturePaymentUI((result: any) => {}, (cancelReason: string) => {}); +apiModule.renderProfileSharingUI(["openid", "profile", "email"], (result: any) => {}, (cancelReason: string) => {}); \ No newline at end of file diff --git a/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts new file mode 100644 index 0000000000..07c172d558 --- /dev/null +++ b/PayPal-Cordova-Plugin/PayPal-Cordova-Plugin.d.ts @@ -0,0 +1,615 @@ +// Type definitions for PayPal-Cordova-Plugin 3.1.10 +// Project: https://github.com/paypal/PayPal-Cordova-Plugin +// Definitions by: Justin Unterreiner +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +//#region paypal-mobile-js-helper.js + +/** + * The PayPalItem class defines an optional itemization for a payment. + * + * @see https://developer.paypal.com/docs/api/#item-object for more details. + */ +declare class PayPalItem { + + /** + * @param name Name of the item. 127 characters max. + * @param quantity Number of units. 10 characters max. + * @param price Unit price for this item 10 characters max. + * May be negative for "coupon" etc. + * @param currency ISO standard currency code. + * @param sku The stock keeping unit for this item. 50 characters max (optional). + */ + constructor(name: string, quantity: number, price: string, currency: string, sku?: string); + + /** + * Name of the item. 127 characters max. + */ + name: string; + + /** + * Number of units. 10 characters max. + */ + quantity: number; + + /** + * Unit price for this item 10 characters max. + * May be negative for "coupon" etc. + */ + price: string; + + /** + * ISO standard currency code. + */ + currency: string; + + /** + * The stock keeping unit for this item. 50 characters max (optional). + */ + sku: string; +} + +/** + * The PayPalPaymentDetails class defines optional amount details. + * + * @see https://developer.paypal.com/webapps/developer/docs/api/#details-object for more details. + */ +declare class PayPalPaymentDetails { + + /** + * @param subtotal Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places. + * @param shipping Amount charged for shipping. 10 characters max with support for 2 decimal places. + * @param tax Amount charged for tax. 10 characters max with support for 2 decimal places. + */ + constructor(subtotal: string, shipping: string, tax: string); + + /** + * Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places. + */ + subtotal: string; + + /** + * Amount charged for shipping. 10 characters max with support for 2 decimal places. + */ + shipping: string; + + /** + * Amount charged for tax. 10 characters max with support for 2 decimal places. + */ + tax: string; +} + +/** + * Convenience constructor. Returns a PayPalPayment with the specified amount, currency code, and short description. + */ +declare class PayPalPayment { + + /** + * @param amount The amount of the payment. + * @param currencyCode The ISO 4217 currency for the payment. + * @param shortDescription A short descripton of the payment. + * @param intent • "Sale" for an immediate payment. + * • "Auth" for payment authorization only, to be captured separately at a later time. + * • "Order" for taking an order, with authorization and capture to be done separately at a later time. + * @param details PayPalPaymentDetails object (optional). + */ + constructor(amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails); + + /** + * The amount of the payment. + */ + amount: string; + + /** + * The ISO 4217 currency for the payment. + */ + currency: string; + + /** + * A short descripton of the payment. + */ + shortDescription: string; + + /** + * • "Sale" for an immediate payment. + * • "Auth" for payment authorization only, to be captured separately at a later time. + * • "Order" for taking an order, with authorization and capture to be done separately at a later time. + */ + intent: string; + + /** + * PayPalPaymentDetails object (optional). + */ + details: PayPalPaymentDetails; + + /** + * Optional invoice number, for your tracking purposes. (up to 256 characters). + */ + invoiceNumber: string; + + /** + * Optional text, for your tracking purposes. (up to 256 characters). + */ + custom: string; + + /** + * Optional text which will appear on the customer's credit card statement. (up to 22 characters). + */ + softDescriptor: string; + + /** + * Optional Build Notation code ("BN code"), obtained from partnerprogram@paypal.com, for your tracking purposes. + */ + bnCode: string; + + /** + * Optional array of PayPalItem objects. + * @see PayPalItem + * @note If you provide one or more items, be sure that the various prices correctly sum to the payment `amount` or to `paymentDetails.subtotal`. + */ + items: PayPalItem[]; + + /** + * Optional customer shipping address, if your app wishes to provide this to the SDK. + * @note make sure to set `payPalShippingAddressOption` in PayPalConfiguration to 1 or 3. + */ + shippingAddress: PayPalShippingAddress; +} + +declare class PayPalShippingAddress { + + /** + * @param recipientName Name of the recipient at this address. 50 characters max. + * @param line1 Line 1 of the address (e.g., Number, street, etc). 100 characters max. + * @param line2 Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional. + * @param city City name. 50 characters max. + * @param state 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries. + * @param postalCode ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries. + * @param countryCode 2-letter country code. 2 characters max. + */ + constructor(recipientName: string, line1: string, line2: string, city: string, state: string, postalCode: string, countryCode: string); + + /** + * Name of the recipient at this address. 50 characters max. + */ + recipientName: string; + + /** + * Line 1 of the address (e.g., Number, street, etc). 100 characters max. + */ + line1: string; + + /** + * Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional. + */ + line2: string; + + /** + * City name. 50 characters max. + */ + city: string; + + /** + * 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries. + */ + state: string; + + /** + * ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries. + */ + postalCode: string; + + /** + * 2-letter country code. 2 characters max. + */ + countryCode: string; +} + +declare class PayPalConfiguration { + + /** + * @param options A set of options to use. Any options not specified will assume default values. + */ + constructor(options?: PayPalConfigurationOptions); + + /** + * Will be overridden by email used in most recent PayPal login. + */ + defaultUserEmail: string; + + /** + * Will be overridden by phone country code used in most recent PayPal login + */ + defaultUserPhoneCountryCode: string; + + /** + * Will be overridden by phone number used in most recent PayPal login. + * @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode. + */ + defaultUserPhoneNumber: string; + + /** + * Your company name, as it should be displayed to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantName: string; + + /** + * URL of your company's privacy policy, which will be offered to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantPrivacyPolicyURL: string; + + /** + * URL of your company's user agreement, which will be offered to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantUserAgreementURL: string; + + /** + * If set to false, the SDK will only support paying with PayPal, not with credit cards. + * This applies only to single payments (via PayPalPaymentViewController). + * Future payments (via PayPalFuturePaymentViewController) always use PayPal. + * Defaults to true. + */ + acceptCreditCards: boolean; + + /** + * For single payments, options for the shipping address. + * + * - 0 - PayPalShippingAddressOptionNone: no shipping address applies. + * + * - 1 - PayPalShippingAddressOptionProvided: shipping address will be provided by your app, + * in the shippingAddress property of PayPalPayment. + * + * - 2 - PayPalShippingAddressOptionPayPal: user will choose from shipping addresses on file + * for their PayPal account. + * + * - 3 - PayPalShippingAddressOptionBoth: user will choose from the shipping address provided by your app, + * in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account. + * + * Defaults to 0 (PayPalShippingAddressOptionNone). + */ + payPalShippingAddressOption: number; + + /** + * If set to true, then if the user pays via their PayPal account, + * the SDK will remember the user's PayPal username or phone number; + * if the user pays via their credit card, then the SDK will remember + * the PayPal Vault token representing the user's credit card. + * + * If set to false, then any previously-remembered username, phone number, or + * credit card token will be erased, and subsequent payment information will + * not be remembered. + * + * Defaults to true. + */ + rememberUser: boolean; + + /** + * If not set, or if set to nil, defaults to the device's current language setting. + * + * Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.). + * If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es". + * If the library does not contain localized strings for a specified language, then will fall back to American English. + * + * If you specify only a language code, and that code matches the device's currently preferred language, + * then the library will attempt to use the device's current region as well. + * E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB". + * + * These localizations are currently included: + * da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW. + */ + languageOrLocale: string; + + /** + * Normally, the SDK blurs the screen when the app is backgrounded, + * to obscure credit card or PayPal account details in the iOS-saved screenshot. + * If your app already does its own blurring upon backgrounding, you might choose to disable this. + * Defaults to false. + */ + disableBlurWhenBackgrounding: boolean; + + /** + * If you will present the SDK's view controller within a popover, then set this property to true. + * Defaults to false. (iOS only) + */ + presentingInPopover: boolean; + + /** + * Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will + * cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields. + * + * This setting will have no effect if the operation mode is production. + * Defaults to false. + */ + forceDefaultsInSandbox: boolean; + + /** + * Password to use for sandbox if 'forceDefaultsInSandbox' is set. + */ + sandboxUserPassword: string; + + /** + * PIN to use for sandbox if 'forceDefaultsInSandbox' is set. + */ + sandboxUserPin: string; +} + +/** + * Describes the options that can be passed into the PayPalConfiguration class constructor. + */ +interface PayPalConfigurationOptions { + + /** + * Will be overridden by email used in most recent PayPal login. + */ + defaultUserEmail?: string; + + /** + * Will be overridden by phone country code used in most recent PayPal login + */ + defaultUserPhoneCountryCode?: string; + + /** + * Will be overridden by phone number used in most recent PayPal login. + * @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode. + */ + defaultUserPhoneNumber?: string; + + /** + * Your company name, as it should be displayed to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantName?: string; + + /** + * URL of your company's privacy policy, which will be offered to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantPrivacyPolicyURL?: string; + + /** + * URL of your company's user agreement, which will be offered to the user + * when requesting consent via a PayPalFuturePaymentViewController. + */ + merchantUserAgreementURL?: string; + + /** + * If set to false, the SDK will only support paying with PayPal, not with credit cards. + * This applies only to single payments (via PayPalPaymentViewController). + * Future payments (via PayPalFuturePaymentViewController) always use PayPal. + * Defaults to true. + */ + acceptCreditCards?: boolean; + + /** + * For single payments, options for the shipping address. + * + * - 0 - PayPalShippingAddressOptionNone?: no shipping address applies. + * + * - 1 - PayPalShippingAddressOptionProvided?: shipping address will be provided by your app, + * in the shippingAddress property of PayPalPayment. + * + * - 2 - PayPalShippingAddressOptionPayPal?: user will choose from shipping addresses on file + * for their PayPal account. + * + * - 3 - PayPalShippingAddressOptionBoth?: user will choose from the shipping address provided by your app, + * in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account. + * + * Defaults to 0 (PayPalShippingAddressOptionNone). + */ + payPalShippingAddressOption?: number; + + /** + * If set to true, then if the user pays via their PayPal account, + * the SDK will remember the user's PayPal username or phone number; + * if the user pays via their credit card, then the SDK will remember + * the PayPal Vault token representing the user's credit card. + * + * If set to false, then any previously-remembered username, phone number, or + * credit card token will be erased, and subsequent payment information will + * not be remembered. + * + * Defaults to true. + */ + rememberUser?: boolean; + + /** + * If not set, or if set to nil, defaults to the device's current language setting. + * + * Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.). + * If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es". + * If the library does not contain localized strings for a specified language, then will fall back to American English. + * + * If you specify only a language code, and that code matches the device's currently preferred language, + * then the library will attempt to use the device's current region as well. + * E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB". + * + * These localizations are currently included: + * da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW. + */ + languageOrLocale?: string; + + /** + * Normally, the SDK blurs the screen when the app is backgrounded, + * to obscure credit card or PayPal account details in the iOS-saved screenshot. + * If your app already does its own blurring upon backgrounding, you might choose to disable this. + * Defaults to false. + */ + disableBlurWhenBackgrounding?: boolean; + + /** + * If you will present the SDK's view controller within a popover, then set this property to true. + * Defaults to false. (iOS only) + */ + presentingInPopover?: boolean; + + /** + * Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will + * cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields. + * + * This setting will have no effect if the operation mode is production. + * Defaults to false. + */ + forceDefaultsInSandbox?: boolean; + + /** + * Password to use for sandbox if 'forceDefaultsInSandbox' is set. + */ + sandboxUserPassword?: string; + + /** + * PIN to use for sandbox if 'forceDefaultsInSandbox' is set. + */ + sandboxUserPin?: string; +} + +//#endregion + +//#region cdv-plugin-paypal-mobile-sdk.js + +declare module PayPalCordovaPlugin { + + export interface PayPalClientIds { + PayPalEnvironmentProduction: string; + PayPalEnvironmentSandbox: string; + } + + /** + * Represents the portion of an object that is common to all responses. + */ + export interface BaseResult { + client: Client; + response_type: string; + } + + /** + * Represents the client portion of the response. + */ + export interface Client { + paypal_sdk_version: string; + environment: string; + platform: string; + product_name: string; + } + + /** + * Represents the response for a successful callback from renderSinglePaymentUI(). + */ + export interface SinglePaymentResult extends BaseResult { + response: { + intent: string; + id: string; + state: string; + authorization_id: string; + create_time: string; + }; + } + + /** + * Represents the response for a successful callback from renderFuturePaymentUI(). + */ + export interface FuturePaymentResult extends BaseResult { + response: { + code: string; + }; + } + + export interface PayPalMobileStatic { + /** + * Retrieve the version of the PayPal iOS SDK library. Useful when contacting support. + * + * @param completionCallback a callback function accepting a string + */ + version(completionCallback: (result: string) => void): void; + + /** + * You MUST call this method to initialize the PayPal Mobile SDK. + * + * The PayPal Mobile SDK can operate in different environments to facilitate development and testing. + * + * @param clientIdsForEnvironments set of client ids for environments + * Example: var clientIdsForEnvironments = { + * PayPalEnvironmentProduction : @"my-client-id-for-Production", + * PayPalEnvironmentSandbox : @"my-client-id-for-Sandbox" + * } + * @param completionCallback a callback function on success + */ + init(clientIdsForEnvironments: PayPalCordovaPlugin.PayPalClientIds, completionCallback: () => void): void; + + /** + * You must preconnect to PayPal to prepare the device for processing payments. + * This improves the user experience, by making the presentation of the + * UI faster. The preconnect is valid for a limited time, so + * the recommended time to preconnect is on page load. + * + * @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox" + * @param configuration PayPalConfiguration object, for Future Payments merchantName, merchantPrivacyPolicyURL + * and merchantUserAgreementURL must be set be set + * @param completionCallback a callback function on success + */ + prepareToRender(environment: string, configuration: PayPalConfiguration, completionCallback: () => void): void; + + /** + * Start PayPal UI to collect payment from the user. + * See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/ + * for more documentation of the params. + * + * @param payment PayPalPayment object + * @param completionCallback a callback function accepting a js object, called when the user has completed payment + * @param cancelCallback a callback function accepting a reason string, called when the user cancels the payment + */ + renderSinglePaymentUI(payment: PayPalPayment, completionCallback: (result: PayPalCordovaPlugin.SinglePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void; + + /** + * @deprecated + * Once a user has consented to future payments, when the user subsequently initiates a PayPal payment + * from their device to be completed by your server, PayPal uses a Correlation ID to verify that the + * payment is originating from a valid, user-consented device+application. + * This helps reduce fraud and decrease declines. + * This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device. + * Pass the result to your server, to include in the payment request sent to PayPal. + * Do not otherwise cache or store this value. + * + * @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox" + * @param callback applicationCorrelationID Your server will send this to PayPal in a 'Paypal-Application-Correlation-Id' header. + */ + applicationCorrelationIDForEnvironment(environment: string, completionCallback: (applicationCorrelationId: string) => void): void; + + /** + * Once a user has consented to future payments, when the user subsequently initiates a PayPal payment + * from their device to be completed by your server, PayPal uses a Correlation ID to verify that the + * payment is originating from a valid, user-consented device+application. + * This helps reduce fraud and decrease declines. + * This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device. + * Pass the result to your server, to include in the payment request sent to PayPal. + * Do not otherwise cache or store this value. + * + * @param callback clientMetadataID Your server will send this to PayPal in a 'PayPal-Client-Metadata-Id' header. + */ + clientMetadataID(completionCallback: (clientMetadataId: string) => void): void; + + /** + * Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments + * + * @param completionCallback a callback function accepting a js object with future payment authorization + * @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement + */ + renderFuturePaymentUI(completionCallback: (result: PayPalCordovaPlugin.FuturePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void; + + /** + * Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing + * + * @param scopes scopes Set of requested scope-values. Accepted scopes are: openid, profile, address, email, phone, futurepayments and paypalattributes + * See https://developer.paypal.com/docs/integration/direct/identity/attributes/ for more details + * @param completionCallback a callback function accepting a js object with future payment authorization + * @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement + */ + renderProfileSharingUI(scopes: string[], completionCallback: (result: any) => void, cancelCallback: (cancelReason: string) => void): void; + } +} + +declare var PayPalMobile: PayPalCordovaPlugin.PayPalMobileStatic; + +//#endregion From 32f4b07c46dd23910147f9dc241b93f58cadde22 Mon Sep 17 00:00:00 2001 From: Tag Date: Tue, 11 Aug 2015 16:39:57 +0800 Subject: [PATCH 39/53] Update(node.d.ts): add statusMessage property to interface ServerResponse. --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 1b661d8fad..c8cb054a6d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -453,6 +453,7 @@ declare module "http" { writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void; writeHead(statusCode: number, headers?: any): void; statusCode: number; + statusMessage: string; setHeader(name: string, value: string): void; sendDate: boolean; getHeader(name: string): string; From 3c6d22513e9a25b2660c6dc194bf37dad5d7332c Mon Sep 17 00:00:00 2001 From: Matija Grcic Date: Tue, 11 Aug 2015 10:00:59 +0100 Subject: [PATCH 40/53] Added missing typings for params and return values --- umbraco/umbraco-resources.d.ts | 52 +++++++++--------- umbraco/umbraco-services.d.ts | 97 ++++++++++++++++++---------------- 2 files changed, 79 insertions(+), 70 deletions(-) diff --git a/umbraco/umbraco-resources.d.ts b/umbraco/umbraco-resources.d.ts index 6ddb05cc15..d07d4d3a57 100644 --- a/umbraco/umbraco-resources.d.ts +++ b/umbraco/umbraco-resources.d.ts @@ -3,6 +3,8 @@ // Definitions by: DeCareSystemsIreland // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// + declare module umbraco.resources{ /** @@ -497,7 +499,7 @@ interface IContentResource{ * @returns {Promise} resourcePromise object containing the saved content item. * */ - save(content, isNew: boolean, files): ng.IPromise; + save(content: IContentResource, isNew: boolean, files: any[]): ng.IPromise; /** * @ngdoc method @@ -527,7 +529,7 @@ interface IContentResource{ * @returns {Promise} resourcePromise object containing the saved content item. * */ - publish(content, isNew: boolean, files): ng.IPromise; + publish(content: IContentResource, isNew: boolean, files: any[]): ng.IPromise; /** * @ngdoc method @@ -555,7 +557,7 @@ interface IContentResource{ * @returns {Promise} resourcePromise object containing the saved content item. * */ - sendToPublish(content, isNew: boolean, files): ng.IPromise; + sendToPublish(content: IContentResource, isNew: boolean, files: any[]): ng.IPromise; /** @@ -643,7 +645,7 @@ interface ICurrentUserResource{ * @returns {Promise} resourcePromise object containing the user array. * */ - changePassword(changePasswordArgs): ng.IPromise; + changePassword(changePasswordArgs: any): ng.IPromise; /** * @ngdoc method @@ -653,7 +655,7 @@ interface ICurrentUserResource{ * @description * Gets the configuration of the user membership provider which is used to configure the change password form */ - getMembershipProviderConfig(); + getMembershipProviderConfig(): any; } @@ -729,7 +731,7 @@ interface IDataTypeResource{ */ getById(id: number): ng.IPromise; - getAll(); + getAll() : any; /** * @ngdoc method @@ -796,7 +798,7 @@ interface IDataTypeResource{ * @returns {Promise} resourcePromise object. * */ - save(dataType, preValues: any[], isNew: boolean): ng.IPromise; + save(dataType: Object, preValues: any[], isNew: boolean): ng.IPromise; } /** @@ -880,9 +882,9 @@ interface IEntityResource{ * @returns {Promise} resourcePromise object containing the entity. * */ - getById(id: number, type: string); + getById(id: number, type: string): ng.IPromise; - getByQuery(query, nodeContextId, type: string): ng.IPromise; + getByQuery(query: string, nodeContextId: number|string, type: string): ng.IPromise; /** * @ngdoc method @@ -988,7 +990,7 @@ interface IEntityResource{ * @returns {Promise} resourcePromise object containing the entity array. * */ - search(query: string, type: string, searchFrom, canceler): ng.IPromise; + search(query: string, type: string, searchFrom: any, canceler: any): ng.IPromise; /** * @ngdoc method @@ -1011,7 +1013,7 @@ interface IEntityResource{ * @returns {Promise} resourcePromise object containing the entity array. * */ - searchAll(query: string, canceler): ng.IPromise; + searchAll(query: string, canceler: any): ng.IPromise; } /** @@ -1118,7 +1120,7 @@ interface IMacroResource{ * @param {int} macroId The macro id to get parameters for * */ - getMacroParameters(macroId: number); + getMacroParameters(macroId: number): any; /** * @ngdoc method @@ -1133,7 +1135,7 @@ interface IMacroResource{ * @param {Array} macroParamDictionary A dictionary of macro parameters * */ - getMacroResultAsHtmlForEditor(macroId:number, pageId:number, macroParamDictionary: any[]); + getMacroResultAsHtmlForEditor(macroId: number, pageId: number, macroParamDictionary: any[]): any; } /** @@ -1295,7 +1297,7 @@ interface IMediaResource{ */ getScaffold(parentId: number, alias: string): ng.IPromise; - rootMedia(); + rootMedia(): any; /** * @ngdoc method @@ -1437,9 +1439,9 @@ interface IMediaTypeResource{ **/ interface IMemberResource{ - getPagedResults(memberTypeAlias: string, options); + getPagedResults(memberTypeAlias: string, options: any): any; - getListNode(listName: string); + getListNode(listName: string): any; /** * @ngdoc method @@ -1557,7 +1559,7 @@ interface IMemberResource{ **/ interface IMemberTypeResource{ //return all member types - getTypes(); + getTypes(): any; } /** @@ -1614,11 +1616,11 @@ interface IPackageResource{ */ import(package: string): number; - installFiles(package: string); + installFiles(package: string): void; - installData(package: string); + installData(package: string): void; - cleanUp(package: string); + cleanUp(package: string): void; } @@ -1629,7 +1631,7 @@ interface IPackageResource{ **/ interface ISectionResource{ /** Loads in the data to display the section list */ - getSections(); + getSections(): void; } /** @@ -1713,13 +1715,13 @@ interface IStylesheetResource{ **/ interface ITreeResource{ /** Loads in the data to display the nodes menu */ - loadMenu(node); + loadMenu(node: any): void; /** Loads in the data to display the nodes for an application */ - loadApplication(options); + loadApplication(options: any): void; /** Loads in the data to display the child nodes for a given node */ - loadNodes(options); + loadNodes(options: any): void; } /** @@ -1727,7 +1729,7 @@ interface ITreeResource{ * @name umbraco.resources.userResource **/ interface IUserResource{ - disableUser(userId: number); + disableUser(userId: number): void; } } diff --git a/umbraco/umbraco-services.d.ts b/umbraco/umbraco-services.d.ts index 85fb8fefcd..3954e5f54c 100644 --- a/umbraco/umbraco-services.d.ts +++ b/umbraco/umbraco-services.d.ts @@ -3,6 +3,7 @@ // Definitions by: DeCareSystemsIreland // Definitions: https://github.com/borisyankov/DefinitelyTyped +/// /// declare module umbraco.services { @@ -29,7 +30,7 @@ declare module umbraco.services { * * @param {object} objReject The object to send back with the promise rejection */ - rejectedPromise(objReject: Object); + rejectedPromise(objReject: Object): void; /** * @ngdoc function @@ -40,7 +41,7 @@ declare module umbraco.services { * @description * This checks if a digest/apply is already occuring, if not it will force an apply call */ - safeApply(scope: ng.IScope, fn: Function); + safeApply(scope: ng.IScope, fn: Function): void; /** * @ngdoc function @@ -51,7 +52,7 @@ declare module umbraco.services { * @description * Returns the current form object applied to the scope or null if one is not found */ - getCurrentForm(scope: ng.IScope); + getCurrentForm(scope: ng.IScope): any; /** * @ngdoc function @@ -78,7 +79,7 @@ declare module umbraco.services { * * @param {string} formName The form name to assign */ - getNullForm(formName: string); + getNullForm(formName: string): ng.IFormController; } @@ -151,7 +152,7 @@ declare module umbraco.services { interface IAppState { /** function to validate and set the state on a state object */ - setState(stateObj: IStateObject, key: string, value, stateObjName: string): void; + setState(stateObj: IStateObject, key: string, value: any, stateObjName: string): void; /** function to validate and set the state on a state object */ getState(stateObj: IStateObject, key: string, stateObjName: string): IStateObject; @@ -266,7 +267,7 @@ declare module umbraco.services { * like the content editor, where the model is modified by several * child controllers. */ - set(entity): void; + set(entity: Object): void; /** * @ngdoc function @@ -325,7 +326,7 @@ declare module umbraco.services { * @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); + loadCss(path: string, scope: ng.IScope, attributes: Object, timeout: number): ng.IPromise; /** * @ngdoc method @@ -341,7 +342,7 @@ declare module umbraco.services { * @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); + loadJs(path: string, scope: ng.IScope, attributes: Object, timeout: number): ng.IPromise; /** * @ngdoc method @@ -356,7 +357,7 @@ declare module umbraco.services { * @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); + load(pathArray: string[], scope: ng.IScope): ng.IPromise; } /** @@ -376,7 +377,7 @@ declare module umbraco.services { * @description * Returns all propertes contained for the content item (since the normal model has properties contained inside of tabs) */ - getAllProps(content); + getAllProps(content: any): any; /** * @ngdoc method @@ -387,7 +388,7 @@ declare module umbraco.services { * @description * Returns a letter array for buttons, with the primary one first based on content model, permissions and editor state */ - getAllowedActions(content, creating); + getAllowedActions(content: any, creating: any): string[]; /** * @ngdoc method @@ -400,7 +401,7 @@ declare module umbraco.services { * currently only returns built in system buttons for content and media actions * returns label, alias, action char and hot-key */ - getButtonFromAction(ch: string); + getButtonFromAction(ch: string): any; /** * @ngdoc method @@ -411,7 +412,7 @@ declare module umbraco.services { * @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); + reBindChangedProperties(origContent: any, savedContent: any): void; /** * @ngdoc function @@ -422,7 +423,7 @@ declare module umbraco.services { * @description * A function to handle what happens when we have validation issues from the server side */ - handleSaveError(...args: any[]); + handleSaveError(...args: any[]): void; /** * @ngdoc function @@ -435,7 +436,7 @@ declare module umbraco.services { * 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[]); + handleSuccessfulSave(...args: any[]): void; /** * @ngdoc function @@ -448,7 +449,7 @@ declare module umbraco.services { * 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); + redirectToCreatedContent(id: number, modelState: any): void; } /** @@ -798,7 +799,7 @@ declare module umbraco.services { * @description * Opens a dialog to an embed dialog */ - embedDialog(options); + embedDialog(options: any): void; /** * @ngdoc method @@ -808,7 +809,7 @@ declare module umbraco.services { * @description * Opens a dialog to show a custom YSOD */ - ysodDialog(ysodError); + ysodDialog(ysodError: any): void; } /** Used to broadcast and listen for global events and allow the ability to add async listeners to the callbacks */ @@ -852,7 +853,7 @@ declare module umbraco.services { * 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[]); + setFiles(propertyAlias: string, files: IFile[]): void; /** * @ngdoc function @@ -875,7 +876,7 @@ declare module umbraco.services { * @description * Removes all files from the manager */ - clearFiles(); + clearFiles(): void; } /** @@ -909,7 +910,7 @@ declare module umbraco.services { * * @param {object} args An object containing arguments for form submission */ - submitForm(...args: any[]); + submitForm(...args: any[]): void; /** * @ngdoc function @@ -923,7 +924,7 @@ declare module umbraco.services { * * @param {object} args An object containing arguments for form submission */ - resetForm(...args: any[]); + resetForm(...args: any[]): void; /** * @ngdoc function @@ -937,7 +938,7 @@ declare module umbraco.services { * * @param {object} err The error object returned from the http promise */ - handleError(err: Object); + handleError(err: Object): void; /** * @ngdoc function @@ -950,7 +951,7 @@ declare module umbraco.services { * * @param {object} err The error object returned from the http promise */ - handleServerValidation(modelState: IModelState); + handleServerValidation(modelState: IModelState): void; } @@ -1013,7 +1014,7 @@ declare module umbraco.services { * * @param {Int} index index to remove item from */ - remove(index: number); + remove(index: number): void; /** * @ngdoc method @@ -1057,7 +1058,7 @@ declare module umbraco.services { * * @param {object} args an object containing the macro alias and it's parameter values */ - generateMacroSyntax(...args: any[]); + generateMacroSyntax(...args: any[]): void; /** * @ngdoc function @@ -1070,7 +1071,7 @@ declare module umbraco.services { * * @param {object} args an object containing the macro alias and it's parameter values */ - generateWebFormsSyntax(...args: any[]); + generateWebFormsSyntax(...args: any[]): void; /** * @ngdoc function @@ -1083,7 +1084,7 @@ declare module umbraco.services { * * @param {object} args an object containing the macro alias and it's parameter values */ - generateMvcSyntax(...args: any[]); + generateMvcSyntax(...args: any[]): void; } @@ -1202,7 +1203,7 @@ declare module umbraco.services { * @param {number} width Current width * @param {number} height Current height */ - scaleToMaxSize(maxSize: number, width: number, height: number); + scaleToMaxSize(maxSize: number, width: number, height: number): any; /** * @ngdoc function @@ -1334,7 +1335,7 @@ declare module umbraco.services { 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; + setupTreeEvents(treeEventHandler: any): void; /** * @ngdoc method @@ -1363,7 +1364,7 @@ declare module umbraco.services { _syncPath(path: string[], forceReload: boolean): void; //TODO: This should return a promise - reloadNode(node): void; + reloadNode(node: any): void; //TODO: This should return a promise reloadSection(sectionAlias: string): void; @@ -1408,7 +1409,7 @@ declare module umbraco.services { hideMenu(): void; /** Executes a given menu action */ - executeMenuAction(action, node, section): void; + executeMenuAction(action: any, node: any, section: any): void; /** * @ngdoc method @@ -1879,7 +1880,7 @@ declare module umbraco.services { * @description * Gets all callbacks that has been registered using the subscribe method for the field. */ - getFieldCallbacks(fieldName: string); + getFieldCallbacks(fieldName: string): any; /** * @ngdoc function @@ -2036,7 +2037,7 @@ declare module umbraco.services { * Returns a default configration to fallback on in case none is provided * */ - defaultPrevalues(); IConfiguration; + defaultPrevalues(): IConfiguration; /** * @ngdoc method @@ -2075,7 +2076,7 @@ declare module umbraco.services { * @param {Object} editor the TinyMCE editor instance * @param {Object} $scope the current controller scope */ - createInsertMacro(editor: Object, $scope: ng.IScope); + createInsertMacro(editor: Object, $scope: ng.IScope): void; } /** @@ -2200,7 +2201,7 @@ declare module umbraco.services { * @param {object} treeNode to retrive child node from * @param {int} id id of child node */ - getChildNode(treeNode: Object, id: number); + getChildNode(treeNode: Object, id: number): any; /** * @ngdoc method @@ -2214,7 +2215,7 @@ declare module umbraco.services { * @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); + getDescendantNode(treeNode: Object, id: number, treeAlias: string): any; /** * @ngdoc method @@ -2226,7 +2227,7 @@ declare module umbraco.services { * 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); + getTreeRoot(treeNode: Object): any; /** * @ngdoc method @@ -2252,7 +2253,7 @@ declare module umbraco.services { * @param {string} args.section Section alias * @param {string} args.cacheKey Optional cachekey */ - getTree(args: ITreeArgs) + getTree(args: ITreeArgs): ng.IPromise; /** * @ngdoc method @@ -2265,7 +2266,7 @@ declare module umbraco.services { * @param {object} args Arguments * @param {string} args.treeNode tree node object to retrieve the menu for */ - getMenu(...args: any[]); + getMenu(...args: any[]): any; /** * @ngdoc method @@ -2279,7 +2280,7 @@ declare module umbraco.services { * @param {object} args.node tree node object to retrieve the children for * @param {string} args.section current section alias */ - getChildren(...args: any[]); + getChildren(...args: any[]): any; /** * @ngdoc method @@ -2291,7 +2292,7 @@ declare module umbraco.services { * Re-loads the single node from the server * @param {object} node Tree node to reload */ - reloadNode(node: Object); + reloadNode(node: Object): void; /** * @ngdoc method @@ -2306,6 +2307,12 @@ declare module umbraco.services { getPath(node: Object): string; } + + interface KeyValuePair { + key: string; + value: T; + } + /** * @ngdoc service * @name umbraco.services.umbRequestHelper @@ -2337,7 +2344,7 @@ declare module umbraco.services { * * @param {Array} queryStrings An array of key/value pairs */ - dictionaryToQueryString(queryStrings); + dictionaryToQueryString(queryStrings: KeyValuePair[]): string; /** * @ngdoc method @@ -2352,7 +2359,7 @@ declare module umbraco.services { * @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; + getApiUrl(apiName: string, actionName: string, queryStrings: string|KeyValuePair[]): string; /** * @ngdoc function @@ -2377,7 +2384,7 @@ declare module umbraco.services { */ resourcePromise(httpPromise: ng.IPromise, opts: string | { success: ng.IHttpPromiseCallback; errorMsg: string } | - { success: ng.IHttpPromiseCallback; error: ng.IHttpPromiseCallback }); + { success: ng.IHttpPromiseCallback; error: ng.IHttpPromiseCallback }): umb.resources.IResourcePromise| Object; } } From a8310cd918d6cf092693fe8eac2cbe5decee0965 Mon Sep 17 00:00:00 2001 From: Slavo Vojacek Date: Tue, 11 Aug 2015 14:54:33 +0100 Subject: [PATCH 41/53] Update moment-node.d.ts According to http://momentjs.com/docs/#/parsing/is-valid/, there is a invalidAt() method, which is missing in this definition file. Source: https://github.com/moment/moment/blob/develop/src/lib/moment/valid.js#L13 Thanks, --- moment/moment-node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 3728f898f7..9781e93683 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -401,6 +401,7 @@ declare module moment { unix(timestamp: number): Moment; invalid(parsingFlags?: Object): Moment; + invalidAt(): number; isMoment(): boolean; isMoment(m: any): boolean; isDate(m: any): boolean; From 18e75c5f19f01fbd5324f6234a79872d5379f1b3 Mon Sep 17 00:00:00 2001 From: Slavo Vojacek Date: Tue, 11 Aug 2015 15:01:36 +0100 Subject: [PATCH 42/53] Update moment-node.d.ts --- moment/moment-node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/moment/moment-node.d.ts b/moment/moment-node.d.ts index 9781e93683..d56c15649b 100644 --- a/moment/moment-node.d.ts +++ b/moment/moment-node.d.ts @@ -193,6 +193,7 @@ declare module moment { utc(): Moment; // current date/time in UTC mode isValid(): boolean; + invalidAt(): number; year(y: number): Moment; year(): number; @@ -401,7 +402,6 @@ declare module moment { unix(timestamp: number): Moment; invalid(parsingFlags?: Object): Moment; - invalidAt(): number; isMoment(): boolean; isMoment(m: any): boolean; isDate(m: any): boolean; From 934a6ee53761536dba1a2052d46800f3043047b8 Mon Sep 17 00:00:00 2001 From: Christian Schwarz Date: Tue, 11 Aug 2015 20:46:23 +0200 Subject: [PATCH 43/53] Added typings for sequelize-fixtures --- .../sequelize-fixtures-tests.ts | 21 +++++++++++++ sequelize-fixtures/sequelize-fixtures.d.ts | 31 +++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 sequelize-fixtures/sequelize-fixtures-tests.ts create mode 100644 sequelize-fixtures/sequelize-fixtures.d.ts diff --git a/sequelize-fixtures/sequelize-fixtures-tests.ts b/sequelize-fixtures/sequelize-fixtures-tests.ts new file mode 100644 index 0000000000..567cf5967c --- /dev/null +++ b/sequelize-fixtures/sequelize-fixtures-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import Sequelize = require('sequelize'); +import SequelizeFixtures = require('sequelize-fixtures'); + +var sequelize = new Sequelize("", ""); + +SequelizeFixtures.loadFile("", {}).then(() => { }); +SequelizeFixtures.loadFile("", {}, { encoding: "utf8" }).then(() => { }); + +SequelizeFixtures.loadFiles([], {}).then(() => { }); +SequelizeFixtures.loadFiles([], {}, { log: m => { } }).then(() => { }); + +SequelizeFixtures.loadFixture({}, {}).then(() => { }); +sequelize.transaction(function (tx) { + SequelizeFixtures.loadFixture({}, {}, { transaction: tx }).then(() => { }); +}); + +SequelizeFixtures.loadFixtures([], {}).then(() => { }); +SequelizeFixtures.loadFixtures([], {}, { transformFixtureDataFn: (data) => { return data; } }).then(() => { }); \ No newline at end of file diff --git a/sequelize-fixtures/sequelize-fixtures.d.ts b/sequelize-fixtures/sequelize-fixtures.d.ts new file mode 100644 index 0000000000..3cdf3fe8d8 --- /dev/null +++ b/sequelize-fixtures/sequelize-fixtures.d.ts @@ -0,0 +1,31 @@ +// Type definitions for Sequelize-Fixtures 0.4.7 +// Project: https://github.com/domasx2/sequelize-fixtures +// Definitions by: Christian Schwarz +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "sequelize-fixtures" +{ + import * as Sequelize from "sequelize"; + + module SequelizeFixtures { + interface Options { + encoding?: string, + log?: (message: string) => void, + transaction?: Sequelize.Transaction, + transformFixtureDataFn?: (data: any) => any + } + + interface SequelizeFixturesStatic { + loadFile(file: string, models: any, options?: Options): Sequelize.Promise; + loadFiles(files: string[], models: any, options?: Options): Sequelize.Promise; + loadFixture(fixture: any, models: any, options?: Options): Sequelize.Promise; + loadFixtures(fixtures: any[], models: any, options?: Options): Sequelize.Promise; + } + } + + var sequelizeFixtures: SequelizeFixtures.SequelizeFixturesStatic; + + export = sequelizeFixtures; +} \ No newline at end of file From 784bd0eb526dbcd3cef8e69ea65aff486d3dae9b Mon Sep 17 00:00:00 2001 From: luckyllama Date: Tue, 11 Aug 2015 14:31:04 -0700 Subject: [PATCH 44/53] Adding "offset" velocity option Adding the "offset" option used in the "scroll" method. --- velocity-animate/velocity-animate.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/velocity-animate/velocity-animate.d.ts b/velocity-animate/velocity-animate.d.ts index b25a31408c..523098423a 100644 --- a/velocity-animate/velocity-animate.d.ts +++ b/velocity-animate/velocity-animate.d.ts @@ -60,5 +60,6 @@ declare module jquery.velocity { _cacheValues?: boolean; container?: JQuery; axis?: string; + offset?: number; } } From 4c461b900e4eb187130fad184ed115c95b803ce7 Mon Sep 17 00:00:00 2001 From: Victor Miroshnikov Date: Wed, 12 Aug 2015 11:29:16 +0200 Subject: [PATCH 45/53] Adding definition file for ua-parser-js --- ua-parser-js/ua-parser-js-tests.ts | 44 +++++++++ ua-parser-js/ua-parser-js.d.ts | 150 +++++++++++++++++++++++++++++ 2 files changed, 194 insertions(+) create mode 100644 ua-parser-js/ua-parser-js-tests.ts create mode 100644 ua-parser-js/ua-parser-js.d.ts diff --git a/ua-parser-js/ua-parser-js-tests.ts b/ua-parser-js/ua-parser-js-tests.ts new file mode 100644 index 0000000000..02ddf1403f --- /dev/null +++ b/ua-parser-js/ua-parser-js-tests.ts @@ -0,0 +1,44 @@ +/// + +function test_parser(){ + var ua = 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6'; + var parser = new UAParser(ua); + var result = parser.getResult(); + + parser.getUA() + parser.setUA("foo") + + result.ua + + // browser + result.browser.name + result.browser.version + parser.getBrowser().name + parser.getBrowser().version + + // device + result.device.model + result.device.type + result.device.vendor + + parser.getDevice().model + parser.getDevice().type + parser.getDevice().vendor + + // Engine + result.engine.name + result.engine.version + parser.getEngine().name + parser.getEngine().version + + // OS + result.os.name + result.os.version + parser.getOS().name + parser.getOS().version + + // CPU + result.cpu.architecture + parser.getCPU().architecture + +} diff --git a/ua-parser-js/ua-parser-js.d.ts b/ua-parser-js/ua-parser-js.d.ts new file mode 100644 index 0000000000..5ac748dcf5 --- /dev/null +++ b/ua-parser-js/ua-parser-js.d.ts @@ -0,0 +1,150 @@ +// Type definitions for js-cookie v2.0 +// Project: https://github.com/faisalman/ua-parser-js +// Definitions by: Viktor Miroshnikov +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module UAParser { + + export interface IBrowser { + /** + * Possible values : + * Amaya, Android Browser, Arora, Avant, Baidu, Blazer, Bolt, Camino, Chimera, Chrome, + * Chromium, Comodo Dragon, Conkeror, Dillo, Dolphin, Doris, Edge, Epiphany, Fennec, + * Firebird, Firefox, Flock, GoBrowser, iCab, ICE Browser, IceApe, IceCat, IceDragon, + * Iceweasel, IE [Mobile], Iron, Jasmine, K-Meleon, Konqueror, Kindle, Links, + * Lunascape, Lynx, Maemo, Maxthon, Midori, Minimo, MIUI Browser, [Mobile] Safari, + * Mosaic, Mozilla, Netfront, Netscape, NetSurf, Nokia, OmniWeb, Opera [Mini/Mobi/Tablet], + * Phoenix, Polaris, QQBrowser, RockMelt, Silk, Skyfire, SeaMonkey, SlimBrowser, Swiftfox, + * Tizen, UCBrowser, Vivaldi, w3m, Yandex + * + */ + name: string; + + /** + * Determined dynamically + */ + version: string; + } + + export interface IDevice { + /** + * Determined dynamically + */ + model: string; + + /** + * Possible type: + * console, mobile, tablet, smarttv, wearable, embedded + */ + type: string; + + /** + * Possible vendor: + * Acer, Alcatel, Amazon, Apple, Archos, Asus, BenQ, BlackBerry, Dell, GeeksPhone, + * Google, HP, HTC, Huawei, Jolla, Lenovo, LG, Meizu, Microsoft, Motorola, Nexian, + * Nintendo, Nokia, Nvidia, Ouya, Palm, Panasonic, Polytron, RIM, Samsung, Sharp, + * Siemens, Sony-Ericsson, Sprint, Xbox, ZTE + */ + vendor: string; + } + + export interface IEngine { + /** + * Possible name: + * Amaya, EdgeHTML, Gecko, iCab, KHTML, Links, Lynx, NetFront, NetSurf, Presto, + * Tasman, Trident, w3m, WebKit + */ + name: string; + /** + * Determined dynamically + */ + version: string; + } + + export interface IOS{ + /** + * Possible 'os.name' + * AIX, Amiga OS, Android, Arch, Bada, BeOS, BlackBerry, CentOS, Chromium OS, Contiki, + * Fedora, Firefox OS, FreeBSD, Debian, DragonFly, Gentoo, GNU, Haiku, Hurd, iOS, + * Joli, Linpus, Linux, Mac OS, Mageia, Mandriva, MeeGo, Minix, Mint, Morph OS, NetBSD, + * Nintendo, OpenBSD, OpenVMS, OS/2, Palm, PCLinuxOS, Plan9, Playstation, QNX, RedHat, + * RIM Tablet OS, RISC OS, Sailfish, Series40, Slackware, Solaris, SUSE, Symbian, Tizen, + * Ubuntu, UNIX, VectorLinux, WebOS, Windows [Phone/Mobile], Zenwalk + */ + name: string; + /** + * Determined dynamically + */ + version: string; + } + + export interface ICPU{ + /** + * Possible architecture: + * 68k, amd64, arm, arm64, avr, ia32, ia64, irix, irix64, mips, mips64, pa-risc, + * ppc, sparc, sparc64 + */ + architecture: string; + } + + export interface IResult{ + ua: string; + browser: IBrowser; + device: IDevice; + engine: IEngine; + os: IOS; + cpu: ICPU; + } + +} + +declare class UAParser { + /** + * Returns browser information + */ + getBrowser(): UAParser.IBrowser; + /** + * Returns OS information + */ + getOS(): UAParser.IOS; + + /** + * Returns browsers engine information + */ + getEngine(): UAParser.IEngine; + + /** + * Returns device information + */ + getDevice(): UAParser.IDevice; + + /** + * Returns parsed CPU information + */ + getCPU(): UAParser.ICPU; + + /** + * Returns UA string of current instance + */ + getUA(): string; + + /** + * Set & parse UA string + */ + setUA(ua: string): void; + + /** + * Returns parse result + */ + getResult(): UAParser.IResult; + + /** + * Create a new parser + */ + constructor (); + + /** + * Create a new parser with UA prepopulated + */ + constructor (ua: string); +} From d202e275b263219946050e94463a5250c0ac93f6 Mon Sep 17 00:00:00 2001 From: Steve Ognibene Date: Wed, 12 Aug 2015 16:27:16 -0400 Subject: [PATCH 46/53] Fleshed out some other ways to write tests with Nodeunit. --- nodeunit/nodeunit-tests.ts | 82 +++++++++++++++++++++++++++++++++++++- nodeunit/nodeunit.d.ts | 27 ++++++++----- 2 files changed, 97 insertions(+), 12 deletions(-) diff --git a/nodeunit/nodeunit-tests.ts b/nodeunit/nodeunit-tests.ts index bdd705b0e3..e7cf5e73e9 100644 --- a/nodeunit/nodeunit-tests.ts +++ b/nodeunit/nodeunit-tests.ts @@ -14,10 +14,10 @@ var block: () =>{ }; export var testGroup: nodeunit.ITestGroup = { - setUp: function (callback: nodeunit.ICallbackFunction) { + setUp: (callback) => { callback(); }, - tearDown: function (callback: nodeunit.ICallbackFunction) { + tearDown: (callback) => { callback(); }, test1: function (test: nodeunit.Test) { @@ -55,5 +55,83 @@ export var testGroup: nodeunit.ITestGroup = { test.done(error); test.done(); + }, + "This is a test with a nice description": (test: nodeunit.Test) => { + test.done(); } }; + + +// see https://github.com/caolan/nodeunit/blob/master/examples/nested/nested_reporter_test.unit.js for example. +// (https://github.com/caolan/nodeunit/commit/9fee91149324f79753eadbcf8993399a7d76da40) + + + +var testCase = nodeunit.testCase; + +export var testCaseGroup = testCase({ + "Test 0.1": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + }, + + "TC 1": testCase({ + "TC 1.1": testCase({ + "Test 1.1.1": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + } + }) + }), + + "TC 2": testCase({ + "TC 2.1": testCase({ + "TC 2.1.1": testCase({ + "Test 2.1.1.1": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + }, + + "Test 2.1.1.2": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + } + }), + + "TC 2.2.1": testCase({ + "Test 2.2.1.1": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + }, + + "TC 2.2.1.1": testCase({ + "Test 2.2.1.1.1": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + }, + }), + + "Test 2.2.1.2": function(test: nodeunit.Test) { + test.ok(true); + test.done(); + } + }) + }) + }), + + "TC 3": testCase({ + "TC 3.1": testCase({ + "TC 3.1.1": testCase({ + "Test 3.1.1.1 (should fail)": function(test: nodeunit.Test) { + test.ok(false); + test.done(); + } + }) + }) + }) +}); + + + + + diff --git a/nodeunit/nodeunit.d.ts b/nodeunit/nodeunit.d.ts index c427dbf171..2775ee23c5 100644 --- a/nodeunit/nodeunit.d.ts +++ b/nodeunit/nodeunit.d.ts @@ -6,6 +6,11 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/nodeunit.d.ts declare module 'nodeunit' { + export interface ITestCase { + (testCase: {[property: string]: ITestBody | ITestGroup | void}) : void; + } + export var testCase : ITestCase; + export interface Test { done: ICallbackFunction; expect(num: number): void; @@ -31,15 +36,15 @@ declare module 'nodeunit' { // Test Group Usage: // var testGroup: nodeunit.ITestGroup = { - // setUp: function (callback: nodeunit.ICallbackFunction): void { - // callback(); - // }, - // tearDown: function (callback: nodeunit.ICallbackFunction): void { - // callback(); - // }, - // test1: function (test: nodeunit.Test): void { - // test.done(); - // } + // setUp: (callback) => { + // callback(); + // }, + // tearDown: (callback) => { + // callback(); + // }, + // test1: (test: nodeunit.Test) => { + // test.done(); + // } // } // exports.testgroup = testGroup; @@ -48,12 +53,14 @@ declare module 'nodeunit' { } export interface ITestGroup { + /** The setUp function is run before each test */ setUp?: (callback: ICallbackFunction) => void; + /** The tearDown function is run after each test calls test.done() */ tearDown?: (callback: ICallbackFunction) => void; + [property: string] : ITestGroup | ITestBody | ((callback: ICallbackFunction) => void); } export interface ICallbackFunction { (err?: any): void; } } - From f3c213e2e30881b38e9ec3a599df8db70baa099d Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 9 Aug 2015 19:38:14 +0500 Subject: [PATCH 47/53] lodash: added _.add() method --- lodash/lodash-tests.ts | 8 ++++++++ lodash/lodash.d.ts | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index d36b5dfc4e..b72ddddcb0 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1086,6 +1086,14 @@ result = _([1]).toPlainObject(); result = _([]).toPlainObject(); result = _({}).toPlainObject(); +/******** + * Math * + ********/ + +// _.add +result = _.add(1, 1); +result = _(1).add(1); + /********** * Objects * ***********/ diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7c41117466..b576ccd7ef 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5908,6 +5908,28 @@ declare module _ { toPlainObject(value?: any): Object; } + /******** + * Math * + ********/ + + //_.add + interface LoDashStatic { + /** + * Adds two numbers. + * @param augend The first number to add. + * @param addend The second number to add. + * @return Returns the sum. + */ + add(augend: number, addend: number): number; + } + + interface LoDashWrapper { + /** + * @see _.add + */ + add(addend: number): number; + } + /************* * Objects * *************/ From 9a7dc3c0e24da917c32524e14d9b3efdbd952729 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 10 Aug 2015 23:21:35 +0500 Subject: [PATCH 48/53] lodash: changed _.create() method --- lodash/lodash-tests.ts | 19 +++++++++++++++++++ lodash/lodash.d.ts | 29 +++++++++++++++++++---------- 2 files changed, 38 insertions(+), 10 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index d36b5dfc4e..c0a8c85470 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1113,6 +1113,25 @@ result = <_.LoDashObjectWrapper>_({ 'name': 'moe' }).extend({ 'age': 40 return typeof a == 'undefined' ? b : a; }); +// _.create +interface TestCreateProto { + a: number; +} +interface TestCreateProps { + b: string; +} +interface TestCreateTResult extends TestCreateProto, TestCreateProps {} +var testCreateProto: TestCreateProto; +var testCreateProps: TestCreateProps; +result = <{}>_.create(testCreateProto); +result = <{}>_.create(testCreateProto, testCreateProps); +result = _.create(testCreateProto); +result = _.create(testCreateProto, testCreateProps); +result = <{}>_(testCreateProto).create().value(); +result = <{}>_(testCreateProto).create(testCreateProps).value(); +result = _(testCreateProto).create().value(); +result = _(testCreateProto).create(testCreateProps).value(); + result = _.clone(stoogesAges); result = _.clone(stoogesAges, true); result = _.clone(stoogesAges, true, function (value) { diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7c41117466..8fb368f8b9 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -6104,6 +6104,25 @@ declare module _ { } + //_.create + interface LoDashStatic { + /** + * Creates an object that inherits from the given prototype object. If a properties object is provided its own + * enumerable properties are assigned to the created object. + * @param prototype The object to inherit from. + * @param properties The properties to assign to the object. + * @return Returns the new object. + */ + create(prototype: Object, properties?: Object): TResult; + } + + interface LoDashObjectWrapper { + /** + * @see _.create + */ + create(properties?: Object): LoDashObjectWrapper; + } + //_.clone interface LoDashStatic { /** @@ -7391,16 +7410,6 @@ declare module _ { constant(): () => TResult; } - //_.create - interface LoDashStatic { - /** - * Creates an object that inherits from the given prototype object. If a properties object is provided its own enumerable properties are assigned to the created object. - * @param prototype The object to inherit from. - * @param properties The properties to assign to the object. - */ - create(prototype: Object, properties?: Object): Object; - } - interface ListIterator { (value: T, index: number, collection: T[]): TResult; } From ee4d7e5e9cc0fa1642f31b1135333869a83b2b4d Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 9 Aug 2015 20:21:01 +0500 Subject: [PATCH 49/53] lodash: added _.isMatch() method --- lodash/lodash-tests.ts | 9 +++++++++ lodash/lodash.d.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index d36b5dfc4e..f6048025e9 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1060,6 +1060,15 @@ result = _(1).gte(2); result = _([]).gte(2); result = _({}).gte(2); +// _.isMatch +var testIsMatchCustiomizerFn: (value: any, other: any, indexOrKey: number|string) => boolean; +result = _.isMatch({}, {}); +result = _.isMatch({}, {}, testIsMatchCustiomizerFn); +result = _.isMatch({}, {}, testIsMatchCustiomizerFn, {}); +result = _({}).isMatch({}); +result = _({}).isMatch({}, testIsMatchCustiomizerFn); +result = _({}).isMatch({}, testIsMatchCustiomizerFn, {}); + // _.lt result = _.lt(1, 2); result = _(1).lt(2); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 7c41117466..7ea01692ea 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -5861,6 +5861,33 @@ declare module _ { gte(other: any): boolean; } + //_.isMatch + interface isMatchCustomizer { + (value: any, other: any, indexOrKey?: number|string): boolean; + } + + interface LoDashStatic { + /** + * Performs a deep comparison between object and source to determine if object contains equivalent property + * values. If customizer is provided it’s invoked to compare values. If customizer returns undefined + * comparisons are handled by the method instead. The customizer is bound to thisArg and invoked with three + * arguments: (value, other, index|key). + * @param object The object to inspect. + * @param source The object of property values to match. + * @param customizer The function to customize value comparisons. + * @param thisArg The this binding of customizer. + * @return Returns true if object is a match, else false. + */ + isMatch(object: Object, source: Object, customizer?: isMatchCustomizer, thisArg?: any): boolean; + } + + interface LoDashObjectWrapper { + /** + * @see _.isMatch + */ + isMatch(source: Object, customizer?: isMatchCustomizer, thisArg?: any): boolean; + } + //_.lt interface LoDashStatic { /** From 8ccedd8242b9ae4516b2e88c28c742f6ad87a1c1 Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Mon, 10 Aug 2015 22:09:17 +0500 Subject: [PATCH 50/53] lodash: added _.propertyOf() method --- lodash/lodash-tests.ts | 11 +++++++++++ lodash/lodash.d.ts | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index d36b5dfc4e..9ffe258979 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -1439,6 +1439,17 @@ result = _.result(object, 'stuff'); var tempObject = {}; result = _.runInContext(tempObject); +// _.propertyOf +interface TestPropertyOfObject { + a: { + b: number[]; + } +} +var testPropertyOfObject: TestPropertyOfObject; +result = <(path: string|string[]) => any>_.propertyOf({}); +result = <(path: string|string[]) => any>_.propertyOf(testPropertyOfObject); +result = <(path: string|string[]) => any>_({}).propertyOf().value(); + result = <_.TemplateExecutor>_.template('hello <%= name %>'); result = _.template('<%- value %>', { 'value': '