From ee872c633411d2524cafc68d339f016acbfa1fd6 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Sun, 14 Sep 2014 00:08:00 +0300 Subject: [PATCH 01/38] Added definitions for "cors" and "tea-merge" --- cors/cors-tests.ts | 11 +++++++++++ cors/cors.d.ts | 24 ++++++++++++++++++++++++ tea-merge/tea-merge-tests.ts | 6 ++++++ tea-merge/tea-merge.d.ts | 9 +++++++++ 4 files changed, 50 insertions(+) create mode 100644 cors/cors-tests.ts create mode 100644 cors/cors.d.ts create mode 100644 tea-merge/tea-merge-tests.ts create mode 100644 tea-merge/tea-merge.d.ts diff --git a/cors/cors-tests.ts b/cors/cors-tests.ts new file mode 100644 index 000000000..a3f5ea10e --- /dev/null +++ b/cors/cors-tests.ts @@ -0,0 +1,11 @@ +/// + +import express = require('express'); +import cors = require('cors'); + +var app = express(); +app.use(cors()); +app.use(cors({ + maxAge: 100, + credentials: true +})); diff --git a/cors/cors.d.ts b/cors/cors.d.ts new file mode 100644 index 000000000..92fdd9634 --- /dev/null +++ b/cors/cors.d.ts @@ -0,0 +1,24 @@ +// Type definitions for cors +// Project: https://github.com/troygoode/node-cors/ +// Definitions by: Mihhail Lapushkin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +declare module "cors" { + import express = require('express'); + + module e { + interface CorsOptions { + origin?: any; + methods?: any; + allowedHeaders?: any; + exposedHeaders?: any; + credentials?: boolean; + maxAge?: number; + } + } + + function e(options?: e.CorsOptions): express.RequestHandler; + export = e; +} \ No newline at end of file diff --git a/tea-merge/tea-merge-tests.ts b/tea-merge/tea-merge-tests.ts new file mode 100644 index 000000000..9d59bd65e --- /dev/null +++ b/tea-merge/tea-merge-tests.ts @@ -0,0 +1,6 @@ +/// + +import merge = require('tea-merge'); + +merge({ a: 1 }, { b: 2 }, { c: 'hello' }); +merge({ a1: true, a2: { b: 'hello' } }, { bca: [], a2: { c: 'world' } }); diff --git a/tea-merge/tea-merge.d.ts b/tea-merge/tea-merge.d.ts new file mode 100644 index 000000000..2000e9bcd --- /dev/null +++ b/tea-merge/tea-merge.d.ts @@ -0,0 +1,9 @@ +// Type definitions for tea-merge +// Project: https://github.com/qualiancy/tea-merge +// Definitions by: Mihhail Lapushkin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +declare module "tea-merge" { + function e(destination: Object, ...sources: Object[]): Object; + export = e; +} \ No newline at end of file From a63e25478678d2cf4e6f646717b06ac30392ace7 Mon Sep 17 00:00:00 2001 From: mihhail-lapushkin Date: Wed, 17 Sep 2014 20:34:25 +0300 Subject: [PATCH 02/38] Cordova Contacts plugin fix In find() method the onError callback should be optional. https://cordova.apache.org/docs/en/3.3.0/cordova_contacts_contacts.md.ht ml#contacts.find --- cordova/plugins/Contacts.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index f054c12d0..afc3aa903 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -32,7 +32,7 @@ interface Contacts { */ find(fields: string[], onSuccess: (contacts: Contact[]) => void, - onError: (error: ContactError) => void, + onError?: (error: ContactError) => void, options?: ContactFindOptions): void; } From 52444b5afa70f89d846fa4e0d8671bc90fc169b7 Mon Sep 17 00:00:00 2001 From: Ralf Kruse Date: Sun, 10 May 2015 02:23:43 +0200 Subject: [PATCH 03/38] getElementByPoint returns Snap.Element --- snapsvg/snapsvg.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapsvg/snapsvg.d.ts b/snapsvg/snapsvg.d.ts index a900680bc..cce6e6750 100644 --- a/snapsvg/snapsvg.d.ts +++ b/snapsvg/snapsvg.d.ts @@ -43,7 +43,7 @@ declare module Snap { export function ajax(url:string,callback:Function,scope?:Object):XMLHttpRequest; export function format(token:string,json:Object):string; export function fragment(varargs:any):Fragment; - export function getElementByPoint(x:number,y:number):Object; + export function getElementByPoint(x:number,y:number):Snap.Element; export function is(o:any,type:string):boolean; export function load(url:string,callback:Function,scope?:Object):void; export function plugin(f:Function):void; From bfcc6ddbc0c3d3761d7935f60cf46bf99a24ff1f Mon Sep 17 00:00:00 2001 From: Ralf Kruse Date: Sun, 10 May 2015 02:24:05 +0200 Subject: [PATCH 04/38] Snap.Element has an id property --- snapsvg/snapsvg.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/snapsvg/snapsvg.d.ts b/snapsvg/snapsvg.d.ts index cce6e6750..c7add1165 100644 --- a/snapsvg/snapsvg.d.ts +++ b/snapsvg/snapsvg.d.ts @@ -131,6 +131,7 @@ declare module Snap { getSubpath(from:number,to:number):string; getTotalLength():number; hasClass(value:string):boolean; + id:string; inAnim():Object; innerSVG():string; insertAfter(el:Snap.Element):Snap.Element; From 6befcf5e84a99dcee756f5f304c3e003683e7f8e Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:51:07 -0400 Subject: [PATCH 05/38] MediaStream typings --- webrtc/MediaStream.d.ts | 308 +++++++++++++++++++++------------------- 1 file changed, 165 insertions(+), 143 deletions(-) diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 54de34e38..6db34de94 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -5,161 +5,183 @@ // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +/// + +interface ConstrainBooleanParameters { + exact: boolean; + ideal: boolean; +} + +interface NumberRange { + max: number; + min: number; +} + +interface ConstrainNumberRange extends NumberRange { + exact: number; + ideal: number; +} + +interface ConstrainStringParameters { + exact: string | string[]; + ideal: string | string[]; +} + interface MediaStreamConstraints { - audio: any; - video: any; + video?: boolean | MediaTrackConstraints; + audio?: boolean | MediaTrackConstraints; } -declare var MediaStreamConstraints: { - prototype: MediaStreamConstraints; - new (): MediaStreamConstraints; -}; interface MediaTrackConstraints { - mandatory: MediaTrackConstraintSet; - optional: MediaTrackConstraint[]; + advanced: MediaTrackConstraintSet[]; +} + +declare module W3C { + type LongRange = NumberRange; + type DoubleRange = NumberRange; + type ConstrainBoolean = boolean | ConstrainBooleanParameters; + type ConstrainNumber = number | ConstrainNumberRange; + type ConstrainLong = ConstrainNumber; + type ConstrainDouble = ConstrainNumber; + type ConstrainString = string | string[] | ConstrainStringParameters; } -declare var MediaTrackConstraints: { - prototype: MediaTrackConstraints; - new (): MediaTrackConstraints; -}; -// ks - Not defined in the source doc. interface MediaTrackConstraintSet { + width: W3C.ConstrainLong; + height: W3C.ConstrainLong; + aspectRatio: W3C.ConstrainDouble; + frameRate: W3C.ConstrainDouble; + facingMode: W3C.ConstrainString; + volume: W3C.ConstrainDouble; + sampleRate: W3C.ConstrainLong; + sampleSize: W3C.ConstrainLong; + echoCancellation: W3C.ConstrainBoolean; + latency: W3C.ConstrainDouble; + deviceId: W3C.ConstrainString; + groupId: W3C.ConstrainString; } -declare var MediaTrackConstraintSet: { - prototype: MediaTrackConstraintSet; - new (): MediaTrackConstraintSet; -}; -// ks - Not defined in the source doc. -interface MediaTrackConstraint { +interface MediaTrackSupportedConstraints { + width: boolean; + height: boolean; + aspectRatio: boolean; + frameRate: boolean; + facingMode: boolean; + volume: boolean; + sampleRate: boolean; + sampleSize: boolean; + echoCancellation: boolean; + latency: boolean; + deviceId: boolean; + groupId: boolean; +} + +interface MediaStream extends EventTarget { + id: string; + active: boolean; + + onactive: EventListener; + oninactive: EventListener; + onaddtrack: (event: MediaStreamTrackEvent) => any; + onremovetrack: (event: MediaStreamTrackEvent) => any; + + clone(): MediaStream; + stop(): void; + + getAudioTracks(): MediaStreamTrack[]; + getVideoTracks(): MediaStreamTrack[]; + getTracks(): MediaStreamTrack[]; + + getTrackById(trackId: string): MediaStreamTrack; + + addTrack(track: MediaStreamTrack): void; + removeTrack(track: MediaStreamTrack): void; +} + +interface MediaStreamTrackEvent extends Event { + track: MediaStreamTrack; +} + +interface MediaStreamTrack extends EventTarget { + id: string; + kind: string; + label: string; + enabled: boolean; + muted: boolean; + remote: boolean; + readyState: string; + + onmute: EventListener; + onunmute: EventListener; + onended: EventListener; + onoverconstrained: EventListener; + + clone(): MediaStreamTrack; + + stop(): void; + + getCapabilities(): MediaTrackCapabilities; + getConstraints(): MediaTrackConstraints; + getSettings(): MediaTrackSettings; + applyConstraints(constraints: MediaTrackConstraints): Promise; +} + +interface MediaTrackCapabilities { + width: number | W3C.LongRange; + height: number | W3C.LongRange; + aspectRatio: number | W3C.DoubleRange; + frameRate: number | W3C.DoubleRange; + facingMode: string; + volume: number | W3C.DoubleRange; + sampleRate: number | W3C.LongRange; + sampleSize: number | W3C.LongRange; + echoCancellation: boolean[]; + latency: number | W3C.DoubleRange; + deviceId: string; + groupId: string; +} + +interface MediaTrackSettings { + width: number; + height: number; + aspectRatio: number; + frameRate: number; + facingMode: string; + volume: number; + sampleRate: number; + sampleSize: number; + echoCancellation: boolean; + latency: number; + deviceId: string; + groupId: string; +} + +interface MediaStreamError { + name: string; + message: string; + constraintName: string; +} + +interface NavigatorGetUserMedia { + (constraints: MediaStreamConstraints, + successCallback: (stream: MediaStream) => void, + errorCallback: (error: MediaStreamError) => void): void; } -declare var MediaTrackConstraint: { - prototype: MediaTrackConstraint; - new (): MediaTrackConstraints; -}; interface Navigator { - getUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void) : void; - webkitGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; - mozGetUserMedia(constraints: MediaStreamConstraints, - successCallback: (stream: any) => void, - errorCallback: (error: Error) => void): void; + getUserMedia: NavigatorGetUserMedia; + + webkitGetUserMedia: NavigatorGetUserMedia; + + mozGetUserMedia: NavigatorGetUserMedia; + + msGetUserMedia: NavigatorGetUserMedia; + + mediaDevices: MediaDevices; } -interface EventHandler { (event: Event): void; } - -interface NavigatorUserMediaSuccessCallback { - (stream: LocalMediaStream): void; +interface MediaDevices { + getSupportedConstraints(): MediaTrackSupportedConstraints; + + getUserMedia(constraints: MediaStreamConstraints): Promise; } - -interface NavigatorUserMediaError { - PERMISSION_DENIED: number; // = 1; - code: number; -} -declare var NavigatorUserMediaError: { - prototype: NavigatorUserMediaError; - new (): NavigatorUserMediaError; - PERMISSION_DENIED: number; // = 1; -}; - -interface NavigatorUserMediaErrorCallback { - (error: NavigatorUserMediaError): void; -} - -interface MediaStreamTrackList { - length: number; - item: MediaStreamTrack; - add(track: MediaStreamTrack): void; - remove(track: MediaStreamTrack): void; - onaddtrack: (event: Event) => void; - onremovetrack: (event: Event) => void; -} -declare var MediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; -declare var webkitMediaStreamTrackList: { - prototype: MediaStreamTrackList; - new (): MediaStreamTrackList; -}; - -interface MediaStream extends EventTarget{ - label: string; - id: string; - getAudioTracks(): MediaStreamTrackList; - getVideoTracks(): MediaStreamTrackList; - ended: boolean; - onended: (event: Event) => void; -} -declare var MediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; -declare var webkitMediaStream: { - prototype: MediaStream; - new (): MediaStream; - new (trackContainers: MediaStream[]): MediaStream; - new (trackContainers: MediaStreamTrackList[]): MediaStream; - new (trackContainers: MediaStreamTrack[]): MediaStream; -}; - -// an - not defined in source doc. -interface SourceInfo { - label: string; - id: string; - kind: string; - facing: string; -} -declare var SourceInfo: { - prototype: SourceInfo; -}; - -interface LocalMediaStream extends MediaStream { - stop(): void; -} - -interface MediaStreamTrack extends EventTarget{ - kind: string; - label: string; - enabled: boolean; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - readyState: number; - onmute: (event: Event) => void; - onunmute: (event: Event) => void; - onended: (event: Event) => void; -} -declare var MediaStreamTrack: { - prototype: MediaStreamTrack; - new (): MediaStreamTrack; - LIVE: number; // = 0; - MUTED: number; // = 1; - ENDED: number; // = 2; - getSources: (callback: (sources: SourceInfo[]) => void) => void; -}; - -interface streamURL extends URL { - createObjectURL(stream: MediaStream): string; -} -//declare var URL: { -// prototype: MediaStreamTrack; -// new (): URL; -// createObjectURL(stream: MediaStream): string; -//} - -interface WebkitURL extends streamURL { -} -declare var webkitURL: { - prototype: WebkitURL; - new (): streamURL; - createObjectURL(stream: MediaStream): string; -}; From 35e40c5d8500681f7d05c9aef81ad50f9e043c85 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Mon, 20 Jul 2015 18:52:58 -0400 Subject: [PATCH 06/38] some WebAudio interface missing methods --- webaudioapi/waa.d.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/webaudioapi/waa.d.ts b/webaudioapi/waa.d.ts index 3ccc78b78..80823700a 100644 --- a/webaudioapi/waa.d.ts +++ b/webaudioapi/waa.d.ts @@ -171,3 +171,35 @@ declare enum OscillatorType { triangle, custom } + +interface AudioContextConstructor { + new(): AudioContext; +} + +interface Window { + AudioContext: AudioContextConstructor; +} + +interface AudioContext { + createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode; +} + +interface MediaStreamAudioSourceNode extends AudioNode { + +} + +interface AudioBuffer { + copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; + + copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; +} + +interface AudioNode { + disconnect(destination: AudioNode): void; +} + +interface AudioContext { + suspend(): Promise; + resume(): Promise; + close(): Promise; +} From 7f8dfda9a76069741b448ca029d273c68ef98e38 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:34:16 -0400 Subject: [PATCH 07/38] Fix test cases --- webrtc/MediaStream-tests.ts | 28 ++++++++++++-------------- webrtc/MediaStream.d.ts | 40 +++++++++++++++++++++---------------- 2 files changed, 36 insertions(+), 32 deletions(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 0d4e710b8..516abcb02 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -2,16 +2,16 @@ var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true }; var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; -var mediaTrackConstraintArray: MediaTrackConstraint[] = []; +var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } navigator.getUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); @@ -20,12 +20,11 @@ navigator.getUserMedia(mediaStreamConstraints, navigator.webkitGetUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); @@ -35,12 +34,11 @@ navigator.webkitGetUserMedia(mediaStreamConstraints, navigator.mozGetUserMedia(mediaStreamConstraints, stream => { - console.log('label:' + stream.label); - console.log('ended:' + stream.ended); - stream.onended = (event:Event) => console.log('Stream ended'); - stream.addEventListener("ended", (event:Event) => console.log('Stream ended')); + var track: MediaStreamTrack = stream.getTracks()[0]; + console.log('label:' + track.label); + console.log('ended:' + track.readyState); + track.onended = (event:Event) => console.log('Track ended'); var objectUrl = URL.createObjectURL(stream); - var wkObjectUrl = webkitURL.createObjectURL(stream); }, error => { console.log('Error message: ' + error.message); diff --git a/webrtc/MediaStream.d.ts b/webrtc/MediaStream.d.ts index 6db34de94..f52551a14 100644 --- a/webrtc/MediaStream.d.ts +++ b/webrtc/MediaStream.d.ts @@ -4,6 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped // Taken from http://dev.w3.org/2011/webrtc/editor/getusermedia.html +// version: W3C Editor's Draft 29 June 2015 /// @@ -32,10 +33,6 @@ interface MediaStreamConstraints { audio?: boolean | MediaTrackConstraints; } -interface MediaTrackConstraints { - advanced: MediaTrackConstraintSet[]; -} - declare module W3C { type LongRange = NumberRange; type DoubleRange = NumberRange; @@ -46,19 +43,23 @@ declare module W3C { type ConstrainString = string | string[] | ConstrainStringParameters; } +interface MediaTrackConstraints extends MediaTrackConstraintSet { + advanced?: MediaTrackConstraintSet[]; +} + interface MediaTrackConstraintSet { - width: W3C.ConstrainLong; - height: W3C.ConstrainLong; - aspectRatio: W3C.ConstrainDouble; - frameRate: W3C.ConstrainDouble; - facingMode: W3C.ConstrainString; - volume: W3C.ConstrainDouble; - sampleRate: W3C.ConstrainLong; - sampleSize: W3C.ConstrainLong; - echoCancellation: W3C.ConstrainBoolean; - latency: W3C.ConstrainDouble; - deviceId: W3C.ConstrainString; - groupId: W3C.ConstrainString; + width?: W3C.ConstrainLong; + height?: W3C.ConstrainLong; + aspectRatio?: W3C.ConstrainDouble; + frameRate?: W3C.ConstrainDouble; + facingMode?: W3C.ConstrainString; + volume?: W3C.ConstrainDouble; + sampleRate?: W3C.ConstrainLong; + sampleSize?: W3C.ConstrainLong; + echoCancellation?: W3C.ConstrainBoolean; + latency?: W3C.ConstrainDouble; + deviceId?: W3C.ConstrainString; + groupId?: W3C.ConstrainString; } interface MediaTrackSupportedConstraints { @@ -102,6 +103,11 @@ interface MediaStreamTrackEvent extends Event { track: MediaStreamTrack; } +declare enum MediaStreamTrackState { + "live", + "ended" +} + interface MediaStreamTrack extends EventTarget { id: string; kind: string; @@ -109,7 +115,7 @@ interface MediaStreamTrack extends EventTarget { enabled: boolean; muted: boolean; remote: boolean; - readyState: string; + readyState: MediaStreamTrackState; onmute: EventListener; onunmute: EventListener; From d821276efc1882cb363f783c2071ad5b44ebe781 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:39:59 -0400 Subject: [PATCH 08/38] LocalMediaStream is deprecated --- chrome/chrome.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chrome/chrome.d.ts b/chrome/chrome.d.ts index 1df792b42..a8a48b82e 100755 --- a/chrome/chrome.d.ts +++ b/chrome/chrome.d.ts @@ -1822,7 +1822,7 @@ declare module chrome.tabCapture { videoConstraints?: MediaTrackConstraints; } - export function capture(options: CaptureOptions, callback: (stream: LocalMediaStream) => void): void; + export function capture(options: CaptureOptions, callback: (stream: MediaStream) => void): void; export function getCapturedTabs(callback: (result: CaptureInfo[]) => void): void; } From f081c7118745dec548382e0975a803835336cff1 Mon Sep 17 00:00:00 2001 From: Gabriel Garcia Date: Fri, 24 Jul 2015 18:44:40 -0400 Subject: [PATCH 09/38] mandatory/optional is deprecated --- webrtc/MediaStream-tests.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webrtc/MediaStream-tests.ts b/webrtc/MediaStream-tests.ts index 516abcb02..c309a281b 100644 --- a/webrtc/MediaStream-tests.ts +++ b/webrtc/MediaStream-tests.ts @@ -3,7 +3,8 @@ var mediaStreamConstraints: MediaStreamConstraints = { audio: true, video: true var mediaTrackConstraintSet: MediaTrackConstraintSet = {}; var mediaTrackConstraintArray: MediaTrackConstraintSet[] = []; -var mediaTrackConstraints: MediaTrackConstraints = { mandatory: mediaTrackConstraintSet, optional: mediaTrackConstraintArray } +var mediaTrackConstraints: MediaTrackConstraints = mediaTrackConstraintSet; +var mediaTrackConstraints2: MediaTrackConstraints = { advanced: mediaTrackConstraintArray }; navigator.getUserMedia(mediaStreamConstraints, stream => { From b8130a65bc3284dd1ac1cde827370771b35dc6ee Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 11:52:32 +0200 Subject: [PATCH 10/38] Moved pixi to pixi.js https://www.npmjs.com/package/pixi has been deprecated in favor of the official https://www.npmjs.com/package/pixi.js --- pixi/pixi-tests.ts => pixi.js/pixi.js-tests.ts | 2 +- .../pixi.js-tests.ts.tscparams | 0 pixi/pixi.d.ts => pixi.js/pixi.js.d.ts | 0 pixi/pixi.d.ts.tscparams => pixi.js/pixi.js.d.ts.tscparams | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename pixi/pixi-tests.ts => pixi.js/pixi.js-tests.ts (99%) rename pixi/pixi-tests.ts.tscparams => pixi.js/pixi.js-tests.ts.tscparams (100%) rename pixi/pixi.d.ts => pixi.js/pixi.js.d.ts (100%) rename pixi/pixi.d.ts.tscparams => pixi.js/pixi.js.d.ts.tscparams (100%) diff --git a/pixi/pixi-tests.ts b/pixi.js/pixi.js-tests.ts similarity index 99% rename from pixi/pixi-tests.ts rename to pixi.js/pixi.js-tests.ts index 6600bb121..65fb7458a 100644 --- a/pixi/pixi-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,4 +1,4 @@ -/// +/// function PixiTests() { diff --git a/pixi/pixi-tests.ts.tscparams b/pixi.js/pixi.js-tests.ts.tscparams similarity index 100% rename from pixi/pixi-tests.ts.tscparams rename to pixi.js/pixi.js-tests.ts.tscparams diff --git a/pixi/pixi.d.ts b/pixi.js/pixi.js.d.ts similarity index 100% rename from pixi/pixi.d.ts rename to pixi.js/pixi.js.d.ts diff --git a/pixi/pixi.d.ts.tscparams b/pixi.js/pixi.js.d.ts.tscparams similarity index 100% rename from pixi/pixi.d.ts.tscparams rename to pixi.js/pixi.js.d.ts.tscparams From d2fc6f24c572f34949ffc3fbd25c773d3eebf706 Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:13:35 +0200 Subject: [PATCH 11/38] Updated pixi.js definitions to v2 --- pixi.js/pixi.js-tests.ts | 34 +- pixi.js/pixi.js.d.ts | 2000 +++++++++++++++++++++++++++++++++----- 2 files changed, 1741 insertions(+), 293 deletions(-) diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 65fb7458a..309f7f66a 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -3,7 +3,7 @@ function PixiTests() { -var stage = new PIXI.Stage(0xFFFFFF, true); +var stage = new PIXI.Stage(0xFFFFFF); stage.interactive = true; @@ -70,15 +70,7 @@ var count = 0; stage.click = stage.tap = function() { - if(!container.filter) - { - container.mask = thing; - PIXI.runList(stage); - } - else - { - container.mask = null; - } + container.mask = null; } /* @@ -136,15 +128,13 @@ function animate() { /* 13 */ // create an new instance of a pixi stage -var stage = new PIXI.Stage(0xFFFFFF, true); - -stage.setInteractive(true); +var stage = new PIXI.Stage(0xFFFFFF); var sprite= PIXI.Sprite.fromImage("spinObj_02.png"); //stage.addChild(sprite); // create a renderer instance // the 5the parameter is the anti aliasing -var renderer = PIXI.autoDetectRenderer(620, 380, null, false, true); +var renderer = PIXI.autoDetectRenderer(620, 380); // set the canvas width and height to fill the screen //renderer.view.style.width = window.innerWidth + "px"; @@ -352,10 +342,7 @@ function init() var assetsToLoader = ["desyrel.fnt"]; // create a new loader - var loader = new PIXI.AssetLoader(assetsToLoader); - - // use callback - loader.onComplete = onAssetsLoaded; + var loader = new PIXI.AssetLoader(assetsToLoader, false); //begin load @@ -369,7 +356,6 @@ function init() bitmapFontText.position.x = 620 - bitmapFontText.width - 20; bitmapFontText.position.y = 20; - PIXI.runList(bitmapFontText) stage.addChild(bitmapFontText); @@ -439,7 +425,7 @@ function init() // create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e, true); +var stage = new PIXI.Stage(0x97c56e); // create a renderer instance var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); @@ -487,7 +473,7 @@ function animate33() { // create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e, true); +var stage = new PIXI.Stage(0x97c56e); // create a renderer instance var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); @@ -586,7 +572,7 @@ function animate44() { var stage = new PIXI.Stage(0x66FF99); // create a renderer instance -var renderer = PIXI.autoDetectRenderer(400, 300, null, true); +var renderer = PIXI.autoDetectRenderer(400, 300, null); // add the renderer view element to the DOM document.body.appendChild(renderer.view); @@ -630,7 +616,7 @@ function animate55() { // create an new instance of a pixi stage // the second parameter is interactivity... var interactive = true; -var stage = new PIXI.Stage(0x000000, interactive); +var stage = new PIXI.Stage(0x000000); // create a renderer instance. var renderer = PIXI.autoDetectRenderer(620, 400); @@ -765,8 +751,6 @@ stage.addChild(pixiLogo); pixiLogo.position.x = 620 - 56; pixiLogo.position.y = 400- 32; -pixiLogo.setInteractive(true); - pixiLogo.click = pixiLogo.tap = function(){ var win=window.open("https://github.com/GoodBoyDigital/pixi.js", '_blank'); diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index c86c1bd47..0452e7432 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1,448 +1,1912 @@ -// Type definitions for PIXI 1.3 +// Type definitions for PIXI 2.2.8 2015-03-24 // Project: https://github.com/GoodBoyDigital/pixi.js/ -// Definitions by: xperiments +// Definitions by: clark-stevenson // Definitions: https://github.com/borisyankov/DefinitelyTyped -declare module PIXI -{ +declare module PIXI { - /* STATICS */ - export var gl:WebGLRenderingContext; - export var BaseTextureCache: {}; - export var texturesToUpdate: BaseTexture[]; - export var texturesToDestroy: BaseTexture[]; - export var TextureCache: {}; - export var FrameCache: {}; - export var blendModes:{ NORMAL:number; SCREEN:number; }; + export var WEBGL_RENDERER: number; + export var CANVAS_RENDERER: number; + export var VERSION: string; + export enum blendModes { - /* MODULE FUNCTIONS */ - export function autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?: boolean): IPixiRenderer; - export function FilterBlock( mask:Graphics ):void; - export function MaskFilter( graphics:Graphics ):void; + NORMAL, + ADD, + MULTIPLY, + SCREEN, + OVERLAY, + DARKEN, + LIGHTEN, + COLOR_DODGE, + COLOR_BURN, + HARD_LIGHT, + SOFT_LIGHT, + DIFFERENCE, + EXCLUSION, + HUE, + SATURATION, + COLOR, + LUMINOSITY - - /* DEBUG METHODS */ - - export function runList( x ):void; - - /*INTERFACES*/ - - export interface IBasicCallback - { - ():void } - export interface IEvent - { + export enum scaleModes { + + DEFAULT, + LINEAR, + NEAREST + + } + + export var defaultRenderOptions: PixiRendererOptions; + + export var INTERACTION_REQUENCY: number; + export var AUTO_PREVENT_DEFAULT: boolean; + + export var PI_2: number; + export var RAD_TO_DEG: number; + export var DEG_TO_RAD: number; + + export var RETINA_PREFIX: string; + export var identityMatrix: Matrix; + export var glContexts: WebGLRenderingContext[]; + export var instances: any[]; + + export var BaseTextureCache: { [key: string]: BaseTexture } + export var TextureCache: { [key: string]: Texture } + + export function isPowerOfTwo(width: number, height: number): boolean; + + export function rgb2hex(rgb: number[]): string; + export function hex2rgb(hex: string): number[]; + + export function autoDetectRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; + export function autoDetectRecommendedRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; + + export function canUseNewCanvasBlendModes(): boolean; + export function getNextPowerOfTwo(number: number): number; + + export function AjaxRequest(): XMLHttpRequest; + + export function CompileFragmentShader(gl: WebGLRenderingContext, shaderSrc: string[]): any; + export function CompileProgram(gl: WebGLRenderingContext, vertexSrc: string[], fragmentSrc: string[]): any; + + + export interface IEventCallback { + (e?: IEvent): void + } + + export interface IEvent { type: string; content: any; } - export interface IHitArea - { - contains(x: number, y: number):boolean; + export interface HitArea { + contains(x: number, y: number): boolean; } - export interface IInteractionDataCallback - { - (interactionData: InteractionData):void + export interface IInteractionDataCallback { + (interactionData: InteractionData): void } - export interface IPixiRenderer - { + export interface PixiRenderer { + + autoResize: boolean; + clearBeforeRender: boolean; + height: number; + resolution: number; + transparent: boolean; + type: number; view: HTMLCanvasElement; + width: number; + + destroy(): void; render(stage: Stage): void; + resize(width: number, height: number): void; + } - export interface IBitmapTextStyle - { + export interface PixiRendererOptions { + + autoResize?: boolean; + antialias?: boolean; + clearBeforeRender?: boolean; + preserveDrawingBuffer?: boolean; + resolution?: number; + transparent?: boolean; + view?: HTMLCanvasElement; + + } + + export interface BitmapTextStyle { + font?: string; align?: string; + tint?: string; + } - export interface ITextStyle - { - font?: string; - stroke?: string; + export interface TextStyle { + + align?: string; + dropShadow?: boolean; + dropShadowColor?: string; + dropShadowAngle?: number; + dropShadowDistance?: number; fill?: string; - align?: string; + font?: string; + lineJoin?: string; + stroke?: string; strokeThickness?: number; wordWrap?: boolean; - wordWrapWidth?:number; + wordWrapWidth?: number; + } + export interface Loader { - - /* CLASES */ - - export class AssetLoader extends EventTarget - { - assetURLs: string[]; - onComplete: IBasicCallback; - onProgress: IBasicCallback; - constructor(assetURLs: string[], crossorigin?:boolean ); load(): void; + } - export class BaseTexture extends EventTarget - { + export interface MaskData { + + alpha: number; + worldTransform: number[]; + + } + + export interface RenderSession { + + context: CanvasRenderingContext2D; + maskManager: CanvasMaskManager; + scaleMode: scaleModes; + smoothProperty: string; + roundPixels: boolean; + + } + + export interface ShaderAttribute { + // TODO: Find signature of shader attributes + } + + export interface FilterBlock { + + visible: boolean; + renderable: boolean; + + } + + export class AbstractFilter { + + constructor(fragmentSrc: string[], uniforms: any); + + dirty: boolean; + padding: number; + uniforms: any; + fragmentSrc: string[]; + + apply(frameBuffer: WebGLFramebuffer): void; + syncUniforms(): void; + + } + + export class AlphaMaskFilter extends AbstractFilter { + + constructor(texture: Texture); + + map: Texture; + + onTextureLoaded(): void; + + } + + export class AsciiFilter extends AbstractFilter { + + size: number; + + } + + export class AssetLoader implements Mixin { + + assetURLs: string[]; + crossorigin: boolean; + loadersByType: { [key: string]: Loader }; + + constructor(assetURLs: string[], crossorigin?: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + + } + + export class AtlasLoader implements Mixin { + + url: string; + baseUrl: string; + crossorigin: boolean; + loaded: boolean; + + constructor(url: string, crossorigin: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class BaseTexture implements Mixin { + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): BaseTexture; + + constructor(source: HTMLImageElement, scaleMode: scaleModes); + constructor(source: HTMLCanvasElement, scaleMode: scaleModes); + height: number; + hasLoaded: boolean; + mipmap: boolean; + premultipliedAlpha: boolean; + resolution: number; + scaleMode: scaleModes; + source: HTMLImageElement; width: number; - source: string; - constructor(source: HTMLImageElement); - constructor(source: HTMLCanvasElement); - destroy():void; + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + destroy(): void; + dirty(): void; + updateSourceImage(newSrc: string): void; + unloadFromGPU(): void; - static fromImage(imageUrl: string, crossorigin?:boolean ): BaseTexture; } - export class BitmapFontLoader extends EventTarget - { - baseUrl:string; - crossorigin:boolean; - texture:Texture; - url:string; - constructor(url: string, crossorigin?: boolean); - load():void; + export class BitmapFontLoader implements Mixin { + + constructor(url: string, crossorigin: boolean); + + baseUrl: string; + crossorigin: boolean; + texture: Texture; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + } - export class BitmapText extends DisplayObjectContainer - { - width:number; - height:number; - constructor(text: string, style: IBitmapTextStyle); - setStyle(style: IBitmapTextStyle): void; + export class BitmapText extends DisplayObjectContainer { + + static fonts: any; + + constructor(text: string, style: BitmapTextStyle); + + dirty: boolean; + fontName: string; + fontSize: number; + maxWidth: number; + textWidth: number; + textHeight: number; + tint: number; + style: BitmapTextStyle; + setText(text: string): void; + setStyle(style: BitmapTextStyle): void; + } - export class CanvasRenderer implements IPixiRenderer - { + export class BlurFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + + } + + export class BlurXFilter extends AbstractFilter { + + blur: number; + + } + + export class BlurYFilter extends AbstractFilter { + + blur: number; + + } + + export class CanvasBuffer { + + constructor(width: number, height: number); + + canvas: HTMLCanvasElement; context: CanvasRenderingContext2D; height: number; - view: HTMLCanvasElement; width: number; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean); - render(stage: Stage): void; - resize(width: number, height: number):void; + + clear(): void; + resize(width: number, height: number): void; + } - export class Circle implements IHitArea - { + export class CanvasMaskManager { + + pushMask(maskData: MaskData, renderSession: RenderSession): void; + popMask(renderSession: RenderSession): void; + + } + + export class CanvasRenderer implements PixiRenderer { + + constructor(width?: number, height?: number, options?: PixiRendererOptions); + + autoResize: boolean; + clearBeforeRender: boolean; + context: CanvasRenderingContext2D; + count: number; + height: number; + maskManager: CanvasMaskManager; + refresh: boolean; + renderSession: RenderSession; + resolution: number; + transparent: boolean; + type: number; + view: HTMLCanvasElement; + width: number; + + destroy(removeView?: boolean): void; + render(stage: Stage): void; + resize(width: number, height: number): void; + + } + + export class CanvasTinter { + + static getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; + static tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static roundColor(color: number): void; + + static cacheStepsPerColorChannel: number; + static convertTintToImage: boolean; + static canUseMultiply: boolean; + static tintMethod: any; + + } + + export class Circle implements HitArea { + + constructor(x: number, y: number, radius: number); + x: number; y: number; radius: number; - constructor(x: number, y: number, radius: number); + clone(): Circle; - contains(x: number, y: number):boolean; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + } - // TODO what is renderGroup - export class CustomRenderable extends DisplayObject - { - constructor(); - renderCanvas(renderer: CanvasRenderer): void; - initWebGL(renderer: WebGLRenderer): void; - renderWebGL(renderGroup: any, projectionMatrix: any): void; + export class ColorMatrixFilter extends AbstractFilter { + + matrix: Matrix; + } - export class DisplayObject - { - x: number; - y: number; + export class ColorStepFilter extends AbstractFilter { + + step: number; + + } + + export class ConvolutionFilter extends AbstractFilter { + + constructor(matrix: number[], width: number, height: number); + + matrix: Matrix; + width: number; + height: number; + + } + + export class CrossHatchFilter extends AbstractFilter { + + blur: number; + + } + + export class DisplacementFilter extends AbstractFilter { + + constructor(texture: Texture); + + map: Texture; + offset: Point; + scale: Point; + + } + + export class DotScreenFilter extends AbstractFilter { + + angle: number; + scale: Point; + + } + + export class DisplayObject { + alpha: number; buttonMode: boolean; - filter:boolean; - hitArea: IHitArea; + cacheAsBitmap: boolean; + defaultCursor: string; + filterArea: Rectangle; + filters: AbstractFilter[]; + hitArea: HitArea; + interactive: boolean; + mask: Graphics; parent: DisplayObjectContainer; pivot: Point; position: Point; - rotation: number; renderable: boolean; + rotation: number; scale: Point; stage: Stage; visible: boolean; worldAlpha: number; - constructor(); - static autoDetectRenderer(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean): IPixiRenderer; - click: IInteractionDataCallback; - mousedown: IInteractionDataCallback; - mouseout: IInteractionDataCallback; - mouseover: IInteractionDataCallback; - mouseup: IInteractionDataCallback; - mouseupoutside: IInteractionDataCallback; - mousemove: IInteractionDataCallback; - tap: IInteractionDataCallback; - touchend: IInteractionDataCallback; - touchendoutside: IInteractionDataCallback; - touchstart: IInteractionDataCallback; - touchmove: IInteractionDataCallback; + worldVisible: boolean; + x: number; + y: number; - //deprecated - setInteractive(interactive: boolean): void; + click(e: InteractionData): void; + displayObjectUpdateTransform(): void; + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + generateTexture(resolution: number, scaleMode: scaleModes, renderer: PixiRenderer): RenderTexture; + mousedown(e: InteractionData): void; + mouseout(e: InteractionData): void; + mouseover(e: InteractionData): void; + mouseup(e: InteractionData): void; + mousemove(e: InteractionData): void; + mouseupoutside(e: InteractionData): void; + rightclick(e: InteractionData): void; + rightdown(e: InteractionData): void; + rightup(e: InteractionData): void; + rightupoutside(e: InteractionData): void; + setStageReference(stage: Stage): void; + tap(e: InteractionData): void; + toGlobal(position: Point): Point; + toLocal(position: Point, from: DisplayObject): Point; + touchend(e: InteractionData): void; + touchendoutside(e: InteractionData): void; + touchstart(e: InteractionData): void; + touchmove(e: InteractionData): void; + updateTransform(): void; - // getters setters - interactive:boolean; - mask:Graphics; } - export class DisplayObjectContainer extends DisplayObject - { + export class DisplayObjectContainer extends DisplayObject { + + constructor(); + children: DisplayObject[]; - constructor(); + height: number; + width: number; - addChild(child: DisplayObject): void; - addChildAt(child: DisplayObject, index: number): void; - getChildAt(index:number):DisplayObject; - removeChild(child: DisplayObject): void; + addChild(child: DisplayObject): DisplayObject; + addChildAt(child: DisplayObject, index: number): DisplayObject; + getBounds(): Rectangle; + getChildAt(index: number): DisplayObject; + getChildIndex(child: DisplayObject): number; + getLocalBounds(): Rectangle; + removeChild(child: DisplayObject): DisplayObject; + removeChildAt(index: number): DisplayObject; + removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; + removeStageReference(): void; + setChildIndex(child: DisplayObject, index: number): void; swapChildren(child: DisplayObject, child2: DisplayObject): void; + } - export class Ellipse implements IHitArea - { + export class Ellipse implements HitArea { + + constructor(x: number, y: number, width: number, height: number); + x: number; y: number; width: number; height: number; - constructor(x: number, y: number, width: number, height: number); clone(): Ellipse; - contains(x: number, y: number):boolean; - getBounds():Rectangle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + } - export class EventTarget - { - addEventListener(type: string, listener: (event: IEvent) => void ); - removeEventListener(type: string, listener: (event: IEvent) => void ); - dispatchEvent(event: IEvent); + export class Event { + + constructor(target: any, name: string, data: any); + + target: any; + type: string; + data: any; + timeStamp: number; + + stopPropagation(): void; + preventDefault(): void; + stopImmediatePropagation(): void; + } - export class Graphics extends DisplayObjectContainer - { - lineWidth:number; - lineColor:string; - constructor(); + export class EventTarget { + + static mixin(obj: any): void; + + } + + export class FilterTexture { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: scaleModes); + + fragmentSrc: string[]; + frameBuffer: WebGLFramebuffer; + gl: WebGLRenderingContext; + program: WebGLProgram; + scaleMode: number; + texture: WebGLTexture; - beginFill(color?: number, alpha?: number): void; clear(): void; - drawCircle(x: number, y: number, radius: number): void; - drawElipse(x: number, y: number, width: number, height: number): void; - drawRect(x: number, y: number, width: number, height: number): void; - endFill(): void; - lineStyle(lineWidth?: number, color?: number, alpha?: number ): void; - lineTo(x: number, y: number): void; - moveTo(x: number, y: number): void; + resize(width: number, height: number): void; + destroy(): void; - static POLY:number; - static RECT:number; - static CIRC:number; - static ELIP:number; } - export class ImageLoader extends EventTarget - { - texture:Texture; + export class GraphicsData { + + constructor(lineWidth?: number, lineColor?: number, lineAlpha?: number, fillColor?: number, fillAlpha?: number, fill?: boolean, shape?: any); + + lineWidth: number; + lineColor: number; + lineAlpha: number; + fillColor: number; + fillAlpha: number; + fill: boolean; + shape: any; + type: number; + + } + + export class Graphics extends DisplayObjectContainer { + + static POLY: number; + static RECT: number; + static CIRC: number; + static ELIP: number; + static RREC: number; + + blendMode: number; + boundsPadding: number; + fillAlpha: number; + isMask: boolean; + lineWidth: number; + lineColor: number; + tint: number; + worldAlpha: number; + + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + beginFill(color?: number, alpha?: number): Graphics; + bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; + clear(): Graphics; + destroyCachedSprite(): void; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(...path: any[]): Graphics; + drawRect(x: number, y: number, width: number, height: number): Graphics; + drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; + drawShape(shape: Circle): GraphicsData; + drawShape(shape: Rectangle): GraphicsData; + drawShape(shape: Ellipse): GraphicsData; + drawShape(shape: Polygon): GraphicsData; + endFill(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + lineTo(x: number, y: number): Graphics; + moveTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + + } + + export class GrayFilter extends AbstractFilter { + + gray: number; + + } + + export class ImageLoader implements Mixin { + constructor(url: string, crossorigin?: boolean); + + texture: Texture; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + load(): void; + loadFramedSpriteSheet(frameWidth: number, frameHeight: number, textureName: string): void; + } - /* TODO determine type of originalEvent*/ - export class InteractionData - { + export class InteractionData { + global: Point; target: Sprite; - constructor(); - originalEvent:any; - getLocalPosition(displayObject: DisplayObject): Point; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + } - export class InteractionManager - { + export class InteractionManager { + + currentCursorStyle: string; + last: number; mouse: InteractionData; + mouseOut: boolean; + mouseoverEnabled: boolean; + onMouseMove: Function; + onMouseDown: Function; + onMouseOut: Function; + onMouseUp: Function; + onTouchStart: Function; + onTouchEnd: Function; + onTouchMove: Function; + pool: InteractionData[]; + resolution: number; stage: Stage; - touchs:{ [id:string]:InteractionData }; + touches: { [id: string]: InteractionData }; + constructor(stage: Stage); } - export class JsonLoader extends EventTarget - { - url:string; - crossorigin: boolean; - baseUrl:string; - loaded:boolean; - constructor(url: string, crossorigin?: boolean); - load(): void; + export class InvertFilter extends AbstractFilter { + + invert: number; + } - export class MovieClip extends Sprite - { + export class JsonLoader implements Mixin { + + constructor(url: string, crossorigin?: boolean); + + baseUrl: string; + crossorigin: boolean; + loaded: boolean; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class Matrix { + + a: number; + b: number; + c: number; + d: number; + tx: number; + ty: number; + + append(matrix: Matrix): Matrix; + apply(pos: Point, newPos: Point): Point; + applyInverse(pos: Point, newPos: Point): Point; + determineMatrixArrayType(): number[]; + identity(): Matrix; + rotate(angle: number): Matrix; + fromArray(array: number[]): void; + translate(x: number, y: number): Matrix; + toArray(transpose: boolean): number[]; + scale(x: number, y: number): Matrix; + + } + + export interface Mixin { + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + } + + export class MovieClip extends Sprite { + + static fromFrames(frames: string[]): MovieClip; + static fromImages(images: HTMLImageElement[]): HTMLImageElement; + + constructor(textures: Texture[]); + animationSpeed: number; - currentFrame:number; + currentFrame: number; loop: boolean; playing: boolean; textures: Texture[]; - constructor(textures: Texture[]); - onComplete:IBasicCallback; + totalFrames: number; + gotoAndPlay(frameNumber: number): void; gotoAndStop(frameNumber: number): void; + onComplete(): void; play(): void; stop(): void; + } - export class Point - { + export class NoiseFilter extends AbstractFilter { + + noise: number; + + } + + export class NormalMapFilter extends AbstractFilter { + + map: Texture; + offset: Point; + scale: Point; + + } + + export class PixelateFilter extends AbstractFilter { + + size: number; + + } + + export interface IPixiShader { + + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class PixiShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + + attributes: ShaderAttribute[]; + defaultVertexSrc: string[]; + dirty: boolean; + firstRun: boolean; + textureCount: number; + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + initSampler2D(): void; + initUniforms(): void; + syncUniforms(): void; + + destroy(): void; + init(): void; + + } + + export class PixiFastShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + + textureCount: number; + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class PrimitiveShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class ComplexPrimitiveShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class StripShader implements IPixiShader { + + constructor(gl: WebGLRenderingContext); + fragmentSrc: string[]; + gl: WebGLRenderingContext; + program: WebGLProgram; + vertexSrc: string[]; + + destroy(): void; + init(): void; + + } + + export class Point { + + constructor(x?: number, y?: number); + x: number; y: number; - constructor(x: number, y: number); + clone(): Point; + set(x: number, y: number): void; + } - export class Polygon implements IHitArea - { - points: Point[]; + export class Polygon implements HitArea { constructor(points: Point[]); constructor(points: number[]); constructor(...points: Point[]); constructor(...points: number[]); + points: any[]; //number[] Point[] + clone(): Polygon; - contains( x:number, y:number ):boolean; + contains(x: number, y: number): boolean; + } - export class Rectangle implements IHitArea - { + export class Rectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number); + x: number; y: number; width: number; height: number; - constructor(x: number, y: number, width: number, height: number); + clone(): Rectangle; - contains(x: number, y: number):boolean; + contains(x: number, y: number): boolean; + } - export class RenderTexture extends Texture - { - constructor(width: number, height: number); - resize(width: number, height: number): void; + export class RGBSplitFilter extends AbstractFilter { + + red: Point; + green: Point; + blue: Point; + } - export class Sprite extends DisplayObjectContainer - { - anchor: Point; - blendMode: number; - texture: Texture; + export class Rope extends Strip { - //getters setters - height: number; + points: Point[]; + vertices: number[]; + + constructor(texture: Texture, points: Point[]); + + refresh(): void; + setTexture(texture: Texture): void; + + } + + export class RoundedRectangle implements HitArea { + + constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); + + x: number; + y: number; width: number; + height: number; + radius: number; + + clone(): RoundedRectangle; + contains(x: number, y: number): boolean; + + } + + export class SepiaFilter extends AbstractFilter { + + sepia: number; + + } + + export class SmartBlurFilter extends AbstractFilter { + + blur: number; + + } + + export class SpineLoader implements Mixin { + + url: string; + crossorigin: boolean; + loaded: boolean; + + constructor(url: string, crossOrigin: boolean); + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + + } + + export class SpineTextureLoader { + + constructor(basePath: string, crossorigin: boolean); + + load(page: AtlasPage, file: string): void; + unload(texture: BaseTexture): void; + + } + + export class Sprite extends DisplayObjectContainer { + + static fromFrame(frameId: string): Sprite; + static fromImage(url: string, crossorigin?: boolean, scaleMode?: scaleModes): Sprite; constructor(texture: Texture); - static fromFrame(frameId: string): Sprite; - static fromImage(url: string): Sprite; + anchor: Point; + blendMode: blendModes; + shader: IPixiShader; + texture: Texture; + tint: number; + setTexture(texture: Texture): void; + } - /* TODO determine type of frames */ - export class SpriteSheetLoader extends EventTarget - { - url:string; - crossorigin:boolean; - baseUrl:string; - texture:Texture; - frames:Object; + export class SpriteBatch extends DisplayObjectContainer { + + constructor(texture?: Texture); + + ready: boolean; + textureThing: Texture; + + initWebGL(gl: WebGLRenderingContext): void; + + } + + export class SpriteSheetLoader implements Mixin { + constructor(url: string, crossorigin?: boolean); - load(); + + baseUrl: string; + crossorigin: boolean; + frames: any; + texture: Texture; + url: string; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + load(): void; + } - export class Stage extends DisplayObjectContainer - { - interactive:boolean; - interactionManager:InteractionManager; - constructor(backgroundColor: number, interactive?: boolean); + export class Stage extends DisplayObjectContainer { + + constructor(backgroundColor: number); + + interactionManager: InteractionManager; + getMousePosition(): Point; setBackgroundColor(backgroundColor: number): void; + setInteractionDelegate(domElement: HTMLElement): void; + } - export class Text extends Sprite - { - constructor(text: string, style: ITextStyle); - destroy(destroyTexture:boolean):void; + export class Strip extends DisplayObjectContainer { + + static DrawModes: { + + TRIANGLE_STRIP: number; + TRIANGLES: number; + + } + + constructor(texture: Texture); + + blendMode: number; + colors: number[]; + dirty: boolean; + indices: number[]; + canvasPadding: number; + texture: Texture; + uvs: number[]; + vertices: number[]; + + getBounds(matrix?: Matrix): Rectangle; + + } + + export class Text extends Sprite { + + constructor(text: string, style?: TextStyle); + + static fontPropertiesCanvas: any; + static fontPropertiesContext: any; + static fontPropertiesCache: any; + + context: CanvasRenderingContext2D; + resolution: number; + + destroy(destroyTexture: boolean): void; + setStyle(style: TextStyle): void; setText(text: string): void; - setStyle(style: ITextStyle): void; + } - export class Texture extends EventTarget - { + export class Texture implements Mixin { + + static emptyTexture: Texture; + + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): Texture; + static fromFrame(frameId: string): Texture; + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle); + baseTexture: BaseTexture; + crop: Rectangle; frame: Rectangle; - trim:Point; - render( displayObject:DisplayObject, position:Point, clear:boolean ):void; - constructor(baseTexture: BaseTexture, frame?: Rectangle); - destroy(destroyBase:boolean):void; + height: number; + noFrame: boolean; + requiresUpdate: boolean; + trim: Point; + width: number; + scope: any; + valid: boolean; + + listeners(eventName: string): Function[]; + emit(eventName: string, data?: any): boolean; + dispatchEvent(eventName: string, data?: any): boolean; + on(eventName: string, fn: Function): Function; + addEventListener(eventName: string, fn: Function): Function; + once(eventName: string, fn: Function): Function; + off(eventName: string, fn: Function): Function; + removeAllEventListeners(eventName: string): void; + + destroy(destroyBase: boolean): void; setFrame(frame: Rectangle): void; - static addTextureToCache(texture: Texture, id: string): void; - static fromCanvas(canvas: HTMLCanvasElement): Texture; - static fromFrame(frameId: string): Texture; - static fromImage(imageUrl: string, crossorigin?: boolean): Texture; - static removeTextureFromCache(id: any): Texture; } - export class TilingSprite extends DisplayObjectContainer - { - width:number; - height:number; - texture:Texture; + export class TilingSprite extends Sprite { + + constructor(texture: Texture, width: number, height: number); + + blendMode: number; + texture: Texture; + tint: number; tilePosition: Point; tileScale: Point; - constructor(texture: Texture, width: number, height: number); - setTexture( texture: Texture ):void; + tileScaleOffset: Point; + + destroy(): void; + generateTilingTexture(forcePowerOfTwo?: boolean): void; + setTexture(texture: Texture): void; + } - export class WebGLBatch - { - constructor(webGLContext: WebGLRenderingContext); - clean():void; - restoreLostContext(gl:WebGLRenderingContext); - init(sprite: Sprite): void; - insertAfter(sprite: Sprite, previousSprite: Sprite): void; - insertBefore(sprite: Sprite, nextSprite: Sprite): void; - growBatch(): void; - merge(batch: WebGLBatch): void; - refresh(): void; - remove(sprite: Sprite): void; - render(): void; - split(sprite: Sprite): WebGLBatch; - update(): void; + export class TiltShiftFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + } - /* Determine type of Object */ - export class WebGLRenderGroup - { - render(projection:Object):void; + export class TiltShiftXFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + } - export class WebGLRenderer implements IPixiRenderer - { + export class TiltShiftYFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + + } + + export class TwistFilter extends AbstractFilter { + + angle: number; + offset: Point; + radius: number; + + } + + export class VideoTexture extends BaseTexture { + + static baseTextureFromVideo(video: HTMLVideoElement, scaleMode: number): BaseTexture; + static textureFromVideo(video: HTMLVideoElement, scaleMode: number): Texture; + static fromUrl(videoSrc: string, scaleMode: number): Texture; + + autoUpdate: boolean; + + destroy(): void; + updateBound(): void; + onPlayStart(): void; + onPlayStop(): void; + onCanPlay(): void; + + } + + export class WebGLBlendModeManager { + + currentBlendMode: number; + + destroy(): void; + setBlendMode(blendMode: number): boolean; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLFastSpriteBatch { + + constructor(gl: CanvasRenderingContext2D); + + currentBatchSize: number; + currentBaseTexture: BaseTexture; + currentBlendMode: number; + renderSession: RenderSession; + drawing: boolean; + indexBuffer: any; + indices: number[]; + lastIndexCount: number; + matrix: Matrix; + maxSize: number; + shader: IPixiShader; + size: number; + vertexBuffer: any; + vertices: number[]; + vertSize: number; + + end(): void; + begin(spriteBatch: SpriteBatch, renderSession: RenderSession): void; + destroy(removeView?: boolean): void; + flush(): void; + render(spriteBatch: SpriteBatch): void; + renderSprite(sprite: Sprite): void; + setContext(gl: WebGLRenderingContext): void; + start(): void; + stop(): void; + + } + + export class WebGLFilterManager { + + filterStack: AbstractFilter[]; + transparent: boolean; + offsetX: number; + offsetY: number; + + applyFilterPass(filter: AbstractFilter, filterArea: Texture, width: number, height: number): void; + begin(renderSession: RenderSession, buffer: ArrayBuffer): void; + destroy(): void; + initShaderBuffers(): void; + popFilter(): void; + pushFilter(filterBlock: FilterBlock): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLGraphics { + + static graphicsDataPool: any[]; + + static renderGraphics(graphics: Graphics, renderRession: RenderSession): void; + static updateGraphics(graphics: Graphics, gl: WebGLRenderingContext): void; + static switchMode(webGL: WebGLRenderingContext, type: number): any; //WebGLData + static buildRectangle(graphicsData: GraphicsData, webGLData: any): void; + static buildRoundedRectangle(graphicsData: GraphicsData, webGLData: any): void; + static quadraticBezierCurve(fromX: number, fromY: number, cpX: number, cpY: number, toX: number, toY: number): number[]; + static buildCircle(graphicsData: GraphicsData, webGLData: any): void; + static buildLine(graphicsData: GraphicsData, webGLData: any): void; + static buildComplexPoly(graphicsData: GraphicsData, webGLData: any): void; + static buildPoly(graphicsData: GraphicsData, webGLData: any): boolean; + + reset(): void; + upload(): void; + + } + + export class WebGLGraphicsData { + + constructor(gl: WebGLRenderingContext); + + gl: WebGLRenderingContext; + glPoints: any[]; + color: number[]; + points: any[]; + indices: any[]; + buffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + mode: number; + alpha: number; + dirty: boolean; + + reset(): void; + upload(): void; + + } + + export class WebGLMaskManager { + + destroy(): void; + popMask(renderSession: RenderSession): void; + pushMask(maskData: any[], renderSession: RenderSession): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLRenderer implements PixiRenderer { + + static createWebGLTexture(texture: Texture, gl: WebGLRenderingContext): void; + + constructor(width?: number, height?: number, options?: PixiRendererOptions); + + autoResize: boolean; + clearBeforeRender: boolean; + contextLost: boolean; + contextLostBound: Function; + contextRestoreLost: boolean; + contextRestoredBound: Function; + height: number; + gl: WebGLRenderingContext; + offset: Point; + preserveDrawingBuffer: boolean; + projection: Point; + resolution: number; + renderSession: RenderSession; + shaderManager: WebGLShaderManager; + spriteBatch: WebGLSpriteBatch; + maskManager: WebGLMaskManager; + filterManager: WebGLFilterManager; + stencilManager: WebGLStencilManager; + blendModeManager: WebGLBlendModeManager; + transparent: boolean; + type: number; view: HTMLCanvasElement; - constructor(width: number, height: number, view?: HTMLCanvasElement, transparent?: boolean, antialias?:boolean ); + width: number; + + destroy(): void; + initContext(): void; + mapBlendModes(): void; render(stage: Stage): void; + renderDisplayObject(displayObject: DisplayObject, projection: Point, buffer: WebGLBuffer): void; resize(width: number, height: number): void; + updateTexture(texture: Texture): void; + + } + + export class WebGLShaderManager { + + maxAttibs: number; + attribState: any[]; + stack: any[]; + tempAttribState: any[]; + + destroy(): void; + setAttribs(attribs: ShaderAttribute[]): void; + setContext(gl: WebGLRenderingContext): void; + setShader(shader: IPixiShader): boolean; + + } + + export class WebGLStencilManager { + + stencilStack: any[]; + reverse: boolean; + count: number; + + bindGraphics(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + destroy(): void; + popStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + pushStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; + setContext(gl: WebGLRenderingContext): void; + + } + + export class WebGLSpriteBatch { + + blendModes: number[]; + colors: number[]; + currentBatchSize: number; + currentBaseTexture: Texture; + defaultShader: AbstractFilter; + dirty: boolean; + drawing: boolean; + indices: number[]; + lastIndexCount: number; + positions: number[]; + textures: Texture[]; + shaders: IPixiShader[]; + size: number; + sprites: any[]; //todo Sprite[]? + vertices: number[]; + vertSize: number; + + begin(renderSession: RenderSession): void; + destroy(): void; + end(): void; + flush(shader?: IPixiShader): void; + render(sprite: Sprite): void; + renderBatch(texture: Texture, size: number, startIndex: number): void; + renderTilingSprite(sprite: TilingSprite): void; + setBlendMode(blendMode: blendModes): void; + setContext(gl: WebGLRenderingContext): void; + start(): void; + stop(): void; + + } + + export class RenderTexture extends Texture { + + constructor(width?: number, height?: number, renderer?: PixiRenderer, scaleMode?: scaleModes, resolution?: number); + + frame: Rectangle; + baseTexture: BaseTexture; + renderer: PixiRenderer; + resolution: number; + valid: boolean; + + clear(): void; + getBase64(): string; + getCanvas(): HTMLCanvasElement; + getImage(): HTMLImageElement; + resize(width: number, height: number, updateBase: boolean): void; + render(displayObject: DisplayObject, position?: Point, clear?: boolean): void; + + } + + //SPINE + + export class BoneData { + + constructor(name: string, parent?: any); + + name: string; + parent: any; + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + + } + + export class SlotData { + + constructor(name: string, boneData: BoneData); + + name: string; + boneData: BoneData; + r: number; + g: number; + b: number; + a: number; + attachmentName: string; + + } + + export class Bone { + + constructor(boneData: BoneData, parent?: any); + + data: BoneData; + parent: any; + yDown: boolean; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + worldRotation: number; + worldScaleX: number; + worldScaleY: number; + + updateWorldTransform(flipX: boolean, flip: boolean): void; + setToSetupPose(): void; + + } + + export class Slot { + + constructor(slotData: SlotData, skeleton: Skeleton, bone: Bone); + + data: SlotData; + skeleton: Skeleton; + bone: Bone; + r: number; + g: number; + b: number; + a: number; + attachment: RegionAttachment; + setAttachment(attachment: RegionAttachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + + } + + export class Skin { + + constructor(name: string); + + name: string; + attachments: any; + + addAttachment(slotIndex: number, name: string, attachment: RegionAttachment): void; + getAttachment(slotIndex: number, name: string): void; + + } + + export class Animation { + + constructor(name: string, timelines: ISpineTimeline[], duration: number); + + name: string; + timelines: ISpineTimeline[]; + duration: number; + apply(skeleton: Skeleton, time: number, loop: boolean): void; + min(skeleton: Skeleton, time: number, loop: boolean, alpha: number): void; + + } + + export class Curves { + + constructor(frameCount: number); + + curves: number[]; + + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + + } + + export interface ISpineTimeline { + + curves: Curves; + frames: number[]; + + getFrameCount(): number; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class RotateTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, angle: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class TranslateTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class ScaleTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class ColorTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class AttachmentTimeline implements ISpineTimeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + attachmentNames: string[]; + slotIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, time: number, alpha: number): void; + + } + + export class SkeletonData { + + bones: Bone[]; + slots: Slot[]; + skins: Skin[]; + animations: Animation[]; + defaultSkin: Skin; + + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findAnimation(animationName: string): Animation; + + } + + export class Skeleton { + + constructor(skeletonData: SkeletonData); + + data: SkeletonData; + bones: Bone[]; + slots: Slot[]; + drawOrder: any[]; + x: number; + y: number; + skin: Skin; + r: number; + g: number; + b: number; + a: number; + time: number; + flipX: boolean; + flipY: boolean; + + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + fineBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): void; + setSkin(newSkin: Skin): void; + getAttachmentBySlotName(slotName: string, attachmentName: string): RegionAttachment; + getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): RegionAttachment; + setAttachment(slotName: string, attachmentName: string): void; + update(data: number): void; + + } + + export class RegionAttachment { + + offset: number[]; + uvs: number[]; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + width: number; + height: number; + rendererObject: any; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + + setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; + updateOffset(): void; + computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; + + } + + export class AnimationStateData { + + constructor(skeletonData: SkeletonData); + + skeletonData: SkeletonData; + animationToMixTime: any; + defaultMix: number; + + setMixByName(fromName: string, toName: string, duration: number): void; + setMix(from: string, to: string): number; + + } + + export class AnimationState { + + constructor(stateData: any); + + animationSpeed: number; + current: any; + previous: any; + currentTime: number; + previousTime: number; + currentLoop: boolean; + previousLoop: boolean; + mixTime: number; + mixDuration: number; + queue: Animation[]; + + update(delta: number): void; + apply(skeleton: any): void; + clearAnimation(): void; + setAnimation(animation: any, loop: boolean): void; + setAnimationByName(animationName: string, loop: boolean): void; + addAnimationByName(animationName: string, loop: boolean, delay: number): void; + addAnimation(animation: any, loop: boolean, delay: number): void; + isComplete(): number; + + } + + export class SkeletonJson { + + constructor(attachmentLoader: AtlasAttachmentLoader); + + attachmentLoader: AtlasAttachmentLoader; + scale: number; + + readSkeletonData(root: any): SkeletonData; + readAttachment(skin: Skin, name: string, map: any): RegionAttachment; + readAnimation(name: string, map: any, skeletonData: SkeletonData): void; + readCurve(timeline: ISpineTimeline, frameIndex: number, valueMap: any): void; + toColor(hexString: string, colorIndex: number): number; + + } + + export class Atlas { + + static FORMAT: { + + alpha: number; + intensity: number; + luminanceAlpha: number; + rgb565: number; + rgba4444: number; + rgb888: number; + rgba8888: number; + + } + + static TextureFilter: { + + nearest: number; + linear: number; + mipMap: number; + mipMapNearestNearest: number; + mipMapLinearNearest: number; + mipMapNearestLinear: number; + mipMapLinearLinear: number; + + } + + static textureWrap: { + + mirroredRepeat: number; + clampToEdge: number; + repeat: number; + + } + + constructor(atlasText: string, textureLoader: AtlasLoader); + + textureLoader: AtlasLoader; + pages: AtlasPage[]; + regions: AtlasRegion[]; + + findRegion(name: string): AtlasRegion; + dispose(): void; + updateUVs(page: AtlasPage): void; + + } + + export class AtlasPage { + + name: string; + format: number; + minFilter: number; + magFilter: number; + uWrap: number; + vWrap: number; + rendererObject: any; + width: number; + height: number; + + } + + export class AtlasRegion { + + page: AtlasPage; + name: string; + x: number; + y: number; + width: number; + height: number; + u: number; + v: number; + u2: number; + v2: number; + offsetX: number; + offsetY: number; + originalWidth: number; + originalHeight: number; + index: number; + rotate: boolean; + splits: any[]; + pads: any[]; + + } + + export class AtlasReader { + + constructor(text: string); + + lines: string[]; + index: number; + + trim(value: string): string; + readLine(): string; + readValue(): string; + readTuple(tuple: number): number; + + } + + export class AtlasAttachmentLoader { + + constructor(atlas: Atlas); + + atlas: Atlas; + + newAttachment(skin: Skin, type: number, name: string): RegionAttachment; + + } + + export class Spine extends DisplayObjectContainer { + + constructor(url: string); + + autoUpdate: boolean; + spineData: any; + skeleton: Skeleton; + stateData: AnimationStateData; + state: AnimationState; + slotContainers: DisplayObjectContainer[]; + + createSprite(slot: Slot, descriptor: { name: string }): Sprite[]; + update(dt: number): void; + } } -declare function requestAnimFrame( animate: PIXI.IBasicCallback ); - - -declare module PIXI.PolyK -{ - export function Triangulate( p:number[]):number[]; -} - - +declare function requestAnimFrame(callback: Function): void; +declare module PIXI.PolyK { + export function Triangulate(p: number[]): number[]; +} \ No newline at end of file From d5557c6a5a666883277e0df2d2e3dfacefd5b39c Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:34:26 +0200 Subject: [PATCH 12/38] Updated pixi.js definitions to v3 --- pixi.js/pixi.js-tests.ts | 3709 ++++++++++++++++++++-------- pixi.js/pixi.js-tests.ts.tscparams | 1 - pixi.js/pixi.js.d.ts | 3196 +++++++++++------------- pixi.js/pixi.js.d.ts.tscparams | 1 - 4 files changed, 4149 insertions(+), 2758 deletions(-) delete mode 100644 pixi.js/pixi.js-tests.ts.tscparams delete mode 100644 pixi.js/pixi.js.d.ts.tscparams diff --git a/pixi.js/pixi.js-tests.ts b/pixi.js/pixi.js-tests.ts index 309f7f66a..6a462fc2e 100644 --- a/pixi.js/pixi.js-tests.ts +++ b/pixi.js/pixi.js-tests.ts @@ -1,1177 +1,2762 @@ -/// +/// -function PixiTests() -{ +module basics { -var stage = new PIXI.Stage(0xFFFFFF); + export class Basics { -stage.interactive = true; + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; -var bg = PIXI.Sprite.fromImage("BGrotate.jpg"); -bg.anchor.x = 0.5; -bg.anchor.y = 0.5; + private stage: PIXI.Container; -bg.position.x = 620/2; -bg.position.y = 380/2; + private bunny: PIXI.Sprite; -stage.addChild(bg); + constructor() { -var container = new PIXI.DisplayObjectContainer(); -container.position.x = 620/2; -container.position.y = 380/2; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); -var bgFront = PIXI.Sprite.fromImage("SceneRotate.jpg"); -bgFront.anchor.x = 0.5; -bgFront.anchor.y = 0.5; + // create the root of the scene graph + this.stage = new PIXI.Container(); -container.addChild(bgFront); + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); -var light2 = PIXI.Sprite.fromImage("LightRotate2.png"); -light2.anchor.x = 0.5; -light2.anchor.y = 0.5; -container.addChild(light2); + // create a new Sprite using the texture + this.bunny = new PIXI.Sprite(texture); -var light1 = PIXI.Sprite.fromImage("LightRotate1.png"); -light1.anchor.x = 0.5; -light1.anchor.y = 0.5; -container.addChild(light1); + // center the sprite's anchor point + this.bunny.anchor.x = 0.5; + this.bunny.anchor.y = 0.5; -var panda = PIXI.Sprite.fromImage("panda.png"); -panda.anchor.x = 0.5; -panda.anchor.y = 0.5; + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; -container.addChild(panda); + //add it to the stage + this.stage.addChild(this.bunny); -stage.addChild(container); + this.animate(); -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(620, 380); + } -renderer.view.style.position = "absolute" -renderer.view.style.marginLeft = "-310px"; -renderer.view.style.marginTop = "-190px"; -renderer.view.style.top = "50%"; -renderer.view.style.left = "50%"; -renderer.view.style.display = "block"; + private animate = (): void => { -// add render view to DOM -document.body.appendChild(renderer.view); + requestAnimationFrame(this.animate); -// lets create moving shape -var thing = new PIXI.Graphics(); -stage.addChild(thing); -thing.position.x = 620/2; -thing.position.y = 380/2; -thing.lineStyle(0); + this.bunny.rotation += 0.1; -container.mask = thing; + this.renderer.render(this.stage); -var count = 0; + } -stage.click = stage.tap = function() -{ - container.mask = null; -} - -/* - * Add a pixi Logo! - */ -var logo = PIXI.Sprite.fromImage("../../logo_small.png") -stage.addChild(logo); - -logo.anchor.x = 1; -logo.position.x = 620 -logo.scale.x = logo.scale.y = 0.5; -logo.position.y = 320 -logo.interactive = true; -logo.buttonMode = true; - -logo.click = logo.tap = function() -{ - window.open("https://github.com/GoodBoyDigital/pixi.js", "_blank") -} - -var help = new PIXI.Text("Click to turn masking on / off.", {font:"bold 12pt Arial", fill:"white"}); -help.position.y = 350; -help.position.x = 10; -stage.addChild(help); - -requestAnimFrame(animate); - -function animate() { - - bg.rotation += 0.01; - bgFront.rotation -= 0.01; - - light1.rotation += 0.02; - light2.rotation += 0.01; - - panda.scale.x = 1 + Math.sin(count) * 0.04; - panda.scale.y = 1 + Math.cos(count) * 0.04; - - count += 0.1; - - thing.clear(); - thing.lineStyle(5, 0x16f1ff, 1); - thing.beginFill(0x8bc5ff, 0.4); - thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count)* 20); - thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count)* 20); - thing.lineTo(-120 + Math.cos(count)* 20, 100 + Math.sin(count)* 20); - thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.rotation = count * 0.1; - - renderer.render(stage); - requestAnimFrame( animate ); -} - -/* 13 */ - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0xFFFFFF); - -var sprite= PIXI.Sprite.fromImage("spinObj_02.png"); -//stage.addChild(sprite); -// create a renderer instance -// the 5the parameter is the anti aliasing -var renderer = PIXI.autoDetectRenderer(620, 380); - -// set the canvas width and height to fill the screen -//renderer.view.style.width = window.innerWidth + "px"; -//renderer.view.style.height = window.innerHeight + "px"; -renderer.view.style.display = "block"; - -// add render view to DOM -document.body.appendChild(renderer.view); - -var graphics = new PIXI.Graphics(); - - -// set a fill and line style -graphics.beginFill(0xFF3300); -graphics.lineStyle(10, 0xffd900, 1); - -// draw a shape -graphics.moveTo(50,50); -graphics.lineTo(250, 50); -graphics.lineTo(100, 100); -graphics.lineTo(250, 220); -graphics.lineTo(50, 220); -graphics.lineTo(50, 50); -graphics.endFill(); - -// set a fill and line style again -graphics.lineStyle(10, 0xFF0000, 0.8); -graphics.beginFill(0xFF700B, 1); - -// draw a second shape -graphics.moveTo(210,300); -graphics.lineTo(450,320); -graphics.lineTo(570,350); -graphics.lineTo(580,20); -graphics.lineTo(330,120); -graphics.lineTo(410,200); -graphics.lineTo(210,300); -graphics.endFill(); - -// draw a rectangel -graphics.lineStyle(2, 0x0000FF, 1); -graphics.drawRect(50, 250, 100, 100); - -// draw a circle -graphics.lineStyle(0); -graphics.beginFill(0xFFFF0B, 0.5); -graphics.drawCircle(470, 200,100); - -graphics.lineStyle(20, 0x33FF00); -graphics.moveTo(30,30); -graphics.lineTo(600, 300); - - -stage.addChild(graphics); - -// lets create moving shape -var thing = new PIXI.Graphics(); -stage.addChild(thing); -thing.position.x = 620/2; -thing.position.y = 380/2; - -var count = 0; - -stage.click = stage.tap = function() -{ - graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); - graphics.moveTo(Math.random() * 620,Math.random() * 380); - graphics.lineTo(Math.random() * 620,Math.random() * 380); -} - -requestAnimFrame(animate); - -function animate1() { - - thing.clear(); - - count += 0.1; - - thing.clear(); - thing.lineStyle(30, 0xff0000, 1); - thing.beginFill(0xffFF00, 0.5); - - thing.moveTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - thing.lineTo(120 + Math.cos(count) * 20, -100 + Math.sin(count)* 20); - thing.lineTo(120 + Math.sin(count) * 20, 100 + Math.cos(count)* 20); - thing.lineTo(-120 + Math.cos(count)* 20, 100 + Math.sin(count)* 20); - thing.lineTo(-120 + Math.sin(count) * 20, -100 + Math.cos(count)* 20); - - thing.rotation = count * 0.1; - renderer.render(stage); - requestAnimFrame( animate ); -} - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x000000); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(800, 600); - -// set the canvas width and height to fill the screen -renderer.view.style.width = window.innerWidth + "px"; -renderer.view.style.height = window.innerHeight + "px"; -renderer.view.style.display = "block"; - -// add render view to DOM -document.body.appendChild(renderer.view); - -// OOH! SHINY! -// create two render textures.. these dynamic textures will be used to draw the scene into itself -var renderTexture = new PIXI.RenderTexture(800, 600); -var renderTexture2 = new PIXI.RenderTexture(800, 600); -var currentTexture = renderTexture; - -// create a new sprite that uses the render texture we created above -var outputSprite = new PIXI.Sprite(currentTexture); - -// align the sprite -outputSprite.position.x = 800/2; -outputSprite.position.y = 600/2; -outputSprite.anchor.x = 0.5; -outputSprite.anchor.y = 0.5; - -// add to stage -stage.addChild(outputSprite); - -var stuffContainer = new PIXI.DisplayObjectContainer(); - -stuffContainer.position.x = 800/2; -stuffContainer.position.y = 600/2 - -stage.addChild(stuffContainer); - -// create an array of image ids.. -var fruits = ["spinObj_01.png", "spinObj_02.png", - "spinObj_03.png", "spinObj_04.png", - "spinObj_05.png", "spinObj_06.png", - "spinObj_07.png", "spinObj_08.png"]; - -// create an array of items -var items = []; - -// now create some items and randomly position them in the stuff container -for (var i=0; i < 20; i++) -{ - var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); - item.position.x = Math.random() * 400 - 200; - item.position.y = Math.random() * 400 - 200; - - item.anchor.x = 0.5; - item.anchor.y = 0.5; - - stuffContainer.addChild(item); - console.log("_") - items.push(item); -}; - -// used for spinning! -var count = 0; - - -requestAnimFrame(animate); - -function animate2() { - - requestAnimFrame( animate ); - - for (var i=0; i < items.length; i++) - { - // rotate each item - var item = items[i]; - item.rotation += 0.1; - }; - - count += 0.01; - - // swap the buffers.. - var temp = renderTexture; - renderTexture = renderTexture2; - renderTexture2 = temp; - - - // set the new texture - outputSprite.setTexture(renderTexture); - - // twist this up! - stuffContainer.rotation -= 0.01 - outputSprite.scale.x = outputSprite.scale.y = 1 + Math.sin(count) * 0.2; - - // render the stage to the texture - // the true clears the texture before content is rendered - renderTexture2.render(stage, new PIXI.Point(0,0), true); - - // and finally render the stage - renderer.render(stage); -} - - -//// - - - -function init() -{ - var assetsToLoader = ["desyrel.fnt"]; - - // create a new loader - var loader = new PIXI.AssetLoader(assetsToLoader, false); - - //begin load - - // create an new instance of a pixi stage - var stage = new PIXI.Stage(0x66FF99); - - loader.load(); - function onAssetsLoaded() - { - var bitmapFontText = new PIXI.BitmapText("bitmap fonts are\n now supported!", {font: "35px Desyrel", align: "right"}); - bitmapFontText.position.x = 620 - bitmapFontText.width - 20; - bitmapFontText.position.y = 20; - - stage.addChild(bitmapFontText); - - - } - - - - // add a shiney background.. - var background = PIXI.Sprite.fromImage("textDemoBG.jpg"); - stage.addChild(background); - - // create a renderer instance - var renderer = PIXI.autoDetectRenderer(620, 400); - // add the renderer view element to the DOM - document.body.appendChild(renderer.view); - - requestAnimFrame(animate); - - // create some white text using the Snippet webfont - var textSample = new PIXI.Text("Pixi.js can has\nmultiline text!", {font: "35px Snippet", fill: "white", align: "left"}); - textSample.position.x = 20; - textSample.position.y = 20; - - // create a text object with a nice stroke - var spinningText = new PIXI.Text("I'm fun!", {font: "bold 60px Podkova", fill: "#cc00ff", align: "center", stroke: "#FFFFFF", strokeThickness: 6}); - // setting the anchor point to 0.5 will center align the text... great for spinning! - spinningText.anchor.x = spinningText.anchor.y = 0.5; - spinningText.position.x = 620 / 2; - spinningText.position.y = 400 / 2; - - // create a text object that will be updated.. - var countingText = new PIXI.Text("COUNT 4EVAR: 0", {font: "bold italic 60px Arvo", fill: "#3e1707", align: "center", stroke: "#a4410e", strokeThickness: 7}); - countingText.position.x = 620 / 2; - countingText.position.y = 320; - countingText.anchor.x = 0.5; - - stage.addChild(textSample); - stage.addChild(spinningText); - stage.addChild(countingText); - - var count = 0; - var score = 0; - - function animate() { - - requestAnimFrame( animate ); - count++; - if(count == 50) - { - count = 0; - score++; - // update the text... - countingText.setText("COUNT 4EVAR: " + score); - - } - // just for fun, lets rotate the text - spinningText.rotation += 0.03; - - // render the stage - renderer.render(stage); - } -} - - -///// - - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("p2.jpeg"); - -// create a tiling sprite.. -// requires a texture, width and height -// to work in webGL the texture size must be a power of two -var tilingSprite = new PIXI.TilingSprite(texture, window.innerWidth, window.innerHeight) - -var count = 0; - -stage.addChild(tilingSprite); - -function animate33() { - - requestAnimFrame( animate ); - - - count += 0.005 - tilingSprite.tileScale.x = 2 + Math.sin(count); - tilingSprite.tileScale.y = 2 + Math.cos(count); - - tilingSprite.tilePosition.x += 1; - tilingSprite.tilePosition.y += 1; - - // just for fun, lets rotate mr rabbit a little - //stage.interactionManager.update(); - // render the stage - renderer.render(stage); -} - - - -///// - - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x97c56e); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(window.innerWidth, window.innerHeight, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("bunny.png"); - -for (var i=0; i < 10; i++) -{ - createBunny(Math.random() * window.innerWidth, Math.random() * window.innerHeight) -}; - - -function createBunny(x, y) -{ - // create our little bunny friend.. - var bunny = new PIXI.Sprite(texture); - // bunny.width = 300; - // enable the bunny to be interactive.. this will allow it to respond to mouse and touch events - bunny.interactive = true; - // this button mode will mean the hand cursor appears when you rollover the bunny with your mouse - bunny.buttonMode = true; - - // center the bunnys anchor point - bunny.anchor.x = 0.5; - bunny.anchor.y = 0.5; - // make it a bit bigger, so its easier to touch - bunny.scale.x = bunny.scale.y = 3; - - - // use the mousedown and touchstart - bunny.mousedown = bunny.touchstart = function(data) - { - // stop the default event... - data.originalEvent.preventDefault(); - - // store a refference to the data - // The reason for this is because of multitouch - // we want to track the movement of this particular touch - this.data = data; - this.alpha = 0.9; - this.dragging = true; - }; - - // set the events for when the mouse is released or a touch is released - bunny.mouseup = bunny.mouseupoutside = bunny.touchend = bunny.touchendoutside = function(data) - { - this.alpha = 1 - this.dragging = false; - // set the interaction data to null - this.data = null; - }; - - // set the callbacks for when the mouse or a touch moves - bunny.mousemove = bunny.touchmove = function(data) - { - if(this.dragging) - { - // need to get parent coords.. - var newPosition = this.data.getLocalPosition(this.parent); - this.position.x = newPosition.x; - this.position.y = newPosition.y; - } - } - - // move the sprite to its designated position - bunny.position.x = x; - bunny.position.y = y; - - // add it to the stage - stage.addChild(bunny); -} - -function animate44() { - - requestAnimFrame( animate ); - - // just for fun, lets rotate mr rabbit a little - //stage.interactionManager.update(); - // render the stage - renderer.render(stage); -} - - - -//// - -// create an new instance of a pixi stage -var stage = new PIXI.Stage(0x66FF99); - -// create a renderer instance -var renderer = PIXI.autoDetectRenderer(400, 300, null); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); -renderer.view.style.position = "absolute"; -renderer.view.style.top = "0px"; -renderer.view.style.left = "0px"; -requestAnimFrame( animate ); - -// create a texture from an image path -var texture = PIXI.Texture.fromImage("bunny.png"); -// create a new Sprite using the texture -var bunny = new PIXI.Sprite(texture); - -// center the sprites anchor point -bunny.anchor.x = 0.5; -bunny.anchor.y = 0.5; - -// move the sprite t the center of the screen -bunny.position.x = 200; -bunny.position.y = 150; - -stage.addChild(bunny); - -function animate55() { - - requestAnimFrame( animate ); - - // just for fun, lets rotate mr rabbit a little - bunny.rotation += 0.1; - - // render the stage - renderer.render(stage); -} - - - -/////// - - - -// create an new instance of a pixi stage -// the second parameter is interactivity... -var interactive = true; -var stage = new PIXI.Stage(0x000000); - -// create a renderer instance. -var renderer = PIXI.autoDetectRenderer(620, 400); - -// add the renderer view element to the DOM -document.body.appendChild(renderer.view); - -requestAnimFrame( animate ); - -// create a background.. -var background = PIXI.Sprite.fromImage("button_test_BG.jpg"); - -// add background to stage.. -stage.addChild(background); - -// create some textures from an image path -var textureButton = PIXI.Texture.fromImage("button.png"); -var textureButtonDown = PIXI.Texture.fromImage("buttonDown.png"); -var textureButtonOver = PIXI.Texture.fromImage("buttonOver.png"); - -var buttons = []; - -var buttonPositions = [175,75, - 600-145, 75, - 600/2 - 20, 400/2 + 10, - 175, 400-75, - 600-115, 400-95]; - - -for (var i=0; i < 5; i++) -{ - var button = new PIXI.Sprite(textureButton); - button.buttonMode = true; - - button.anchor.x = 0.5; - button.anchor.y = 0.5; - - button.position.x = buttonPositions[i*2]; - button.position.y = buttonPositions[i*2 + 1]; - - // make the button interactive.. - button.interactive = true; - - // set the mousedown and touchstart callback.. - button.mousedown = button.touchstart = function(data){ - - this.isdown = true; - this.setTexture(textureButtonDown); - this.alpha = 1; - } - - // set the mouseup and touchend callback.. - button.mouseup = button.touchend = button.mouseupoutside = button.touchendoutside = function(data){ - this.isdown = false; - - if(this.isOver) - { - this.setTexture(textureButtonOver); - } - else - { - this.setTexture(textureButton); - } - } - - // set the mouseover callback.. - button.mouseover = function(data){ - - this.isOver = true; - - if(this.isdown)return - - this.setTexture(textureButtonOver) - } - - // set the mouseout callback.. - button.mouseout = function(data){ - - this.isOver = false; - if(this.isdown)return - this.setTexture(textureButton) - } - - button.click = function(data){ - // click! - console.log("CLICK!"); - // alert("CLICK!") - } - - button.tap = function(data){ - // click! - console.log("TAP!!"); - //this.alpha = 0.5; - } - - // add it to the stage - stage.addChild(button); - - // add button to array - buttons.push(button); -}; - -// set some silly values.. - -buttons[0].scale.x = 1.2; - -buttons[1].scale.y = 1.2; - -buttons[2].rotation = Math.PI/10; - -buttons[3].scale.x = 0.8; -buttons[3].scale.y = 0.8; - -buttons[4].scale.x = 0.8; -buttons[4].scale.y = 1.2; -buttons[4].rotation = Math.PI; -// var button1 = -function animate66() { - - requestAnimFrame( animate ); - // render the stage - - // do a test.. - - renderer.render(stage); -} - -// add a logo! -var pixiLogo = PIXI.Sprite.fromImage("pixi.png"); -stage.addChild(pixiLogo); - -pixiLogo.position.x = 620 - 56; -pixiLogo.position.y = 400- 32; - -pixiLogo.click = pixiLogo.tap = function(){ - - var win=window.open("https://github.com/GoodBoyDigital/pixi.js", '_blank'); + } } +module basics { -////// + export class Click { + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + private stage: PIXI.Container; -var w = 1024; -var h = 768; + private sprite: PIXI.Sprite; -var n = 2000; -var d = 1; -var current = 1; -var objs = 17; -var vx = 0; -var vy = 0; -var vz = 0; -var points1 = []; -var points2 = []; -var points3 = []; -var tpoint1 = []; -var tpoint2 = []; -var tpoint3 = []; -var balls = []; + constructor() { -function start() { + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - var ballTexture = PIXI.Texture.fromImage("assets/pixel.png"); + // create the root of the scene graph + this.stage = new PIXI.Container(); - renderer = PIXI.autoDetectRenderer(w, h); + this.sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + this.sprite.position.set(230, 264); + this.sprite.interactive = true; + this.sprite.on('mousedown', this.onDown, this); + this.sprite.on('touchstart', this.onDown, this); - stage = new PIXI.Stage(0x000000); + //add it to the stage + this.stage.addChild(this.sprite); - document.body.appendChild(renderer.view); + //start animatng + this.animate(); - makeObject(0); + } - for (var i = 0; i < n; i++) - { - tpoint1[i] = points1[i]; - tpoint2[i] = points2[i]; - tpoint3[i] = points3[i]; + private onDown = (eventData: PIXI.interaction.InteractionData): void => { - var tempBall = new PIXI.Sprite(ballTexture); - tempBall.anchor.x = 0.5; - tempBall.anchor.y = 0.5; - tempBall.alpha = 0.5; - balls[i] = tempBall; + this.sprite.scale.x += 0.3; + this.sprite.scale.y += 0.3; - stage.addChild(tempBall); - } + } + private animate = (): void => { + requestAnimationFrame(this.animate); - setTimeout(nextObject, 5000); + this.renderer.render(this.stage); - requestAnimFrame(update); + } + + } } -function nextObject () { +module basics { - current++; + export class Container { - if (current > objs) - { - current = 0; - } + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - makeObject(current); + private stage: PIXI.Container; - setTimeout(nextObject, 8000); + private container: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + this.container.addChild(bunny); + + }; + + }; + + /* + * All the bunnies are added to the container with the addChild method + * when you do this, all the bunnies become children of the container, and when a container moves, + * so do all its children. + * This gives you a lot of flexibility and makes it easier to position elements on the screen + */ + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } } -function makeObject ( t ) { +module basics { - var xd; + export class CustomFilter { - switch (t) - { - case 0: + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - for (var i = 0; i < n; i++) - { - points1[i] = -50 + Math.round(Math.random() * 100); - points2[i] = 0; - points3[i] = 0; - } - break; + private stage: PIXI.Container; - case 1: + private background: PIXI.Sprite; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(t * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(t * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + private filter: CustomizedFilter; - case 2: + constructor() { - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(t * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(t * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - case 3: + // create the root of the scene graph + this.stage = new PIXI.Container(); - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + this.background = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.background.scale.set(1.3, 1); + this.stage.addChild(this.background); - case 4: - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + PIXI.loader.add('shader', '../../_assets/basics/shader.frag'); + PIXI.loader.once('complete', this.onLoaded, this); + PIXI.loader.load(); - case 5: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + private onLoaded(loader: PIXI.loaders.Loader, res: any) { - case 6: + var fragmentSrc = res.shader.data; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + this.filter = new CustomizedFilter(fragmentSrc); + this.background.filters = [this.filter]; - case 7: + this.animate(); - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - case 8: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + private animate = (): void => { - case 9: + this.filter.uniforms.customUniform.value += 0.04; - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + this.renderer.render(this.stage); + requestAnimationFrame(this.animate); - case 10: + } - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.cos(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; + } - case 11: + export class CustomizedFilter extends PIXI.AbstractFilter { - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; + constructor(fragmentSource: string | string[]) { + super(null, fragmentSource, { + customUniform: { + type: '1f', + value: 0 + } + }) + } - case 12: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 13: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 14: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.sin(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.sin(xd) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 15: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(i * 360 / n) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - - case 16: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(i * 360 / n) * 10); - points2[i] = (Math.sin(i * 360 / n) * 10) * (Math.sin(xd) * 10); - points3[i] = Math.sin(xd) * 100; - } - break; - - case 17: - - for (var i = 0; i < n; i++) - { - xd = -90 + Math.round(Math.random() * 180); - points1[i] = (Math.cos(xd) * 10) * (Math.cos(xd) * 10); - points2[i] = (Math.cos(i * 360 / n) * 10) * (Math.sin(i * 360 / n) * 10); - points3[i] = Math.sin(i * 360 / n) * 100; - } - break; - } + } } +module basics { + export class Graphics { -function update() -{ - var x3d, y3d, z3d, tx, ty, tz, ox; + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; - if (d < 250) - { - d++; - } + private stage: PIXI.Container; - vx += 0.0075; - vy += 0.0075; - vz += 0.0075; + private graphics: PIXI.Graphics; - for (var i = 0; i < n; i++) - { - if (points1[i] > tpoint1[i]) { tpoint1[i] = tpoint1[i] + 1; } - if (points1[i] < tpoint1[i]) { tpoint1[i] = tpoint1[i] - 1; } - if (points2[i] > tpoint2[i]) { tpoint2[i] = tpoint2[i] + 1; } - if (points2[i] < tpoint2[i]) { tpoint2[i] = tpoint2[i] - 1; } - if (points3[i] > tpoint3[i]) { tpoint3[i] = tpoint3[i] + 1; } - if (points3[i] < tpoint3[i]) { tpoint3[i] = tpoint3[i] - 1; } + constructor() { - x3d = tpoint1[i]; - y3d = tpoint2[i]; - z3d = tpoint3[i]; + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); - ty = (y3d * Math.cos(vx)) - (z3d * Math.sin(vx)); - tz = (y3d * Math.sin(vx)) + (z3d * Math.cos(vx)); - tx = (x3d * Math.cos(vy)) - (tz * Math.sin(vy)); - tz = (x3d * Math.sin(vy)) + (tz * Math.cos(vy)); - ox = tx; - tx = (tx * Math.cos(vz)) - (ty * Math.sin(vz)); - ty = (ox * Math.sin(vz)) + (ty * Math.cos(vz)); + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; - balls[i].position.x = (512 * tx) / (d - tz) + w / 2; - balls[i].position.y = (h/2) - (512 * ty) / (d - tz); + this.graphics = new PIXI.Graphics(); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); - } + // set a fill and a line style again and draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.beginFill(0xFF700B, 1); + this.graphics.drawRect(50, 250, 120, 120); - renderer.render(stage); + // draw a rounded rectangle + this.graphics.lineStyle(2, 0xFF00FF, 1); + this.graphics.beginFill(0xFF00BB, 0.25); + this.graphics.drawRoundedRect(150, 450, 300, 100, 15); + this.graphics.endFill(); - requestAnimFrame(update); -} + // draw a circle, set the lineStyle to zero so the circle doesn't have an outline + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 90, 60); + this.graphics.endFill(); + this.stage.addChild(this.graphics); + // start animating + this.animate(); -/////// + } + private animate = (): void => { + requestAnimationFrame(this.animate); -// Globals, globals everywhere and not a drop to drink -var w = 1024; -var h = 768; -var starCount = 2500; -var sx = 1.0 + (Math.random() / 20); -var sy = 1.0 + (Math.random() / 20); -var slideX = w / 2; -var slideY = h / 2; -var stars = []; + this.renderer.render(this.stage); -function start2() { + } - var ballTexture = PIXI.Texture.fromImage("assets/bubble_32x32.png"); - - renderer = PIXI.autoDetectRenderer(w, h); - - stage = new PIXI.Stage(0x000000); - - document.body.appendChild(renderer.view); - - for (var i = 0; i < starCount; i++) - { - var tempBall = new PIXI.Sprite(ballTexture); - - tempBall.position.x = (Math.random() * w) - slideX; - tempBall.position.y = (Math.random() * h) - slideY; - tempBall.anchor.x = 0.5; - tempBall.anchor.y = 0.5; - - stars.push({ sprite: tempBall, x: tempBall.position.x, y: tempBall.position.y }); - - stage.addChild(tempBall); - } - - document.getElementById('rnd').onclick = newWave; - document.getElementById('sx').innerHTML = 'SX: ' + sx + '
SY: ' + sy; - - - - requestAnimFrame(update); + } } -function newWave () { +module basics { - sx = 1.0 + (Math.random() / 20); - sy = 1.0 + (Math.random() / 20); - document.getElementById('sx').innerHTML = 'SX: ' + sx + '
SY: ' + sy; + export class RenderTexture { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + + private sprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.container = new PIXI.Container(); + + this.stage.addChild(this.container); + + for (var j = 0; j < 5; j++) { + + for (var i = 0; i < 5; i++) { + + var bunny: PIXI.Sprite = PIXI.Sprite.fromImage('../../_assets/basics/bunny.png'); + bunny.x = 40 * i; + bunny.y = 40 * j; + bunny.rotation = Math.random() * (Math.PI * 2); + this.container.addChild(bunny); + + }; + + }; + + this.renderTexture = new PIXI.RenderTexture(this.renderer, 300, 200, PIXI.SCALE_MODES.LINEAR, 0.1); + + this.sprite = new PIXI.Sprite(this.renderTexture); + this.sprite.x = 450; + this.sprite.y = 60; + this.stage.addChild(this.sprite); + + this.container.x = 100; + this.container.y = 60; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.renderTexture.render(this.container); + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } } +module basics { + + export class SpriteSheet { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private movie: PIXI.extras.MovieClip; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader.add('../../_assets/basics/fighter.json').load((loader: PIXI.loaders.Loader, object: any): void => { + + // create an array of textures from an image path + var frames: PIXI.Texture[] = []; + + for (var i = 0; i < 30; i++) { + + var val = i < 10 ? '0' + i : i; + + // magically works since the spritesheet was loaded with the pixi loader + frames.push(PIXI.Texture.fromFrame('rollSequence00' + val + '.png')); + } -function update22() -{ - for (var i = 0; i < starCount; i++) - { - stars[i].sprite.position.x = stars[i].x + slideX; - stars[i].sprite.position.y = stars[i].y + slideY; - stars[i].x = stars[i].x * sx; - stars[i].y = stars[i].y * sy; + // create a MovieClip (brings back memories from the days of Flash, right ?) + this.movie = new PIXI.extras.MovieClip(frames); - if (stars[i].x > w) - { - stars[i].x = stars[i].x - w; - } - else if (stars[i].x < -w) - { - stars[i].x = stars[i].x + w; - } + /* + * A MovieClip inherits all the properties of a PIXI sprite + * so you can change its position, its anchor, mask it, etc + */ + this.movie.position.set(300); + this.movie.anchor.set(0.5); + this.movie.animationSpeed = 0.5; + this.movie.play(); - if (stars[i].y > h) - { - stars[i].y = stars[i].y - h; - } - else if (stars[i].y < -h) - { - stars[i].y = stars[i].y + h; - } - } + this.stage.addChild(this.movie); - renderer.render(stage); + this.animate(); + + }); + + } + + private animate = (): void => { + + this.movie.rotation += 0.01; + + //render the stage container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } - requestAnimFrame(update); } -} \ No newline at end of file +module basics { + + export class Text { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private basicText: PIXI.Text; + + private richText: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.basicText = new PIXI.Text('Basic Text in Pixi'); + this.basicText.x = 30; + this.basicText.y = 90; + + this.stage.addChild(this.basicText); + + var style: PIXI.TextStyle = { + font: '36px Arial bold italic', + fill: '#F7EDCA', + stroke: '#4a1850', + strokeThickness: 5, + dropShadow: true, + dropShadowColor: '#000000', + dropShadowAngle: Math.PI / 6, + dropShadowDistance: 6, + wordWrap: true, + wordWrapWidth: 440 + }; + + this.richText = new PIXI.Text('Rich Text with a lot of options and across multiple lines', style); + this.richText.x = 30; + this.richText.y = 180; + + this.stage.addChild(this.richText); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module basics { + + export class TexturedMesh { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private strip: PIXI.mesh.Rope; + + private graphics: PIXI.Graphics; + + private count: number; + + private points: PIXI.Point[]; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + this.ropeLength = 918 / 20; + this.ropeLength = 45; + + this.points = []; + + for (var i = 0; i < 25; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + }; + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.position.x = -40; + this.strip.position.y = 300; + this.stage.addChild(this.strip); + + this.graphics = new PIXI.Graphics(); + this.graphics.x = this.strip.x; + this.graphics.y = this.strip.y; + this.stage.addChild(this.graphics); + + //start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + //make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + }; + + //render the stage + this.renderer.render(this.stage); + + this.renderPoints(); + + requestAnimationFrame(this.animate); + + } + + private renderPoints(): void { + + this.graphics.clear(); + + this.graphics.lineStyle(2, 0xffc2c2); + this.graphics.moveTo(this.points[0].x, this.points[0].y); + + for (var i = 1; i < this.points.length; i++) { + this.graphics.lineTo(this.points[i].x, this.points[i].y); + }; + + for (var i = 1; i < this.points.length; i++) { + this.graphics.beginFill(0xff0022); + this.graphics.drawCircle(this.points[i].x, this.points[i].y, 10); + this.graphics.endFill(); + }; + + } + + } + +} + +module basics { + + export class TilingSprite { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private tilingSprite: PIXI.extras.TilingSprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image path + this.texture = PIXI.Texture.fromImage('../../_assets/p2.jpeg'); + + /* create a tiling sprite ... + * requires a texture, a width and a height + * in WebGL the image size should preferably be a power of two + */ + this.tilingSprite = new PIXI.extras.TilingSprite(this.texture, this.renderer.width, this.renderer.height); + this.stage.addChild(this.tilingSprite); + + this.count = 0; + + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + this.tilingSprite.tileScale.x = 2 + Math.sin(this.count); + this.tilingSprite.tileScale.y = 2 + Math.cos(this.count); + + this.tilingSprite.tilePosition.x += 1; + this.tilingSprite.tilePosition.y += 1; + + // render the root container + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module basics { + + export class Video { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private videoSprite: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a video texture from a path + this.texture = PIXI.Texture.fromVideo('../../_assets/testVideo.mp4'); + + //create a new sprite using the video texture (yes it's that easy) + this.videoSprite = new PIXI.Sprite(this.texture); + this.videoSprite.width = this.renderer.width; + this.videoSprite.height = this.renderer.height; + this.stage.addChild(this.videoSprite); + + this.stage.addChild(this.videoSprite); + + this.animate(); + + } + + private animate = (): void => { + + //render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class AlphaMask { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Container; + + private cells: PIXI.Sprite; + + private mask: PIXI.Sprite; + + private target: PIXI.Point; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.background = PIXI.Sprite.fromImage('../../_assets/bkg.jpg'); + this.stage.addChild(this.background); + + this.cells = PIXI.Sprite.fromImage('../../_assets/cells.png'); + this.cells.scale.set(1.5, 1.5); + + this.mask = PIXI.Sprite.fromImage('../../_assets/flowerTop.png'); + this.mask.anchor.set(0.5); + this.mask.position.x = 310; + this.mask.position.y = 190; + + this.cells.mask = this.mask; + + this.stage.addChild(this.mask); + + this.stage.addChild(this.cells); + + this.target = new PIXI.Point(); + + this.reset(); + + this.animate(); + + } + + private reset(): void { + + this.target.x = Math.floor(Math.random() * 550); + this.target.y = Math.floor(Math.random() * 300); + + } + + private animate = (): void => { + + this.mask.position.x += (this.target.x - this.mask.x) * 0.1; + this.mask.position.y += (this.target.y - this.mask.y) * 0.1; + + if (Math.abs(this.mask.x - this.target.x) < 1) { + this.reset(); + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class Batch { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private sprites: PIXI.ParticleContainer; + + private maggots: BatchDude[]; + + private tick: number; + + private dudeBounds: PIXI.Rectangle; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.sprites = new PIXI.ParticleContainer(10000, { + + scale: true, + position: true, + rotation: true, + uvs: true, + alpha: true + + }); + this.stage.addChild(this.sprites); + + // create an array to store all the sprites + this.maggots = []; + + var totalSprites = this.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100; + + for (var i = 0; i < totalSprites; i++) { + + // create a new Sprite + var dude = new BatchDude(PIXI.Texture.fromImage('../../_assets/tinyMaggot.png')); + + dude.tint = Math.random() * 0xE8D4CD; + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // different maggots, different sizes + dude.scale.set(0.8 + Math.random() * 0.3); + + // scatter them all + dude.x = Math.random() * this.renderer.width; + dude.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0x808080; + + // create a random direction in radians + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the sprite over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed between 0 - 2, and these maggots are slooww + dude.speed = (2 + Math.random() * 2) * 0.2; + + dude.offset = Math.random() * 100; + + // finally we push the dude into the maggots array so it it can be easily accessed later + this.maggots.push(dude); + + this.sprites.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the sprites and update their position + for (var i = 0; i < this.maggots.length; i++) { + + var dude = this.maggots[i]; + dude.scale.y = 0.95 + Math.sin(this.tick + dude.offset) * 0.05; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y); + dude.position.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y); + dude.rotation = -dude.direction + Math.PI; + + // wrap the maggots + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BatchDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +module demos { + + export class BlendModes { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private dudeArray: BlendModesDude[]; + + private totalDudes: number; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new background sprite + this.background = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.stage.addChild(this.background); + + // create an array to store a reference to the dudes + this.dudeArray = []; + + this.totalDudes = 20; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new BlendModesDude(PIXI.Texture.fromImage('../../_assets/flowerTop.png')); + + dude.anchor.set(0.5); + + // set a random scale for the dude + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally let's set the dude to be at a random position... + dude.position.x = Math.floor(Math.random() * this.renderer.width); + dude.position.y = Math.floor(Math.random() * this.renderer.height); + + // The important bit of this example, this is how you change the default blend mode of the sprite + dude.blendMode = PIXI.BLEND_MODES.ADD; + + // create some extra properties that will control movement + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the dudeArray so it it can be easily accessed later + this.dudeArray.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box box for the little maggots + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + this.tick = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update the positions + for (var i = 0; i < this.dudeArray.length; i++) { + + var dude = this.dudeArray[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + } + + // increment the ticker + this.tick += 0.1; + + // time to render the stage ! + this.renderer.render(this.stage); + + // request another animation frame... + requestAnimationFrame(this.animate); + + } + + } + + export class BlendModesDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + offset: number; + + constructor(texture: PIXI.Texture) { + + super(texture); + + } + + } + +} + +module demos { + + export class CacheAsBitmap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private aliens: PIXI.Sprite[]; + + private alienContainer: PIXI.Container; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // load resources + PIXI.loader + .add('spritesheet', '../../_assets/monsters.json') + .load(this.onAssetsLoaded); + + // holder to store aliens + this.aliens = []; + + this.count = 0; + + // create an empty container + this.alienContainer = new PIXI.Container(); + this.alienContainer.position.x = 400; + this.alienContainer.position.y = 300; + + // make the stage interactive + this.stage.interactive = true; + + this.stage.addChild(this.alienContainer); + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.alienContainer.cacheAsBitmap = !this.alienContainer.cacheAsBitmap; + + //feel free to play with what's below + //var sprite = new PIXI.Sprite(this.alienContainer.generateTexture()); + //this.stage.addChild(sprite); + //sprite.position.x = Math.random() * 800; + //sprite.position.y = Math.random() * 600; + + } + + private onAssetsLoaded = (): void => { + + // add a bunch of aliens with textures from image paths + + var alienFrames = ['eggHead.png', 'flowerTop.png', 'helmlok.png', 'skully.png']; + + for (var i = 0; i < 100; i++) { + + var frameName = alienFrames[i % 4]; + + // create an alien using the frame name.. + var alien = PIXI.Sprite.fromFrame(frameName); + alien.tint = Math.random() * 0xFFFFFF; + + /* + * fun fact for the day :) + * another way of doing the above would be + * var texture = PIXI.Texture.fromFrame(frameName); + * var alien = new PIXI.Sprite(texture); + */ + alien.position.x = Math.random() * 800 - 400; + alien.position.y = Math.random() * 600 - 300; + alien.anchor.x = 0.5; + alien.anchor.y = 0.5; + this.aliens.push(alien); + this.alienContainer.addChild(alien); + + } + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // let's rotate the aliens a little bit + for (var i = 0; i < 100; i++) { + var alien = this.aliens[i]; + alien.rotation += 0.1; + } + + this.count += 0.01; + + this.alienContainer.scale.x = Math.sin(this.count); + this.alienContainer.scale.y = Math.sin(this.count); + + this.alienContainer.rotation += 0.01; + + // render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class DraggableBunny extends PIXI.Sprite { + + //todo I dont know what event.data is at this time + private data: any; + + private dragging: boolean; + + constructor(texture?: PIXI.Texture) { + + super(texture); + + // enable the bunny to be interactive... this will allow it to respond to mouse and touch events + this.interactive = true; + + // this button mode will mean the hand cursor appears when you roll over the bunny with your mouse + this.buttonMode = true; + + // center the bunny's anchor point + this.anchor.set(0.5); + + // make it a bit bigger, so it's easier to grab + this.scale.set(3); + + // setup events + this + // events for drag start + .on('mousedown', this.onDragStart) + .on('touchstart', this.onDragStart) + // events for drag end + .on('mouseup', this.onDragEnd) + .on('mouseupoutside', this.onDragEnd) + .on('touchend', this.onDragEnd) + .on('touchendoutside', this.onDragEnd) + // events for drag move + .on('mousemove', this.onDragMove) + .on('touchmove', this.onDragMove); + + } + + private onDragStart = (event: PIXI.interaction.InteractionEvent): void => { + + // store a reference to the data + // the reason for this is because of multitouch + // we want to track the movement of this particular touch + this.data = event.data; + this.alpha = 0.5; + this.dragging = true; + + } + + private onDragEnd = (event: PIXI.interaction.InteractionEvent): void => { + + //set interactiondata to null + this.data = null; + this.alpha = 1; + this.dragging = false; + + } + + private onDragMove = (event: PIXI.interaction.InteractionEvent): void => { + + if (this.dragging) { + var newPosition = this.data.getLocalPosition(this.parent); + this.position.x = newPosition.x; + this.position.y = newPosition.y; + } + + } + + } + + export class Dragging { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private texture: PIXI.Texture; + + private data: PIXI.interaction.InteractionData; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + //create a texture from an image + this.texture = PIXI.Texture.fromImage('../../_assets/bunny.png'); + + for (var i = 0; i < 10; i++) { + this.createBunny(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600)); + } + + // start animating + this.animate(); + + } + + private createBunny(x: number, y: number): void { + + // create our little bunny friend.. + var bunny = new DraggableBunny(this.texture); + + // move the sprite to its designated position + bunny.position.x = x; + bunny.position.y = y; + + // add it to the stage + this.stage.addChild(bunny); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module demos { + + export class GraphicsDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private thing: PIXI.Graphics; + + private graphics: PIXI.Graphics; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.graphics = new PIXI.Graphics(); + + // set a fill and line style + this.graphics.beginFill(0xFF3300); + this.graphics.lineStyle(10, 0xffd900, 1); + + // draw a shape + this.graphics.moveTo(50, 50); + this.graphics.lineTo(250, 50); + this.graphics.lineTo(100, 100); + this.graphics.lineTo(250, 220); + this.graphics.lineTo(50, 220); + this.graphics.lineTo(50, 50); + this.graphics.endFill(); + + // set a fill and line style again + this.graphics.lineStyle(10, 0xFF0000, 0.8); + this.graphics.beginFill(0xFF700B, 1); + + // draw a second shape + this.graphics.moveTo(210, 300); + this.graphics.lineTo(450, 320); + this.graphics.lineTo(570, 350); + this.graphics.quadraticCurveTo(600, 0, 480, 100); + this.graphics.lineTo(330, 120); + this.graphics.lineTo(410, 200); + this.graphics.lineTo(210, 300); + this.graphics.endFill(); + + // draw a rectangle + this.graphics.lineStyle(2, 0x0000FF, 1); + this.graphics.drawRect(50, 250, 100, 100); + + // draw a circle + this.graphics.lineStyle(0); + this.graphics.beginFill(0xFFFF0B, 0.5); + this.graphics.drawCircle(470, 200, 100); + this.graphics.endFill(); + + this.graphics.lineStyle(20, 0x33FF00); + this.graphics.moveTo(30, 30); + this.graphics.lineTo(600, 300); + + this.stage.addChild(this.graphics); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = 620 / 2; + this.thing.position.y = 380 / 2; + + this.count = 0; + + // Just click on the stage to draw random lines + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + // start animating + this.animate(); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + this.graphics.lineStyle(Math.random() * 30, Math.random() * 0xFFFFFF, 1); + this.graphics.moveTo(Math.random() * 620, Math.random() * 380); + this.graphics.bezierCurveTo(Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380, + Math.random() * 620, Math.random() * 380); + } + + private animate = (): void => { + + this.thing.clear(); + + this.count += 0.1; + + this.thing.clear(); + this.thing.lineStyle(10, 0xff0000, 1); + this.thing.beginFill(0xffFF00, 0.5); + + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + + this.thing.rotation = this.count * 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + } + + } + +} + +module demos { + + export class Interactivity { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private buttons: InteractivityButton[]; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a background... + this.background = PIXI.Sprite.fromImage('../../_assets/button_test_BG.jpg'); + this.background.width = this.renderer.width; + this.background.height = this.renderer.height; + + // add background to stage... + this.stage.addChild(this.background); + + this.buttons = []; + + var buttonPositions = [ + 175, 75, + 655, 75, + 410, 325, + 150, 465, + 685, 445 + ]; + + function noop(): void { + console.log('click'); + } + + // create some textures from an image path + var textureButton = PIXI.Texture.fromImage('../../_assets/button.png'); + var textureButtonDown = PIXI.Texture.fromImage('../../_assets/buttonDown.png'); + var textureButtonOver = PIXI.Texture.fromImage('../../_assets/buttonOver.png'); + + for (var i = 0; i < 5; i++) { + + var button = new InteractivityButton(textureButton, textureButtonDown, textureButtonOver); + + button.position.x = buttonPositions[i * 2]; + button.position.y = buttonPositions[i * 2 + 1]; + + button.tap = noop; + button.click = noop; + + // add it to the stage + this.stage.addChild(button); + + // add button to array + this.buttons.push(button); + + } + + // set some silly values... + this.buttons[0].scale.set(1.2); + + this.buttons[2].rotation = Math.PI / 10; + + this.buttons[3].scale.set(0.8); + + this.buttons[4].scale.set(0.8, 1.2); + this.buttons[4].rotation = Math.PI; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class InteractivityButton extends PIXI.Sprite { + + private textureButton: PIXI.Texture; + private textureButtonDown: PIXI.Texture; + private textureButtonOver: PIXI.Texture; + + tap: Function; + click: Function; + + isdown: boolean; + isOver: boolean; + + constructor(textureButton: PIXI.Texture, textureButtonDown: PIXI.Texture, textureButtonOver: PIXI.Texture) { + + super(textureButton); + + // create some textures from an image path + this.textureButton = textureButton; + this.textureButtonDown = textureButtonDown; + this.textureButtonOver = textureButtonOver; + + this.buttonMode = true; + this.anchor.set(0.5); + + // make the button interactive... + this.interactive = true; + + this + // set the mousedown and touchstart callback... + .on('mousedown', this.onButtonDown) + .on('touchstart', this.onButtonDown) + + // set the mouseup and touchend callback... + .on('mouseup', this.onButtonUp) + .on('touchend', this.onButtonUp) + .on('mouseupoutside', this.onButtonUp) + .on('touchendoutside', this.onButtonUp) + + // set the mouseover callback... + .on('mouseover', this.onButtonOver) + + // set the mouseout callback... + .on('mouseout', this.onButtonOut) + + // you can also listen to click and tap events : + //.on('click', this.noop) + + } + + private onButtonDown = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = true; + this.texture = this.textureButtonDown; + this.alpha = 1; + + } + + private onButtonUp = (event: PIXI.interaction.InteractionEvent): void => { + + this.isdown = false; + + if (this.isOver) { + this.texture = this.textureButtonOver; + } + else { + this.texture = this.textureButton; + } + } + + private onButtonOver = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = true; + + if (this.isdown) { + return; + } + + this.texture = this.textureButtonOver; + + } + + private onButtonOut = (event: PIXI.interaction.InteractionEvent): void => { + + this.isOver = false; + + if (this.isdown) { + return; + } + + this.texture = this.textureButton; + } + + } + +} + +module demos { + + export class Masking { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + + private light1: PIXI.Sprite; + + private light2: PIXI.Sprite; + + private panda: PIXI.Sprite; + + private thing: PIXI.Graphics; + + private count: number; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, antialias: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.bg = PIXI.Sprite.fromImage('../../_assets/BGrotate.jpg'); + this.bg.anchor.x = 0.5; + this.bg.anchor.y = 0.5; + + this.bg.position.x = this.renderer.width / 2; + this.bg.position.y = this.renderer.height / 2; + + this.stage.addChild(this.bg); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + // add a bunch of sprites + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.x = 0.5; + this.bgFront.anchor.y = 0.5; + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.x = 0.5; + this.light2.anchor.y = 0.5; + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.x = 0.5; + this.light1.anchor.y = 0.5; + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.x = 0.5; + this.panda.anchor.y = 0.5; + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + // let's create a moving shape + this.thing = new PIXI.Graphics(); + this.stage.addChild(this.thing); + this.thing.position.x = this.renderer.width / 2; + this.thing.position.y = this.renderer.height / 2; + this.thing.lineStyle(0); + + this.container.mask = this.thing; + + this.count = 0; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + this.help = new PIXI.Text('Click to turn masking on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 26; + this.help.position.x = 10; + this.stage.addChild(this.help); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.bg.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + this.thing.clear(); + + this.thing.beginFill(0x8bc5ff, 0.4); + this.thing.moveTo(-120 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.cos(this.count) * 20, -100 + Math.sin(this.count) * 20); + this.thing.lineTo(120 + Math.sin(this.count) * 20, 100 + Math.cos(this.count) * 20); + this.thing.lineTo(-120 + Math.cos(this.count) * 20, 100 + Math.sin(this.count) * 20); + this.thing.lineTo(-120 + Math.sin(this.count) * 20, -300 + Math.cos(this.count) * 20); + this.thing.lineTo(-320 + Math.sin(this.count) * 20, -100 + Math.cos(this.count) * 20); + this.thing.rotation = this.count * 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + private onClick = (event: PIXI.interaction.InteractionEvent): void => { + + if (!this.container.mask) { + this.container.mask = this.thing; + } + else { + this.container.mask = null; + } + } + + } + +} + +module demos { + + export class MovieClipDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('spritesheet', '../../_assets/mc.json') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader): void => { + + // create an array to store the textures + var explosionTextures: PIXI.Texture[] = []; + var i: number; + + for (i = 0; i < 26; i++) { + + var texture = PIXI.Texture.fromFrame('Explosion_Sequence_A ' + (i + 1) + '.png'); + explosionTextures.push(texture); + + } + + for (i = 0; i < 50; i++) { + + // create an explosion MovieClip + var explosion = new PIXI.extras.MovieClip(explosionTextures); + + explosion.position.x = Math.random() * 800; + explosion.position.y = Math.random() * 600; + explosion.anchor.x = 0.5; + explosion.anchor.y = 0.5; + + explosion.rotation = Math.random() * Math.PI; + + explosion.scale.set(0.75 + Math.random() * 0.5); + + explosion.gotoAndPlay(Math.random() * 27); + + this.stage.addChild(explosion); + + } + + // start animating + this.animate(); + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module demos { + + export class RenderTextureDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private renderTexture: PIXI.RenderTexture; + private renderTexture2: PIXI.RenderTexture; + private currentTexture: PIXI.RenderTexture; + + private outputSprite: PIXI.Sprite; + private stuffContainer: PIXI.Container; + private items: PIXI.Sprite[]; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create two render textures... these dynamic textures will be used to draw the scene into itself + this.renderTexture = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.renderTexture2 = new PIXI.RenderTexture(this.renderer, this.renderer.width, this.renderer.height); + this.currentTexture = this.renderTexture; + + // create a new sprite that uses the render texture we created above + this.outputSprite = new PIXI.Sprite(this.currentTexture); + + // align the sprite + this.outputSprite.position.x = 400; + this.outputSprite.position.y = 300; + this.outputSprite.anchor.set(0.5); + + // add to stage + this.stage.addChild(this.outputSprite); + + this.stuffContainer = new PIXI.Container(); + + this.stuffContainer.position.x = 400; + this.stuffContainer.position.y = 300; + + this.stage.addChild(this.stuffContainer); + + // create an array of image ids.. + var fruits = [ + '../../_assets/spinObj_01.png', + '../../_assets/spinObj_02.png', + '../../_assets/spinObj_03.png', + '../../_assets/spinObj_04.png', + '../../_assets/spinObj_05.png', + '../../_assets/spinObj_06.png', + '../../_assets/spinObj_07.png', + '../../_assets/spinObj_08.png' + ]; + + // create an array of items + this.items = []; + + // now create some items and randomly position them in the stuff container + for (var i = 0; i < 20; i++) { + + var item = PIXI.Sprite.fromImage(fruits[i % fruits.length]); + item.position.x = Math.random() * 400 - 200; + item.position.y = Math.random() * 400 - 200; + + item.anchor.set(0.5); + + this.stuffContainer.addChild(item); + + this.items.push(item); + + } + + // used for spinning! + this.count = 0; + + // start animating + this.animate(); + + } + + private animate = (): void => { + + for (var i = 0; i < this.items.length; i++) { + // rotate each item + var item = this.items[i]; + item.rotation += 0.1; + } + + this.count += 0.01; + + // swap the buffers ... + var temp = this.renderTexture; + this.renderTexture = this.renderTexture2; + this.renderTexture2 = temp; + + // set the new texture + this.outputSprite.texture = this.renderTexture; + + // twist this up! + this.stuffContainer.rotation -= 0.01; + this.outputSprite.scale.set(1 + Math.sin(this.count) * 0.2); + + // render the stage to the texture + // the 'true' clears the texture before the content is rendered + this.renderTexture2.render(this.stage, null, false); + + // and finally render the stage + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class StripDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private count: number; + + private points: PIXI.Point[]; + + private strip: PIXI.mesh.Rope; + + private snakeContainer: PIXI.Container; + + private ropeLength: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.count = 0; + + // build a rope! + this.ropeLength = 918 / 20; + + this.points = []; + + for (var i = 0; i < 20; i++) { + this.points.push(new PIXI.Point(i * this.ropeLength, 0)); + } + + this.strip = new PIXI.mesh.Rope(PIXI.Texture.fromImage('../../_assets/snake.png'), this.points); + this.strip.x = -459; + + this.snakeContainer = new PIXI.Container(); + this.snakeContainer.position.x = 400; + this.snakeContainer.position.y = 300; + + this.snakeContainer.scale.set(800 / 1100); + this.stage.addChild(this.snakeContainer); + + this.snakeContainer.addChild(this.strip); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.1; + + // make the snake + for (var i = 0; i < this.points.length; i++) { + + this.points[i].y = Math.sin((i * 0.5) + this.count) * 30; + + this.points[i].x = i * this.ropeLength + Math.cos((i * 0.3) + this.count) * 20; + + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class TextDemo { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bitmapFontText: PIXI.extras.BitmapText; + + private background: PIXI.Sprite; + + private textSample: PIXI.Text; + + private spinningText: PIXI.Text; + + private countingText: PIXI.Text; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader + .add('desyrel', '../../_assets/desyrel.xml') + .load(this.onAssetsLoaded); + + // start animating + this.animate(); + + } + + private onAssetsLoaded = (): void => { + + this.bitmapFontText = new PIXI.extras.BitmapText('bitmap fonts are\n now supported!', { font: '35px Desyrel', align: 'right' }); + + this.bitmapFontText.position.x = 600 - this.bitmapFontText.textWidth; + this.bitmapFontText.position.y = 20; + + this.stage.addChild(this.bitmapFontText); + + // add a shiny background... + this.background = PIXI.Sprite.fromImage('../../_assets/textDemoBG.jpg'); + this.stage.addChild(this.background); + + // create some white text using the Snippet webfont + this.textSample = new PIXI.Text('Pixi.js can has\n multiline text!', { font: '35px Snippet', fill: 'white', align: 'left' }); + this.textSample.position.set(20); + + // create a text object with a nice stroke + this.spinningText = new PIXI.Text('I\'m fun!', { font: 'bold 60px Arial', fill: '#cc00ff', align: 'center', stroke: '#FFFFFF', strokeThickness: 6 }); + + // setting the anchor point to 0.5 will center align the text... great for spinning! + this.spinningText.anchor.set(0.5); + this.spinningText.position.x = 310; + this.spinningText.position.y = 200; + + // create a text object that will be updated... + this.countingText = new PIXI.Text('COUNT 4EVAR: 0', { font: 'bold italic 60px Arvo', fill: '#3e1707', align: 'center', stroke: '#a4410e', strokeThickness: 7 }); + + this.countingText.position.x = 310; + this.countingText.position.y = 320; + this.countingText.anchor.x = 0.5; + + this.stage.addChild(this.textSample); + this.stage.addChild(this.spinningText); + this.stage.addChild(this.countingText); + + this.count = 0; + + } + + private animate = (): void => { + + + this.renderer.render(this.stage); + + this.count += 0.05; + + // update the text with a new string + this.countingText.text = 'COUNT 4EVAR: ' + Math.floor(this.count); + + // let's spin the spinning text + this.spinningText.rotation += 0.03; + + requestAnimationFrame(this.animate); + } + + } + +} + +module demos { + + export class TextureSwap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bol: boolean; + + private texture: PIXI.Texture; + private secondTexture: PIXI.Texture; + + private dude: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bol = false; + + //an image path + this.texture = PIXI.Texture.fromImage('../../_assets/flowerTop.png'); + + // create a second texture + this.secondTexture = PIXI.Texture.fromImage('../../_assets/eggHead.png'); + + // create a new Sprite using the texture + this.dude = new PIXI.Sprite(this.texture); + + // center the sprites anchor point + this.dude.anchor.set(0.5); + + // move the sprite to the center of the screen + this.dude.position.x = this.renderer.width / 2; + this.dude.position.y = this.renderer.height / 2; + + this.stage.addChild(this.dude); + + // make the sprite interactive + this.dude.interactive = true; + + this.dude.on('click', (): void => { + this.bol = !this.bol; + + if (this.bol) { + this.dude.texture = this.secondTexture; + } + else { + this.dude.texture = this.texture; + } + }); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.dude.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module demos { + + export class Tinting { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private totalDudes: number = 10; + private aliens: TintingDude[]; + + private dudeBounds: PIXI.Rectangle; + + private tick: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // holder to store the aliens + this.aliens = []; + + this.tick = 0; + + for (var i = 0; i < this.totalDudes; i++) { + + // create a new Sprite that uses the image name that we just generated as its source + var dude = new TintingDude(); + + // set the anchor point so the texture is centerd on the sprite + dude.anchor.set(0.5); + + // set a random scale for the dude - no point them all being the same size! + dude.scale.set(0.8 + Math.random() * 0.3); + + // finally lets set the dude to be at a random position.. + dude.position.x = Math.random() * this.renderer.width; + dude.position.y = Math.random() * this.renderer.height; + + dude.tint = Math.random() * 0xFFFFFF; + + // create some extra properties that will control movement : + // create a random direction in radians. This is a number between 0 and PI*2 which is the equivalent of 0 - 360 degrees + dude.direction = Math.random() * Math.PI * 2; + + // this number will be used to modify the direction of the dude over time + dude.turningSpeed = Math.random() - 0.8; + + // create a random speed for the dude between 0 - 2 + dude.speed = 2 + Math.random() * 2; + + // finally we push the dude into the aliens array so it it can be easily accessed later + this.aliens.push(dude); + + this.stage.addChild(dude); + + } + + // create a bounding box for the little dudes + var dudeBoundsPadding = 100; + this.dudeBounds = new PIXI.Rectangle(-dudeBoundsPadding, + -dudeBoundsPadding, + this.renderer.width + dudeBoundsPadding * 2, + this.renderer.height + dudeBoundsPadding * 2); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // iterate through the dudes and update their position + for (var i = 0; i < this.aliens.length; i++) { + + var dude = this.aliens[i]; + dude.direction += dude.turningSpeed * 0.01; + dude.position.x += Math.sin(dude.direction) * dude.speed; + dude.position.y += Math.cos(dude.direction) * dude.speed; + dude.rotation = -dude.direction - Math.PI / 2; + + // wrap the dudes by testing their bounds... + if (dude.position.x < this.dudeBounds.x) { + dude.position.x += this.dudeBounds.width; + } + else if (dude.position.x > this.dudeBounds.x + this.dudeBounds.width) { + dude.position.x -= this.dudeBounds.width; + } + + if (dude.position.y < this.dudeBounds.y) { + dude.position.y += this.dudeBounds.height; + } + else if (dude.position.y > this.dudeBounds.y + this.dudeBounds.height) { + dude.position.y -= this.dudeBounds.height; + } + + } + + // increment the ticker + this.tick += 0.1; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + export class TintingDude extends PIXI.Sprite { + + direction: number; + speed: number; + turningSpeed: number; + + constructor() { + super(PIXI.Texture.fromImage('../../_assets/eggHead.png')); + } + + } + +} + +module demos { + + export class TransparentBackground { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bunny: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb, transparent: true }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + // create a new Sprite from an image path. + this.bunny = PIXI.Sprite.fromImage('../../_assets/bunny.png'); + + // center the sprite's anchor point + this.bunny.anchor.set(0.5); + + // move the sprite to the center of the screen + this.bunny.position.x = 200; + this.bunny.position.y = 150; + + this.stage.addChild(this.bunny); + + // start animating + this.animate(); + + } + + private animate = (): void => { + + // just for fun, let's rotate mr rabbit a little + this.bunny.rotation += 0.1; + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module filters { + + export class Blur { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private bg: PIXI.Sprite; + + private littleDudes: PIXI.Sprite; + private littleRobot: PIXI.Sprite; + + private blurFilter1: PIXI.filters.BlurFilter; + private blurFilter2: PIXI.filters.BlurFilter; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + this.bg = PIXI.Sprite.fromImage('../../_assets/depth_blur_BG.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + this.stage.addChild(this.bg); + + this.littleDudes = PIXI.Sprite.fromImage('../../_assets/depth_blur_dudes.jpg'); + this.littleDudes.position.x = (this.renderer.width / 2) - 315; + this.littleDudes.position.y = 200; + this.stage.addChild(this.littleDudes); + + this.littleRobot = PIXI.Sprite.fromImage('../../_assets/depth_blur_moby.jpg'); + this.littleRobot.position.x = (this.renderer.width / 2) - 200; + this.littleRobot.position.y = 100; + this.stage.addChild(this.littleRobot); + + this.blurFilter1 = new PIXI.filters.BlurFilter(); + this.blurFilter2 = new PIXI.filters.BlurFilter(); + + this.littleDudes.filters = [this.blurFilter1]; + this.littleRobot.filters = [this.blurFilter2]; + + this.count = 0; + + //nimate + this.animate(); + + } + + private animate = (): void => { + + this.count += 0.005; + + var blurAmount = Math.cos(this.count); + var blurAmount2 = Math.sin(this.count); + + this.blurFilter1.blur = 20 * (blurAmount); + this.blurFilter2.blur = 20 * (blurAmount2); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} + +module filters { + + export class DisplacementMap { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private container: PIXI.Container; + + private padding: number; + + private bounds: PIXI.Rectangle; + + private maggots: DisplacementMapDude[]; + + private displacementSprite: PIXI.Sprite; + + private displacementFilter: PIXI.filters.DisplacementFilter; + + private ring: PIXI.Sprite; + + private bg: PIXI.Sprite; + + private count: number; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + this.container = new PIXI.Container(); + this.stage.addChild(this.container); + + this.padding = 100; + + this.bounds = new PIXI.Rectangle(-this.padding, -this.padding, this.renderer.width + this.padding * 2, this.renderer.height + this.padding * 2); + this.maggots = []; + + for (var i = 0; i < 20; i++) { + + var maggot = new DisplacementMapDude(); + maggot.anchor.set(0.5); + this.container.addChild(maggot); + + maggot.direction = Math.random() * Math.PI * 2; + maggot.speed = 1; + maggot.turnSpeed = Math.random() - 0.8; + + maggot.position.x = Math.random() * this.bounds.width; + maggot.position.y = Math.random() * this.bounds.height; + + maggot.scale.set(1 + Math.random() * 0.3); + maggot.original = maggot.scale.clone(); + this.maggots.push(maggot); + + } + + this.displacementSprite = PIXI.Sprite.fromImage('../../_assets/displace.png'); + this.displacementFilter = new PIXI.filters.DisplacementFilter(this.displacementSprite); + + this.stage.addChild(this.displacementSprite); + + this.container.filters = [this.displacementFilter]; + + this.displacementFilter.scale.x = 110; + this.displacementFilter.scale.y = 110; + + this.ring = PIXI.Sprite.fromImage('../../_assets/ring.png'); + + this.ring.anchor.set(0.5); + + this.ring.visible = false; + + this.stage.addChild(this.ring); + + this.bg = PIXI.Sprite.fromImage('../../_assets/bkg-grass.jpg'); + this.bg.width = this.renderer.width; + this.bg.height = this.renderer.height; + + this.bg.alpha = 0.4; + + this.container.addChild(this.bg); + + this.stage + .on('mousemove', this.onPointerMove) + .on('touchmove', this.onPointerMove); + + this.count = 0; + + this.animate(); + + } + + private onPointerMove = (eventData: PIXI.interaction.InteractionEvent): void => { + + this.ring.visible = true; + + this.displacementSprite.x = eventData.data.global.x - 100; + this.displacementSprite.y = eventData.data.global.y - this.displacementSprite.height / 2; + + this.ring.position.x = eventData.data.global.x - 25; + this.ring.position.y = eventData.data.global.y; + + }; + + private animate = (): void => { + + this.count += 0.05; + + for (var i = 0; i < this.maggots.length; i++) { + var maggot = this.maggots[i]; + + maggot.direction += maggot.turnSpeed * 0.01; + maggot.position.x += Math.sin(maggot.direction) * maggot.speed; + maggot.position.y += Math.cos(maggot.direction) * maggot.speed; + + maggot.rotation = -maggot.direction - Math.PI / 2; + + maggot.scale.x = maggot.original.x + Math.sin(this.count) * 0.2; + + // wrap the maggots around as the crawl + if (maggot.position.x < this.bounds.x) { + maggot.position.x += this.bounds.width; + } + else if (maggot.position.x > this.bounds.x + this.bounds.width) { + maggot.position.x -= this.bounds.width; + } + + if (maggot.position.y < this.bounds.y) { + maggot.position.y += this.bounds.height; + } + else if (maggot.position.y > this.bounds.y + this.bounds.height) { + maggot.position.y -= this.bounds.height; + } + } + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + }; + + } + + export class DisplacementMapDude extends PIXI.Sprite { + + direction: number; + speed: number; + turnSpeed: number; + original: PIXI.Point; + + constructor() { + + super(PIXI.Texture.fromImage('../../_assets/maggot.png')); + + } + + } + +} + +module filters { + + export class Filter { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private background: PIXI.Sprite; + + private filter: PIXI.filters.ColorMatrixFilter; + + private container: PIXI.Container; + + private bgFront: PIXI.Sprite; + private light2: PIXI.Sprite; + private light1: PIXI.Sprite; + private panda: PIXI.Sprite; + + private count: number; + private switchy: boolean; + + private help: PIXI.Text; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + // create a texture from an image path + var texture: PIXI.Texture = PIXI.Texture.fromImage("../../_assets/basics/bunny.png"); + + this.background = PIXI.Sprite.fromImage('_assets/BGrotate.jpg'); + this.background.anchor.set(0.5); + + this.background.position.x = this.renderer.width / 2; + this.background.position.y = this.renderer.height / 2; + + this.filter = new PIXI.filters.ColorMatrixFilter(); + + this.container = new PIXI.Container(); + this.container.position.x = this.renderer.width / 2; + this.container.position.y = this.renderer.height / 2; + + this.bgFront = PIXI.Sprite.fromImage('../../_assets/SceneRotate.jpg'); + this.bgFront.anchor.set(0.5); + + this.container.addChild(this.bgFront); + + this.light2 = PIXI.Sprite.fromImage('../../_assets/LightRotate2.png'); + this.light2.anchor.set(0.5); + this.container.addChild(this.light2); + + this.light1 = PIXI.Sprite.fromImage('../../_assets/LightRotate1.png'); + this.light1.anchor.set(0.5); + this.container.addChild(this.light1); + + this.panda = PIXI.Sprite.fromImage('../../_assets/panda.png'); + this.panda.anchor.set(0.5); + + this.container.addChild(this.panda); + + this.stage.addChild(this.container); + + this.stage.filters = [this.filter]; + + this.count = 0; + this.switchy = false; + + this.stage.on('click', this.onClick); + this.stage.on('tap', this.onClick); + + + this.help = new PIXI.Text('Click to turn filters on / off.', { font: 'bold 12pt Arial', fill: 'white' }); + this.help.position.y = this.renderer.height - 25; + this.help.position.x = 10; + + this.stage.addChild(this.help); + + //nimate + this.animate(); + + } + + private onClick = (): void => { + + this.switchy = !this.switchy; + + if (!this.switchy) { + this.stage.filters = [this.filter]; + } + else { + this.stage.filters = null; + } + + } + + private animate = (): void => { + + this.background.rotation += 0.01; + this.bgFront.rotation -= 0.01; + + this.light1.rotation += 0.02; + this.light2.rotation += 0.01; + + this.panda.scale.x = 1 + Math.sin(this.count) * 0.04; + this.panda.scale.y = 1 + Math.cos(this.count) * 0.04; + + this.count += 0.1; + + var matrix = this.filter.matrix; + + matrix[1] = Math.sin(this.count) * 3; + matrix[2] = Math.cos(this.count); + matrix[3] = Math.cos(this.count) * 1.5; + matrix[4] = Math.sin(this.count / 3) * 2; + matrix[5] = Math.sin(this.count / 2); + matrix[6] = Math.sin(this.count / 4); + + this.renderer.render(this.stage); + + requestAnimationFrame(this.animate); + + } + + } + +} diff --git a/pixi.js/pixi.js-tests.ts.tscparams b/pixi.js/pixi.js-tests.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/pixi.js/pixi.js-tests.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - diff --git a/pixi.js/pixi.js.d.ts b/pixi.js/pixi.js.d.ts index 0452e7432..8e83cbf1e 100644 --- a/pixi.js/pixi.js.d.ts +++ b/pixi.js/pixi.js.d.ts @@ -1,601 +1,251 @@ -// Type definitions for PIXI 2.2.8 2015-03-24 +// Type definitions for Pixi.js 3.0.7 // Project: https://github.com/GoodBoyDigital/pixi.js/ // Definitions by: clark-stevenson // Definitions: https://github.com/borisyankov/DefinitelyTyped +declare class PIXI { + + static VERSION: string; + static PI_2: number; + static RAD_TO_DEG: number; + static DEG_TO_RAD: number; + static TARGET_FPMS: number; + static RENDER_TYPE: { + UNKNOWN: number; + WEBGL: number; + CANVAS: number; + }; + static BLEND_MODES: { + NORMAL: number; + ADD: number; + MULTIPLY: number; + SCREEN: number; + OVERLAY: number; + DARKEN: number; + LIGHTEN: number; + COLOR_DODGE: number; + COLOR_BURN: number; + HARD_LIGHT: number; + SOFT_LIGHT: number; + DIFFERENCE: number; + EXCLUSION: number; + HUE: number; + SATURATION: number; + COLOR: number; + LUMINOSITY: number; + + }; + static DRAW_MODES: { + POINTS: number; + LINES: number; + LINE_LOOP: number; + LINE_STRIP: number; + TRIANGLES: number; + TRIANGLE_STRIP: number; + TRIANGLE_FAN: number; + }; + static SCALE_MODES: { + DEFAULT: number; + LINEAR: number; + NEAREST: number; + }; + static RETINA_PREFIX: string; + static RESOLUTION: number; + static FILTER_RESOLUTION: number; + static DEFAULT_RENDER_OPTIONS: { + view: HTMLCanvasElement; + resolution: number; + antialias: boolean; + forceFXAA: boolean; + autoResize: boolean; + transparent: boolean; + backgroundColor: number; + clearBeforeRender: boolean; + preserveDrawingBuffer: boolean; + roundPixels: boolean; + }; + static SHAPES: { + POLY: number; + RECT: number; + CIRC: number; + ELIP: number; + RREC: number; + }; + static SPRITE_BATCH_SIZE: number; + +} + declare module PIXI { - export var WEBGL_RENDERER: number; - export var CANVAS_RENDERER: number; - export var VERSION: string; + export function autoDetectRenderer(width: number, height: number, options?: PIXI.RendererOptions, noWebGL?: boolean): PIXI.WebGLRenderer | PIXI.CanvasRenderer; + export var loader: PIXI.loaders.Loader; - export enum blendModes { + //https://github.com/primus/eventemitter3 + export class EventEmitter { - NORMAL, - ADD, - MULTIPLY, - SCREEN, - OVERLAY, - DARKEN, - LIGHTEN, - COLOR_DODGE, - COLOR_BURN, - HARD_LIGHT, - SOFT_LIGHT, - DIFFERENCE, - EXCLUSION, - HUE, - SATURATION, - COLOR, - LUMINOSITY + listeners(event: string): Function[]; + emit(event: string, ...args: any[]): boolean; + on(event: string, fn: Function, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + removeListener(event: string, fn: Function, once?: boolean): EventEmitter; + removeAllListeners(event: string): EventEmitter; + + off(event: string, fn: Function, once?: boolean): EventEmitter; + addListener(event: string, fn: Function, context?: any): EventEmitter; } - export enum scaleModes { + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////////CORE////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// - DEFAULT, - LINEAR, - NEAREST + //display - } + export class DisplayObject extends EventEmitter implements interaction.InteractiveTarget { - export var defaultRenderOptions: PixiRendererOptions; + //begin extras.cacheAsBitmap see https://github.com/pixijs/pixi-typescript/commit/1207b7f4752d79a088d6a9a465a3ec799906b1db + protected _originalRenderWebGL: WebGLRenderer; + protected _originalRenderCanvas: CanvasRenderer; + protected _originalUpdateTransform: boolean; + protected _originalHitTest: any; + protected _cachedSprite: any; + protected _originalDestroy: any; - export var INTERACTION_REQUENCY: number; - export var AUTO_PREVENT_DEFAULT: boolean; - - export var PI_2: number; - export var RAD_TO_DEG: number; - export var DEG_TO_RAD: number; - - export var RETINA_PREFIX: string; - export var identityMatrix: Matrix; - export var glContexts: WebGLRenderingContext[]; - export var instances: any[]; - - export var BaseTextureCache: { [key: string]: BaseTexture } - export var TextureCache: { [key: string]: Texture } - - export function isPowerOfTwo(width: number, height: number): boolean; - - export function rgb2hex(rgb: number[]): string; - export function hex2rgb(hex: string): number[]; - - export function autoDetectRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; - export function autoDetectRecommendedRenderer(width?: number, height?: number, options?: PixiRendererOptions): PixiRenderer; - - export function canUseNewCanvasBlendModes(): boolean; - export function getNextPowerOfTwo(number: number): number; - - export function AjaxRequest(): XMLHttpRequest; - - export function CompileFragmentShader(gl: WebGLRenderingContext, shaderSrc: string[]): any; - export function CompileProgram(gl: WebGLRenderingContext, vertexSrc: string[], fragmentSrc: string[]): any; - - - export interface IEventCallback { - (e?: IEvent): void - } - - export interface IEvent { - type: string; - content: any; - } - - export interface HitArea { - contains(x: number, y: number): boolean; - } - - export interface IInteractionDataCallback { - (interactionData: InteractionData): void - } - - export interface PixiRenderer { - - autoResize: boolean; - clearBeforeRender: boolean; - height: number; - resolution: number; - transparent: boolean; - type: number; - view: HTMLCanvasElement; - width: number; - - destroy(): void; - render(stage: Stage): void; - resize(width: number, height: number): void; - - } - - export interface PixiRendererOptions { - - autoResize?: boolean; - antialias?: boolean; - clearBeforeRender?: boolean; - preserveDrawingBuffer?: boolean; - resolution?: number; - transparent?: boolean; - view?: HTMLCanvasElement; - - } - - export interface BitmapTextStyle { - - font?: string; - align?: string; - tint?: string; - - } - - export interface TextStyle { - - align?: string; - dropShadow?: boolean; - dropShadowColor?: string; - dropShadowAngle?: number; - dropShadowDistance?: number; - fill?: string; - font?: string; - lineJoin?: string; - stroke?: string; - strokeThickness?: number; - wordWrap?: boolean; - wordWrapWidth?: number; - - } - - export interface Loader { - - load(): void; - - } - - export interface MaskData { - - alpha: number; - worldTransform: number[]; - - } - - export interface RenderSession { - - context: CanvasRenderingContext2D; - maskManager: CanvasMaskManager; - scaleMode: scaleModes; - smoothProperty: string; - roundPixels: boolean; - - } - - export interface ShaderAttribute { - // TODO: Find signature of shader attributes - } - - export interface FilterBlock { - - visible: boolean; - renderable: boolean; - - } - - export class AbstractFilter { - - constructor(fragmentSrc: string[], uniforms: any); - - dirty: boolean; - padding: number; - uniforms: any; - fragmentSrc: string[]; - - apply(frameBuffer: WebGLFramebuffer): void; - syncUniforms(): void; - - } - - export class AlphaMaskFilter extends AbstractFilter { - - constructor(texture: Texture); - - map: Texture; - - onTextureLoaded(): void; - - } - - export class AsciiFilter extends AbstractFilter { - - size: number; - - } - - export class AssetLoader implements Mixin { - - assetURLs: string[]; - crossorigin: boolean; - loadersByType: { [key: string]: Loader }; - - constructor(assetURLs: string[], crossorigin?: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - - } - - export class AtlasLoader implements Mixin { - - url: string; - baseUrl: string; - crossorigin: boolean; - loaded: boolean; - - constructor(url: string, crossorigin: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class BaseTexture implements Mixin { - - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): BaseTexture; - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): BaseTexture; - - constructor(source: HTMLImageElement, scaleMode: scaleModes); - constructor(source: HTMLCanvasElement, scaleMode: scaleModes); - - height: number; - hasLoaded: boolean; - mipmap: boolean; - premultipliedAlpha: boolean; - resolution: number; - scaleMode: scaleModes; - source: HTMLImageElement; - width: number; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - destroy(): void; - dirty(): void; - updateSourceImage(newSrc: string): void; - unloadFromGPU(): void; - - } - - export class BitmapFontLoader implements Mixin { - - constructor(url: string, crossorigin: boolean); - - baseUrl: string; - crossorigin: boolean; - texture: Texture; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class BitmapText extends DisplayObjectContainer { - - static fonts: any; - - constructor(text: string, style: BitmapTextStyle); - - dirty: boolean; - fontName: string; - fontSize: number; - maxWidth: number; - textWidth: number; - textHeight: number; - tint: number; - style: BitmapTextStyle; - - setText(text: string): void; - setStyle(style: BitmapTextStyle): void; - - } - - export class BlurFilter extends AbstractFilter { - - blur: number; - blurX: number; - blurY: number; - - } - - export class BlurXFilter extends AbstractFilter { - - blur: number; - - } - - export class BlurYFilter extends AbstractFilter { - - blur: number; - - } - - export class CanvasBuffer { - - constructor(width: number, height: number); - - canvas: HTMLCanvasElement; - context: CanvasRenderingContext2D; - height: number; - width: number; - - clear(): void; - resize(width: number, height: number): void; - - } - - export class CanvasMaskManager { - - pushMask(maskData: MaskData, renderSession: RenderSession): void; - popMask(renderSession: RenderSession): void; - - } - - export class CanvasRenderer implements PixiRenderer { - - constructor(width?: number, height?: number, options?: PixiRendererOptions); - - autoResize: boolean; - clearBeforeRender: boolean; - context: CanvasRenderingContext2D; - count: number; - height: number; - maskManager: CanvasMaskManager; - refresh: boolean; - renderSession: RenderSession; - resolution: number; - transparent: boolean; - type: number; - view: HTMLCanvasElement; - width: number; - - destroy(removeView?: boolean): void; - render(stage: Stage): void; - resize(width: number, height: number): void; - - } - - export class CanvasTinter { - - static getTintedTexture(sprite: Sprite, color: number): HTMLCanvasElement; - static tintWithMultiply(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; - static roundColor(color: number): void; - - static cacheStepsPerColorChannel: number; - static convertTintToImage: boolean; - static canUseMultiply: boolean; - static tintMethod: any; - - } - - export class Circle implements HitArea { - - constructor(x: number, y: number, radius: number); - - x: number; - y: number; - radius: number; - - clone(): Circle; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - - export class ColorMatrixFilter extends AbstractFilter { - - matrix: Matrix; - - } - - export class ColorStepFilter extends AbstractFilter { - - step: number; - - } - - export class ConvolutionFilter extends AbstractFilter { - - constructor(matrix: number[], width: number, height: number); - - matrix: Matrix; - width: number; - height: number; - - } - - export class CrossHatchFilter extends AbstractFilter { - - blur: number; - - } - - export class DisplacementFilter extends AbstractFilter { - - constructor(texture: Texture); - - map: Texture; - offset: Point; - scale: Point; - - } - - export class DotScreenFilter extends AbstractFilter { - - angle: number; - scale: Point; - - } - - export class DisplayObject { - - alpha: number; - buttonMode: boolean; cacheAsBitmap: boolean; - defaultCursor: string; - filterArea: Rectangle; - filters: AbstractFilter[]; - hitArea: HitArea; - interactive: boolean; - mask: Graphics; - parent: DisplayObjectContainer; - pivot: Point; - position: Point; - renderable: boolean; - rotation: number; - scale: Point; - stage: Stage; - visible: boolean; - worldAlpha: number; - worldVisible: boolean; - x: number; - y: number; - click(e: InteractionData): void; - displayObjectUpdateTransform(): void; - getBounds(matrix?: Matrix): Rectangle; - getLocalBounds(): Rectangle; - generateTexture(resolution: number, scaleMode: scaleModes, renderer: PixiRenderer): RenderTexture; - mousedown(e: InteractionData): void; - mouseout(e: InteractionData): void; - mouseover(e: InteractionData): void; - mouseup(e: InteractionData): void; - mousemove(e: InteractionData): void; - mouseupoutside(e: InteractionData): void; - rightclick(e: InteractionData): void; - rightdown(e: InteractionData): void; - rightup(e: InteractionData): void; - rightupoutside(e: InteractionData): void; - setStageReference(stage: Stage): void; - tap(e: InteractionData): void; - toGlobal(position: Point): Point; - toLocal(position: Point, from: DisplayObject): Point; - touchend(e: InteractionData): void; - touchendoutside(e: InteractionData): void; - touchstart(e: InteractionData): void; - touchmove(e: InteractionData): void; + protected _renderCachedWebGL(renderer: WebGLRenderer): void; + protected _initCachedDisplayObject(renderer: WebGLRenderer): void; + protected _renderCachedCanvas(renderer: CanvasRenderer): void; + protected _initCachedDisplayObjectCanvas(renderer: CanvasRenderer): void; + protected _getCachedBounds(): Rectangle; + protected _destroyCachedDisplayObject(): void; + protected _cacheAsBitmapDestroy(): void; + //end extras.cacheAsBitmap + + protected _sr: number; + protected _cr: number; + protected _bounds: Rectangle; + protected _currentBounds: Rectangle; + protected _mask: Rectangle; + protected _cachedObject: any; + updateTransform(): void; + position: Point; + scale: Point; + pivot: Point; + rotation: number; + renderable: boolean; + alpha: number; + visible: boolean; + parent: Container; + worldAlpha: number; + worldTransform: Matrix; + filterArea: Rectangle; + + x: number; + y: number; + worldVisible: boolean; + mask: Graphics | Sprite; + filters: AbstractFilter[]; + name: string; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + toGlobal(position: Point): Point; + toLocal(position: Point, from?: DisplayObject): Point; + generateTexture(renderer: CanvasRenderer | WebGLRenderer, scaleMode: number, resolution: number): Texture; + destroy(): void; + getChildByName(name: string): DisplayObject; + getGlobalPosition(point: Point): Point; + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + on(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'click', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mousedown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseout', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseover', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'mouseupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightclick', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightdown', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightup', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'rightupoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'tap', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchend', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchendoutside', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchmove', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: 'touchstart', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + } - export class DisplayObjectContainer extends DisplayObject { + export class Container extends DisplayObject { - constructor(); + protected _renderWebGL(renderer: WebGLRenderer): void; + protected _renderCanvas(renderer: CanvasRenderer): void; + + protected onChildrenChange: () => void; children: DisplayObject[]; - height: number; + width: number; + height: number; addChild(child: DisplayObject): DisplayObject; addChildAt(child: DisplayObject, index: number): DisplayObject; - getBounds(): Rectangle; - getChildAt(index: number): DisplayObject; + swapChildren(child: DisplayObject, child2: DisplayObject): void; getChildIndex(child: DisplayObject): number; - getLocalBounds(): Rectangle; + setChildIndex(child: DisplayObject, index: number): void; + getChildAt(index: number): DisplayObject; removeChild(child: DisplayObject): DisplayObject; removeChildAt(index: number): DisplayObject; removeChildren(beginIndex?: number, endIndex?: number): DisplayObject[]; - removeStageReference(): void; - setChildIndex(child: DisplayObject, index: number): void; - swapChildren(child: DisplayObject, child2: DisplayObject): void; + destroy(destroyChildren?: boolean): void; + generateTexture(renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer, resolution?: number, scaleMode?: number): Texture; + + renderWebGL(renderer: WebGLRenderer): void; + renderCanvas(renderer: CanvasRenderer): void; + + once(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + once(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'added', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + on(event: 'removed', fn: (event: interaction.InteractionEvent) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; } - export class Ellipse implements HitArea { - - constructor(x: number, y: number, width: number, height: number); - - x: number; - y: number; - width: number; - height: number; - - clone(): Ellipse; - contains(x: number, y: number): boolean; - getBounds(): Rectangle; - - } - - export class Event { - - constructor(target: any, name: string, data: any); - - target: any; - type: string; - data: any; - timeStamp: number; - - stopPropagation(): void; - preventDefault(): void; - stopImmediatePropagation(): void; - - } - - export class EventTarget { - - static mixin(obj: any): void; - - } - - export class FilterTexture { - - constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: scaleModes); - - fragmentSrc: string[]; - frameBuffer: WebGLFramebuffer; - gl: WebGLRenderingContext; - program: WebGLProgram; - scaleMode: number; - texture: WebGLTexture; - - clear(): void; - resize(width: number, height: number): void; - destroy(): void; - - } + //graphics export class GraphicsData { - constructor(lineWidth?: number, lineColor?: number, lineAlpha?: number, fillColor?: number, fillAlpha?: number, fill?: boolean, shape?: any); + constructor(lineWidth: number, lineColor: number, lineAlpha: number, fillColor: number, fillAlpha: number, fill: boolean, shape: Circle | Rectangle | Ellipse | Polygon); lineWidth: number; lineColor: number; @@ -603,137 +253,75 @@ declare module PIXI { fillColor: number; fillAlpha: number; fill: boolean; - shape: any; + shape: Circle | Rectangle | Ellipse | Polygon; type: number; + clone(): GraphicsData; + + protected _lineTint: number; + protected _fillTint: number; + } + export class Graphics extends Container { - export class Graphics extends DisplayObjectContainer { + protected boundsDirty: boolean; + protected dirty: boolean; + protected glDirty: boolean; - static POLY: number; - static RECT: number; - static CIRC: number; - static ELIP: number; - static RREC: number; - - blendMode: number; - boundsPadding: number; fillAlpha: number; - isMask: boolean; lineWidth: number; lineColor: number; tint: number; - worldAlpha: number; + blendMode: number; + isMask: boolean; + boundsPadding: number; - arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise: boolean): Graphics; - arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; - beginFill(color?: number, alpha?: number): Graphics; + clone(): Graphics; + lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; + moveTo(x: number, y: number): Graphics; + lineTo(x: number, y: number): Graphics; + quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; bezierCurveTo(cpX: number, cpY: number, cpX2: number, cpY2: number, toX: number, toY: number): Graphics; - clear(): Graphics; - destroyCachedSprite(): void; - drawCircle(x: number, y: number, radius: number): Graphics; - drawEllipse(x: number, y: number, width: number, height: number): Graphics; - drawPolygon(...path: any[]): Graphics; + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics; + arc(cx: number, cy: number, radius: number, startAngle: number, endAngle: number, anticlockwise?: boolean): Graphics; + beginFill(color: number, alpha?: number): Graphics; + endFill(): Graphics; drawRect(x: number, y: number, width: number, height: number): Graphics; drawRoundedRect(x: number, y: number, width: number, height: number, radius: number): Graphics; - drawShape(shape: Circle): GraphicsData; - drawShape(shape: Rectangle): GraphicsData; - drawShape(shape: Ellipse): GraphicsData; - drawShape(shape: Polygon): GraphicsData; - endFill(): Graphics; - lineStyle(lineWidth?: number, color?: number, alpha?: number): Graphics; - lineTo(x: number, y: number): Graphics; - moveTo(x: number, y: number): Graphics; - quadraticCurveTo(cpX: number, cpY: number, toX: number, toY: number): Graphics; + drawCircle(x: number, y: number, radius: number): Graphics; + drawEllipse(x: number, y: number, width: number, height: number): Graphics; + drawPolygon(path: number[]| Point[]): Graphics; + clear(): Graphics; + //todo + generateTexture(renderer: WebGLRenderer | CanvasRenderer, resolution?: number, scaleMode?: number): Texture; + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + updateLocalBounds(): void; + drawShape(shape: Circle | Rectangle | Ellipse | Polygon): GraphicsData; } - - export class GrayFilter extends AbstractFilter { - - gray: number; - + export interface GraphicsRenderer extends ObjectRenderer { + //yikes todo + } + export interface WebGLGraphicsData { + //yikes todo! } - export class ImageLoader implements Mixin { + //math - constructor(url: string, crossorigin?: boolean); + export class Point { - texture: Texture; + x: number; + y: number; - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; + constructor(x?: number, y?: number); - load(): void; - loadFramedSpriteSheet(frameWidth: number, frameHeight: number, textureName: string): void; + clone(): Point; + copy(p: Point): void; + equals(p: Point): boolean; + set(x?: number, y?: number): void; } - - export class InteractionData { - - global: Point; - target: Sprite; - originalEvent: Event; - - getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; - - } - - export class InteractionManager { - - currentCursorStyle: string; - last: number; - mouse: InteractionData; - mouseOut: boolean; - mouseoverEnabled: boolean; - onMouseMove: Function; - onMouseDown: Function; - onMouseOut: Function; - onMouseUp: Function; - onTouchStart: Function; - onTouchEnd: Function; - onTouchMove: Function; - pool: InteractionData[]; - resolution: number; - stage: Stage; - touches: { [id: string]: InteractionData }; - - constructor(stage: Stage); - } - - export class InvertFilter extends AbstractFilter { - - invert: number; - - } - - export class JsonLoader implements Mixin { - - constructor(url: string, crossorigin?: boolean); - - baseUrl: string; - crossorigin: boolean; - loaded: boolean; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - export class Matrix { a: number; @@ -743,175 +331,60 @@ declare module PIXI { tx: number; ty: number; - append(matrix: Matrix): Matrix; - apply(pos: Point, newPos: Point): Point; - applyInverse(pos: Point, newPos: Point): Point; - determineMatrixArrayType(): number[]; - identity(): Matrix; - rotate(angle: number): Matrix; fromArray(array: number[]): void; + toArray(transpose?: boolean, out?: number[]): number[]; + apply(pos: Point, newPos?: Point): Point; + applyInverse(pos: Point, newPos?: Point): Point; translate(x: number, y: number): Matrix; - toArray(transpose: boolean): number[]; scale(x: number, y: number): Matrix; + rotate(angle: number): Matrix; + append(matrix: Matrix): Matrix; + prepend(matrix: Matrix): Matrix; + invert(): Matrix; + identity(): Matrix; + clone(): Matrix; + copy(matrix: Matrix): Matrix; + + static IDENTITY: Matrix; + static TEMP_MATRIX: Matrix; } - export interface Mixin { + export interface HitArea { - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; + contains(x: number, y: number): boolean; } - export class MovieClip extends Sprite { + export class Circle implements HitArea { - static fromFrames(frames: string[]): MovieClip; - static fromImages(images: HTMLImageElement[]): HTMLImageElement; - - constructor(textures: Texture[]); - - animationSpeed: number; - currentFrame: number; - loop: boolean; - playing: boolean; - textures: Texture[]; - totalFrames: number; - - gotoAndPlay(frameNumber: number): void; - gotoAndStop(frameNumber: number): void; - onComplete(): void; - play(): void; - stop(): void; - - } - - export class NoiseFilter extends AbstractFilter { - - noise: number; - - } - - export class NormalMapFilter extends AbstractFilter { - - map: Texture; - offset: Point; - scale: Point; - - } - - export class PixelateFilter extends AbstractFilter { - - size: number; - - } - - export interface IPixiShader { - - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class PixiShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - - attributes: ShaderAttribute[]; - defaultVertexSrc: string[]; - dirty: boolean; - firstRun: boolean; - textureCount: number; - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - initSampler2D(): void; - initUniforms(): void; - syncUniforms(): void; - - destroy(): void; - init(): void; - - } - - export class PixiFastShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - - textureCount: number; - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class PrimitiveShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class ComplexPrimitiveShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class StripShader implements IPixiShader { - - constructor(gl: WebGLRenderingContext); - fragmentSrc: string[]; - gl: WebGLRenderingContext; - program: WebGLProgram; - vertexSrc: string[]; - - destroy(): void; - init(): void; - - } - - export class Point { - - constructor(x?: number, y?: number); + constructor(x?: number, y?: number, radius?: number); x: number; y: number; + radius: number; + type: number; - clone(): Point; - set(x: number, y: number): void; + clone(): Circle; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; } + export class Ellipse implements HitArea { + constructor(x?: number, y?: number, width?: number, height?: number); + + x: number; + y: number; + width: number; + height: number; + type: number; + + clone(): Ellipse; + contains(x: number, y: number): boolean; + getBounds(): Rectangle; + + } export class Polygon implements HitArea { constructor(points: Point[]); @@ -919,13 +392,15 @@ declare module PIXI { constructor(...points: Point[]); constructor(...points: number[]); - points: any[]; //number[] Point[] + closed: boolean; + points: number[]; + type: number; clone(): Polygon; contains(x: number, y: number): boolean; - } + } export class Rectangle implements HitArea { constructor(x?: number, y?: number, width?: number, height?: number); @@ -934,32 +409,14 @@ declare module PIXI { y: number; width: number; height: number; + type: number; + + static EMPTY: Rectangle; clone(): Rectangle; contains(x: number, y: number): boolean; } - - export class RGBSplitFilter extends AbstractFilter { - - red: Point; - green: Point; - blue: Point; - - } - - export class Rope extends Strip { - - points: Point[]; - vertices: number[]; - - constructor(texture: Texture, points: Point[]); - - refresh(): void; - setTexture(texture: Texture): void; - - } - export class RoundedRectangle implements HitArea { constructor(x?: number, y?: number, width?: number, height?: number, radius?: number); @@ -969,944 +426,1295 @@ declare module PIXI { width: number; height: number; radius: number; + type: number; - clone(): RoundedRectangle; + static EMPTY: Rectangle; + + clone(): Rectangle; contains(x: number, y: number): boolean; } - export class SepiaFilter extends AbstractFilter { + //particles - sepia: number; + export interface ParticleContainerProperties { + scale?: boolean; + position?: boolean; + rotation?: boolean; + uvs?: boolean; + alpha?: boolean; } + export class ParticleContainer extends Container { - export class SmartBlurFilter extends AbstractFilter { + constructor(size?: number, properties?: ParticleContainerProperties, batchSize?: number); - blur: number; + protected _maxSize: number; + protected _batchSize: number; - } - - export class SpineLoader implements Mixin { - - url: string; - crossorigin: boolean; - loaded: boolean; - - constructor(url: string, crossOrigin: boolean); - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class SpineTextureLoader { - - constructor(basePath: string, crossorigin: boolean); - - load(page: AtlasPage, file: string): void; - unload(texture: BaseTexture): void; - - } - - export class Sprite extends DisplayObjectContainer { - - static fromFrame(frameId: string): Sprite; - static fromImage(url: string, crossorigin?: boolean, scaleMode?: scaleModes): Sprite; - - constructor(texture: Texture); - - anchor: Point; - blendMode: blendModes; - shader: IPixiShader; - texture: Texture; - tint: number; - - setTexture(texture: Texture): void; - - } - - export class SpriteBatch extends DisplayObjectContainer { - - constructor(texture?: Texture); - - ready: boolean; - textureThing: Texture; - - initWebGL(gl: WebGLRenderingContext): void; - - } - - export class SpriteSheetLoader implements Mixin { - - constructor(url: string, crossorigin?: boolean); - - baseUrl: string; - crossorigin: boolean; - frames: any; - texture: Texture; - url: string; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - load(): void; - - } - - export class Stage extends DisplayObjectContainer { - - constructor(backgroundColor: number); - - interactionManager: InteractionManager; - - getMousePosition(): Point; - setBackgroundColor(backgroundColor: number): void; - setInteractionDelegate(domElement: HTMLElement): void; - - } - - export class Strip extends DisplayObjectContainer { - - static DrawModes: { - - TRIANGLE_STRIP: number; - TRIANGLES: number; - - } - - constructor(texture: Texture); + protected onChildrenChange: () => void; + interactiveChildren: boolean; blendMode: number; - colors: number[]; - dirty: boolean; - indices: number[]; - canvasPadding: number; - texture: Texture; - uvs: number[]; - vertices: number[]; + roundPixels: boolean; - getBounds(matrix?: Matrix): Rectangle; + setProperties(properties: ParticleContainerProperties): void; + + } + export interface ParticleBuffer { + + gl: WebGLRenderingContext; + vertSize: number; + vertByteSize: number; + size: number; + dynamicProperties: any[]; + staticProperties: any[]; + + staticStride: number; + staticBuffer: any; + staticData: any; + dynamicStride: number; + dynamicBuffer: any; + dynamicData: any; + + initBuffers(): void; + bind(): void; + destroy(): void; + + } + export interface ParticleRenderer { + + } + export interface ParticleShader { } - export class Text extends Sprite { + //renderers - constructor(text: string, style?: TextStyle); + export interface RendererOptions { - static fontPropertiesCanvas: any; - static fontPropertiesContext: any; - static fontPropertiesCache: any; + view?: HTMLCanvasElement; + transparent?: boolean + antialias?: boolean; + resolution?: number; + clearBeforeRendering?: boolean; + preserveDrawingBuffer?: boolean; + forceFXAA?: boolean; + roundPixels?: boolean; + + } + export class SystemRenderer extends EventEmitter { + + protected _backgroundColor: number; + protected _backgroundColorRgb: number[]; + protected _backgroundColorString: string; + protected _tempDisplayObjectParent: any; + protected _lastObjectRendered: DisplayObject; + + constructor(system: string, width?: number, height?: number, options?: RendererOptions); + + type: number; + width: number; + height: number; + view: HTMLCanvasElement; + resolution: number; + transparent: boolean; + autoResize: boolean; + blendModes: any; //todo? + preserveDrawingBuffer: boolean; + clearBeforeRender: boolean; + backgroundColor: number; + + render(object: DisplayObject): void; + resize(width: number, height: number): void; + destroy(removeView?: boolean): void; + + } + export class CanvasRenderer extends SystemRenderer { + + protected renderDisplayObject(displayObject: DisplayObject, context: CanvasRenderingContext2D): void; + protected _mapBlendModes(): void; + + constructor(width?: number, height?: number, options?: RendererOptions); context: CanvasRenderingContext2D; - resolution: number; - - destroy(destroyTexture: boolean): void; - setStyle(style: TextStyle): void; - setText(text: string): void; - - } - - export class Texture implements Mixin { - - static emptyTexture: Texture; - - static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: scaleModes): Texture; - static fromFrame(frameId: string): Texture; - static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: scaleModes): Texture; - static addTextureToCache(texture: Texture, id: string): void; - static removeTextureFromCache(id: string): Texture; - - constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle); - - baseTexture: BaseTexture; - crop: Rectangle; - frame: Rectangle; - height: number; - noFrame: boolean; - requiresUpdate: boolean; - trim: Point; - width: number; - scope: any; - valid: boolean; - - listeners(eventName: string): Function[]; - emit(eventName: string, data?: any): boolean; - dispatchEvent(eventName: string, data?: any): boolean; - on(eventName: string, fn: Function): Function; - addEventListener(eventName: string, fn: Function): Function; - once(eventName: string, fn: Function): Function; - off(eventName: string, fn: Function): Function; - removeAllEventListeners(eventName: string): void; - - destroy(destroyBase: boolean): void; - setFrame(frame: Rectangle): void; - - } - - export class TilingSprite extends Sprite { - - constructor(texture: Texture, width: number, height: number); - - blendMode: number; - texture: Texture; - tint: number; - tilePosition: Point; - tileScale: Point; - tileScaleOffset: Point; - - destroy(): void; - generateTilingTexture(forcePowerOfTwo?: boolean): void; - setTexture(texture: Texture): void; - - } - - export class TiltShiftFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - } - - export class TiltShiftXFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - - export class TiltShiftYFilter extends AbstractFilter { - - blur: number; - gradientBlur: number; - start: number; - end: number; - - updateDelta(): void; - - } - - export class TwistFilter extends AbstractFilter { - - angle: number; - offset: Point; - radius: number; - - } - - export class VideoTexture extends BaseTexture { - - static baseTextureFromVideo(video: HTMLVideoElement, scaleMode: number): BaseTexture; - static textureFromVideo(video: HTMLVideoElement, scaleMode: number): Texture; - static fromUrl(videoSrc: string, scaleMode: number): Texture; - - autoUpdate: boolean; - - destroy(): void; - updateBound(): void; - onPlayStart(): void; - onPlayStop(): void; - onCanPlay(): void; - - } - - export class WebGLBlendModeManager { - + refresh: boolean; + maskManager: CanvasMaskManager; + roundPixels: boolean; + currentScaleMode: number; currentBlendMode: number; + smoothProperty: string; - destroy(): void; - setBlendMode(blendMode: number): boolean; - setContext(gl: WebGLRenderingContext): void; + render(object: DisplayObject): void; + resize(w: number, h: number): void; } + export class CanvasBuffer { - export class WebGLFastSpriteBatch { + protected clear(): void; - constructor(gl: CanvasRenderingContext2D); + constructor(width: number, height: number); - currentBatchSize: number; - currentBaseTexture: BaseTexture; - currentBlendMode: number; - renderSession: RenderSession; - drawing: boolean; - indexBuffer: any; - indices: number[]; - lastIndexCount: number; - matrix: Matrix; - maxSize: number; - shader: IPixiShader; - size: number; - vertexBuffer: any; - vertices: number[]; - vertSize: number; + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; - end(): void; - begin(spriteBatch: SpriteBatch, renderSession: RenderSession): void; - destroy(removeView?: boolean): void; - flush(): void; - render(spriteBatch: SpriteBatch): void; - renderSprite(sprite: Sprite): void; - setContext(gl: WebGLRenderingContext): void; - start(): void; - stop(): void; - - } - - export class WebGLFilterManager { - - filterStack: AbstractFilter[]; - transparent: boolean; - offsetX: number; - offsetY: number; - - applyFilterPass(filter: AbstractFilter, filterArea: Texture, width: number, height: number): void; - begin(renderSession: RenderSession, buffer: ArrayBuffer): void; - destroy(): void; - initShaderBuffers(): void; - popFilter(): void; - pushFilter(filterBlock: FilterBlock): void; - setContext(gl: WebGLRenderingContext): void; - - } - - export class WebGLGraphics { - - static graphicsDataPool: any[]; - - static renderGraphics(graphics: Graphics, renderRession: RenderSession): void; - static updateGraphics(graphics: Graphics, gl: WebGLRenderingContext): void; - static switchMode(webGL: WebGLRenderingContext, type: number): any; //WebGLData - static buildRectangle(graphicsData: GraphicsData, webGLData: any): void; - static buildRoundedRectangle(graphicsData: GraphicsData, webGLData: any): void; - static quadraticBezierCurve(fromX: number, fromY: number, cpX: number, cpY: number, toX: number, toY: number): number[]; - static buildCircle(graphicsData: GraphicsData, webGLData: any): void; - static buildLine(graphicsData: GraphicsData, webGLData: any): void; - static buildComplexPoly(graphicsData: GraphicsData, webGLData: any): void; - static buildPoly(graphicsData: GraphicsData, webGLData: any): boolean; - - reset(): void; - upload(): void; - - } - - export class WebGLGraphicsData { - - constructor(gl: WebGLRenderingContext); - - gl: WebGLRenderingContext; - glPoints: any[]; - color: number[]; - points: any[]; - indices: any[]; - buffer: WebGLBuffer; - indexBuffer: WebGLBuffer; - mode: number; - alpha: number; - dirty: boolean; - - reset(): void; - upload(): void; - - } - - export class WebGLMaskManager { - - destroy(): void; - popMask(renderSession: RenderSession): void; - pushMask(maskData: any[], renderSession: RenderSession): void; - setContext(gl: WebGLRenderingContext): void; - - } - - export class WebGLRenderer implements PixiRenderer { - - static createWebGLTexture(texture: Texture, gl: WebGLRenderingContext): void; - - constructor(width?: number, height?: number, options?: PixiRendererOptions); - - autoResize: boolean; - clearBeforeRender: boolean; - contextLost: boolean; - contextLostBound: Function; - contextRestoreLost: boolean; - contextRestoredBound: Function; - height: number; - gl: WebGLRenderingContext; - offset: Point; - preserveDrawingBuffer: boolean; - projection: Point; - resolution: number; - renderSession: RenderSession; - shaderManager: WebGLShaderManager; - spriteBatch: WebGLSpriteBatch; - maskManager: WebGLMaskManager; - filterManager: WebGLFilterManager; - stencilManager: WebGLStencilManager; - blendModeManager: WebGLBlendModeManager; - transparent: boolean; - type: number; - view: HTMLCanvasElement; width: number; + height: number; - destroy(): void; - initContext(): void; - mapBlendModes(): void; - render(stage: Stage): void; - renderDisplayObject(displayObject: DisplayObject, projection: Point, buffer: WebGLBuffer): void; resize(width: number, height: number): void; - updateTexture(texture: Texture): void; + destroy(): void; + + } + export class CanvasGraphics { + + static renderGraphicsMask(graphics: Graphics, context: CanvasRenderingContext2D): void; + static updateGraphicsTint(graphics: Graphics): void; + + static renderGraphics(graphics: Graphics, context: CanvasRenderingContext2D): void; + + } + export class CanvasMaskManager { + + pushMask(maskData: any, renderer: WebGLRenderer | CanvasRenderer): void; + popMask(renderer: WebGLRenderer | CanvasRenderer): void; + destroy(): void; + + } + export class CanvasTinter { + + static getTintedTexture(sprite: DisplayObject, color: number): HTMLCanvasElement; + static tintWithMultiply(texture: Texture, color: number, canvas: HTMLDivElement): void; + static tintWithOverlay(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static tintWithPerPixel(texture: Texture, color: number, canvas: HTMLCanvasElement): void; + static roundColor(color: number): number; + static cacheStepsPerColorChannel: number; + static convertTintToImage: boolean; + static vanUseMultiply: boolean; + static tintMethod: Function; + + } + export class WebGLRenderer extends SystemRenderer { + + protected _useFXAA: boolean; + protected _FXAAFilter: filters.FXAAFilter; + protected _contextOptions: { + alpha: boolean; + antiAlias: boolean; + premultipliedAlpha: boolean; + stencil: boolean; + preseveDrawingBuffer: boolean; + } + protected _renderTargetStack: RenderTarget[]; + + protected _initContext(): void; + protected _createContext(): void; + protected handleContextLost: (event: WebGLContextEvent) => void; + protected _mapGlModes(): void; + + constructor(width?: number, height?: number, options?: RendererOptions); + + drawCount: number; + shaderManager: ShaderManager; + maskManager: MaskManager; + stencilManager: StencilManager; + filterManager: FilterManager; + blendModeManager: BlendModeManager; + currentRenderTarget: RenderTarget; + currentRenderer: ObjectRenderer; + + render(object: DisplayObject): void; + renderDisplayObject(displayObject: DisplayObject, renderTarget: RenderTarget, clear: boolean): void; + setObjectRenderer(objectRenderer: ObjectRenderer): void; + setRenderTarget(renderTarget: RenderTarget): void; + updateTexture(texture: BaseTexture | Texture): BaseTexture | Texture; + destroyTexture(texture: BaseTexture | Texture): void; + + } + export class AbstractFilter { + + protected vertexSrc: string[]; + protected fragmentSrc: string[]; + + constructor(vertexSrc?: string | string[], fragmentSrc?: string | string[], uniforms?: any); + + uniforms: any; + + padding: number; + + getShader(renderer: WebGLRenderer): Shader; + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget, clear?: boolean): void; + syncUniform(uniform: WebGLUniformLocation): void; + + } + export class SpriteMaskFilter extends AbstractFilter { + + constructor(sprite: Sprite); + + maskSprite: Sprite; + maskMatrix: Matrix; + + applyFilter(renderer: WebGLRenderbuffer, input: RenderTarget, output: RenderTarget): void; + map: Texture; + offset: Point; + + } + export class BlendModeManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + setBlendMode(blendMode: number): boolean; } - export class WebGLShaderManager { + export class FilterManager extends WebGLManager { + + constructor(renderer: WebGLRenderer); + + filterStack: any[]; + renderer: WebGLRenderer; + texturePool: any[]; + + onContextChange: () => void; + setFilterStack(filterStack: any[]): void; + pushFilter(target: RenderTarget, filters: any[]): void; + popFilter(): AbstractFilter; + getRenderTarget(clear?: boolean): RenderTarget; + protected returnRenderTarget(renderTarget: RenderTarget): void; + applyFilter(shader: Shader, inputTarget: RenderTarget, outputTarget: RenderTarget, clear?: boolean): void; + calculateMappedMatrix(filterArea: Rectangle, sprite: Sprite, outputMatrix?: Matrix): Matrix; + capFilterArea(filterArea: Rectangle): void; + resize(width: number, height: number): void; + destroy(): void; + + } + + export class MaskManager extends WebGLManager { + + stencilStack: StencilMaskStack; + reverse: boolean; + count: number; + alphaMaskPool: any[]; + + pushMask(target: RenderTarget, maskData: any): void; + popMask(target: RenderTarget, maskData: any): void; + pushSpriteMask(target: RenderTarget, maskData: any): void; + popSpriteMask(): void; + pushStencilMask(target: RenderTarget, maskData: any): void; + popStencilMask(target: RenderTarget, maskData: any): void; + + } + export class ShaderManager extends WebGLManager { + + protected _currentId: number; + protected currentShader: Shader; + + constructor(renderer: WebGLRenderer); maxAttibs: number; attribState: any[]; - stack: any[]; tempAttribState: any[]; + stack: any[]; + setAttribs(attribs: any[]): void; + setShader(shader: Shader): boolean; destroy(): void; - setAttribs(attribs: ShaderAttribute[]): void; - setContext(gl: WebGLRenderingContext): void; - setShader(shader: IPixiShader): boolean; } + export class StencilManager extends WebGLManager { - export class WebGLStencilManager { + constructor(renderer: WebGLRenderer); + + setMaskStack(stencilMaskStack: StencilMaskStack): void; + pushStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + bindGraphics(graphics: Graphics, webGLData: WebGLGraphicsData): void; + popStencil(graphics: Graphics, webGLData: WebGLGraphicsData): void; + destroy(): void; + pushMask(maskData: any[]): void; + popMask(maskData: any[]): void; + + } + export class WebGLManager { + + protected onContextChange: () => void; + + constructor(renderer: WebGLRenderer); + + renderer: WebGLRenderer; + + destroy(): void; + + } + export class Shader { + + protected attributes: any; + protected textureCount: number; + protected uniforms: any; + + protected _glCompile(type: any, src: any): Shader; + + constructor(shaderManager: ShaderManager, vertexSrc: string, fragmentSrc: string, uniforms: any, attributes: any); + + uuid: number; + gl: WebGLRenderingContext; + shaderManager: ShaderManager; + program: WebGLProgram; + vertexSrc: string; + fragmentSrc: string; + + init(): void; + cachUniformLocations(keys: string): void; + cacheAttributeLocations(keys: string): void; + compile(): WebGLProgram; + syncUniform(uniform: any): void; + syncUniforms(): void; + initSampler2D(uniform: any): void; + destroy(): void; + + } + export class ComplexPrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class PrimitiveShader extends Shader { + + constructor(shaderManager: ShaderManager); + + } + export class TextureShader extends Shader { + + constructor(shaderManager: ShaderManager, vertexSrc?: string, fragmentSrc?: string, customUniforms?: any, customAttributes?: any); + + } + export interface StencilMaskStack { stencilStack: any[]; reverse: boolean; count: number; - bindGraphics(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - destroy(): void; - popStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - pushStencil(graphics: Graphics, webGLData: any[], renderSession: RenderSession): void; - setContext(gl: WebGLRenderingContext): void; - } + export class ObjectRenderer extends WebGLManager { - export class WebGLSpriteBatch { - - blendModes: number[]; - colors: number[]; - currentBatchSize: number; - currentBaseTexture: Texture; - defaultShader: AbstractFilter; - dirty: boolean; - drawing: boolean; - indices: number[]; - lastIndexCount: number; - positions: number[]; - textures: Texture[]; - shaders: IPixiShader[]; - size: number; - sprites: any[]; //todo Sprite[]? - vertices: number[]; - vertSize: number; - - begin(renderSession: RenderSession): void; - destroy(): void; - end(): void; - flush(shader?: IPixiShader): void; - render(sprite: Sprite): void; - renderBatch(texture: Texture, size: number, startIndex: number): void; - renderTilingSprite(sprite: TilingSprite): void; - setBlendMode(blendMode: blendModes): void; - setContext(gl: WebGLRenderingContext): void; start(): void; stop(): void; + flush(): void; + render(object?: any): void; + + } + export class RenderTarget { + + constructor(gl: WebGLRenderingContext, width: number, height: number, scaleMode: number, resolution: number, root: boolean); + + gl: WebGLRenderingContext; + frameBuffer: WebGLFramebuffer; + texture: Texture; + size: Rectangle; + resolution: number; + projectionMatrix: Matrix; + transform: Matrix; + frame: Rectangle; + stencilBuffer: WebGLRenderbuffer; + stencilMaskStack: StencilMaskStack; + filterStack: any[]; + scaleMode: number; + root: boolean; + + clear(bind?: boolean): void; + attachStencilBuffer(): void; + activate(): void; + calculateProjection(protectionFrame: Matrix): void; + resize(width: number, height: number): void; + destroy(): void; + + } + export interface Quad { + + gl: WebGLRenderingContext; + vertices: number[]; + uvs: number[]; + colors: number[]; + indices: number[]; + vertexBuffer: WebGLBuffer; + indexBuffer: WebGLBuffer; + + map(rect: Rectangle, rect2: Rectangle): void; + upload(): void; } + //sprites + + export class Sprite extends Container { + + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + protected _texture: Texture; + protected _width: number; + protected _height: number; + protected cachedTint: number; + + protected _onTextureUpdate(): void; + + constructor(texture?: Texture); + + anchor: Point; + tint: number; + blendMode: number; + shader: Shader; + texture: Texture; + + width: number; + height: number; + + getBounds(matrix?: Matrix): Rectangle; + getLocalBounds(): Rectangle; + containsPoint(point: Point): boolean; + destroy(destroyTexture?: boolean, destroyBaseTexture?: boolean): void; + + } + export class SpriteRenderer extends ObjectRenderer { + + protected renderBatch(texture: Texture, size: number, startIndex: number): void; + + vertSize: number; + vertByteSize: number; + size: number; + vertices: number[]; + positions: number[]; + colors: number[]; + indices: number[]; + currentBatchSize: number; + sprites: Sprite[]; + shader: Shader; + + render(sprite: Sprite): void; + flush(): void; + start(): void; + destroy(): void; + + } + + //text + + export interface TextStyle { + + font?: string; + fill?: string | number; + align?: string; + stroke?: string | number; + strokeThickness?: number; + wordWrap?: boolean; + wordWrapWidth?: number; + lineHeight?: number; + dropShadow?: boolean; + dropShadowColor?: string | number; + dropShadowAngle?: number; + dropShadowDistance?: number; + padding?: number; + textBaseline?: string; + lineJoin?: string; + miterLimit?: number; + + } + export class Text extends Sprite { + + static fontPropertiesCache: any; + static fontPropertiesCanvas: HTMLCanvasElement; + static fontPropertiesContext: CanvasRenderingContext2D; + + protected _text: string; + protected _style: TextStyle; + + protected updateText(): void; + protected updateTexture(): void; + protected determineFontProperties(fontStyle: TextStyle): TextStyle; + protected wordWrap(text: string): boolean; + + constructor(text?: string, style?: TextStyle, resolution?: number); + + canvas: HTMLCanvasElement; + context: CanvasRenderingContext2D; + dirty: boolean; + resolution: number; + text: string; + style: TextStyle; + + width: number; + height: number; + + } + + //textures + + export class BaseTexture extends EventEmitter { + + static fromImage(imageUrl: string, crossorigin?: boolean, scaleMode?: number): BaseTexture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): BaseTexture; + + protected _glTextures: any[]; + + protected _sourceLoaded(): void; + + constructor(source: HTMLImageElement | HTMLCanvasElement, scaleMode?: number, resolution?: number); + + uuid: number; + resolution: number; + width: number; + height: number; + realWidth: number; + realHeight: number; + scaleMode: number; + hasLoaded: boolean; + isLoading: boolean; + source: HTMLImageElement | HTMLCanvasElement; + premultipliedAlpha: boolean; + imageUrl: string; + isPowerOfTwo: boolean; + mipmap: boolean; + + update(): void; + loadSource(source: HTMLImageElement | HTMLCanvasElement): void; + destroy(): void; + dispose(): void; + updateSourceImage(newSrc: string): void; + + on(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'dispose', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'error', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'loaded', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: 'update', fn: (baseTexture: BaseTexture) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + } export class RenderTexture extends Texture { - constructor(width?: number, height?: number, renderer?: PixiRenderer, scaleMode?: scaleModes, resolution?: number); + protected renderWebGL(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + protected renderCanvas(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; - frame: Rectangle; - baseTexture: BaseTexture; - renderer: PixiRenderer; + constructor(renderer: CanvasRenderer | WebGLRenderer, width?: number, height?: number, scaleMode?: number, resolution?: number); + + width: number; + height: number; resolution: number; + renderer: CanvasRenderer | WebGLRenderer; valid: boolean; + render(displayObject: DisplayObject, matrix?: Matrix, clear?: boolean, updateTransform?: boolean): void; + resize(width: number, height: number, updateBase?: boolean): void; clear(): void; + destroy(): void; + getImage(): HTMLImageElement; + getPixels(): number[]; + getPixel(x: number, y: number): number[]; getBase64(): string; getCanvas(): HTMLCanvasElement; - getImage(): HTMLImageElement; - resize(width: number, height: number, updateBase: boolean): void; - render(displayObject: DisplayObject, position?: Point, clear?: boolean): void; } - - //SPINE - - export class BoneData { - - constructor(name: string, parent?: any); - - name: string; - parent: any; - length: number; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - - } - - export class SlotData { - - constructor(name: string, boneData: BoneData); - - name: string; - boneData: BoneData; - r: number; - g: number; - b: number; - a: number; - attachmentName: string; - - } - - export class Bone { - - constructor(boneData: BoneData, parent?: any); - - data: BoneData; - parent: any; - yDown: boolean; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; - worldRotation: number; - worldScaleX: number; - worldScaleY: number; - - updateWorldTransform(flipX: boolean, flip: boolean): void; - setToSetupPose(): void; - - } - - export class Slot { - - constructor(slotData: SlotData, skeleton: Skeleton, bone: Bone); - - data: SlotData; - skeleton: Skeleton; - bone: Bone; - r: number; - g: number; - b: number; - a: number; - attachment: RegionAttachment; - setAttachment(attachment: RegionAttachment): void; - setAttachmentTime(time: number): void; - getAttachmentTime(): number; - setToSetupPose(): void; - - } - - export class Skin { - - constructor(name: string); - - name: string; - attachments: any; - - addAttachment(slotIndex: number, name: string, attachment: RegionAttachment): void; - getAttachment(slotIndex: number, name: string): void; - - } - - export class Animation { - - constructor(name: string, timelines: ISpineTimeline[], duration: number); - - name: string; - timelines: ISpineTimeline[]; - duration: number; - apply(skeleton: Skeleton, time: number, loop: boolean): void; - min(skeleton: Skeleton, time: number, loop: boolean, alpha: number): void; - - } - - export class Curves { - - constructor(frameCount: number); - - curves: number[]; - - setLinear(frameIndex: number): void; - setStepped(frameIndex: number): void; - setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; - getCurvePercent(frameIndex: number, percent: number): number; - - } - - export interface ISpineTimeline { - - curves: Curves; - frames: number[]; - - getFrameCount(): number; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class RotateTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, angle: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class TranslateTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class ScaleTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, x: number, y: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class ColorTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - boneIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class AttachmentTimeline implements ISpineTimeline { - - constructor(frameCount: number); - - curves: Curves; - frames: number[]; - attachmentNames: string[]; - slotIndex: number; - - getFrameCount(): number; - setFrame(frameIndex: number, time: number, attachmentName: string): void; - apply(skeleton: Skeleton, time: number, alpha: number): void; - - } - - export class SkeletonData { - - bones: Bone[]; - slots: Slot[]; - skins: Skin[]; - animations: Animation[]; - defaultSkin: Skin; - - findBone(boneName: string): Bone; - findBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - findSkin(skinName: string): Skin; - findAnimation(animationName: string): Animation; - - } - - export class Skeleton { - - constructor(skeletonData: SkeletonData); - - data: SkeletonData; - bones: Bone[]; - slots: Slot[]; - drawOrder: any[]; - x: number; - y: number; - skin: Skin; - r: number; - g: number; - b: number; - a: number; - time: number; - flipX: boolean; - flipY: boolean; - - updateWorldTransform(): void; - setToSetupPose(): void; - setBonesToSetupPose(): void; - setSlotsToSetupPose(): void; - getRootBone(): Bone; - findBone(boneName: string): Bone; - fineBoneIndex(boneName: string): number; - findSlot(slotName: string): Slot; - findSlotIndex(slotName: string): number; - setSkinByName(skinName: string): void; - setSkin(newSkin: Skin): void; - getAttachmentBySlotName(slotName: string, attachmentName: string): RegionAttachment; - getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): RegionAttachment; - setAttachment(slotName: string, attachmentName: string): void; - update(data: number): void; - - } - - export class RegionAttachment { - - offset: number[]; - uvs: number[]; - x: number; - y: number; - rotation: number; - scaleX: number; - scaleY: number; + export class Texture extends BaseTexture { + + static fromImage(imageUrl: string, crossOrigin?: boolean, scaleMode?: number): Texture; + static fromFrame(frameId: string): Texture; + static fromCanvas(canvas: HTMLCanvasElement, scaleMode?: number): Texture; + static fromVideo(video: HTMLVideoElement | string, scaleMode?: number): Texture; + static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; + static addTextureToCache(texture: Texture, id: string): void; + static removeTextureFromCache(id: string): Texture; + static EMPTY: Texture; + + protected _frame: Rectangle; + protected _uvs: TextureUvs; + + protected onBaseTextureUpdated(baseTexture: BaseTexture): void; + protected onBaseTextureLoaded(baseTexture: BaseTexture): void; + protected _updateUvs(): void; + + constructor(baseTexture: BaseTexture, frame?: Rectangle, crop?: Rectangle, trim?: Rectangle, rotate?: boolean); + + noFrame: boolean; + baseTexture: BaseTexture; + trim: Rectangle; + valid: boolean; + requiresUpdate: boolean; width: number; height: number; - rendererObject: any; - regionOffsetX: number; - regionOffsetY: number; - regionWidth: number; - regionHeight: number; - regionOriginalWidth: number; - regionOriginalHeight: number; - - setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; - updateOffset(): void; - computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; - - } - - export class AnimationStateData { - - constructor(skeletonData: SkeletonData); - - skeletonData: SkeletonData; - animationToMixTime: any; - defaultMix: number; - - setMixByName(fromName: string, toName: string, duration: number): void; - setMix(from: string, to: string): number; - - } - - export class AnimationState { - - constructor(stateData: any); - - animationSpeed: number; - current: any; - previous: any; - currentTime: number; - previousTime: number; - currentLoop: boolean; - previousLoop: boolean; - mixTime: number; - mixDuration: number; - queue: Animation[]; - - update(delta: number): void; - apply(skeleton: any): void; - clearAnimation(): void; - setAnimation(animation: any, loop: boolean): void; - setAnimationByName(animationName: string, loop: boolean): void; - addAnimationByName(animationName: string, loop: boolean, delay: number): void; - addAnimation(animation: any, loop: boolean, delay: number): void; - isComplete(): number; - - } - - export class SkeletonJson { - - constructor(attachmentLoader: AtlasAttachmentLoader); - - attachmentLoader: AtlasAttachmentLoader; - scale: number; - - readSkeletonData(root: any): SkeletonData; - readAttachment(skin: Skin, name: string, map: any): RegionAttachment; - readAnimation(name: string, map: any, skeletonData: SkeletonData): void; - readCurve(timeline: ISpineTimeline, frameIndex: number, valueMap: any): void; - toColor(hexString: string, colorIndex: number): number; - - } - - export class Atlas { - - static FORMAT: { - - alpha: number; - intensity: number; - luminanceAlpha: number; - rgb565: number; - rgba4444: number; - rgb888: number; - rgba8888: number; - - } - - static TextureFilter: { - - nearest: number; - linear: number; - mipMap: number; - mipMapNearestNearest: number; - mipMapLinearNearest: number; - mipMapNearestLinear: number; - mipMapLinearLinear: number; - - } - - static textureWrap: { - - mirroredRepeat: number; - clampToEdge: number; - repeat: number; - - } - - constructor(atlasText: string, textureLoader: AtlasLoader); - - textureLoader: AtlasLoader; - pages: AtlasPage[]; - regions: AtlasRegion[]; - - findRegion(name: string): AtlasRegion; - dispose(): void; - updateUVs(page: AtlasPage): void; - - } - - export class AtlasPage { - - name: string; - format: number; - minFilter: number; - magFilter: number; - uWrap: number; - vWrap: number; - rendererObject: any; - width: number; - height: number; - - } - - export class AtlasRegion { - - page: AtlasPage; - name: string; - x: number; - y: number; - width: number; - height: number; - u: number; - v: number; - u2: number; - v2: number; - offsetX: number; - offsetY: number; - originalWidth: number; - originalHeight: number; - index: number; + crop: Rectangle; rotate: boolean; - splits: any[]; - pads: any[]; + + frame: Rectangle; + + update(): void; + destroy(destroyBase?: boolean): void; + clone(): Texture; } + export class TextureUvs { - export class AtlasReader { + x0: number; + y0: number; + x1: number; + y1: number; + x2: number; + y2: number; + x3: number; + y3: number; - constructor(text: string); - - lines: string[]; - index: number; - - trim(value: string): string; - readLine(): string; - readValue(): string; - readTuple(tuple: number): number; + set(frame: Rectangle, baseFrame: Rectangle, rotate: boolean): void; } + export class VideoBaseTexture extends BaseTexture { - export class AtlasAttachmentLoader { + static fromVideo(video: HTMLVideoElement, scaleMode?: number): VideoBaseTexture; + static fromUrl(videoSrc: string | any | string[]| any[]): VideoBaseTexture; - constructor(atlas: Atlas); + protected _loaded: boolean; - atlas: Atlas; + protected _onUpdate(): void; + protected _onPlayStart(): void; + protected _onPlayStop(): void; + protected _onCanPlay(): void; - newAttachment(skin: Skin, type: number, name: string): RegionAttachment; - - } - - export class Spine extends DisplayObjectContainer { - - constructor(url: string); + constructor(source: HTMLVideoElement, scaleMode?: number); autoUpdate: boolean; - spineData: any; - skeleton: Skeleton; - stateData: AnimationStateData; - state: AnimationState; - slotContainers: DisplayObjectContainer[]; - createSprite(slot: Slot, descriptor: { name: string }): Sprite[]; - update(dt: number): void; + destroy(): void; } + //utils + + export class utils { + + static uuid(): number; + static hex2rgb(hex: number, out?: number[]): number[]; + static hex2String(hex: number): string; + static rbg2hex(rgb: Number[]): number; + static canUseNewCanvasBlendModel(): boolean; + static getNextPowerOfTwo(number: number): number; + static isPowerOfTwo(width: number, height: number): boolean; + static getResolutionOfUrl(url: string): boolean; + static sayHello(type: string): void; + static isWebGLSupported(): boolean; + static sign(n: number): number; + static TextureCache: any; + static BaseTextureCache: any; + + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////EXTRAS//////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module extras { + + export interface BitmapTextStyle { + + font?: string | { + + name?: string; + size?: number; + + }; + align?: string; + tint?: number; + + } + export class BitmapText extends Container { + + static fonts: any; + + protected _glyphs: Sprite[]; + protected _font: string | { + tint: number; + align: string; + name: string; + size: number; + } + protected _text: string; + + protected updateText(): void; + + constructor(text: string, style?: BitmapTextStyle); + + textWidth: number; + textHeight: number; + maxWidth: number; + dirty: boolean; + + tint: number; + align: string; + font: string | { + tint: number; + align: string; + name: string; + size: number; + } + text: string; + + } + export class MovieClip extends Sprite { + + static fromFrames(frame: string[]): MovieClip; + static fromImages(images: string[]): MovieClip; + + protected _textures: Texture; + protected _currentTime: number; + + protected update(deltaTime: number): void; + + constructor(textures: Texture[]); + + animationSpeed: number; + loop: boolean; + onComplete: () => void; + currentFrame: number; + playing: boolean; + + totalFrames: number; + textures: Texture[]; + + stop(): void; + play(): void; + gotoAndStop(frameName: number): void; + gotoAndPlay(frameName: number): void; + destroy(): void; + + } + export class TilingSprite extends Sprite { + + //This is really unclean but is the only way :( + //See http://stackoverflow.com/questions/29593905/typescript-declaration-extending-class-with-static-method/29595798#29595798 + //Thanks bas! + static fromFrame(frameId: string): Sprite; + static fromImage(imageId: string, crossorigin?: boolean, scaleMode?: number): Sprite; + + static fromFrame(frameId: string, width?: number, height?: number): TilingSprite; + static fromImage(imageId: string, width?: number, height?: number, crossorigin?: boolean, scaleMode?: number): TilingSprite; + + protected _tileScaleOffset: Point; + protected _tilingTexture: boolean; + protected _refreshTexture: boolean; + protected _uvs: TextureUvs[]; + + constructor(texture: Texture, width: number, height: number); + + tileScale: Point; + tilePosition: Point; + + width: number; + height: number; + originalTexture: Texture; + + getBounds(): Rectangle; + generateTilingTexture(renderer: WebGLRenderer | CanvasRenderer, texture: Texture, forcePowerOfTwo?: boolean): Texture; + containsPoint(point: Point): boolean; + destroy(): void; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////FILTERS//////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + module filters { + + export class AsciiFilter extends AbstractFilter { + size: number; + } + export class BloomFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + + } + export class BlurFilter extends AbstractFilter { + + protected blurXFilter: BlurXFilter; + protected blurYFilter: BlurYFilter; + + blur: number; + passes: number; + blurX: number; + blurY: number; + + } + export class BlurXFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class BlurYFilter extends AbstractFilter { + + passes: number; + strength: number; + blur: number; + + } + export class SmartBlurFilter extends AbstractFilter { + + } + export class ColorMatrixFilter extends AbstractFilter { + + protected _loadMatrix(matrix: number[], multiply: boolean): void; + protected _multiply(out: number[], a: number[], b: number[]): void; + protected _colorMatrix(matrix: number[]): void; + + matrix: number[]; + + brightness(b: number, multiply?: boolean): void; + greyscale(scale: number, multiply?: boolean): void; + blackAndWhite(multiply?: boolean): void; + hue(rotation: number, multiply?: boolean): void; + contrast(amount: number, multiply?: boolean): void; + saturate(amount: number, multiply?: boolean): void; + desaturate(multiply?: boolean): void; + negative(multiply?: boolean): void; + sepia(multiply?: boolean): void; + technicolor(multiply?: boolean): void; + polaroid(multiply?: boolean): void; + toBGR(multiply?: boolean): void; + kodachrome(multiply?: boolean): void; + browni(multiply?: boolean): void; + vintage(multiply?: boolean): void; + colorTone(desaturation: number, toned: number, lightColor: string, darkColor: string, multiply?: boolean): void; + night(intensity: number, multiply?: boolean): void; + predator(amount: number, multiply?: boolean): void; + lsd(multiply?: boolean): void; + reset(): void; + + } + export class ColorStepFilter extends AbstractFilter { + + step: number; + + } + export class ConvolutionFilter extends AbstractFilter { + + constructor(matrix: number[], width: number, height: number); + + matrix: number[]; + width: number; + height: number; + + } + export class CrossHatchFilter extends AbstractFilter { + + } + export class DisplacementFilter extends AbstractFilter { + + constructor(sprite: Sprite, scale?: number); + + map: Texture; + + scale: Point; + + } + export class DotScreenFilter extends AbstractFilter { + + scale: number; + angle: number; + + } + export class BlurYTintFilter extends AbstractFilter { + + blur: number; + + } + export class DropShadowFilter extends AbstractFilter { + + blur: number; + blurX: number; + blurY: number; + color: number; + alpha: number; + distance: number; + angle: number; + + } + export class GrayFilter extends AbstractFilter { + + gray: number; + + } + export class InvertFilter extends AbstractFilter { + + invert: number; + + } + export class NoiseFilter extends AbstractFilter { + + noise: number; + + } + export class PixelateFilter extends AbstractFilter { + + size: Point; + + } + export class RGBSplitFilter extends AbstractFilter { + + red: number; + green: number; + blue: number; + + } + export class SepiaFilter extends AbstractFilter { + + sepia: number; + + } + export class ShockwaveFilter extends AbstractFilter { + + center: number[]; + params: any; + time: number; + + } + export class TiltShiftAxisFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + updateDelta(): void; + + } + export class TiltShiftFilter extends AbstractFilter { + + blur: number; + gradientBlur: number; + start: number; + end: number; + + } + export class TiltShiftXFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TiltShiftYFilter extends AbstractFilter { + + updateDelta(): void; + + } + export class TwistFilter extends AbstractFilter { + + offset: Point; + radius: number; + angle: number; + + } + export class FXAAFilter extends AbstractFilter { + + applyFilter(renderer: WebGLRenderer, input: RenderTarget, output: RenderTarget): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ////////////////////////////INTERACTION/////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module interaction { + + export interface InteractionEvent { + + stopped: boolean; + target: any; + type: string; + data: InteractionData; + stopPropagation(): void; + + } + + export class InteractionData { + + global: Point; + target: DisplayObject; + originalEvent: Event; + + getLocalPosition(displayObject: DisplayObject, point?: Point, globalPos?: Point): Point; + + } + + export class InteractionManager { + + protected interactionDOMElement: HTMLElement; + protected eventsAdded: boolean; + protected _tempPoint: Point; + + protected setTargetElement(element: HTMLElement, resolution: number): void; + protected addEvents(): void; + protected removeEvents(): void; + protected dispatchEvent(displayObject: DisplayObject, eventString: string, eventData: any): void; + protected onMouseDown: (event: Event) => void; + protected processMouseDown: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseUp: (event: Event) => void; + protected processMouseUp: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseMove: (event: Event) => void; + protected processMouseMove: (displayObject: DisplayObject, hit: boolean) => void; + protected onMouseOut: (event: Event) => void; + protected processMouseOverOut: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchStart: (event: Event) => void; + protected processTouchStart: (DisplayObject: DisplayObject, hit: boolean) => void; + protected onTouchEnd: (event: Event) => void; + protected processTouchEnd: (displayObject: DisplayObject, hit: boolean) => void; + protected onTouchMove: (event: Event) => void; + protected processTouchMove: (displayObject: DisplayObject, hit: boolean) => void; + protected getTouchData(touchEvent: InteractionData): InteractionData; + protected returnTouchData(touchData: InteractionData): void; + + constructor(renderer: CanvasRenderer | WebGLRenderer, options?: { autoPreventDefault?: boolean; interactionFrequence?: number; }); + + renderer: CanvasRenderer | WebGLRenderer; + autoPreventDefault: boolean; + interactionFrequency: number; + mouse: InteractionData; + eventData: { + stopped: boolean; + target: any; + type: any; + data: InteractionData; + }; + interactiveDataPool: InteractionData[]; + last: number; + currentCursorStyle: string; + resolution: number; + update(deltaTime: number): void; + + mapPositionToPoint(point: Point, x: number, y: number): void; + processInteractive(point: Point, displayObject: DisplayObject, func: (displayObject: DisplayObject, hit: boolean) => void, hitTest: boolean, interactive: boolean): boolean; + destroy(): void; + + } + + export interface InteractiveTarget { + + interactive: boolean; + buttonMode: boolean; + interactiveChildren: boolean; + defaultCursor: string; + hitArea: HitArea; + + } + + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////LOADER///////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + //https://github.com/englercj/resource-loader/blob/master/src/Loader.js + + export module loaders { + export interface LoaderOptions { + + crossOrigin?: boolean; + loadType?: number; + xhrType?: string; + + } + export class Loader extends EventEmitter { + + constructor(baseUrl?: string, concurrency?: number); + + baseUrl: string; + progress: number; + loading: boolean; + resources: Resource[]; + + add(name: string, url: string, options?: LoaderOptions, cb?: () => void): Loader; + add(url: string, options?: LoaderOptions, cb?: () => void): Loader; + //todo I am not sure of object literal notional (or its options) so just allowing any but would love to improve this + add(obj: any, options?: LoaderOptions, cb?: () => void): Loader; + + on(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + on(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + on(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + on(event: string, fn: Function, context?: any): EventEmitter; + + once(event: 'complete', fn: (loader: loaders.Loader, object: any) => void, context?: any): EventEmitter; + once(event: 'error', fn: (error: Error, loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'load', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'progress', fn: (loader: loaders.Loader, resource: Resource) => void, context?: any): EventEmitter; + once(event: 'start', fn: (loader: loaders.Loader) => void, context?: any): EventEmitter; + once(event: string, fn: Function, context?: any): EventEmitter; + + before(fn: Function): Loader; + pre(fn: Function): Loader; + + after(fn: Function): Loader; + use(fn: Function): Loader; + + reset(): void; + + load(cb?: (loader: loaders.Loader, object: any) => void): Loader; + + } + export class Resource extends EventEmitter { + + static LOAD_TYPE: { + XHR: number; + IMAGE: number; + AUDIO: number; + VIDEO: number; + }; + + static XHR_READ_STATE: { + UNSENT: number; + OPENED: number; + HEADERS_RECIEVED: number; + LOADING: number; + DONE: number; + }; + + static XHR_RESPONSE_TYPE: { + DEFAULT: number; + BUFFER: number; + BLOB: number; + DOCUMENT: number; + JSON: number; + TEXT: number; + }; + + constructor(name?: string, url?: string | string[], options?: LoaderOptions); + + name: string; + texture: Texture; + url: string; + data: any; + crossOrigin: string; + loadType: number; + xhrType: string; + error: Error; + xhr: XMLHttpRequest; + + complete(): void; + load(cb?: () => void): void; + + } + } + + ////////////////////////////////////////////////////////////////////////////// + ///////////////////////////////MESH/////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////////// + + export module mesh { + + export class Mesh extends Container { + + static DRAW_MODES: { + TRIANGLE_MESH: number; + TRIANGLES: number; + } + + constructor(texture: Texture, vertices?: number[], uvs?: number[], indices?: number[], drawMode?: number); + + texture: Texture; + uvs: number[]; + vertices: number[]; + indices: number[]; + dirty: boolean; + blendMode: number; + canvasPadding: number; + drawMode: number; + + getBounds(matrix?: Matrix): Rectangle; + containsPoint(point: Point): boolean; + + protected _texture: Texture; + + protected _renderCanvasTriangleMesh(context: CanvasRenderingContext2D): void; + protected _renderCanvasTriangles(context: CanvasRenderingContext2D): void; + protected _renderCanvasDrawTriangle(context: CanvasRenderingContext2D, vertices: number, uvs: number, index0: number, index1: number, index2: number): void; + protected renderMeshFlat(Mesh: Mesh): void; + protected _onTextureUpdate(): void; + + } + export class Rope extends Mesh { + + protected _ready: boolean; + + protected getTextureUvs(): TextureUvs; + + constructor(texture: Texture, points: Point[]); + + points: Point[]; + colors: number[]; + + refresh(): void; + + } + + export class MeshRenderer extends ObjectRenderer { + + protected _initWebGL(mesh: Mesh): void; + + indices: number[]; + + constructor(renderer: WebGLRenderer); + + render(mesh: Mesh): void; + flush(): void; + start(): void; + destroy(): void; + + } + + export interface MeshShader extends Shader { } + + } + + module ticker { + + export var shared: Ticker; + + export class Ticker { + + protected _tick(time: number): void; + protected _emitter: EventEmitter; + protected _requestId: number; + protected _maxElapsedMS: number; + + protected _requestIfNeeded(): void; + protected _cancelIfNeeded(): void; + protected _startIfPossible(): void; + + autoStart: boolean; + deltaTime: number; + elapsedMS: number; + lastTime: number; + speed: number; + started: boolean; + + FPS: number; + minFPS: number; + + add(fn: (deltaTime: number) => void, context?: any): Ticker; + addOnce(fn: (deltaTime: number) => void, context?: any): Ticker; + remove(fn: (deltaTime: number) => void, context?: any): Ticker; + start(): void; + stop(): void; + update(): void; + + } + + } } -declare function requestAnimFrame(callback: Function): void; - -declare module PIXI.PolyK { - export function Triangulate(p: number[]): number[]; +declare module 'pixi.js' { + export = PIXI; } \ No newline at end of file diff --git a/pixi.js/pixi.js.d.ts.tscparams b/pixi.js/pixi.js.d.ts.tscparams deleted file mode 100644 index d3f5a12fa..000000000 --- a/pixi.js/pixi.js.d.ts.tscparams +++ /dev/null @@ -1 +0,0 @@ - From 95fe96133fdb83bb295e5ee6a27725dd5a91e725 Mon Sep 17 00:00:00 2001 From: Bob Fanger Date: Fri, 31 Jul 2015 12:43:34 +0200 Subject: [PATCH 13/38] Added definitions for the "Pixi.js plugin that enables Spine support." --- pixi-spine/pixi-spine-tests.ts | 312 +++++++++++++ pixi-spine/pixi-spine.d.ts | 812 +++++++++++++++++++++++++++++++++ 2 files changed, 1124 insertions(+) create mode 100644 pixi-spine/pixi-spine-tests.ts create mode 100644 pixi-spine/pixi-spine.d.ts diff --git a/pixi-spine/pixi-spine-tests.ts b/pixi-spine/pixi-spine-tests.ts new file mode 100644 index 000000000..71ecf3147 --- /dev/null +++ b/pixi-spine/pixi-spine-tests.ts @@ -0,0 +1,312 @@ +/// +/// + +module Spine { + + export class Dragon { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private dragon: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + + PIXI.loader.add('dragon', '../../_assets/spine/dragon.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.dragon = new PIXI.spine.Spine(res.dragon.spineData); + this.dragon.skeleton.setToSetupPose(); + this.dragon.update(0); + this.dragon.autoUpdate = false; + + //create a container for the spin animation and add the animation to it + var dragonCage: PIXI.Container = new PIXI.Container(); + dragonCage.addChild(this.dragon); + + // measure the spine animation and position it inside its container to align it to the origin + var localRect: PIXI.Rectangle = this.dragon.getLocalBounds(); + this.dragon.position.set(-localRect.x, -localRect.y); + + // now we can scale, position and rotate the container as any other display object + var scale = Math.min((this.renderer.width * 0.7) / dragonCage.width, (this.renderer.height * 0.7) / dragonCage.height); + dragonCage.scale.set(scale, scale); + dragonCage.position.set((this.renderer.width - dragonCage.width) * 0.5, (this.renderer.height - dragonCage.height) * 0.5); + + // add the container to the stage + this.stage.addChild(dragonCage); + + // once position and scaled, set the animation to play + this.dragon.state.setAnimationByName(0, 'flying', true); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + // update the spine animation, only needed if dragon.autoupdate is set to false + this.dragon.update(0.01666666666667); // HARDCODED FRAMERATE! + + this.renderer.render(this.stage); + + } + + } + +} + +module Spine { + + export class Goblin { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private goblin: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('goblins', '../../_assets/spine/goblins.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.goblin = new PIXI.spine.Spine(res.goblins.spineData); + this.goblin.skeleton.setSkinByName('goblin'); + this.goblin.skeleton.setSlotsToSetupPose(); + + this.goblin.position.x = 400; + this.goblin.position.y = 600; + this.goblin.scale.set(1.5); + + this.goblin.state.setAnimationByName(0, 'walk', true); + + this.stage.addChild(this.goblin); + + this.stage.on('click', () => { + + // change current skin + var currentSkinName = this.goblin.skeleton.skin.name; + var newSkinName = (currentSkinName === 'goblin' ? 'goblingirl' : 'goblin'); + this.goblin.skeleton.setSkinByName(newSkinName); + this.goblin.skeleton.setSlotsToSetupPose(); + + }); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + +} + +module Spine { + + export class Pixie { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private pixie: PIXI.spine.Spine; + + private position: number; + private background: PIXI.Sprite; + private background2: PIXI.Sprite; + private foreground: PIXI.Sprite; + private foreground2: PIXI.Sprite; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('pixie', '../../_assets/spine/pixie.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + this.background = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); + this.background2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_BGtile.jpg'); + this.stage.addChild(this.background); + this.stage.addChild(this.background2); + + this.foreground = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); + this.foreground2 = PIXI.Sprite.fromImage('../../_assets/spine/iP4_ground.png'); + this.stage.addChild(this.foreground); + this.stage.addChild(this.foreground2); + this.foreground.position.y = this.foreground2.position.y = 640 - this.foreground2.height; + + this.pixie = new PIXI.spine.Spine(res.pixie.spineData); + + var scale = 0.3; + + this.pixie.position.x = 1024 / 3; + this.pixie.position.y = 500; + + this.pixie.scale.x = this.pixie.scale.y = scale; + + this.stage.addChild(this.pixie); + + this.pixie.stateData.setMixByName('running', 'jump', 0.2); + this.pixie.stateData.setMixByName('jump', 'running', 0.4); + + this.pixie.state.setAnimationByName(0, 'running', true); + + this.stage.on('mousedown', this.onTouchStart); + this.stage.on('touchstart', this.onTouchStart); + + this.animate(); + + } + + private onTouchStart = (): void => { + + this.pixie.state.setAnimationByName(0, 'jump', false); + this.pixie.state.addAnimationByName(0, 'running', true, 0); + + } + + private animate = (): void => { + + this.position += 10; + + this.background.position.x = -(this.position * 0.6); + this.background.position.x %= 1286 * 2; + if (this.background.position.x < 0) { + this.background.position.x += 1286 * 2; + } + this.background.position.x -= 1286; + + this.background2.position.x = -(this.position * 0.6) + 1286; + this.background2.position.x %= 1286 * 2; + if (this.background2.position.x < 0) { + this.background2.position.x += 1286 * 2; + } + this.background2.position.x -= 1286; + + this.foreground.position.x = -this.position; + this.foreground.position.x %= 1286 * 2; + if (this.foreground.position.x < 0) { + this.foreground.position.x += 1286 * 2; + } + this.foreground.position.x -= 1286; + + this.foreground2.position.x = -this.position + 1286; + this.foreground2.position.x %= 1286 * 2; + if (this.foreground2.position.x < 0) { + this.foreground2.position.x += 1286 * 2; + } + this.foreground2.position.x -= 1286; + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + module Spine { + + export class SpineBoy { + + private renderer: PIXI.CanvasRenderer | PIXI.WebGLRenderer; + + private stage: PIXI.Container; + + private spineboy: PIXI.spine.Spine; + + constructor() { + + this.renderer = PIXI.autoDetectRenderer(800, 600, { backgroundColor: 0x1099bb }); + document.body.appendChild(this.renderer.view); + + // create the root of the scene graph + this.stage = new PIXI.Container(); + this.stage.interactive = true; + + PIXI.loader.add('spineboy', '../../_assets/spine/spineboy.json').load(this.onAssetsLoaded); + + } + + private onAssetsLoaded = (loader: PIXI.loaders.Loader, res: any): void => { + + //initiate the spine animation + this.spineboy = new PIXI.spine.Spine(res.spineboy.spineData); + this.spineboy.position.x = this.renderer.width / 2; + this.spineboy.position.y = this.renderer.height; + this.spineboy.scale.set(1.5); + + // set up the mixes! + this.spineboy.stateData.setMixByName('walk', 'jump', 0.2); + this.spineboy.stateData.setMixByName('jump', 'walk', 0.4); + + // play animation + this.spineboy.state.setAnimationByName(0, 'walk', true); + + this.stage.addChild(this.spineboy); + + + this.stage.on('click', () => { + + this.spineboy.state.setAnimationByName(0, 'jump', false); + this.spineboy.state.addAnimationByName(0, 'walk', true, 0); + + }); + + this.animate(); + + } + + private animate = (): void => { + + requestAnimationFrame(this.animate); + + this.renderer.render(this.stage); + + } + + } + + } + +} \ No newline at end of file diff --git a/pixi-spine/pixi-spine.d.ts b/pixi-spine/pixi-spine.d.ts new file mode 100644 index 000000000..e39dffa42 --- /dev/null +++ b/pixi-spine/pixi-spine.d.ts @@ -0,0 +1,812 @@ +// Type definitions for pixi-spine 1.0.4 +// Project: https://github.com/pixijs/pixi-spine/ +// Definitions by: martijncroezen +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +declare module PIXI { + + export module spine { + + export interface Timeline { + + frames: number[]; + + getFrameCount(): number; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export interface Attachment { + + name: string; + type: number; + + } + + export class Animation { + + constructor(name: string, timelines?: Timeline[], duration?: number); + + apply(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: Event[]): void; + mix(skeleton: Skeleton, lastTime: number, time: number, loop?: boolean, events?: any[], alpha?: number): void; + binarySearch(values: number[], target: number, step: number): number; + binarySearch1(values: number[], target: number): number; + linearSearch(values: number[], target: number, step: number): number; + + name: string; + timelines: Timeline[]; + duration: number; + + } + + export class AnimationState { + + data: AnimationStateData; + tracks: TrackEntry[]; + events: Event[]; + onStart: (index: number) => void; + onEnd: (trackIndex: number) => void; + onComplete: (i: number, count: number) => void; + onEvent: (i: number, event: Event) => void; + timeScale: number; + + constructor(stateData: AnimationStateData); + + update(delta: number): void; + apply(skeleton: Skeleton): void; + clearTracks(): void; + clearTrack(trackIndex: number): void; + private _expandToIndex(index: number): TrackEntry; + setCurrent(index: number, entry: TrackEntry): void; + setAnimationByName(trackIndex: number, animationName: string, loop: boolean): TrackEntry; + setAnimation(trackIndex: number, animation: Animation, loop: boolean): TrackEntry; + addAnimationByName(trackIndex: number, animationName: string, loop: boolean, delay: number): TrackEntry; + addAnimation(trackIndex: number, animation: Animation, loop: boolean, delay: number): TrackEntry; + getCurrent(trackIndex: number): TrackEntry; + + } + + export class Spine extends PIXI.Container { + + constructor(spineData: any); + + static fromAtlas(resourceName: string): Spine; + + update(dt: number): void; + + private autoUpdateTransform(): void; + private createSprite(slot: Slot, attachment: Attachment): Sprite; + private createMesh(slot, attachment) + + spineData: any; + skeleton: Skeleton; + stateData: AnimationStateData; + state: AnimationState; + slotContainers: PIXI.Container[]; + autoUpdate: boolean; + + } + + export class AnimationStateData { + + constructor(skeletonData: SkeletonData); + + private _skelentonData: SkeletonData; + private animationToMixTime: number; + defaultMix: number; + skeletonData: SkeletonData; + setMixByName(fromName: string, toName: string, duration: number): void; + setMix(from: Animation, to: Animation, duration: number): void; + getMix(from: Animation, to: Animation): number; + + } + + export class AttachmentType { + + static region: number; + static boundingbox: number; + static mesh: number; + static skinnedmesh: number; + + } + + export class Bone { + + data: BoneData; + skeleton: Skeleton; + parent: Bone; + + constructor(boneData: BoneData, skeleton: Skeleton, parent: Bone); + + x: number; + y: number; + rotation: number; + rotationIK: number; + scaleX: number; + scaleY: number; + flipX: boolean; + flipY: boolean; + m00: number; + m01: number; + worldX: number; + m10: number; + m11: number; + worldY: number; + worldRotation: number;; + worldScaleX: number; + worldScaleY: number; + worldFlipX: boolean; + worldFlipY: boolean; + + updateWorldTransform(): void; + setToSetupPose(): void; + worldToLocal(world: number[]): void; + localToWorld(local: number[]): void; + + } + + export class BoneData { + + name: string; + parent: Bone; + + constructor(name: string, parent: Bone); + + length: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + inheritScale: boolean; + inheritRotation: boolean; + flipX: boolean; + flipY: boolean; + + } + + export class BoundingBoxAttachment implements Attachment { + + constructor(name: string); + + name: string; + vertices: number[]; + type: number; + + computeWorldVertices(x: number, y: number, bone: Bone, worldVertices: number[]): void; + + } + + export class ColorTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + slotIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, r: number, g: number, b: number, a: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Curves { + + constructor(frameCount: number[]); + + curves: number[]; + + setLinear(frameIndex: number): void; + setStepped(frameIndex: number): void; + setCurve(frameIndex: number, cx1: number, cy1: number, cx2: number, cy2: number): void; + getCurvePercent(frameIndex: number, percent: number): number; + + } + + export class DrawOrderTimeline implements Timeline { + + constructor(frameCount: number); + + frames: number[]; + drawOrders: number[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, drawOrder: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Event { + + constructor(data: any); + + data: any; + intValue: number; + floatValue: number; + stringValue: string; + + } + + export class EventData { + + constructor(name: string); + + name: string; + + intValue: number; + floatValue: number; + stringValue: string; + + } + + export class EventTimeline implements Timeline { + + constructor(frameCount: number); + + frames: number[]; + events: Event[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, event: Event): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + + export class FfdTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + frameVertices: number[]; + slotIndex: number; + attachment: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class FlipXTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class FlipYTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, vertices: number[]): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class IkConstraint { + + constructor(data: IkConstraintData, skeleton: Skeleton); + + data: IkConstraintData; + mix: number; + bendDirection: number; + bones: Bone[]; + target: Bone; + + apply(): void; + apply1(bone: Bone, targetX: number, targetY: number, alpha: number): void; + apply2(parent: Bone, child: Bone, targetX: number, targetY: number, bendDirection: number, alpha: number): void; + + } + + export class IkConstraintData { + + constructor(name: string); + + name: string; + bones: Bone[]; + target: Bone; + bendDirection: number; + mix: number; + + } + + export class IkConstraintTimeline implements Timeline { + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + ikConstraintIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class MeshAttachment implements Attachment { + + constructor(name: string); + + name: string; + type: number; + vertices: number[]; + uvs: number[] + regionUVs: number[] + triangles: number[] + hullLength: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionU: number; + regionV: number; + regionU2: number; + regionV2: number; + regionRotate: boolean; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + edges: number[]; + width: number; + height: number; + + updateUVs(): void; + computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; + + } + + export class RegionAttachment implements Attachment { + + constructor(name: string); + + name: string; + offset: number[]; + uvs: number[] + type: number; + x: number; + y: number; + rotation: number; + scaleX: number; + scaleY: number; + width: number; + height: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + + updateOffset(): void; + setUVs(u: number, v: number, u2: number, v2: number, rotate: number): void; + computeVertices(x: number, y: number, bone: Bone, vertices: number[]): void; + + } + + export class RotateTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class ScaleTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, mix: number, bendDirection: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Skeleton { + + constructor(skeletonData: SkeletonData); + + data: SkeletonData; + bones: Bone[]; + slots: Slot[]; + drawOrder: Slot[]; + ikConstraints: IkConstraint[]; + boneCache: Bone[][]; + x: number; + y: number; + skin: Skin; + r: number; + g: number; + b: number; + a: number; + time: number; + flipX: boolean; + flipY: boolean; + + updateCache(): void; + updateWorldTransform(): void; + setToSetupPose(): void; + setBonesToSetupPose(): void; + setSlotsToSetupPose(): void; + getRootBone(): Bone; + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + setSkinByName(skinName: string): Skin; + setSkin(newSkin: Skin): void; + getAttachmentBySlotName(slotName: string, attachmentName: string): Attachment; + getAttachmentBySlotIndex(slotIndex: number, attachmentName: string): Attachment + setAttachment(slotName: string, attachmentName: string): void; + findIkConstraint(ikConstraintName: string): IkConstraint; + update(delta: number): void; + resetDrawOrder(): void; + + } + + export class SkeletonBounds { + + polygonPool: Polygon[]; + polygons: Polygon[]; + boundingBoxes: BoundingBoxAttachment[]; + minX: number; + minY: number; + maxX: number; + maxY: number; + + update(skeleton: Skeleton, updateAabb: boolean): void; + aabbCompute(): void; + aabbContainsPoint(x: number, y: number): void; + aabbIntersectsSegment(x1: number, y1: number, x2: number, y2: number): boolean; + aabbIntersectsSkeleton(bounds: SkeletonBounds): boolean; + containsPoint(x: number, y: number): BoundingBoxAttachment; + intersectsSegment(x1: number, y1: number, x2: number, y2: number): BoundingBoxAttachment; + polygonContainsPoint(polygon: Polygon, x: number, y: number): boolean; + polygonIntersectsSegment(polygon: Polygon, x1: number, y1: number, x2: number, y2: number): boolean; + getPolygon(attachment: Attachment): Polygon; + getWidth(): number; + getHeight(): number; + + } + + export class SkeletonData { + + bones: Bone[]; + slots: Slot[]; + skins: Skin[]; + events: Event[]; + animations: Animation[]; + ikConstraints: IkConstraint[]; + name: string; + defaultSkin: Skin; + width: number; + height: number; + version: any; + hash: any; + + findBone(boneName: string): Bone; + findBoneIndex(boneName: string): number; + findSlot(slotName: string): Slot; + findSlotIndex(slotName: string): number; + findSkin(skinName: string): Skin; + findEvent(eventName: string): Event; + findAnimation(animationName: string): Animation + findIkConstraint(ikConstraintName: string): IkConstraint; + + } + + export class SkeletonJsonParser { + + constructor(attachmentLoader: any); + + attachmentLoader: any; + scale: number; + + readSkeletonData(root: Bone, name: string): void; + readAttachment(skin: Skin, name: string, map: any): void; + readAnimation(name: string, map: any, skeletonData: SkeletonData): void; + readCurve(timeline: Timeline, frameIndex: number, valueMap: any): void; + toColor(hexString: string, colorIndex: string): number; + getFloatArray(map: any, name: string, scale: number): number[]; + getIntArray(map: any, name: string): number[]; + + } + + export class Skin { + + constructor(name: string); + + name: string; + attachments: Attachment[]; + addAttachment(slotIndex: number, name: string, attachment: Attachment): void; + getAttachment(slotIndex: number, name: string): Attachment; + + protected _attachAll(skeleton: Skeleton, oldSkin: Skin): void; + + } + + export class SkinnedMeshAttachment implements Attachment { + + constructor(name: string); + + name: string; + type: number; + bones: number[]; + weights: number[]; + uvs: number[]; + regionUVs: number[]; + triangles: number[]; + hullLength: number; + r: number; + g: number; + b: number; + a: number; + path: string; + rendererObject: any; + regionU: number; + regionV: number; + regionU2: number; + regionV2: number; + regionRotate: boolean; + regionOffsetX: number; + regionOffsetY: number; + regionWidth: number; + regionHeight: number; + regionOriginalWidth: number; + regionOriginalHeight: number; + edges: number[]; + width: number; + height: number; + + updateUVs(u: number, v: number, u2: number, v2: number, rotate: boolean): void; + computeWorldVertices(x: number, y: number, slot: Slot, worldVertices: number[]): void; + + } + + export class Slot { + + constructor(slotData: SlotData, bone: Bone); + + data: SlotData; + bone: Bone; + r: number; + g: number; + b: number; + a: number; + _attachmentTime: number; + attachment: Attachment; + attachmentVertices: number[]; + setAttachment(attachment: Attachment): void; + setAttachmentTime(time: number): void; + getAttachmentTime(): number; + setToSetupPose(): void; + + } + + export class SlotData { + + constructor(name: string, boneData: BoneData); + + name: string; + boneData: BoneData; + + static PIXI_BLEND_MODE_MAP: { + multiply: number; + screen: number; + additive: number; + normal: number; + }; + r: number; + g: number; + b: number; + a: number; + attachmentName: string; + blendMode: number; + + } + + export class TrackEntry { + + next: TrackEntry; + previous: TrackEntry; + animation: Animation; + loop: boolean; + delay: number; + time: number; + lastTime: number; + endTime: number; + timeScale: number; + mixTime: number; + mixDuration: number; + mix: number; + onStart: (index: number) => void; + onEnd: (trackIndex: number) => void; + onComplete: (i: number, count: number) => void; + onEvent: (i: number, event: Event) => void; + + } + + export class TranslateTimeline implements Timeline { + + constructor(frameCount: number); + + curves: Curves[]; + frames: number[]; + boneIndex: number; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, x: number, y: number): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class Atlas { + + constructor(atlasText: string, baseUrl: string, crossOrigin: any); + + pages: AtlasPage[]; + regions: AtlasRegion[]; + texturesLoading: number; + + findRegion(name: string): AtlasRegion; + dispose(): void; + updateUVs(page: AtlasPage): void; + + Format: { + + alpha: number; + intensity: number; + luminanceAlpha: number; + rgb565: number; + rgba4444: number; + rgb888: number; + rgba8888: number; + + }; + + TextureFilter: { + + nearest: number; + linear: number; + mipMap: number; + mipMapNearestNearest: number; + mipMapLinearNearest: number; + mipMapNearestLinear: number; + mipMapLinearLinear: number; + + }; + + TextureWrap: { + + mirroredRepeat: number; + clampToEdge: number; + repeat: number; + + }; + + } + + export class AtlasAttachmentParser { + + constructor(atlas: Atlas); + + newRegionAttachment(skin: Skin, name: string, path: string): RegionAttachment; + newMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; + newSkinnedMeshAttachment(skin: Skin, name: string, path: string): SkinnedMeshAttachment; + newBoundingBoxAttachment(skin: Skin, name: string): BoundingBoxAttachment; + + } + + export class AtlasPage { + name: string; + format: any; + minFilter: any; + magFilter: any; + uWrap: any; + vWrap: any; + rendererObject: any; + width: number; + height: number; + + } + + export class AtlasReader { + constructor(text: string); + + lines: string[]; + index: number; + + trim(value: string): string; + readLine(): string; + readValue(): string; + readTuple(tuple: number): number; + + } + + export class AtlasRegion { + + page: AtlasPage; + name: string; + x: number; + y: number; + width: number; + height: number; + u: number; + v: number; + u2: number; + v2: number; + offsetX: number; + offsetY: number; + originalWidth: number; + originalHeight: number; + index: number; + rotate: boolean; + splits: any; + pads: any; + + + } + + export class AttachmentTimeline implements Timeline { + + constructor(frameCount: number); + + slotIndex: number; + frames: number[]; + attachmentNames: string[]; + + getFrameCount(): number; + setFrame(frameIndex: number, time: number, attachmentName: string): void; + apply(skeleton: Skeleton, lastTime: number, time: number, firedEvents: Event[], alpha: number): void; + + } + + export class atlasParser { + + constructor(resource: any, next: any); + + AnimCache: any; + enableCaching: boolean; + + } + + } + +} \ No newline at end of file From 2ee0d57fae6bb5a7a298a563da13233bb59f5fdf Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Fri, 31 Jul 2015 14:46:55 -0600 Subject: [PATCH 14/38] 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 9780c504d..d4e6376d6 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 65d2fd923..96c9d33c7 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/38] 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 000000000..6ddb05cc1 --- /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 000000000..85fb8fefc --- /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 000000000..9afccd474 --- /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 000000000..f00d25b1a --- /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/38] 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 000000000..f1e5d2d42 --- /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 000000000..3a55b7769 --- /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/38] 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 96c9d33c7..a0f948fe6 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/38] 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 14efc9c00..aee658f4d 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 ea93f2e70..c5602884d 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/38] 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 2b6caeddf..ef3909e9f 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 e514901e942ceb125f9a80051b7bba7ca0e6bd47 Mon Sep 17 00:00:00 2001 From: Guillaume Mouron Date: Sat, 8 Aug 2015 19:55:35 +0200 Subject: [PATCH 20/38] 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 af708cf0a..fc8e5a70f 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 21/38] 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 38bae0d57..92ce84a9d 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 b45ba637c..cd55bdfb1 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 7978766eb..19f686ef5 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 1b661d8fa..aca3cbee1 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 22/38] 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 eaefbf473..466fc33a1 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 6944fcceb..a5118a764 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 9adacf679010c3cedc50409c1bd280fa8582a021 Mon Sep 17 00:00:00 2001 From: Brian Surowiec Date: Mon, 10 Aug 2015 04:06:13 -0400 Subject: [PATCH 23/38] 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 9a5c1cd7c..efb63d006 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 6ed8be8e3..1a36d21a2 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 348f3e62bd158ab75aeae74ac5e31496503549f5 Mon Sep 17 00:00:00 2001 From: Jason Saelhof Date: Mon, 10 Aug 2015 09:17:57 -0600 Subject: [PATCH 24/38] 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 d4e6376d6..9780c504d 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 25/38] 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 6946da972..b25a31408 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 26/38] 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 3a55b7769..b92f24411 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 27/38] 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 896a2d60e..981f363b2 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 28/38] 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 210032f86..69a4f9152 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 cd21d77e9..8876f6981 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 29/38] 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 b92f24411..63bf7eaa0 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 3c6d22513e9a25b2660c6dc194bf37dad5d7332c Mon Sep 17 00:00:00 2001 From: Matija Grcic Date: Tue, 11 Aug 2015 10:00:59 +0100 Subject: [PATCH 30/38] 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 6ddb05cc1..d07d4d3a5 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 85fb8fefc..3954e5f54 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 784bd0eb526dbcd3cef8e69ea65aff486d3dae9b Mon Sep 17 00:00:00 2001 From: luckyllama Date: Tue, 11 Aug 2015 14:31:04 -0700 Subject: [PATCH 31/38] 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 b25a31408..523098423 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 f3c213e2e30881b38e9ec3a599df8db70baa099d Mon Sep 17 00:00:00 2001 From: Ilya Mochalov Date: Sun, 9 Aug 2015 19:38:14 +0500 Subject: [PATCH 32/38] 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 d36b5dfc4..b72ddddcb 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 7c4111746..b576ccd7e 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 33/38] 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 d36b5dfc4..c0a8c8547 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 7c4111746..8fb368f8b 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 34/38] 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 d36b5dfc4..f6048025e 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 7c4111746..7ea01692e 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 35/38] 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 d36b5dfc4..9ffe25897 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': '