Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Bret Little
2013-04-02 13:35:21 -06:00
201 changed files with 204414 additions and 11950 deletions

13
.gitignore vendored
View File

@@ -14,3 +14,16 @@
.DS_Store
_Resharper.DefinitelyTyped
bin
obj
Properties
# VIM backup files
*~
# test folder
!_infrastructure/tests/*
!_infrastructure/tests/*.js
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js

6
.travis.yml Normal file
View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- 0.8
notifications:
email: false

View File

@@ -0,0 +1,73 @@
/// <reference path="AzureMobileServicesClient.d.ts" />
//create base client istance and read properties
var client = new WindowsAzure.MobileServiceClient("your-azure-mobile-application-URL", "your-azure-application-KEY");
console.log("Azure application URL: " + client.applicationUrl);
console.log("Azure application KEY: " + client.applicationKey.replace(/./gi,'*')); //KEEP IT SECRET!!!
//user authentication, to make it work follow this guide: http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-users-html/?fb=it-it#add-authentication
if (client.currentUser === null) {
client.login("facebook")
.then((u: Microsoft.WindowsAzure.User) => alert(u.level))
.done(() => alert("USER: " + client.currentUser.userId),
(e) => alert("ERROR: " + e));
} else { client.logout(); }
//define an interface that map to server side Table data
interface TodoItem { id?: number; text?: string; complete?: bool; }
var data: TodoItem[];
var tableTodoItems = client.getTable('todoitem');
//read all data from server using Promise .then() and error handling in .done()
tableTodoItems.read()
.then((retList: TodoItem[]) => {
data = retList; return retList.length
})
.done((n: number) =>
alert(n + " items downloaded"), (e) => alert("ERROR: " + e));
//define simple handler used in callback calls for insert/update and delete
function handlerInsUpd(e, i) => { if (!e) data.push(<TodoItem> i); };
function handlerDelErr(e) => { if (e) alert("ERROR: " + e); }
//insert one data passing info in POST + custom data in QueryString + simple callback handler
tableTodoItems.insert({ text: 'hello world!', complete: false }, {timestamp: new Date()} , handlerInsUpd);
//update last item changing complete and calling simple handler when done
var todo = data.pop();
todo.complete = !todo.complete;
tableTodoItems.update(todo, null, handlerInsUpd)
//delete first item
tableTodoItems.del({ id: data[0].id },null).done(null, handlerDelErr)
//testing some simple Query fluent
var query = tableTodoItems.select('text', 'id')
.where({ complete: false })
.orderBy('text')
query.read().done(printOut); //Execute query remotly and return data filtered
//testing more complicated Query in composition with previous using function Predicate and Projection
var minlength = 15; //parameter value for filter Predicate
query.where(function (len: number) { return this.text != null && this.text.length > len }, minlength)
.orderByDescending('id').skip(2).take(3) //some other ordering and paging filters
.select(function () { return { abc: this.text + '|' + this.id }; }) //Projection
.read().done(printOut); //return 3 object {abd: 'ttttttttttttttt|ID'}
//function that printout the query result in JSON
function printOut(ret:any[]) {
if (!ret) console.log("NO DATA FOUND!")
else for (var i = 0; i < ret.length; i++) {
console.log(JSON.stringify(ret[i])); }
}

View File

@@ -0,0 +1,94 @@
// Type definitions for Microsoft.Windows.Azure.MobileService.Web-1.0.0
// Project: https://<your-azure-mobileservice-project>.azure-mobile.net/client/MobileServices.Web-1.0.0.min.js
// Definitions by: Morosinotto Daniele <https://github.com/dmorosinotto/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
module Microsoft.WindowsAzure {
// MobileServiceClient object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554219.aspx
interface MobileServiceClient {
new (applicationUrl: string, applicationKey: string): MobileServiceClient;
applicationUrl: string;
applicationKey: string;
currentUser: User;
//for provider:string use one of ProviderEnum: 'microsoftaccount', 'facebook', 'twitter', 'google'
login(provider: string, token: string, callback: (error: any, user: User) => void ): void;
login(provider: string, token: string): asyncPromise;
login(provider: string, callback: (error: any, user: User) => void ): void;
login(provider: string): asyncPromise;
logout(): void;
getTable(tableName: string): MobileServiceTable;
withFilter(serviceFilter: (request: any, next: (request: any, callback: (error:any, response: any) => void ) => void, callback: (error: any, response: any) => void ) => void ) : MobileServiceClient;
}
// User object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554220.aspx
interface User {
getIdentities(): any;// { [providerName: string]: { userId: string, accessToken: string, accessTokenSecret?: string }; };
accessTokens: any; // { [providerName: string]: string; }
level: string; //for level:string use one of LevelEnum: 'admin','anonymous','authenticated'
userId: string;
}
// Interface to Platform.async(func) => Platform.Promise based on code MobileServices.Web-1.0.0.js
interface asyncPromise {
then(onSuccess: (result: any) => any, onError?: (error: any) => any): asyncPromise;
done(onSuccess?: (result: any) => void , onError?: (error: any) => void ): void;
}
// MobileServiceTable object based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj554239.aspx
interface MobileServiceTable extends IQuery {
new (tableName: string, client: MobileServiceClient): MobileServiceTable;
getTableName(): string;
getMobileServiceClient(): MobileServiceClient;
insert(istance: any, paramsQS: Object, callback: (error: any, retInserted: any) => any): void;
insert(istance: any, paramsQS: Object): asyncPromise;
insert(istance: any): asyncPromise;
update(istance: any, paramsQS: Object, callback: (error: any, retUpdated: any) => any): void;
update(istance: any, paramsQS: Object): asyncPromise;
update(istance: any): asyncPromise;
lookup(id: number, paramsQS: Object, callback: (error: any, retValue: any) => any): void;
lookup(id: number, paramsQS: Object): asyncPromise;
lookup(id: number): asyncPromise;
del(istance: any, paramsQS: Object, callback: (error?: any) => void ): void;
del(istance: any, paramsQS: Object): asyncPromise;
del(istance: any): asyncPromise;
read(query: IQuery, paramsQS: Object, callback: (error: any, retValues: any) => any): void;
read(query: IQuery, paramsQS: Object): asyncPromise;
read(query: IQuery): asyncPromise;
read(): asyncPromise;
}
// Interface to describe Query object fluent creation based on Microsoft Azure documentation: http://msdn.microsoft.com/en-us/library/windowsazure/jj613353.aspx
interface IQuery {
read(paramsQS?: Object): asyncPromise;
orderBy(...propName: string[]): IQuery;
orderByDescending(...propName: string[]): IQuery;
select(...propNameSelected: string[]): IQuery;
select(funcProjectionFromThis: () => any): IQuery;
where(mapObjFilterCriteria: any): IQuery;
where(funcPredicateOnThis: (...qParams: any[]) => bool, ...qValues: any[]): IQuery;
skip(n: number): IQuery;
take(n: number): IQuery;
includeTotalCount(): IQuery;
//internals found looking into code MobileServices.Web-1.0.0.js
//new (tableName: string, context: any): IQuery;
//getComponents(): any;
//toOData(): string;
}
interface WindowsAzureStatic {
MobileServiceClient: MobileServiceClient;
}
}
declare var WindowsAzure: Microsoft.WindowsAzure.WindowsAzureStatic;

49
Q/Q-tests.ts Normal file
View File

@@ -0,0 +1,49 @@
/// <reference path="Q.d.ts" />
var delay = function (delay) {
var d = Q.defer();
setTimeout(d.resolve, delay);
return d.promise;
};
Q.when(delay(1000), function () {
console.log('Hello, World!');
});
var eventually = function (eventually) {
return Q.delay(eventually, 1000);
};
var x = Q.all([1, 2, 3].map(eventually));
Q.when(x, function (x) {
console.log(x);
});
Q.all([
eventually(10),
eventually(20)
])
.spread(function (x, y) {
console.log(x, y);
});
Q.fcall(function () { })
.then(function () { })
.then(function () { })
.then(function () { })
.then(function (value4) {
// Do something with value4
}, function (error) {
// Handle any error from step1 through step4
}).done();
Q.allResolved([])
.then(function (promises: Qpromise[]) {
promises.forEach(function (promise) {
if (promise.isFulfilled()) {
var value = promise.valueOf();
} else {
var exception = promise.valueOf().exception;
}
})
});

63
Q/Q.d.ts vendored Normal file
View File

@@ -0,0 +1,63 @@
// Type definitions for Q
// Project: https://github.com/kriskowal/q
// Definitions by: Barrie Nemetchek
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Qdeferred {
promise: Qpromise;
resolve(value: any): any;
reject(reason: any);
notify(value: any);
makeNodeResolver(): Function;
}
interface Qpromise {
fail(errorCallback: Function): Qpromise;
fin(finallyCallback: Function): Qpromise;
then(onFulfilled: Function, onRejected?: Function, onProgress?: Function): Qpromise;
spread(onFulfilled: Function, onRejected?: Function): Qpromise;
catch(onRejected: Function): Qpromise;
progress(onProgress: Function): Qpromise;
done(onFulfilled?: Function, onRejected?: Function, onProgress?: Function): Qpromise;
get (propertyName: String): Qpromise;
set (propertyName: String, value: any): Qpromise;
delete (propertyName: String): Qpromise;
post(methodName: String, args: any[]): Qpromise;
invoke(methodName: String, ...args: any[]): Qpromise;
keys(): Qpromise;
fapply(args: any[]): Qpromise;
fcall(method: Function, ...args: any[]): Qpromise;
timeout(ms: number): Qpromise;
delay(ms: number): Qpromise;
isFulfilled(): bool;
isRejected(): bool;
isPending(): bool;
valueOf(): any;
}
interface QStatic {
when(value: any, onFulfilled: Function, onRejected?: Function): Qpromise;
try(method: Function, ...args: any[]): Qpromise;
fbind(method: Function, ...args: any[]): Qpromise;
fcall(method: Function, ...args: any[]): Qpromise;
all(promises: Qpromise[]): Qpromise;
allResolved(promises: Qpromise[]): Qpromise;
spread(onFulfilled: Function, onRejected: Function): Qpromise;
timeout(ms: number): Qpromise;
delay(ms: number): Qpromise;
delay(value: any, ms: number): Qpromise;
isFulfilled(): bool;
isRejected(): bool;
isPending(): bool;
valueOf(): any;
defer(): Qdeferred;
(value: any): Qpromise;
reject(): Qpromise;
promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise;
isPromise(value: any): bool;
async(generatorFunction: any): Qdeferred;
nextTick(callback: Function);
oneerror: any;
longStackJumpLimit: number;
}
declare var Q: QStatic;

75
Q/q.module-tests.ts Normal file
View File

@@ -0,0 +1,75 @@
/// <reference path="q.module.d.ts" />
/// <reference path="../jasmine/jasmine.d.ts" />
import Q = module("q");
describe("q", function () {
it("should return", function (done) {
Q({ myValue: true }).then(function (obj) {
if (obj.myValue) done();
else done("didn't work =(");
},
(err) => done(err));
});
it("should process all", function (done: (err?) => void ) {
Q.all([Q(1), Q(2), Q(3)]).then(function (arr: number[]) {
var sum = arr.reduce(function (memo, cur) {
return memo + cur;
}, 0);
if (sum === 6) done();
else done({ actual: sum });
},
(err) => done(err));
});
});
var delay = function (delay) {
var d = Q.defer();
setTimeout(d.resolve, delay);
return d.promise;
};
Q.when(delay(1000), function () {
console.log('Hello, World!');
});
var eventually = function (eventually) {
return Q.delay(eventually, 1000);
};
var x = Q.all([1, 2, 3].map(eventually));
Q.when(x, function (x) {
console.log(x);
});
Q.all([
eventually(10),
eventually(20)
])
.spread(function (x, y) {
console.log(x, y);
});
Q.fcall(function () { })
.then(function () { })
.then(function () { })
.then(function () { })
.then(function (value4) {
// Do something with value4
}, function (error) {
// Handle any error from step1 through step4
}).done();
Q.allResolved([])
.then(function (promises: Qpromise[]) {
promises.forEach(function (promise) {
if (promise.isFulfilled()) {
var value = promise.valueOf();
} else {
var exception = promise.valueOf().exception;
}
})
});

27
Q/q.module.d.ts vendored Normal file
View File

@@ -0,0 +1,27 @@
/// <reference path="Q.d.ts" />
module "q" {
export function when(value: any, onFulfilled: Function, onRejected?: Function): Qpromise;
export function try(method: Function, ...args: any[]): Qpromise;
export function fbind(method: Function, ...args: any[]): Qpromise;
export function fcall(method: Function, ...args: any[]): Qpromise;
export function all(promises: Qpromise[]): Qpromise;
export function allResolved(promises: Qpromise[]): Qpromise;
export function spread(onFulfilled: Function, onRejected: Function): Qpromise;
export function timeout(ms: number): Qpromise;
export function delay(ms: number): Qpromise;
export function delay(value: any, ms: number): Qpromise;
export function isFulfilled(): bool;
export function isRejected(): bool;
export function isPending(): bool;
export function valueOf(): any;
export function defer(): Qdeferred;
export function (value: any): Qpromise;
export function reject(): Qpromise;
export function promise(factory: { resolve: Function; reject: Function; notify: Function; }): Qpromise;
export function isPromise(value: any): bool;
export function async(generatorFunction: any): Qdeferred;
export function nextTick(callback: Function);
export var oneerror: any;
export var longStackJumpLimit: number;
}

311
README.md
View File

@@ -1,142 +1,169 @@
DefinitelyTyped
===============
The repository for *high quality* TypeScript type definitions.
Use a definition file like this:
```
/// <reference path="jquery.d.ts" />
```
Contributor Guidelines
----------------------
Definition files should be called 'library.d.ts'.
In case there are multiple versions supported, the latest one will be without a version number in the file name.
Older versions will be in the form of 'library-1.0.d.ts'.
Test files called 'library-tests.ts'.
They are not runnable, in the TDD way.
They contain code that should compile with no errors, usually taken from the documentation.samples of the library.
It is very desirable each new contribution to contain tests too.
Other means to get the definitions
----------------------------------
[TypeScript definition package manager](https://github.com/Diullei/tsd)
NuGet package(s) coming soon
List of Definitions
-------------------
* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/))
* [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov))
* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov))
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber))
* [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon))
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton))
* [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/))
* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog))
* [History.js](https://github.com/balupton/History.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dániel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos))
* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/))
* [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode))
* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon))
* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm))
* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.jNotify]( http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/))
* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/))
* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit))
* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel](https://github.com/JudahGabriel))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
* [Knockout.Viewmodel](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder))
* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr))
* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov))
* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/))
* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov))
* [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH))
* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/))
* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei))
* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov))
* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev))
* [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov))
* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com))
* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov))
* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos))
* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac))
* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov))
* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42))
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov))
* [ZeroClipboard] (https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith] (https://github.com/ejsmith))
Requested Definitions
---------------------
* [Rickshaw](https://github.com/shutterstock/rickshaw)
* [Crossfilter](https://github.com/square/crossfilter)
* [dc.js](https://github.com/NickQiZhu/dc.js)
* [store.js](https://github.com/marcuswestin/store.js)
* [google.visualizations](https://developers.google.com/chart/)
* [Tags Manager](http://welldonethings.com/tags/manager)
* [jsoneditoronline](https://github.com/wjosdejong/jsoneditoronline)
* [Tags Manager](http://welldonethings.com/tags/manager)
* [Prelude.ls](http://gkz.github.com/prelude-ls/)
* [MooTools](http://mootools.net/)
* [Lo-Dash](http://lodash.com/)
DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
===============
The repository for *high quality* TypeScript type definitions.
Use a definition file like this:
```
/// <reference path="jquery.d.ts" />
```
Contributor Guidelines
----------------------
See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute)
Other means to get the definitions
----------------------------------
* [NuGet packages](http://nuget.org/packages?q=Definitelytyped)
* [TypeScript definition package manager](https://github.com/Diullei/tsd)
* [tsdpm](http://www.tsdpm.com/) - Online search
List of Definitions
-------------------
* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei))
* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/))
* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/))
* [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov))
* [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) (by [Blake Niemyjski](https://github.com/niemyjski))
* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov))
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber))
* [CodeMirror](http://codemirror.net) (by [Fran<EFBFBD>ois de Campredon](https://github.com/fdecampredon))
* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem))
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton))
* [dust](http://linkedin.github.com/dustjs) (by [Marcelo Dezem](https://github.com/mdezem))
* [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/))
* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov))
* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/))
* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei))
* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/))
* [glDatePicker](http://glad.github.com/glDatePicker/) (by [D<EFBFBD>niel Tar](https://github.com/qcz))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper))
* [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog))
* [History.js](https://github.com/balupton/History.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov))
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [D<EFBFBD>niel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos))
* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/))
* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/))
* [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode))
* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [Fran<EFBFBD>ois Guillot](http://fguillot.developpez.com/))
* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [Fran<EFBFBD>ois de Campredon](https://github.com/fdecampredon))
* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm))
* [jQuery.form](http://malsup.com/jquery/form/) (by [Fran<EFBFBD>ois Guillot](http://fguillot.developpez.com/))
* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/))
* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/))
* [jQuery.timeago](http://timeago.yarp.com/) (by [Fran<EFBFBD>ois Guillot](http://fguillot.developpez.com/))
* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/))
* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit))
* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel](https://github.com/JudahGabriel))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
* [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising))
* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper))
* [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon))
* [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder))
* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone] (https://github.com/vbortone))
* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr))
* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield))
* [Mousetrap](http://craig.is/killing/mice) (by [D<EFBFBD>niel Tar](https://github.com/qcz))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov))
* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/))
* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov))
* [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH))
* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/))
* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei))
* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle))
* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov))
* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev))
* [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone))
* [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov))
* [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone))
* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com))
* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/))
* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov))
* [trunk8](https://github.com/rviscomi/trunk8) (by [Blake Niemyjski](https://github.com/niemyjski))
* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos))
* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac))
* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau))
* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov))
* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42))
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov))
* [ZeroClipboard](https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith](https://github.com/ejsmith))
Requested Definitions
---------------------
* [Rickshaw](https://github.com/shutterstock/rickshaw)
* [jQuery ScrollTo](https://github.com/balupton/jquery-scrollto)
* [Crossfilter](https://github.com/square/crossfilter)
* [dc.js](https://github.com/NickQiZhu/dc.js)
* [google.visualizations](https://developers.google.com/chart/)
* [Prelude.ls](http://gkz.github.com/prelude-ls/)
* [MooTools](http://mootools.net/)
* [Lo-Dash](http://lodash.com/)
* [java](https://github.com/nearinfinity/node-java)

View File

@@ -0,0 +1,57 @@
var ExecResult = (function () {
function ExecResult() {
this.stdout = "";
this.stderr = "";
}
return ExecResult;
})();
var WindowsScriptHostExec = (function () {
function WindowsScriptHostExec() { }
WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch (e) {
result.stderr = e.message;
result.exitCode = 1;
handleResult(result);
return;
}
while(process.Status != 0) {
}
result.exitCode = process.ExitCode;
if(!process.StdOut.AtEndOfStream) {
result.stdout = process.StdOut.ReadAll();
}
if(!process.StdErr.AtEndOfStream) {
result.stderr = process.StdErr.ReadAll();
}
handleResult(result);
};
return WindowsScriptHostExec;
})();
var NodeExec = (function () {
function NodeExec() { }
NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
};
return NodeExec;
})();
var Exec = (function () {
var global = Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
})();

View File

@@ -0,0 +1,77 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Allows for executing a program with command-line arguments and reading the result
interface IExec {
exec: (filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) => void;
}
declare var require;
class ExecResult {
public stdout = "";
public stderr = "";
public exitCode: number;
}
class WindowsScriptHostExec implements IExec {
public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch(e) {
result.stderr = e.message;
result.exitCode = 1
handleResult(result);
return;
}
// Wait for it to finish running
while (process.Status != 0) { /* todo: sleep? */ }
result.exitCode = process.ExitCode;
if(!process.StdOut.AtEndOfStream) result.stdout = process.StdOut.ReadAll();
if(!process.StdErr.AtEndOfStream) result.stderr = process.StdErr.ReadAll();
handleResult(result);
}
}
class NodeExec implements IExec {
public exec(filename: string, cmdLineArgs: string[], handleResult: (ExecResult) => void) : void {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
}
}
var Exec: IExec = function() : IExec {
var global = <any>Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
}();

View File

@@ -0,0 +1,425 @@
var IOUtils;
(function (IOUtils) {
function createDirectoryStructure(ioHost, dirName) {
if(ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if(parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
function createFileAndFolderStructure(ioHost, fileName, useUTF8) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
IOUtils.createFileAndFolderStructure = createFileAndFolderStructure;
function throwIOError(message, error) {
var errorMessage = message;
if(error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
IOUtils.throwIOError = throwIOError;
})(IOUtils || (IOUtils = {}));
var IO = (function () {
function getWindowsScriptHostIO() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject() {
if(streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj) {
streamObjectPool.push(obj);
}
var args = [];
for(var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function (path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2;
streamObj.Charset = 'x-ansi';
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2);
streamObj.Position = 0;
if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) {
streamObj.Charset = 'unicode';
} else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) {
streamObj.Charset = 'utf-8';
}
var str = streamObj.ReadText(-1);
streamObj.Close();
releaseStreamObject(streamObj);
return str;
} catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function (path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function (path) {
return fso.FileExists(path);
},
resolvePath: function (path) {
return fso.GetAbsolutePathName(path);
},
dirName: function (path) {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath, partialFilePath) {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while(true) {
if(fso.FileExists(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if(rootPath == "") {
return null;
} else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path) {
try {
if(fso.FileExists(path)) {
fso.DeleteFile(path, true);
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) {
streamObj.WriteText(str, 0);
},
WriteLine: function (str) {
streamObj.WriteText(str, 1);
},
Close: function () {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
}finally {
if(streamObj.State != 0) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function (path) {
return fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function (path, spec, options) {
options = options || {
};
function filesInFolder(folder, root) {
var paths = [];
var fc;
if(options.recursive) {
fc = new Enumerator(folder.subfolders);
for(; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for(; !fc.atEnd(); fc.moveNext()) {
if(!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function (source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode) {
if (typeof exitCode === "undefined") { exitCode = 0; }
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
};
}
;
function getNodeIO() {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function (file) {
try {
var buffer = _fs.readFileSync(file);
switch(buffer[0]) {
case 254:
if(buffer[1] == 255) {
var i = 0;
while((i + 1) < buffer.length) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 255:
if(buffer[1] == 254) {
return buffer.toString("ucs2", 2);
}
break;
case 239:
if(buffer[1] == 187) {
return buffer.toString("utf8", 3);
}
}
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: _fs.writeFileSync,
deleteFile: function (path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function (path) {
return _fs.existsSync(path);
},
createFile: function (path, useUTF8) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if(stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if(stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function (str) {
_fs.writeSync(fd, str);
},
WriteLine: function (str) {
_fs.writeSync(fd, str + '\r\n');
},
Close: function () {
_fs.closeSync(fd);
fd = null;
}
};
},
dir: function dir(path, spec, options) {
options = options || {
};
function filesInFolder(folder) {
var paths = [];
var files = _fs.readdirSync(folder);
for(var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if(options.recursive && stat.isDirectory()) {
paths = paths.concat(filesInFolder(folder + "/" + files[i]));
} else if(stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function (path) {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function (path) {
return _path.resolve(path);
},
dirName: function (path) {
return _path.dirname(path);
},
findFile: function (rootPath, partialFilePath) {
var path = rootPath + "/" + partialFilePath;
while(true) {
if(_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
var parentPath = _path.resolve(rootPath, "..");
if(rootPath === parentPath) {
return null;
} else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function (str) {
process.stdout.write(str);
},
printLine: function (str) {
process.stdout.write(str + '\n');
},
arguments: process.argv.slice(2),
stderr: {
Write: function (str) {
process.stderr.write(str);
},
WriteLine: function (str) {
process.stderr.write(str + '\n');
},
Close: function () {
}
},
stdout: {
Write: function (str) {
process.stdout.write(str);
},
WriteLine: function (str) {
process.stdout.write(str + '\n');
},
Close: function () {
}
},
watchFile: function (filename, callback) {
var firstRun = true;
var processingChange = false;
var fileChanged = function (curr, prev) {
if(!firstRun) {
if(curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if(!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function () {
processingChange = false;
}, 100);
}
}
firstRun = false;
_fs.watchFile(filename, {
persistent: true,
interval: 500
}, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function () {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function (source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
};
}
;
if(typeof ActiveXObject === "function") {
return getWindowsScriptHostIO();
} else if(typeof require === "function") {
return getNodeIO();
} else {
return null;
}
})();

View File

@@ -0,0 +1,525 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
interface IResolvedFile {
content: string;
path: string;
}
interface IFileWatcher {
close(): void;
}
interface IIO {
readFile(path: string): string;
writeFile(path: string, contents: string): void;
createFile(path: string, useUTF8?: bool): ITextWriter;
deleteFile(path: string): void;
dir(path: string, re?: RegExp, options?: { recursive?: bool; deep?: number; }): string[];
fileExists(path: string): bool;
directoryExists(path: string): bool;
createDirectory(path: string): void;
resolvePath(path: string): string;
dirName(path: string): string;
findFile(rootPath: string, partialFilePath: string): IResolvedFile;
print(str: string): void;
printLine(str: string): void;
arguments: string[];
stderr: ITextWriter;
stdout: ITextWriter;
watchFile(filename: string, callback: (string) => void ): IFileWatcher;
run(source: string, filename: string): void;
getExecutingFilePath(): string;
quit(exitCode?: number);
}
module IOUtils {
// Creates the directory including its parent if not already present
function createDirectoryStructure(ioHost: IIO, dirName: string) {
if (ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if (parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
// Creates a file including its directory structure if not already present
export function createFileAndFolderStructure(ioHost: IIO, fileName: string, useUTF8?: bool) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
export function throwIOError(message: string, error: Error) {
var errorMessage = message;
if (error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
}
// Declare dependencies needed for all supported hosts
declare class Enumerator {
public atEnd(): bool;
public moveNext();
public item(): any;
constructor (o: any);
}
declare function setTimeout(callback: () =>void , ms?: number);
declare var require: any;
declare module process {
export var argv: string[];
export var platform: string;
export function on(event: string, handler: (any) => void ): void;
export module stdout {
export function write(str: string);
}
export module stderr {
export function write(str: string);
}
export module mainModule {
export var filename: string;
}
export function exit(exitCode?: number);
}
var IO = (function() {
// Create an IO object for use inside WindowsScriptHost hosts
// Depends on WSCript and FileSystemObject
function getWindowsScriptHostIO(): IIO {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject(): any {
if (streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj: any) {
streamObjectPool.push(obj);
}
var args = [];
for (var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function(path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2; // Text data
streamObj.Charset = 'x-ansi'; // Assume we are reading ansi text
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2); // Read the BOM char
streamObj.Position = 0; // Position has to be at 0 before changing the encoding
if ((bomChar.charCodeAt(0) == 0xFE && bomChar.charCodeAt(1) == 0xFF)
|| (bomChar.charCodeAt(0) == 0xFF && bomChar.charCodeAt(1) == 0xFE)) {
streamObj.Charset = 'unicode';
} else if (bomChar.charCodeAt(0) == 0xEF && bomChar.charCodeAt(1) == 0xBB) {
streamObj.Charset = 'utf-8';
}
// Read the whole file
var str = streamObj.ReadText(-1 /* read from the current position to EOS */);
streamObj.Close();
releaseStreamObject(streamObj);
return <string>str;
}
catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function(path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function(path: string): bool {
return fso.FileExists(path);
},
resolvePath: function(path: string): string {
return fso.GetAbsolutePathName(path);
},
dirName: function(path: string): string {
return fso.GetParentFolderName(path);
},
findFile: function(rootPath: string, partialFilePath: string): IResolvedFile {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while (true) {
if (fso.FileExists(path)) {
try {
var content = this.readFile(path);
return { content: content, path: path };
}
catch (err) {
//Tools.CompilerDiagnostics.debugPrint("Could not find " + path + ", trying parent");
}
}
else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if (rootPath == "") {
return null;
}
else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function(path: string): void {
try {
if (fso.FileExists(path)) {
fso.DeleteFile(path, true); // true: delete read-only files
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8?) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) { streamObj.WriteText(str, 0); },
WriteLine: function (str) { streamObj.WriteText(str, 1); },
Close: function() {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
}
finally {
if (streamObj.State != 0 /*adStateClosed*/) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function(path) {
return <bool>fso.FolderExists(path);
},
createDirectory: function(path) {
try {
if (!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function(path, spec?, options?) {
options = options || <{ recursive?: bool; deep?: number; }>{};
function filesInFolder(folder, root): string[]{
var paths = [];
var fc: Enumerator;
if (options.recursive) {
fc = new Enumerator(folder.subfolders);
for (; !fc.atEnd() ; fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for (; !fc.atEnd() ; fc.moveNext()) {
if (!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function(str) {
WScript.StdOut.Write(str);
},
printLine: function(str) {
WScript.Echo(str);
},
arguments: <string[]>args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function(source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode? : number = 0) {
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
}
};
// Create an IO object for use inside Node.js hosts
// Depends on 'fs' and 'path' modules
function getNodeIO(): IIO {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function(file) {
try {
var buffer = _fs.readFileSync(file);
switch (buffer[0]) {
case 0xFE:
if (buffer[1] == 0xFF) {
// utf16-be. Reading the buffer as big endian is not supported, so convert it to
// Little Endian first
var i = 0;
while ((i + 1) < buffer.length) {
var temp = buffer[i]
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 0xFF:
if (buffer[1] == 0xFE) {
// utf16-le
return buffer.toString("ucs2", 2);
}
break;
case 0xEF:
if (buffer[1] == 0xBB) {
// utf-8
return buffer.toString("utf8", 3);
}
}
// Default behaviour
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: <(path: string, contents: string) => void >_fs.writeFileSync,
deleteFile: function(path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function(path): bool {
return _fs.existsSync(path);
},
createFile: function(path, useUTF8?) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if (stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if (stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 0775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function(str) { _fs.writeSync(fd, str); },
WriteLine: function(str) { _fs.writeSync(fd, str + '\r\n'); },
Close: function() { _fs.closeSync(fd); fd = null; }
};
},
dir: function dir(path, spec?, options?) {
options = options || <{ recursive?: bool; deep?: number; }>{};
function filesInFolder(folder: string, deep?: number): string[]{
var paths = [];
var files = _fs.readdirSync(folder);
for (var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if (options.recursive && stat.isDirectory()) {
if (deep < (options.deep || 100)) {
paths = paths.concat(filesInFolder(folder + "/" + files[i], 1));
}
} else if (stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path, 0);
},
createDirectory: function(path: string): void {
try {
if (!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function(path: string): bool {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function(path: string): string {
return _path.resolve(path);
},
dirName: function(path: string): string {
return _path.dirname(path);
},
findFile: function(rootPath: string, partialFilePath): IResolvedFile {
var path = rootPath + "/" + partialFilePath;
while (true) {
if (_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return { content: content, path: path };
} catch (err) {
//Tools.CompilerDiagnostics.debugPrint(("Could not find " + path) + ", trying parent");
}
}
else {
var parentPath = _path.resolve(rootPath, "..");
// Node will just continue to repeat the root path, rather than return null
if (rootPath === parentPath) {
return null;
}
else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function(str) { process.stdout.write(str) },
printLine: function(str) { process.stdout.write(str + '\n') },
arguments: process.argv.slice(2),
stderr: {
Write: function(str) { process.stderr.write(str); },
WriteLine: function(str) { process.stderr.write(str + '\n'); },
Close: function() { }
},
stdout: {
Write: function(str) { process.stdout.write(str); },
WriteLine: function(str) { process.stdout.write(str + '\n'); },
Close: function() { }
},
watchFile: function(filename: string, callback: (string) => void ): IFileWatcher {
var firstRun = true;
var processingChange = false;
var fileChanged: any = function(curr, prev) {
if (!firstRun) {
if (curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if (!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function() { processingChange = false; }, 100);
}
}
firstRun = false;
_fs.watchFile(filename, { persistent: true, interval: 500 }, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function() {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function(source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
}
};
if (typeof ActiveXObject === "function")
return getWindowsScriptHostIO();
else if (typeof require === "function")
return getNodeIO();
else
return null; // Unsupported host
})();

View File

@@ -0,0 +1,619 @@
var ExecResult = (function () {
function ExecResult() {
this.stdout = "";
this.stderr = "";
}
return ExecResult;
})();
var WindowsScriptHostExec = (function () {
function WindowsScriptHostExec() { }
WindowsScriptHostExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var result = new ExecResult();
var shell = new ActiveXObject('WScript.Shell');
try {
var process = shell.Exec(filename + ' ' + cmdLineArgs.join(' '));
} catch (e) {
result.stderr = e.message;
result.exitCode = 1;
handleResult(result);
return;
}
while(process.Status != 0) {
}
result.exitCode = process.ExitCode;
if(!process.StdOut.AtEndOfStream) {
result.stdout = process.StdOut.ReadAll();
}
if(!process.StdErr.AtEndOfStream) {
result.stderr = process.StdErr.ReadAll();
}
handleResult(result);
};
return WindowsScriptHostExec;
})();
var NodeExec = (function () {
function NodeExec() { }
NodeExec.prototype.exec = function (filename, cmdLineArgs, handleResult) {
var nodeExec = require('child_process').exec;
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
var process = nodeExec(cmdLine, function (error, stdout, stderr) {
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
handleResult(result);
});
};
return NodeExec;
})();
var Exec = (function () {
var global = Function("return this;").call(null);
if(typeof global.ActiveXObject !== "undefined") {
return new WindowsScriptHostExec();
} else {
return new NodeExec();
}
})();
var IOUtils;
(function (IOUtils) {
function createDirectoryStructure(ioHost, dirName) {
if(ioHost.directoryExists(dirName)) {
return;
}
var parentDirectory = ioHost.dirName(dirName);
if(parentDirectory != "") {
createDirectoryStructure(ioHost, parentDirectory);
}
ioHost.createDirectory(dirName);
}
function createFileAndFolderStructure(ioHost, fileName, useUTF8) {
var path = ioHost.resolvePath(fileName);
var dirName = ioHost.dirName(path);
createDirectoryStructure(ioHost, dirName);
return ioHost.createFile(path, useUTF8);
}
IOUtils.createFileAndFolderStructure = createFileAndFolderStructure;
function throwIOError(message, error) {
var errorMessage = message;
if(error && error.message) {
errorMessage += (" " + error.message);
}
throw new Error(errorMessage);
}
IOUtils.throwIOError = throwIOError;
})(IOUtils || (IOUtils = {}));
var IO = (function () {
function getWindowsScriptHostIO() {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var streamObjectPool = [];
function getStreamObject() {
if(streamObjectPool.length > 0) {
return streamObjectPool.pop();
} else {
return new ActiveXObject("ADODB.Stream");
}
}
function releaseStreamObject(obj) {
streamObjectPool.push(obj);
}
var args = [];
for(var i = 0; i < WScript.Arguments.length; i++) {
args[i] = WScript.Arguments.Item(i);
}
return {
readFile: function (path) {
try {
var streamObj = getStreamObject();
streamObj.Open();
streamObj.Type = 2;
streamObj.Charset = 'x-ansi';
streamObj.LoadFromFile(path);
var bomChar = streamObj.ReadText(2);
streamObj.Position = 0;
if((bomChar.charCodeAt(0) == 254 && bomChar.charCodeAt(1) == 255) || (bomChar.charCodeAt(0) == 255 && bomChar.charCodeAt(1) == 254)) {
streamObj.Charset = 'unicode';
} else if(bomChar.charCodeAt(0) == 239 && bomChar.charCodeAt(1) == 187) {
streamObj.Charset = 'utf-8';
}
var str = streamObj.ReadText(-1);
streamObj.Close();
releaseStreamObject(streamObj);
return str;
} catch (err) {
IOUtils.throwIOError("Error reading file \"" + path + "\".", err);
}
},
writeFile: function (path, contents) {
var file = this.createFile(path);
file.Write(contents);
file.Close();
},
fileExists: function (path) {
return fso.FileExists(path);
},
resolvePath: function (path) {
return fso.GetAbsolutePathName(path);
},
dirName: function (path) {
return fso.GetParentFolderName(path);
},
findFile: function (rootPath, partialFilePath) {
var path = fso.GetAbsolutePathName(rootPath) + "/" + partialFilePath;
while(true) {
if(fso.FileExists(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
rootPath = fso.GetParentFolderName(fso.GetAbsolutePathName(rootPath));
if(rootPath == "") {
return null;
} else {
path = fso.BuildPath(rootPath, partialFilePath);
}
}
}
},
deleteFile: function (path) {
try {
if(fso.FileExists(path)) {
fso.DeleteFile(path, true);
}
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
createFile: function (path, useUTF8) {
try {
var streamObj = getStreamObject();
streamObj.Charset = useUTF8 ? 'utf-8' : 'x-ansi';
streamObj.Open();
return {
Write: function (str) {
streamObj.WriteText(str, 0);
},
WriteLine: function (str) {
streamObj.WriteText(str, 1);
},
Close: function () {
try {
streamObj.SaveToFile(path, 2);
} catch (saveError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", saveError);
}finally {
if(streamObj.State != 0) {
streamObj.Close();
}
releaseStreamObject(streamObj);
}
}
};
} catch (creationError) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", creationError);
}
},
directoryExists: function (path) {
return fso.FolderExists(path);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
fso.CreateFolder(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
dir: function (path, spec, options) {
options = options || {
};
function filesInFolder(folder, root) {
var paths = [];
var fc;
if(options.recursive) {
fc = new Enumerator(folder.subfolders);
for(; !fc.atEnd(); fc.moveNext()) {
paths = paths.concat(filesInFolder(fc.item(), root + "/" + fc.item().Name));
}
}
fc = new Enumerator(folder.files);
for(; !fc.atEnd(); fc.moveNext()) {
if(!spec || fc.item().Name.match(spec)) {
paths.push(root + "/" + fc.item().Name);
}
}
return paths;
}
var folder = fso.GetFolder(path);
var paths = [];
return filesInFolder(folder, path);
},
print: function (str) {
WScript.StdOut.Write(str);
},
printLine: function (str) {
WScript.Echo(str);
},
arguments: args,
stderr: WScript.StdErr,
stdout: WScript.StdOut,
watchFile: null,
run: function (source, filename) {
try {
eval(source);
} catch (e) {
IOUtils.throwIOError("Error while executing file '" + filename + "'.", e);
}
},
getExecutingFilePath: function () {
return WScript.ScriptFullName;
},
quit: function (exitCode) {
if (typeof exitCode === "undefined") { exitCode = 0; }
try {
WScript.Quit(exitCode);
} catch (e) {
}
}
};
}
;
function getNodeIO() {
var _fs = require('fs');
var _path = require('path');
var _module = require('module');
return {
readFile: function (file) {
try {
var buffer = _fs.readFileSync(file);
switch(buffer[0]) {
case 254:
if(buffer[1] == 255) {
var i = 0;
while((i + 1) < buffer.length) {
var temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
i += 2;
}
return buffer.toString("ucs2", 2);
}
break;
case 255:
if(buffer[1] == 254) {
return buffer.toString("ucs2", 2);
}
break;
case 239:
if(buffer[1] == 187) {
return buffer.toString("utf8", 3);
}
}
return buffer.toString();
} catch (e) {
IOUtils.throwIOError("Error reading file \"" + file + "\".", e);
}
},
writeFile: _fs.writeFileSync,
deleteFile: function (path) {
try {
_fs.unlinkSync(path);
} catch (e) {
IOUtils.throwIOError("Couldn't delete file '" + path + "'.", e);
}
},
fileExists: function (path) {
return _fs.existsSync(path);
},
createFile: function (path, useUTF8) {
function mkdirRecursiveSync(path) {
var stats = _fs.statSync(path);
if(stats.isFile()) {
IOUtils.throwIOError("\"" + path + "\" exists but isn't a directory.", null);
} else if(stats.isDirectory()) {
return;
} else {
mkdirRecursiveSync(_path.dirname(path));
_fs.mkdirSync(path, 775);
}
}
mkdirRecursiveSync(_path.dirname(path));
try {
var fd = _fs.openSync(path, 'w');
} catch (e) {
IOUtils.throwIOError("Couldn't write to file '" + path + "'.", e);
}
return {
Write: function (str) {
_fs.writeSync(fd, str);
},
WriteLine: function (str) {
_fs.writeSync(fd, str + '\r\n');
},
Close: function () {
_fs.closeSync(fd);
fd = null;
}
};
},
dir: function dir(path, spec, options) {
options = options || {
};
function filesInFolder(folder, deep) {
var paths = [];
var files = _fs.readdirSync(folder);
for(var i = 0; i < files.length; i++) {
var stat = _fs.statSync(folder + "/" + files[i]);
if(options.recursive && stat.isDirectory()) {
if(deep < (options.deep || 100)) {
paths = paths.concat(filesInFolder(folder + "/" + files[i], 1));
}
} else if(stat.isFile() && (!spec || files[i].match(spec))) {
paths.push(folder + "/" + files[i]);
}
}
return paths;
}
return filesInFolder(path, 0);
},
createDirectory: function (path) {
try {
if(!this.directoryExists(path)) {
_fs.mkdirSync(path);
}
} catch (e) {
IOUtils.throwIOError("Couldn't create directory '" + path + "'.", e);
}
},
directoryExists: function (path) {
return _fs.existsSync(path) && _fs.lstatSync(path).isDirectory();
},
resolvePath: function (path) {
return _path.resolve(path);
},
dirName: function (path) {
return _path.dirname(path);
},
findFile: function (rootPath, partialFilePath) {
var path = rootPath + "/" + partialFilePath;
while(true) {
if(_fs.existsSync(path)) {
try {
var content = this.readFile(path);
return {
content: content,
path: path
};
} catch (err) {
}
} else {
var parentPath = _path.resolve(rootPath, "..");
if(rootPath === parentPath) {
return null;
} else {
rootPath = parentPath;
path = _path.resolve(rootPath, partialFilePath);
}
}
}
},
print: function (str) {
process.stdout.write(str);
},
printLine: function (str) {
process.stdout.write(str + '\n');
},
arguments: process.argv.slice(2),
stderr: {
Write: function (str) {
process.stderr.write(str);
},
WriteLine: function (str) {
process.stderr.write(str + '\n');
},
Close: function () {
}
},
stdout: {
Write: function (str) {
process.stdout.write(str);
},
WriteLine: function (str) {
process.stdout.write(str + '\n');
},
Close: function () {
}
},
watchFile: function (filename, callback) {
var firstRun = true;
var processingChange = false;
var fileChanged = function (curr, prev) {
if(!firstRun) {
if(curr.mtime < prev.mtime) {
return;
}
_fs.unwatchFile(filename, fileChanged);
if(!processingChange) {
processingChange = true;
callback(filename);
setTimeout(function () {
processingChange = false;
}, 100);
}
}
firstRun = false;
_fs.watchFile(filename, {
persistent: true,
interval: 500
}, fileChanged);
};
fileChanged();
return {
filename: filename,
close: function () {
_fs.unwatchFile(filename, fileChanged);
}
};
},
run: function (source, filename) {
require.main.filename = filename;
require.main.paths = _module._nodeModulePaths(_path.dirname(_fs.realpathSync(filename)));
require.main._compile(source, filename);
},
getExecutingFilePath: function () {
return process.mainModule.filename;
},
quit: process.exit
};
}
;
if(typeof ActiveXObject === "function") {
return getWindowsScriptHostIO();
} else if(typeof require === "function") {
return getNodeIO();
} else {
return null;
}
})();
var cfg = {
root: '.',
pattern: /.\-tests\.ts/g,
tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ',
exclude: {
'.git': true,
'.gitignore': true,
'package.json': true,
'_infrastructure': true,
'.travis.yml': true,
'LICENSE': true,
'README.md': true,
'_ReSharper.DefinitelyTyped': true,
'obj': true,
'bin': true,
'Properties': true,
'DefinitelyTyped.csproj': true,
'DefinitelyTyped.csproj.user': true,
'DefinitelyTyped.sln': true,
'DefinitelyTyped.v11.suo': true
}
};
if(process.argv.length > 2) {
cfg.root = process.argv[2];
}
var TestFile = (function () {
function TestFile() {
this.errors = [];
}
return TestFile;
})();
var Test = (function () {
function Test(lib) {
this.lib = lib;
this.files = [];
}
return Test;
})();
var Tests = (function () {
function Tests() {
this.tests = [];
}
return Tests;
})();
function getLibDirectory(file) {
return file.substr(cfg.root.length).split('/')[1];
}
function getErrorList(out) {
var splitContentByNewlines = function (content) {
var lines = content.split('\r\n');
if(lines.length === 1) {
lines = content.split('\n');
}
return lines;
};
var result = [];
var lines = splitContentByNewlines(out);
for(var i = 0; i < lines.length; i++) {
if(lines[i]) {
result.push(lines[i]);
}
}
return result;
}
function runTests(testFiles) {
var tests = new Tests();
Exec.exec(cfg.tsc, [
testFiles[testIndex]
], function (ExecResult) {
var lib = getLibDirectory(testFiles[testIndex]);
cache_visited_libs[lib] = true;
var testFile = new TestFile();
testFile.name = testFiles[testIndex];
testFile.errors = getErrorList(ExecResult.stderr);
if(testFile.errors.length == 0) {
total_success++;
} else {
total_failure++;
}
console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length) + ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m'));
var test = new Test(lib);
test.files.push(testFile);
tests.tests.push(test);
testIndex++;
if(testIndex < totalTest) {
Exec.exec(cfg.tsc, [
testFiles[testIndex]
], arguments.callee);
} else {
var withoutTests = {
};
for(var k = 0; k < allFiles.length; k++) {
var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1];
if(!(rootFolder in cfg.exclude)) {
if(!(rootFolder in cache_visited_libs)) {
withoutTests[rootFolder] = true;
}
}
}
var withoutTestsCount = 0;
for(var attr in withoutTests) {
var test = new Test(attr);
tests.tests.push(test);
console.log(' [\033[36m' + attr + '\033[0m] without tests');
withoutTestsCount++;
}
console.log('\n> ' + (total_failure + total_success + withoutTestsCount) + ' tests. ' + '\033[32m' + total_success + ' tests success\033[0m, ' + '\033[31m' + total_failure + ' tests failed\033[0m and ' + withoutTestsCount + ' definitions without tests.\n');
if(total_failure > 0) {
process.exit(1);
}
}
});
}
var testFiles = IO.dir(cfg.root, cfg.pattern, {
recursive: true,
deep: 1
});
var allFiles = IO.dir(cfg.root, null, {
recursive: true
});
var totalTest = testFiles.length;
var testIndex = 0;
var cache_visited_libs = {
};
var total_failure = 0;
var total_success = 0;
var tscVersion = '?.?.?';
Exec.exec(cfg.tsc, [
'-version'
], function (ExecResult) {
tscVersion = ExecResult.stdout;
console.log('$ tsc -version');
console.log(tscVersion);
runTests(testFiles);
});

View File

@@ -0,0 +1,168 @@
/// <reference path='src/exec.ts' />
/// <reference path='src/io.ts' />
var cfg = {
root: '.',
pattern: /.\-tests\.ts/g,
tsc: 'node ./_infrastructure/tests/typescript_0.8.3/tsc.js ',
exclude: {
'.git': true,
'.gitignore': true,
'package.json': true,
'_infrastructure': true,
'.travis.yml': true,
'LICENSE': true,
'README.md': true,
'_ReSharper.DefinitelyTyped': true,
'obj': true,
'bin': true,
'Properties': true,
'DefinitelyTyped.csproj': true,
'DefinitelyTyped.csproj.user': true,
'DefinitelyTyped.sln': true,
'DefinitelyTyped.v11.suo': true
}
};
if (process.argv.length > 2) {
cfg.root = process.argv[2];
}
class TestFile {
public name: string;
public errors: string[] = [];
}
class Test {
public files: TestFile[] = [];
constructor(public lib: string) { }
}
class Tests {
public tests: Test[] = [];
}
function getLibDirectory(file: string) {
return file.substr(cfg.root.length).split('/')[1];
}
function getErrorList(out): string[] {
var splitContentByNewlines = function (content: string) {
var lines = content.split('\r\n');
if (lines.length === 1) {
lines = content.split('\n');
}
return lines;
}
var result: string[] = [];
var lines = splitContentByNewlines(out);
for (var i = 0; i < lines.length; i++) {
if (lines[i]) {
result.push(lines[i]);
}
}
return result;
}
function runTests(testFiles) {
var tests = new Tests();
Exec.exec(
cfg.tsc,
[testFiles[testIndex]],
(ExecResult) => {
var lib = getLibDirectory(testFiles[testIndex]);
cache_visited_libs[lib] = true;
var testFile = new TestFile();
testFile.name = testFiles[testIndex];
testFile.errors = getErrorList(ExecResult.stderr);
if (testFile.errors.length == 0) {
total_success++;
} else {
total_failure++;
}
console.log(' [\033[36m' + lib + '\033[0m] ' + testFiles[testIndex].substr(cfg.root.length)
+ ' - ' + (testFile.errors.length == 0 ? '\033[32msuccess\033[0m' : '\033[31mfailure\033[0m'));
var test = new Test(lib);
test.files.push(testFile);
tests.tests.push(test);
testIndex++;
if (testIndex < totalTest) {
Exec.exec(
cfg.tsc,
[testFiles[testIndex]],
<(ExecResult) => any>arguments.callee);
} else {
var withoutTests = {};
for (var k = 0; k < allFiles.length; k++) {
var rootFolder = allFiles[k].substr(cfg.root.length).split('/')[1];
if (!(rootFolder in cfg.exclude)) {
if (!(rootFolder in cache_visited_libs)) {
withoutTests[rootFolder] = true;
}
}
}
var withoutTestsCount = 0;
for (var attr in withoutTests) {
var test = new Test(attr);
tests.tests.push(test);
console.log(' [\033[36m' + attr + '\033[0m] without tests');
withoutTestsCount++;
}
console.log('\n> ' + (total_failure + total_success + withoutTestsCount)
+ ' tests. '
+ '\033[32m' + total_success + ' tests success\033[0m, '
+ '\033[31m' + total_failure + ' tests failed\033[0m and '
+ withoutTestsCount + ' definitions without tests.\n');
if (total_failure > 0) {
process.exit(1);
}
}
});
}
////// GLOBAL VARS
// get all files: "*-tests.ts"
var testFiles = IO.dir(cfg.root, cfg.pattern, { recursive: true, deep: 1 });
// get all proect files
var allFiles = IO.dir(cfg.root, null, { recursive: true });
var totalTest = testFiles.length;
var testIndex = 0;
var cache_visited_libs = {};
// total
var total_failure = 0;
var total_success = 0;
// var to have current typescript version
var tscVersion = '?.?.?';
////// END GLOBAL VARS
// entry point
Exec.exec(cfg.tsc, ['-version'], (ExecResult) => {
tscVersion = ExecResult.stdout;
console.log('$ tsc -version');
console.log(tscVersion);
runTests(testFiles);
});

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

2937
ace/ace.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

26
ace/all-tests.ts Normal file
View File

@@ -0,0 +1,26 @@
/// <reference path="ace.d.ts" />
var exports: any;
var assert: any;
var MockRenderer = null;
var JavaScriptMode = null;
/// <reference path="tests/ace-default-tests.ts" />
/// <reference path="tests/ace-background_tokenizer-tests.ts" />
/// <reference path="tests/ace-document-tests.ts" />
/// <reference path="tests/ace-edit_session-tests.ts" />
/// <reference path="tests/ace-editor1-tests.ts" />
/// <reference path="tests/ace-editor_highlight_selected_word-tests.ts" />
/// <reference path="tests/ace-editor_navigation-tests.ts" />
/// <reference path="tests/ace-editor_text_edit-tests.ts" />
/// <reference path="tests/ace-multi_select-tests.ts" />
/// <reference path="tests/ace-placeholder-tests.ts" />
/// <reference path="tests/ace-range_list-tests.ts" />
/// <reference path="tests/ace-range-tests.ts" />
/// <reference path="tests/ace-search-tests.ts" />
/// <reference path="tests/ace-selection-tests.ts" />
/// <reference path="tests/ace-token_iterator-tests.ts" />
/// <reference path="tests/ace-virtual_renderer-tests.ts" />

View File

@@ -0,0 +1,131 @@
/// <reference path="../ace.d.ts" />
exports = {
"test create anchor" : function() {
var doc = new AceAjax.Document("juhu");
var anchor = new AceAjax.Anchor(doc, 0, 0);
assert.position(anchor.getPosition(), 0, 0);
assert.equal(anchor.getDocument(), doc);
},
"test insert text in same row before cursor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insert({row: 1, column: 1}, "123");
assert.position(anchor.getPosition(), 1, 7);
},
"test insert lines before cursor should move anchor row": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertLines(1, ["123", "456"]);
assert.position(anchor.getPosition(), 3, 4);
},
"test insert new line before cursor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertNewLine({row: 0, column: 0});
assert.position(anchor.getPosition(), 2, 4);
},
"test insert new line in anchor line before anchor should move anchor column and row": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.insertNewLine({row: 1, column: 2});
assert.position(anchor.getPosition(), 2, 2);
},
"test delete text in anchor line before anchor should move anchor column": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(1, 1, 1, 3));
assert.position(anchor.getPosition(), 1, 2);
},
"test remove range which contains the anchor should move the anchor to the start of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 0, 3);
doc.remove(new AceAjax.Range(0, 1, 1, 3));
assert.position(anchor.getPosition(), 0, 1);
},
"test delete character before the anchor should have no effect": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(1, 4, 1, 5));
assert.position(anchor.getPosition(), 1, 4);
},
"test delete lines in anchor line before anchor should move anchor row": function() {
var doc = new AceAjax.Document("juhu\n1\n2\nkinners");
var anchor = new AceAjax.Anchor(doc, 3, 4);
doc.removeLines(1, 2);
assert.position(anchor.getPosition(), 1, 4);
},
"test remove new line before the cursor": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.removeNewLine(0);
assert.position(anchor.getPosition(), 0, 8);
},
"test delete range which contains the anchor should move anchor to the end of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners");
var anchor = new AceAjax.Anchor(doc, 1, 4);
doc.remove(new AceAjax.Range(0, 2, 1, 2));
assert.position(anchor.getPosition(), 0, 4);
},
"test delete line which contains the anchor should move anchor to the end of the range": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
doc.removeLines(1, 1);
assert.position(anchor.getPosition(), 1, 0);
},
"test remove after the anchor should have no effect": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 2);
doc.remove(new AceAjax.Range(1, 4, 2, 2));
assert.position(anchor.getPosition(), 1, 2);
},
"test anchor changes triggered by document changes should emit change event": function(next) {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
anchor.on("change", function(e) {
assert.position(anchor.getPosition(), 0, 0);
next();
});
doc.remove(new AceAjax.Range(0, 0, 2, 1));
},
"test only fire change event if position changes": function() {
var doc = new AceAjax.Document("juhu\nkinners\n123");
var anchor = new AceAjax.Anchor(doc, 1, 5);
anchor.on("change", function(e) {
assert.fail();
});
doc.remove(new AceAjax.Range(2, 0, 2, 1));
}
};

View File

@@ -0,0 +1,39 @@
/// <reference path="../ace.d.ts" />
function forceTokenize(session) {
for (var i = 0, l = session.getLength(); i < l; i++)
session.getTokens(i)
}
function testStates(session, states) {
for (var i = 0, l = session.getLength(); i < l; i++)
assert.equal(session.bgTokenizer.states[i], states[i])
assert.ok(l == states.length)
}
exports = {
"test background tokenizer update on session change": function() {
var doc = new AceAjax.EditSession([
"/*",
"*/",
"var juhu"
]);
doc.setMode("./mode/javascript")
forceTokenize(doc)
testStates(doc, ["comment", "start", "start"])
doc.remove(new AceAjax.Range(0, 2, 1, 2))
testStates(doc, [null, "start"])
forceTokenize(doc)
testStates(doc, ["comment", "comment"])
doc.insert({ row: 0, column: 2 }, "\n*/")
testStates(doc, [undefined, undefined, "comment"])
forceTokenize(doc)
testStates(doc, ["comment", "start", "start"])
}
};

View File

@@ -0,0 +1,450 @@
/// <reference path="../ace.d.ts" />
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/javascript");
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/javascript");
editor.setValue("the new text here"); // or session.setValue
editor.getValue(); // or session.getValue
editor.session.getTextRange(editor.getSelectionRange());
editor.insert("Something cool");
editor.selection.getCursor();
editor.gotoLine(123);
editor.session.getLength();
editor.getSession().setTabSize(4);
editor.getSession().setUseSoftTabs(true);
document.getElementById('editor').style.fontSize = '12px';
editor.getSession().setUseWrapMode(true);
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.setReadOnly(true); // false to make it editable
editor.resize()
editor.find('needle', {
backwards: false,
wrap: false,
caseSensitive: false,
wholeWord: false,
regExp: false
});
editor.findNext();
editor.findPrevious();
editor.find('foo');
editor.replace('bar');
editor.replaceAll('bar');
editor.getSession().on('change', function (e) {
// e.type, etc
});
editor.getSession().selection.on('changeSelection', function (e) {
});
editor.getSession().selection.on('changeCursor', function (e) {
});
editor.commands.addCommand({
name: 'myCommand',
bindKey: { win: 'Ctrl-M', mac: 'Command-M' },
exec: function (editor) {
//...
},
readOnly: true // false if this command should not apply in readOnly mode
});
editor.moveCursorTo(1, 1);
editor.removeLines();
editor.removeLines();
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(3, 0);
editor.removeLines();
editor.removeLines();
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
var range = editor.getSelectionRange();
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
editor.moveCursorTo(1, 1);
editor.removeLines();
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
assert.equal(session.toString(), "a\nc\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a");
assert.position(editor.getCursorPosition(), 0, 1);
editor.removeLines();
assert.equal(session.toString(), "");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "b\nc");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(3, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nb\nc");
assert.position(editor.getCursorPosition(), 2, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nb");
assert.position(editor.getCursorPosition(), 1, 1);
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 7);
range = editor.getSelectionRange();
assert.position(range.start, 1, 7);
assert.position(range.end, 2, 7);
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString());
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
assert.equal(["", "{"].join("\n"), session.toString());
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n"));
assert.position(editor.getCursorPosition(), 2, 1);
range = editor.getSelectionRange();
assert.position(range.start, 0, 1);
assert.position(range.end, 2, 1);
editor.blockOutdent();
assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n"));
range = editor.getSelectionRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 2, 0);
editor.moveCursorTo(0, 3);
editor.blockOutdent(" ");
assert.equal(session.toString(), " 12");
assert.position(editor.getCursorPosition(), 0, 0);
editor.moveCursorTo(0, 2);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.equal(["// abc", "//cde"].join("\n"), session.toString());
var selection = editor.getSelectionRange();
assert.position(selection.start, 0, 4);
assert.position(selection.end, 1, 4);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.getSelection().selectRight();
editor.getSelection().selectRight();
editor.toggleCommentLines();
assert.equal([" abc", "cde"].join("\n"), session.toString());
assert.range(editor.getSelectionRange(), 0, 0, 1, 1);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.toggleCommentLines();
editor.toggleCommentLines();
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString());
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
editor.moveCursorTo(1, 0);
editor.getSelection().selectUp();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.moveLinesDown();
assert.equal(["33", "11", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
// moving again should have no effect
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
editor.moveCursorTo(2, 1);
editor.getSelection().selectDown();
editor.moveLinesUp();
assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesUp();
assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 0, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 2, 0);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
editor.moveCursorTo(1, 1);
editor.clearSelection();
editor.moveLinesDown();
assert.equal(["11", "33", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 1);
editor.clearSelection();
editor.moveLinesUp();
assert.equal(["11", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 1);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesDown();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 3, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 5, 0);
assert.position(editor.getSelection().getSelectionLead(), 3, 0);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesUp();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
session.setTabSize(2);
session.setUseSoftTabs(true);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setTabSize(5);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setUseSoftTabs(false);
editor.onTextInput("\t");
assert.equal(session.toString(), "\t");
editor.removeLines();
var step1 = session.toString();
assert.equal(step1, "222\n333");
editor.removeLines();
var step2 = session.toString();
assert.equal(step2, "333");
editor.removeLines();
var step3 = session.toString();
assert.equal(step3, "");
var undoManager = new AceAjax.UndoManager();
undoManager.undo();
assert.equal(session.toString(), step2);
undoManager.undo();
assert.equal(session.toString(), step1);
undoManager.undo();
assert.equal(session.toString(), "");
undoManager.undo();
assert.equal(session.toString(), "");
editor.moveCursorTo(1, 1);
editor.remove("left");
assert.equal(session.toString(), "123\n56");
editor.moveCursorTo(1, 0);
editor.remove("left");
assert.equal(session.toString(), "123456");
session.setUseSoftTabs(true);
session.setTabSize(4);
editor.moveCursorTo(1, 8);
editor.remove("left");
assert.equal(session.toString(), "123\n 456");
editor.moveCursorTo(1, 0);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4657", "89"].join("\n"));
editor.moveCursorTo(1, 4);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4576", "89"].join("\n"));
editor.moveCursorTo(1, 1);
editor.getSelection().selectRight();
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.position(editor.getCursorPosition(), 1, 3);
editor.moveCursorTo(1, 2);
editor.removeToLineEnd();
assert.equal(session.getValue(), ["123", "45", "89"].join("\n"));
editor.moveCursorTo(1, 4);
editor.removeToLineEnd();
assert.position(editor.getCursorPosition(), 1, 4);
assert.equal(session.getValue(), ["123", "456789"].join("\n"));
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
editor.moveCursorTo(1, 0);
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
editor.moveCursorTo(1, 0);
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);

View File

@@ -0,0 +1,254 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: insert text in line": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 1 }, "juhu");
assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1juhu2", "34"].join("\n"));
} ,
"test: insert new line": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertNewLine({ row: 0, column: 1 });
assert.equal(doc.getValue(), ["1", "2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1", "2", "34"].join("\n"));
} ,
"test: insert lines at the beginning": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(0, ["aa", "bb"]);
assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["aa", "bb", "12", "34"].join("\n"));
} ,
"test: insert lines at the end": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(2, ["aa", "bb"]);
assert.equal(doc.getValue(), ["12", "34", "aa", "bb"].join("\n"));
} ,
"test: insert lines in the middle": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insertLines(1, ["aa", "bb"]);
assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12", "aa", "bb", "34"].join("\n"));
} ,
"test: insert multi line string at the start": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 0 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["aa", "bb", "cc12", "34"].join("\n"));
} ,
"test: insert multi line string at the end": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 2, column: 0 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12", "34aa", "bb", "cc"].join("\n"));
} ,
"test: insert multi line string in the middle": function() {
var doc = new AceAjax.Document(["12", "34"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.insert({ row: 0, column: 1 }, "aa\nbb\ncc");
assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["12", "34"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["1aa", "bb", "cc2", "34"].join("\n"));
} ,
"test: delete in line": function() {
var doc = new AceAjax.Document(["1234", "5678"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 1, 0, 3));
assert.equal(doc.getValue(), ["14", "5678"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["14", "5678"].join("\n"));
} ,
"test: delete new line": function() {
var doc = new AceAjax.Document(["1234", "5678"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 4, 1, 0));
assert.equal(doc.getValue(), ["12345678"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12345678"].join("\n"));
} ,
"test: delete multi line range line": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(0, 2, 2, 2));
assert.equal(doc.getValue(), ["12cd"].join("\n"));
var d = deltas.concat();
doc.revertDeltas(d);
assert.equal(doc.getValue(), ["1234", "5678", "abcd"].join("\n"));
doc.applyDeltas(d);
assert.equal(doc.getValue(), ["12cd"].join("\n"));
} ,
"test: delete full lines": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var deltas = [];
doc.on("change", function (e) { deltas.push(e.data); });
doc.remove(new AceAjax.Range(1, 0, 3, 0));
assert.equal(doc.getValue(), ["1234", ""].join("\n"));
} ,
"test: remove lines should return the removed lines": function() {
var doc = new AceAjax.Document(["1234", "5678", "abcd"]);
var removed = doc.removeLines(1, 2);
assert.equal(removed.join("\n"), ["5678", "abcd"].join("\n"));
} ,
"test: should handle unix style new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"]);
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: should handle windows style new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("unix");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: set new line mode to 'windows' should use '\\r\\n' as new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\n"));
doc.setNewLineMode("windows");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n"));
} ,
"test: set new line mode to 'unix' should use '\\n' as new lines": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("unix");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
} ,
"test: set new line mode to 'auto' should detect the incoming nl type": function() {
var doc = new AceAjax.Document(["1", "2", "3"].join("\n"));
doc.setNewLineMode("auto");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\n"));
var doc = new AceAjax.Document(["1", "2", "3"].join("\r\n"));
doc.setNewLineMode("auto");
assert.equal(doc.getValue(), ["1", "2", "3"].join("\r\n"));
doc.replace(new AceAjax.Range(0, 0, 2, 1), ["4", "5", "6"].join("\n"));
assert.equal(["4", "5", "6"].join("\n"), doc.getValue());
} ,
"test: set value": function() {
var doc = new AceAjax.Document("1");
assert.equal("1", doc.getValue());
doc.setValue(doc.getValue());
assert.equal("1", doc.getValue());
var doc = new AceAjax.Document("1\n2");
assert.equal("1\n2", doc.getValue());
doc.setValue(doc.getValue());
assert.equal("1\n2", doc.getValue());
}
};

View File

@@ -0,0 +1,919 @@
/// <reference path="../ace.d.ts" />
var lang: any;
function createFoldTestSession() {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"));
session.setUndoManager(new AceAjax.UndoManager());
session.addFold("args...", new AceAjax.Range(0, 13, 0, 18));
session.addFold("foo...", new AceAjax.Range(1, 10, 2, 10));
session.addFold("bar...", new AceAjax.Range(2, 20, 2, 25));
return session;
}
function assertArray(a, b) {
assert.equal(a + "", b + "");
assert.ok(a.length == b.length);
for (var i = 0; i < a.length; i++) {
assert.equal(a[i], b[i]);
}
}
exports = {
"test: find matching opening bracket in Text mode": function() {
var session = new AceAjax.EditSession(["(()(", "())))"]);
assert.position(session.findMatchingBracket({ row: 0, column: 3 }), 0, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 2 }), 1, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 3 }), 0, 3);
assert.position(session.findMatchingBracket({ row: 1, column: 4 }), 0, 0);
assert.equal(session.findMatchingBracket({ row: 1, column: 5 }), null);
} ,
"test: find matching closing bracket in Text mode": function() {
var session = new AceAjax.EditSession(["(()(", "())))"]);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 0, column: 4 }), 1, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 2 }), 0, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 1 }), 1, 3);
assert.equal(session.findMatchingBracket({ row: 0, column: 0 }), null);
} ,
"test: find matching opening bracket in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str (a string) to the console",
" console.log(str);",
" }",
" str += \" bar() }\";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.position(session.findMatchingBracket({ row: 0, column: 14 }), 0, 12);
assert.position(session.findMatchingBracket({ row: 7, column: 1 }), 0, 15);
assert.position(session.findMatchingBracket({ row: 6, column: 20 }), 1, 15);
assert.position(session.findMatchingBracket({ row: 1, column: 22 }), 1, 20);
assert.position(session.findMatchingBracket({ row: 3, column: 31 }), 3, 21);
assert.position(session.findMatchingBracket({ row: 4, column: 24 }), 4, 19);
assert.equal(session.findMatchingBracket({ row: 0, column: 1 }), null);
} ,
"test: find matching closing bracket in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str (a string) to the console",
" console.log(str);",
" }",
" str += \" bar() }\";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.position(session.findMatchingBracket({ row: 0, column: 13 }), 0, 13);
assert.position(session.findMatchingBracket({ row: 0, column: 16 }), 7, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 16 }), 6, 19);
assert.position(session.findMatchingBracket({ row: 1, column: 21 }), 1, 21);
assert.position(session.findMatchingBracket({ row: 3, column: 22 }), 3, 30);
assert.position(session.findMatchingBracket({ row: 4, column: 20 }), 4, 23);
} ,
"test: handle unbalanced brackets in JavaScript mode": function() {
var lines = [
"function foo() {",
" var str = \"{ foo()\";",
" if (debug) {",
" // write str a string) to the console",
" console.log(str);",
" ",
" str += \" bar() \";",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), null);
assert.equal(session.findMatchingBracket({ row: 0, column: 16 }), null);
assert.equal(session.findMatchingBracket({ row: 3, column: 30 }), null);
assert.equal(session.findMatchingBracket({ row: 1, column: 16 }), null);
} ,
"test: match different bracket types": function() {
var session = new AceAjax.EditSession(["({[", ")]}"]);
assert.position(session.findMatchingBracket({ row: 0, column: 1 }), 1, 0);
assert.position(session.findMatchingBracket({ row: 0, column: 2 }), 1, 2);
assert.position(session.findMatchingBracket({ row: 0, column: 3 }), 1, 1);
assert.position(session.findMatchingBracket({ row: 1, column: 1 }), 0, 0);
assert.position(session.findMatchingBracket({ row: 1, column: 2 }), 0, 2);
assert.position(session.findMatchingBracket({ row: 1, column: 3 }), 0, 1);
} ,
"test: move lines down": function() {
var session = new AceAjax.EditSession(["a1", "a2", "a3", "a4"]);
session.moveLinesDown(0, 1);
assert.equal(session.getValue(), ["a3", "a1", "a2", "a4"].join("\n"));
session.moveLinesDown(1, 2);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesDown(2, 3);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesDown(2, 2);
assert.equal(session.getValue(), ["a3", "a4", "a2", "a1"].join("\n"));
} ,
"test: move lines up": function() {
var session = new AceAjax.EditSession(["a1", "a2", "a3", "a4"]);
session.moveLinesUp(2, 3);
assert.equal(session.getValue(), ["a1", "a3", "a4", "a2"].join("\n"));
session.moveLinesUp(1, 2);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesUp(0, 1);
assert.equal(session.getValue(), ["a3", "a4", "a1", "a2"].join("\n"));
session.moveLinesUp(2, 2);
assert.equal(session.getValue(), ["a3", "a1", "a4", "a2"].join("\n"));
} ,
"test: duplicate lines": function() {
var session = new AceAjax.EditSession(["1", "2", "3", "4"]);
session.duplicateLines(1, 2);
assert.equal(session.getValue(), ["1", "2", "3", "2", "3", "4"].join("\n"));
} ,
"test: duplicate last line": function() {
var session = new AceAjax.EditSession(["1", "2", "3"]);
session.duplicateLines(2, 2);
assert.equal(session.getValue(), ["1", "2", "3", "3"].join("\n"));
} ,
"test: duplicate first line": function() {
var session = new AceAjax.EditSession(["1", "2", "3"]);
session.duplicateLines(0, 0);
assert.equal(session.getValue(), ["1", "1", "2", "3"].join("\n"));
} ,
"test: getScreenLastRowColumn": function() {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"??a"
]);
assert.equal(session.getScreenLastRowColumn(0), 4);
assert.equal(session.getScreenLastRowColumn(1), 10);
assert.equal(session.getScreenLastRowColumn(2), 5);
} ,
"test: convert document to screen coordinates": function() {
var session = new AceAjax.EditSession("01234\t567890\t1234");
session.setTabSize(4);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 4), 4);
assert.equal(session.documentToScreenColumn(0, 5), 5);
assert.equal(session.documentToScreenColumn(0, 6), 8);
assert.equal(session.documentToScreenColumn(0, 12), 14);
assert.equal(session.documentToScreenColumn(0, 13), 16);
session.setTabSize(2);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 4), 4);
assert.equal(session.documentToScreenColumn(0, 5), 5);
assert.equal(session.documentToScreenColumn(0, 6), 6);
assert.equal(session.documentToScreenColumn(0, 7), 7);
assert.equal(session.documentToScreenColumn(0, 12), 12);
assert.equal(session.documentToScreenColumn(0, 13), 14);
} ,
"test: convert document to screen coordinates with leading tabs": function() {
var session = new AceAjax.EditSession("\t\t123");
session.setTabSize(4);
assert.equal(session.documentToScreenColumn(0, 0), 0);
assert.equal(session.documentToScreenColumn(0, 1), 4);
assert.equal(session.documentToScreenColumn(0, 2), 8);
assert.equal(session.documentToScreenColumn(0, 3), 9);
} ,
"test: documentToScreen without soft wrap": function() {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"??a"
]);
assert.position(session.documentToScreenPosition(0, 3), 0, 3);
assert.position(session.documentToScreenPosition(1, 3), 1, 4);
assert.position(session.documentToScreenPosition(1, 4), 1, 8);
assert.position(session.documentToScreenPosition(2, 2), 2, 4);
} ,
"test: documentToScreen with soft wrap": function() {
var session = new AceAjax.EditSession(["foo bar foo bar"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(12, 12);
session.adjustWrapLimit(80);
assert.position(session.documentToScreenPosition(0, 11), 0, 11);
assert.position(session.documentToScreenPosition(0, 12), 1, 0);
} ,
"test: documentToScreen with soft wrap and multibyte characters": function() {
var session = new AceAjax.EditSession(["??a"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(2, 2);
session.adjustWrapLimit(80);
assert.position(session.documentToScreenPosition(0, 1), 1, 0);
assert.position(session.documentToScreenPosition(0, 2), 2, 0);
assert.position(session.documentToScreenPosition(0, 4), 2, 1);
} ,
"test: documentToScreen should clip position to the document boundaries": function() {
var session = new AceAjax.EditSession("foo bar\njuhu kinners");
assert.position(session.documentToScreenPosition(-1, 4), 0, 0);
assert.position(session.documentToScreenPosition(3, 0), 1, 12);
} ,
"test: convert screen to document coordinates": function() {
var session = new AceAjax.EditSession("01234\t567890\t1234");
session.setTabSize(4);
assert.equal(session.screenToDocumentColumn(0, 0), 0);
assert.equal(session.screenToDocumentColumn(0, 4), 4);
assert.equal(session.screenToDocumentColumn(0, 5), 5);
assert.equal(session.screenToDocumentColumn(0, 6), 5);
assert.equal(session.screenToDocumentColumn(0, 7), 5);
assert.equal(session.screenToDocumentColumn(0, 8), 6);
assert.equal(session.screenToDocumentColumn(0, 9), 7);
assert.equal(session.screenToDocumentColumn(0, 15), 12);
assert.equal(session.screenToDocumentColumn(0, 19), 16);
session.setTabSize(2);
assert.equal(session.screenToDocumentColumn(0, 0), 0);
assert.equal(session.screenToDocumentColumn(0, 4), 4);
assert.equal(session.screenToDocumentColumn(0, 5), 5);
assert.equal(session.screenToDocumentColumn(0, 6), 6);
assert.equal(session.screenToDocumentColumn(0, 12), 12);
assert.equal(session.screenToDocumentColumn(0, 13), 12);
assert.equal(session.screenToDocumentColumn(0, 14), 13);
} ,
"test: screenToDocument with soft wrap": function() {
var session = new AceAjax.EditSession(["foo bar foo bar"]);
session.setUseWrapMode(true);
session.setWrapLimitRange(12, 12);
session.adjustWrapLimit(80);
assert.position(session.screenToDocumentPosition(1, 0), 0, 12);
assert.position(session.screenToDocumentPosition(0, 11), 0, 11);
// Check if the position is clamped the right way.
assert.position(session.screenToDocumentPosition(0, 12), 0, 11);
assert.position(session.screenToDocumentPosition(0, 20), 0, 11);
} ,
"test: screenToDocument with soft wrap and multi byte characters": function() {
var session = new AceAjax.EditSession(["? a"]);
session.setUseWrapMode(true);
session.adjustWrapLimit(80);
assert.position(session.screenToDocumentPosition(0, 1), 0, 0);
assert.position(session.screenToDocumentPosition(0, 2), 0, 1);
assert.position(session.screenToDocumentPosition(0, 3), 0, 2);
assert.position(session.screenToDocumentPosition(0, 4), 0, 3);
assert.position(session.screenToDocumentPosition(0, 5), 0, 3);
} ,
"test: screenToDocument should clip position to the document boundaries": function() {
var session = new AceAjax.EditSession("foo bar\njuhu kinners");
assert.position(session.screenToDocumentPosition(-1, 4), 0, 0);
assert.position(session.screenToDocumentPosition(0, -1), 0, 0);
assert.position(session.screenToDocumentPosition(0, 30), 0, 7);
assert.position(session.screenToDocumentPosition(2, 4), 1, 12);
assert.position(session.screenToDocumentPosition(1, 30), 1, 12);
assert.position(session.screenToDocumentPosition(20, 50), 1, 12);
assert.position(session.screenToDocumentPosition(20, 5), 1, 12);
// and the same for folded rows
session.addFold("...", new AceAjax.Range(0, 1, 1, 3));
assert.position(session.screenToDocumentPosition(1, 2), 1, 12);
// for wrapped rows
session.setUseWrapMode(true);
session.setWrapLimitRange(5, 5);
assert.position(session.screenToDocumentPosition(4, 1), 1, 12);
} ,
"test: wrapLine split function": function() {
function computeAndAssert(line, assertEqual, wrapLimit?, tabSize?) {
wrapLimit = wrapLimit || 12;
tabSize = tabSize || 4;
line = lang.stringTrimRight(line);
var tokens = AceAjax.EditSession.prototype.$getDisplayTokens(line);
var splits = AceAjax.EditSession.prototype.$computeWrapSplits(tokens, wrapLimit, tabSize);
// console.log("String:", line, "Result:", splits, "Expected:", assertEqual);
assert.ok(splits.length == assertEqual.length);
for (var i = 0; i < splits.length; i++) {
assert.ok(splits[i] == assertEqual[i]);
}
}
// Basic splitting.
computeAndAssert("foo bar foo bar", [12]);
computeAndAssert("foo bar f bar", [12]);
computeAndAssert("foo bar f r", [14]);
computeAndAssert("foo bar foo bar foo bara foo", [12, 25]);
// Don't split if there is only whitespaces/tabs at the end of the line.
computeAndAssert("foo foo foo \t \t", []);
// If there is no space to split, force split.
computeAndAssert("foooooooooooooo", [12]);
computeAndAssert("fooooooooooooooooooooooooooo", [12, 24]);
computeAndAssert("foo bar fooooooooooobooooooo", [8, 20]);
// Basic splitting + tabs.
computeAndAssert("foo \t\tbar", [6]);
computeAndAssert("foo \t \tbar", [7]);
// Ignore spaces/tabs at beginning of split.
computeAndAssert("foo \t \t \t \t bar", [14]);
// Test wrapping for asian characters.
computeAndAssert("??", [1], 2);
computeAndAssert(" ??", [1, 2], 2);
computeAndAssert(" ?\t?", [1, 3], 2);
computeAndAssert(" ??\t?", [1, 4], 4);
// Test wrapping for punctuation.
computeAndAssert(" ab.c;ef++", [1, 3, 5, 7, 8], 2);
computeAndAssert(" a.b", [1, 2, 3], 1);
computeAndAssert("#>>", [1, 2], 1);
} ,
"test get longest line": function() {
var session = new AceAjax.EditSession(["12"]);
session.setTabSize(4);
assert.equal(session.getScreenWidth(), 2);
session.doc.insertNewLine({ row: 0, column: Infinity });
session.doc.insertLines(1, ["123"]);
assert.equal(session.getScreenWidth(), 3);
session.doc.insertNewLine({ row: 0, column: Infinity });
session.doc.insertLines(1, ["\t\t"]);
assert.equal(session.getScreenWidth(), 8);
session.setTabSize(2);
assert.equal(session.getScreenWidth(), 4);
} ,
"test issue 83": function() {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(null, session);
var document = session.getDocument();
session.setUseWrapMode(true);
document.insertLines(0, ["a", "b"]);
document.insertLines(2, ["c", "d"]);
document.removeLines(1, 2);
} ,
"test wrapMode init has to create wrapData array": function() {
var session = new AceAjax.EditSession("foo bar\nfoo bar");
var editor = new AceAjax.Editor(null, session);
var document = session.getDocument();
session.setUseWrapMode(true);
session.setWrapLimitRange(3, 3);
session.adjustWrapLimit(80);
} ,
"test first line blank with wrap": function() {
var session = new AceAjax.EditSession("\nfoo");
session.setUseWrapMode(true);
assert.equal(session.doc.getValue(), ["", "foo"].join("\n"));
} ,
"test first line blank with wrap 2": function() {
var session = new AceAjax.EditSession("");
session.setUseWrapMode(true);
session.setValue("\nfoo");
assert.equal(session.doc.getValue(), ["", "foo"].join("\n"));
} ,
"test fold getFoldDisplayLine": function() {
var session = createFoldTestSession();
function assertDisplayLine(foldLine, str) {
var line = session.getLine(foldLine.end.row);
var displayLine =
session.getFoldDisplayLine(foldLine, foldLine.end.row, line.length);
assert.equal(displayLine, str);
}
} ,
"test foldLine idxToPosition": function() {
var session = createFoldTestSession();
function assertIdx2Pos(foldLineIdx, idx, row, column) {
var foldLine = null;
assert.position(foldLine.idxToPosition(idx), row, column);
}
// "function foo(items) {",
// " for (var i=0; i<items.length; i++) {",
// " alert(items[i] + \"juhu\");",
// " } // Real Tab.",
// "}"
assertIdx2Pos(0, 12, 0, 12);
assertIdx2Pos(0, 13, 0, 13);
assertIdx2Pos(0, 14, 0, 13);
assertIdx2Pos(0, 19, 0, 13);
assertIdx2Pos(0, 20, 0, 18);
assertIdx2Pos(1, 10, 1, 10);
assertIdx2Pos(1, 11, 1, 10);
assertIdx2Pos(1, 15, 1, 10);
assertIdx2Pos(1, 16, 2, 10);
assertIdx2Pos(1, 26, 2, 20);
assertIdx2Pos(1, 27, 2, 20);
assertIdx2Pos(1, 32, 2, 25);
} ,
"test fold documentToScreen": function() {
var session = createFoldTestSession();
function assertDoc2Screen(docRow, docCol, screenRow, screenCol) {
assert.position(
session.documentToScreenPosition(docRow, docCol),
screenRow, screenCol
);
}
// One fold ending in the same row.
assertDoc2Screen(0, 0, 0, 0);
assertDoc2Screen(0, 13, 0, 13);
assertDoc2Screen(0, 14, 0, 13);
assertDoc2Screen(0, 17, 0, 13);
assertDoc2Screen(0, 18, 0, 20);
// Fold ending on some other row.
assertDoc2Screen(1, 0, 1, 0);
assertDoc2Screen(1, 10, 1, 10);
assertDoc2Screen(1, 11, 1, 10);
assertDoc2Screen(1, 99, 1, 10);
assertDoc2Screen(2, 0, 1, 10);
assertDoc2Screen(2, 9, 1, 10);
assertDoc2Screen(2, 10, 1, 16);
assertDoc2Screen(2, 11, 1, 17);
// Fold in the same row with fold over more then one row in the same row.
assertDoc2Screen(2, 19, 1, 25);
assertDoc2Screen(2, 20, 1, 26);
assertDoc2Screen(2, 21, 1, 26);
assertDoc2Screen(2, 24, 1, 26);
assertDoc2Screen(2, 25, 1, 32);
assertDoc2Screen(2, 26, 1, 33);
assertDoc2Screen(2, 99, 1, 40);
// Test one position after the folds. Should be all like normal.
assertDoc2Screen(3, 0, 2, 0);
} ,
"test fold screenToDocument": function() {
var session = createFoldTestSession();
function assertScreen2Doc(docRow, docCol, screenRow, screenCol) {
assert.position(
session.screenToDocumentPosition(screenRow, screenCol),
docRow, docCol
);
}
// One fold ending in the same row.
assertScreen2Doc(0, 0, 0, 0);
assertScreen2Doc(0, 13, 0, 13);
assertScreen2Doc(0, 13, 0, 14);
assertScreen2Doc(0, 18, 0, 20);
assertScreen2Doc(0, 19, 0, 21);
// Fold ending on some other row.
assertScreen2Doc(1, 0, 1, 0);
assertScreen2Doc(1, 10, 1, 10);
assertScreen2Doc(1, 10, 1, 11);
assertScreen2Doc(1, 10, 1, 15);
assertScreen2Doc(2, 10, 1, 16);
assertScreen2Doc(2, 11, 1, 17);
// Fold in the same row with fold over more then one row in the same row.
assertScreen2Doc(2, 19, 1, 25);
assertScreen2Doc(2, 20, 1, 26);
assertScreen2Doc(2, 20, 1, 27);
assertScreen2Doc(2, 20, 1, 31);
assertScreen2Doc(2, 25, 1, 32);
assertScreen2Doc(2, 26, 1, 33);
assertScreen2Doc(2, 33, 1, 99);
// Test one position after the folds. Should be all like normal.
assertScreen2Doc(3, 0, 2, 0);
} ,
"test getFoldsInRange()": function() {
var session = createFoldTestSession();
var foldLines = null;
var folds = foldLines[0].folds.concat(foldLines[1].folds);
function test(startRow, startColumn, endColumn, endRow, folds) {
var r = new AceAjax.Range(startRow, startColumn, endColumn, endRow);
var retFolds = session.getFoldsInRange(r);
assert.ok(retFolds.length == folds.length);
for (var i = 0; i < retFolds.length; i++) {
assert.equal(retFolds[i].range + "", folds[i].range + "");
}
}
test(0, 0, 0, 13, []);
test(0, 0, 0, 14, [folds[0]]);
test(0, 0, 0, 18, [folds[0]]);
test(0, 0, 1, 10, [folds[0]]);
test(0, 0, 1, 11, [folds[0], folds[1]]);
test(0, 18, 1, 11, [folds[1]]);
test(2, 0, 2, 13, [folds[1]]);
test(2, 10, 2, 20, []);
test(2, 10, 2, 11, []);
test(2, 19, 2, 20, []);
} ,
"test fold one-line text insert": function() {
// These are mostly test for the FoldLine.addRemoveChars function.
var session = createFoldTestSession();
var undoManager = session.getUndoManager();
var foldLines = null;
function insert(row, column, text) {
session.insert({ row: row, column: column }, text);
}
var foldLine, fold, folds;
// First line.
foldLine = null;
fold = foldLine.folds[0];
insert(0, 0, "0");
assert.range(foldLine.range, 0, 14, 0, 19);
assert.range(fold.range, 0, 14, 0, 19);
insert(0, 14, "1");
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
insert(0, 20, "2");
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
// Second line.
foldLine = null;
folds = foldLine.folds;
insert(1, 0, "3");
assert.range(foldLine.range, 1, 11, 2, 25);
assert.range(folds[0].range, 1, 11, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
insert(1, 11, "4");
assert.range(foldLine.range, 1, 12, 2, 25);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
insert(2, 10, "5");
assert.range(foldLine.range, 1, 12, 2, 26);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 21, 2, 26);
insert(2, 21, "6");
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
insert(2, 27, "7");
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
// UNDO = REMOVE
undoManager.undo(); // 6
assert.range(foldLine.range, 1, 12, 2, 27);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 22, 2, 27);
undoManager.undo(); // 5
assert.range(foldLine.range, 1, 12, 2, 26);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 21, 2, 26);
undoManager.undo(); // 4
assert.range(foldLine.range, 1, 12, 2, 25);
assert.range(folds[0].range, 1, 12, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
undoManager.undo(); // 3
assert.range(foldLine.range, 1, 11, 2, 25);
assert.range(folds[0].range, 1, 11, 2, 10);
assert.range(folds[1].range, 2, 20, 2, 25);
undoManager.undo(); // Beginning first line.
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 0, 15, 0, 20);
assert.range(foldLines[1].range, 1, 10, 2, 25);
foldLine = null;
fold = foldLine.folds[0];
undoManager.undo(); // 2
assert.range(foldLine.range, 0, 15, 0, 20);
assert.range(fold.range, 0, 15, 0, 20);
undoManager.undo(); // 1
assert.range(foldLine.range, 0, 14, 0, 19);
assert.range(fold.range, 0, 14, 0, 19);
undoManager.undo(); // 0
assert.range(foldLine.range, 0, 13, 0, 18);
assert.range(fold.range, 0, 13, 0, 18);
} ,
"test fold multi-line insert/remove": function() {
var session = createFoldTestSession(),
undoManager = session.getUndoManager(),
foldLines = null;
function insert(row, column, text) {
session.insert({ row: row, column: column }, text);
}
var foldLines = null, foldLine, fold, folds;
insert(0, 0, "\nfo0");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 2, 10, 3, 25);
insert(2, 0, "\nba1");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 3, 13, 4, 25);
insert(3, 10, "\nfo2");
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 25);
insert(5, 10, "\nba3");
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
insert(6, 18, "\nfo4");
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
undoManager.undo(); // 3
assert.equal(foldLines.length, 3);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 10);
assert.range(foldLines[2].range, 6, 13, 6, 18);
undoManager.undo(); // 2
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 4, 6, 5, 25);
undoManager.undo(); // 1
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 3, 13, 4, 25);
undoManager.undo(); // 0
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 1, 16, 1, 21);
assert.range(foldLines[1].range, 2, 10, 3, 25);
undoManager.undo(); // Beginning
assert.equal(foldLines.length, 2);
assert.range(foldLines[0].range, 0, 13, 0, 18);
assert.range(foldLines[1].range, 1, 10, 2, 25);
// TODO: Add test for inseration inside of folds.
} ,
"test fold wrap data compution": function() {
function assertWrap(line0, line1, line2) {
line0 && assertArray(wrapData[0], line0);
line1 && assertArray(wrapData[1], line1);
line2 && assertArray(wrapData[2], line2);
}
function removeFoldAssertWrap(docRow, docColumn, line0, line1, line2) {
session.removeFold(session.getFoldAt(docRow, docColumn));
assertWrap(line0, line1, line2);
}
var lines = [
"foo bar foo bar",
"foo bar foo bar",
"foo bar foo bar"
];
var session = new AceAjax.EditSession(lines.join("\n"));
session.setUseWrapMode(true);
var wrapData = null;
// Do a simple assertion without folds to check basic functionallity.
assertWrap([8], [8], [8]);
// --- Do in line folding ---
// Adding a fold. The split position is inside of the fold. As placeholder
// are not splitable, the split should be before the split.
session.addFold("woot", new AceAjax.Range(0, 4, 0, 15));
assertWrap([4], [8], [8]);
// Remove the fold again which should reset the wrapData.
removeFoldAssertWrap(0, 4, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 6, 0, 9));
assertWrap([6, 13], [8], [8]);
removeFoldAssertWrap(0, 6, [8], [8], [8]);
// The fold fits into the wrap limit - no split expected.
session.addFold("woot", new AceAjax.Range(0, 3, 0, 15));
assertWrap([], [8], [8]);
removeFoldAssertWrap(0, 4, [8], [8], [8]);
// Fold after split position should be all fine.
session.addFold("woot", new AceAjax.Range(0, 8, 0, 15));
assertWrap([8], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
// Fold's placeholder is far too long for wrapSplit.
session.addFold("woot0123456789", new AceAjax.Range(0, 8, 0, 15));
assertWrap([8], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
// Fold's placeholder is far too long for wrapSplit
// + content at the end of the line
session.addFold("woot0123456789", new AceAjax.Range(0, 6, 0, 8));
assertWrap([6, 20], [8], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot0123456789", new AceAjax.Range(0, 6, 0, 8));
session.addFold("woot0123456789", new AceAjax.Range(0, 8, 0, 10));
assertWrap([6, 20, 34], [8], [8]);
session.removeFold(session.getFoldAt(0, 7));
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot0123456789", new AceAjax.Range(0, 7, 0, 9));
session.addFold("woot0123456789", new AceAjax.Range(0, 13, 0, 15));
assertWrap([7, 21, 25], [8], [8]);
session.removeFold(session.getFoldAt(0, 7));
removeFoldAssertWrap(0, 14, [8], [8], [8]);
// --- Do some multiline folding ---
// Add a fold over two lines. Note, that the wrapData[1] stays the
// same. This is an implementation detail and expected behavior.
session.addFold("woot", new AceAjax.Range(0, 8, 1, 15));
assertWrap([8], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 8, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 9, 1, 11));
assertWrap([8, 14], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 9, [8], [8], [8]);
session.addFold("woot", new AceAjax.Range(0, 9, 1, 15));
assertWrap([8], [8 /* See comments */], [8]);
removeFoldAssertWrap(0, 9, [8], [8], [8]);
return session;
} ,
"test add fold": function() {
var session = createFoldTestSession();
var fold;
function tryAddFold(placeholder, range, shouldFail) {
var fail = false;
try {
fold = session.addFold(placeholder, range);
} catch (e) {
fail = true;
}
if (fail != shouldFail) {
throw "Expected to get an exception";
}
}
tryAddFold("foo", new AceAjax.Range(0, 13, 0, 17), false);
tryAddFold("foo", new AceAjax.Range(0, 14, 0, 18), true);
tryAddFold("foo", new AceAjax.Range(0, 13, 0, 18), false);
tryAddFold("f", new AceAjax.Range(0, 13, 0, 18), false);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 21), false);
session.removeFold(fold);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 22), false);
tryAddFold("foo", new AceAjax.Range(0, 18, 0, 19), true);
tryAddFold("foo", new AceAjax.Range(0, 22, 1, 10), false);
} ,
"test add subfolds": function() {
var session = createFoldTestSession();
var fold, oldFold;
var foldData = null;
oldFold = foldData[0].folds[0];
fold = session.addFold("fold0", new AceAjax.Range(0, 10, 0, 21));
assert.equal(foldData[0].folds.length, 1);
assert.equal(fold.subFolds.length, 1);
assert.equal(fold.subFolds[0], oldFold);
session.expandFold(fold);
assert.equal(foldData[0].folds.length, 1);
assert.equal(foldData[0].folds[0], oldFold);
assert.equal(fold.subFolds.length, 0);
fold = session.addFold("fold0", new AceAjax.Range(0, 13, 2, 10));
assert.equal(foldData.length, 1);
assert.equal(fold.subFolds.length, 2);
assert.equal(fold.subFolds[0], oldFold);
session.expandFold(fold);
assert.equal(foldData.length, 2);
assert.equal(foldData[0].folds.length, 1);
assert.equal(foldData[0].folds[0], oldFold);
assert.equal(fold.subFolds.length, 0);
session.unfold(null, true);
fold = session.addFold("fold0", new AceAjax.Range(0, 0, 0, 21));
session.addFold("fold0", new AceAjax.Range(0, 1, 0, 5));
session.addFold("fold0", new AceAjax.Range(0, 6, 0, 8));
assert.equal(fold.subFolds.length, 2);
} ,
"test row cache": function() {
var session = createFoldTestSession();
session.screenToDocumentPosition(2, 3);
session.screenToDocumentPosition(5, 3);
session.screenToDocumentPosition(0, 3);
var pos = session.screenToDocumentPosition(0, 0);
assert.equal(pos.row, 0);
session.screenToDocumentPosition(1, 0);
session.screenToDocumentPosition(1, 3);
session.screenToDocumentPosition(5, 3);
session = new AceAjax.EditSession(new Array(30).join("\n"));
session.documentToScreenPosition(2, 0);
session.documentToScreenPosition(2, 0);
}
};

View File

@@ -0,0 +1,153 @@
/// <reference path="../ace.d.ts" />
exports = {
setUp: function(next) {
this.session1 = new AceAjax.EditSession(["abc", "def"]);
this.session2 = new AceAjax.EditSession(["ghi", "jkl"]);
var editor = new AceAjax.Editor(null);
next();
} ,
"test: change document": function() {
var editor = new AceAjax.Editor(null);
editor.setSession(this.session1);
assert.equal(editor.getSession(), this.session1);
editor.setSession(this.session2);
assert.equal(editor.getSession(), this.session2);
} ,
"test: only changes to the new document should have effect": function () {
var editor = new AceAjax.Editor(null);
var called = false;
editor.onDocumentChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
this.session1.duplicateLines(0, 0);
assert.notOk(called);
this.session2.duplicateLines(0, 0);
assert.ok(called);
} ,
"test: should use cursor of new document": function () {
var editor = new AceAjax.Editor(null);
this.session1.getSelection().moveCursorTo(0, 1);
this.session2.getSelection().moveCursorTo(1, 0);
editor.setSession(this.session1);
assert.position(editor.getCursorPosition(), 0, 1);
editor.setSession(this.session2);
assert.position(editor.getCursorPosition(), 1, 0);
} ,
"test: only changing the cursor of the new doc should not have an effect": function () {
var editor = new AceAjax.Editor(null);
editor.onCursorChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
assert.position(editor.getCursorPosition(), 0, 0);
var called = false;
this.session1.getSelection().moveCursorTo(0, 1);
assert.position(editor.getCursorPosition(), 0, 0);
assert.notOk(called);
this.session2.getSelection().moveCursorTo(1, 1);
assert.position(editor.getCursorPosition(), 1, 1);
assert.ok(called);
} ,
"test: should use selection of new document": function () {
var editor = new AceAjax.Editor(null);
this.session1.getSelection().selectTo(0, 1);
this.session2.getSelection().selectTo(1, 0);
editor.setSession(this.session1);
assert.position(editor.getSelection().getSelectionLead(), 0, 1);
editor.setSession(this.session2);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
} ,
"test: only changing the selection of the new doc should not have an effect": function () {
var editor = new AceAjax.Editor(null);
editor.onSelectionChange = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
var called = false;
this.session1.getSelection().selectTo(0, 1);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
assert.notOk(called);
this.session2.getSelection().selectTo(1, 1);
assert.position(editor.getSelection().getSelectionLead(), 1, 1);
assert.ok(called);
} ,
"test: should use mode of new document": function () {
var editor = new AceAjax.Editor(null);
editor.onChangeMode = function () {
called = true;
};
editor.setSession(this.session1);
editor.setSession(this.session2);
var called = false;
this.session1.setMode(new Text());
assert.notOk(called);
this.session2.setMode(null);
assert.ok(called);
} ,
"test: should use stop worker of old document": function (next) {
var editor = new AceAjax.Editor(null);
var self = this;
// 1. Open an editor and set the session to CssMode
self.editor.setSession(self.session1);
self.session1.setMode(null);
// 2. Add a line or two of valid CSS.
self.session1.setValue("DIV { color: red; }");
// 3. Clear the session value.
self.session1.setValue("");
// 4. Set the session to HtmlMode
self.session1.setMode(null);
// 5. Try to type valid HTML
self.session1.insert({ row: 0, column: 0 }, "<html></html>");
setTimeout(function () {
assert.equal(Object.keys(self.session1.getAnnotations()).length, 0);
next();
}, 600);
}
};

View File

@@ -0,0 +1,214 @@
/// <reference path="../ace.d.ts" />
var lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
"Mauris at arcu mi, eu lobortis mauris. Quisque ut libero eget " +
"diam congue vehicula. Quisque ut odio ut mi aliquam tincidunt. " +
"Duis lacinia aliquam lorem eget eleifend. Morbi eget felis mi. " +
"Duis quam ligula, consequat vitae convallis volutpat, blandit " +
"nec neque. Nulla facilisi. Etiam suscipit lorem ac justo " +
"sollicitudin tristique. Phasellus ut posuere nunc. Aliquam " +
"scelerisque mollis felis non gravida. Vestibulum lacus sem, " +
"posuere non bibendum id, luctus non dolor. Aenean id metus " +
"lorem, vel dapibus est. Donec gravida feugiat augue nec " +
"accumsan.Lorem ipsum dolor sit amet, consectetur adipiscing " +
"elit. Nulla vulputate, velit vitae tincidunt congue, nunc " +
"augue accumsan velit, eu consequat turpis lectus ac orci. " +
"Pellentesque ornare dolor feugiat dui auctor eu varius nulla " +
"fermentum. Sed aliquam odio at velit lacinia vel fermentum " +
"felis sodales. In dignissim magna eget nunc lobortis non " +
"fringilla nibh ullamcorper. Donec facilisis malesuada elit " +
"at egestas. Etiam bibendum, diam vitae tempor aliquet, dui " +
"libero vehicula odio, eget bibendum mauris velit eu lorem.\n" +
"consectetur";
function callHighlighterUpdate(session: AceAjax.IEditSession, firstRow: number, lastRow: number) {
var rangeCount = 0;
var mockMarkerLayer = { drawSingleLineMarker: function () { rangeCount++; } }
return rangeCount;
}
exports = {
setUp: function(next) {
var session = new AceAjax.EditSession(lipsum);
editor = new AceAjax.Editor(new MockRenderer(), session);
var selection = session.getSelection();
next();
} ,
"test: highlight selected words by default": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
assert.equal(editor.getHighlightSelectedWord(), true);
} ,
"test: highlight a word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 9);
selection.selectWord();
var highlighter = null;
assert.ok(highlighter != null);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "ipsum");
assert.equal(highlighter.cache.length, 0);
assert.equal(callHighlighterUpdate(session, 0, 0), 2);
} ,
"test: highlight a word and clear highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 8);
selection.selectWord();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "ipsum");
assert.equal(callHighlighterUpdate(session, 0, 0), 2);
session.highlight("");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: highlight another word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 14);
selection.selectWord();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor");
assert.equal(callHighlighterUpdate(session, 0, 0), 4);
} ,
"test: no selection, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.clearSelection();
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select a word, no highlight": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 14);
selection.selectWord();
editor.setHighlightSelectedWord(false);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select a word with no matches": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.setHighlightSelectedWord(true);
var currentOptions = this.search.getOptions();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
needle: "Mauris"
};
this.search.set(newOptions);
var match = this.search.find(session);
assert.notEqual(match, null, "found a match for 'Mauris'");
this.search.set(currentOptions);
selection.setSelectionRange(match);
assert.equal(session.getTextRange(match), "Mauris");
assert.equal(callHighlighterUpdate(session, 0, 0), 1);
} ,
"test: partial word selection 1": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 14);
selection.selectWord();
selection.selectLeft();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolo");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: partial word selection 2": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 13);
selection.selectWord();
selection.selectRight();
var range = selection.getRange();
assert.equal(session.getTextRange(range), "dolor ");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: partial word selection 3": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 14);
selection.selectWord();
selection.selectLeft();
selection.shiftSelection(1);
var range = selection.getRange();
assert.equal(session.getTextRange(range), "olor");
assert.equal(callHighlighterUpdate(session, 0, 0), 0);
} ,
"test: select last word": function () {
var selection = session.getSelection();
var session = new AceAjax.EditSession(lipsum);
var editor = new AceAjax.Editor(new MockRenderer(), session);
selection.moveCursorTo(0, 1);
var currentOptions = this.search.getOptions();
var newOptions = {
wrap: true,
wholeWord: true,
caseSensitive: true,
backwards: true,
needle: "consectetur"
};
this.search.set(newOptions);
var match = this.search.find(session);
assert.notEqual(match, null, "found a match for 'consectetur'");
assert.position(match.start, 1, 0);
this.search.set(currentOptions);
selection.setSelectionRange(match);
assert.equal(session.getTextRange(match), "consectetur");
assert.equal(callHighlighterUpdate(session, 0, 1), 3);
}
};

View File

@@ -0,0 +1,117 @@
/// <reference path="../ace.d.ts" />
exports = {
createEditSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
return new AceAjax.EditSession(text);
},
"test: navigate to end of file should scroll the last line into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(new MockRenderer(), doc);
editor.navigateFileEnd();
var cursor = editor.getCursorPosition();
assert.ok(editor.getFirstVisibleRow() <= cursor.row);
assert.ok(editor.getLastVisibleRow() >= cursor.row);
},
"test: navigate to start of file should scroll the first row into view": function () {
var doc = this.createEditSession(200, 10);
var editor = new AceAjax.Editor(new MockRenderer(), doc);
editor.moveCursorTo(editor.getLastVisibleRow() + 20);
editor.navigateFileStart();
assert.equal(editor.getFirstVisibleRow(), 0);
},
"test: goto hidden line should scroll the line into the middle of the viewport": function () {
var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(101);
assert.position(editor.getCursorPosition(), 100, 0);
assert.equal(editor.getFirstVisibleRow(), 89);
editor.navigateTo(100, 0);
editor.gotoLine(11);
assert.position(editor.getCursorPosition(), 10, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(100, 0);
editor.gotoLine(6);
assert.position(editor.getCursorPosition(), 5, 0);
assert.equal(0, editor.getFirstVisibleRow(), 0);
editor.navigateTo(100, 0);
editor.gotoLine(1);
assert.position(editor.getCursorPosition(), 0, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(0, 0);
editor.gotoLine(191);
assert.position(editor.getCursorPosition(), 190, 0);
assert.equal(editor.getFirstVisibleRow(), 179);
editor.navigateTo(0, 0);
editor.gotoLine(196);
assert.position(editor.getCursorPosition(), 195, 0);
assert.equal(editor.getFirstVisibleRow(), 180);
},
"test: goto visible line should only move the cursor and not scroll": function () {
var editor = new AceAjax.Editor(new MockRenderer(), this.createEditSession(200, 5));
editor.navigateTo(0, 0);
editor.gotoLine(12);
assert.position(editor.getCursorPosition(), 11, 0);
assert.equal(editor.getFirstVisibleRow(), 0);
editor.navigateTo(30, 0);
editor.gotoLine(33);
assert.position(editor.getCursorPosition(), 32, 0);
assert.equal(editor.getFirstVisibleRow(), 30);
},
"test: navigate from the end of a long line down to a short line and back should maintain the curser column": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "1"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 1);
editor.navigateUp();
assert.position(editor.getCursorPosition(), 0, 6);
},
"test: reset desired column on navigate left or right": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["123456", "12"]));
editor.navigateTo(0, 6);
assert.position(editor.getCursorPosition(), 0, 6);
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 2);
editor.navigateLeft();
assert.position(editor.getCursorPosition(), 1, 1);
editor.navigateUp();
assert.position(editor.getCursorPosition(), 0, 1);
},
"test: typing text should update the desired column": function () {
var editor = new AceAjax.Editor(new MockRenderer(), new AceAjax.EditSession(["1234", "1234567890"]));
editor.navigateTo(0, 3);
editor.insert("juhu");
editor.navigateDown();
assert.position(editor.getCursorPosition(), 1, 7);
}
};

View File

@@ -0,0 +1,498 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: delete line from the middle": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nc\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
editor.removeLines();
assert.equal(session.toString(), "a");
assert.position(editor.getCursorPosition(), 0, 1);
editor.removeLines();
assert.equal(session.toString(), "");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: delete multiple selected lines": function () {
var session = new AceAjax.EditSession(["a", "b", "c", "d"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.removeLines();
assert.equal(session.toString(), "a\nd");
assert.position(editor.getCursorPosition(), 1, 0);
},
"test: delete first line": function () {
var session = new AceAjax.EditSession(["a", "b", "c"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.removeLines();
assert.equal(session.toString(), "b\nc");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: delete last should also delete the new line of the previous line": function () {
var session = new AceAjax.EditSession(["a", "b", "c", ""].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(3, 0);
editor.removeLines();
assert.equal(session.toString(), "a\nb\nc");
assert.position(editor.getCursorPosition(), 2, 1);
editor.removeLines();
assert.equal(session.toString(), "a\nb");
assert.position(editor.getCursorPosition(), 1, 1);
},
"test: indent block": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 3);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", " c12345"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 7);
var range = editor.getSelectionRange();
assert.position(range.start, 1, 7);
assert.position(range.end, 2, 7);
},
"test: indent selected lines": function () {
var session = new AceAjax.EditSession(["a12345", "b12345", "c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectDown();
editor.indent();
assert.equal(["a12345", " b12345", "c12345"].join("\n"), session.toString());
},
"test: no auto indent if cursor is before the {": function () {
var session = new AceAjax.EditSession("{", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 0);
editor.onTextInput("\n");
assert.equal(["", "{"].join("\n"), session.toString());
},
"test: outdent block": function () {
var session = new AceAjax.EditSession([" a12345", " b12345", " c12345"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 5);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.blockOutdent();
assert.equal(session.toString(), [" a12345", "b12345", " c12345"].join("\n"));
assert.position(editor.getCursorPosition(), 2, 1);
var range = editor.getSelectionRange();
assert.position(range.start, 0, 1);
assert.position(range.end, 2, 1);
editor.blockOutdent();
assert.equal(session.toString(), ["a12345", "b12345", "c12345"].join("\n"));
var range = editor.getSelectionRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 2, 0);
},
"test: outent without a selection should update cursor": function () {
var session = new AceAjax.EditSession(" 12");
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 3);
editor.blockOutdent(" ");
assert.equal(session.toString(), " 12");
assert.position(editor.getCursorPosition(), 0, 0);
},
"test: comment lines should perserve selection": function () {
var session = new AceAjax.EditSession([" abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 2);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.equal(["// abc", "//cde"].join("\n"), session.toString());
var selection = editor.getSelectionRange();
assert.position(selection.start, 0, 4);
assert.position(selection.end, 1, 4);
},
"test: uncomment lines should perserve selection": function () {
var session = new AceAjax.EditSession(["// abc", "//cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.getSelection().selectRight();
editor.getSelection().selectRight();
editor.toggleCommentLines();
assert.equal([" abc", "cde"].join("\n"), session.toString());
assert.range(editor.getSelectionRange(), 0, 0, 1, 1);
},
"test: toggle comment lines twice should return the original text": function () {
var session = new AceAjax.EditSession([" abc", "cde", "fg"], new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.getSelection().selectDown();
editor.toggleCommentLines();
editor.toggleCommentLines();
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString());
},
"test: comment lines - if the selection end is at the line start it should stay there": function () {
//select down
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 0);
editor.getSelection().selectDown();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
// select up
var session = new AceAjax.EditSession(["abc", "cde"].join("\n"), new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectUp();
editor.toggleCommentLines();
assert.range(editor.getSelectionRange(), 0, 2, 1, 0);
},
"test: move lines down should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(0, 1);
editor.getSelection().selectDown();
editor.moveLinesDown();
assert.equal(["33", "11", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
// moving again should have no effect
editor.moveLinesDown();
assert.equal(["33", "44", "11", "22"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 2);
assert.position(editor.getSelection().getSelectionLead(), 2, 0);
},
"test: move lines up should select moved lines": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(2, 1);
editor.getSelection().selectDown();
editor.moveLinesUp();
assert.equal(session.toString(), ["11", "33", "44", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
editor.moveLinesUp();
assert.equal(session.toString(), ["33", "44", "11", "22"].join("\n"));
assert.position(editor.getCursorPosition(), 0, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 2, 0);
assert.position(editor.getSelection().getSelectionLead(), 0, 0);
},
"test: move line without active selection should not move cursor relative to the moved line": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.clearSelection();
editor.moveLinesDown();
assert.equal(["11", "33", "22", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 2, 1);
editor.clearSelection();
editor.moveLinesUp();
assert.equal(["11", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 1);
},
"test: copy lines down should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesDown();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 3, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 5, 0);
assert.position(editor.getSelection().getSelectionLead(), 3, 0);
},
"test: copy lines up should select lines and place cursor at the selection start": function () {
var session = new AceAjax.EditSession(["11", "22", "33", "44"].join("\n"));
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectDown();
editor.copyLinesUp();
assert.equal(["11", "22", "33", "22", "33", "44"].join("\n"), session.toString());
assert.position(editor.getCursorPosition(), 1, 0);
assert.position(editor.getSelection().getSelectionAnchor(), 3, 0);
assert.position(editor.getSelection().getSelectionLead(), 1, 0);
},
"test: input a tab with soft tab should convert it to spaces": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(new MockRenderer(), session);
session.setTabSize(2);
session.setUseSoftTabs(true);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
session.setTabSize(5);
editor.onTextInput("\t");
assert.equal(session.toString(), " ");
},
"test: input tab without soft tabs should keep the tab character": function () {
var session = new AceAjax.EditSession("");
var editor = new AceAjax.Editor(new MockRenderer(), session);
session.setUseSoftTabs(false);
editor.onTextInput("\t");
assert.equal(session.toString(), "\t");
},
"test: undo/redo for delete line": function () {
var session = new AceAjax.EditSession(["111", "222", "333"]);
var undoManager = new AceAjax.UndoManager();
session.setUndoManager(undoManager);
var initialText = session.toString();
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.removeLines();
var step1 = session.toString();
assert.equal(step1, "222\n333");
editor.removeLines();
var step2 = session.toString();
assert.equal(step2, "333");
editor.removeLines();
var step3 = session.toString();
assert.equal(step3, "");
undoManager.undo();
assert.equal(session.toString(), step2);
undoManager.undo();
assert.equal(session.toString(), step1);
undoManager.undo();
assert.equal(session.toString(), initialText);
undoManager.undo();
assert.equal(session.toString(), initialText);
},
"test: remove left should remove character left of the cursor": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.remove("left");
assert.equal(session.toString(), "123\n56");
},
"test: remove left should remove line break if cursor is at line start": function () {
var session = new AceAjax.EditSession(["123", "456"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.remove("left");
assert.equal(session.toString(), "123456");
},
"test: remove left should remove tabsize spaces if cursor is on a tab stop and preceeded by spaces": function () {
var session = new AceAjax.EditSession(["123", " 456"]);
session.setUseSoftTabs(true);
session.setTabSize(4);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 8);
editor.remove("left");
assert.equal(session.toString(), "123\n 456");
},
"test: transpose at line start should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
},
"test: transpose in line should swap the charaters before and after the cursor": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4657", "89"].join("\n"));
},
"test: transpose at line end should swap the last two characters": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 4);
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4576", "89"].join("\n"));
},
"test: transpose with non empty selection should be a noop": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 1);
editor.getSelection().selectRight();
editor.transposeLetters();
assert.equal(session.getValue(), ["123", "4567", "89"].join("\n"));
},
"test: transpose should move the cursor behind the last swapped character": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 2);
editor.transposeLetters();
assert.position(editor.getCursorPosition(), 1, 3);
},
"test: remove to line end": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 2);
editor.removeToLineEnd();
assert.equal(session.getValue(), ["123", "45", "89"].join("\n"));
},
"test: remove to line end at line end should remove the new line": function () {
var session = new AceAjax.EditSession(["123", "4567", "89"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 4);
editor.removeToLineEnd();
assert.position(editor.getCursorPosition(), 1, 4);
assert.equal(session.getValue(), ["123", "456789"].join("\n"));
},
"test: transform selection to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
},
"test: transform word to uppercase": function () {
var session = new AceAjax.EditSession(["ajax", "dot", "org"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.toUpperCase()
assert.equal(session.getValue(), ["ajax", "DOT", "org"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
},
"test: transform selection to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.getSelection().selectLineEnd();
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
},
"test: transform word to lowercase": function () {
var session = new AceAjax.EditSession(["AJAX", "DOT", "ORG"]);
var editor = new AceAjax.Editor(new MockRenderer(), session);
editor.moveCursorTo(1, 0);
editor.toLowerCase()
assert.equal(session.getValue(), ["AJAX", "dot", "ORG"].join("\n"));
assert.position(editor.getCursorPosition(), 1, 0);
}
};

View File

@@ -0,0 +1,111 @@
/// <reference path="../ace.d.ts" />
var exec = function (name?, times?, args?) {
do {
editor.commands.exec(name, editor, args);
} while (times-- > 1)
};
var testRanges = function (str) {
assert.equal(editor.selection.getAllRanges() + "", str + "");
}
exports = {
name: "ACE multi_select.js",
"test: multiselect editing": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor.navigateFileEnd();
exec("selectMoreBefore", 3);
assert.ok(editor.inMultiSelectMode);
assert.equal(editor.selection.getAllRanges().length, 4);
var newLine = editor.session.getDocument().getNewLineCharacter();
var copyText = "wwww".split("").join(newLine);
assert.equal(editor.getCopyText(), copyText);
exec("insertstring", 1, "a");
exec("backspace", 2);
assert.equal(editor.session.getValue(), "w1.w2\ntt\ntt");
assert.equal(editor.selection.getAllRanges().length, 4);
exec("selectall");
assert.ok(!editor.inMultiSelectMode);
//assert.equal(editor.selection.getAllRanges().length, 1);
} ,
"test: multiselect navigation": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.we"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor.selectMoreLines(1);
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
assert.ok(editor.inMultiSelectMode);
exec("golinedown");
exec("gotolineend");
testRanges("Range: [1/9] -> [1/9],Range: [2/10] -> [2/10]");
exec("selectwordleft");
testRanges("Range: [1/8] -> [1/9],Range: [2/8] -> [2/10]");
exec("golinedown", 2);
assert.ok(!editor.inMultiSelectMode);
} ,
"test: multiselect session change": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
editor.selectMoreLines(1)
testRanges("Range: [0/0] -> [0/0],Range: [1/0] -> [1/0]");
assert.ok(editor.inMultiSelectMode);
var doc2 = new AceAjax.EditSession(["w1"]);
editor.setSession(doc2);
assert.ok(!editor.inMultiSelectMode);
editor.setSession(doc);
assert.ok(editor.inMultiSelectMode);
} ,
"test: multiselect addRange": function() {
var doc = new AceAjax.EditSession([
"w1.w2",
" wtt.w",
" wtt.w"
]);
editor = new AceAjax.Editor(new MockRenderer(), doc);
var selection = editor.selection;
var range1 = new AceAjax.Range(0, 2, 0, 4);
editor.selection.fromOrientedRange(range1);
var range2 = new AceAjax.Range(0, 3, 0, 4);
selection.addRange(range2);
assert.ok(!editor.inMultiSelectMode);
assert.ok(range2.isEqual(editor.selection.getRange()));
var range3 = new AceAjax.Range(0, 1, 0, 1);
selection.addRange(range3);
assert.ok(editor.inMultiSelectMode);
testRanges([range3, range2]);
var range4 = new AceAjax.Range(0, 0, 4, 0);
selection.addRange(range4);
assert.ok(!editor.inMultiSelectMode);
}
};

View File

@@ -0,0 +1,106 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: simple at the end appending of text": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);");
editor.insert('cd');
assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(abcd, abcd);");
editor.remove('left');
editor.remove('left');
editor.remove('left');
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);");
},
"test: inserting text outside placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);\n", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(2, 0);
editor.insert('b');
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);\nb");
},
"test: insertion at the beginning": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 4);
editor.insert('$');
assert.equal(session.doc.getValue(), "var $a = 10;\nconsole.log($a, $a);");
editor.moveCursorTo(0, 4);
// Have to put this in a setTimeout because the anchor is only fixed later.
setTimeout(function () {
editor.insert('v');
assert.equal(session.doc.getValue(), "var v$a = 10;\nconsole.log(v$a, v$a);");
next();
}, 10);
},
"test: detaching placeholder": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
assert.equal(session.doc.getValue(), "var ab = 10;\nconsole.log(ab, ab);");
p.detach();
editor.insert('cd');
assert.equal(session.doc.getValue(), "var abcd = 10;\nconsole.log(ab, ab);");
},
"test: events": function () {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
var entered = false;
var left = false;
p.on("cursorEnter", function () {
entered = true;
});
p.on("cursorLeave", function () {
left = true;
});
editor.moveCursorTo(0, 0);
editor.moveCursorTo(0, 4);
p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event
assert.ok(entered);
editor.moveCursorTo(1, 0);
p.onCursorChange(); // Have to do this by hand because moveCursorTo doesn't trigger the event
assert.ok(left);
},
"test: cancel": function (next) {
var session = new AceAjax.EditSession("var a = 10;\nconsole.log(a, a);", new JavaScriptMode());
session.setUndoManager(new AceAjax.UndoManager());
var editor = new AceAjax.Editor(new MockRenderer(), session);
var p = new AceAjax.PlaceHolder(session, 1, { row: 0, column: 4 }, [{ row: 1, column: 12 }, { row: 1, column: 15 }]);
editor.moveCursorTo(0, 5);
editor.insert('b');
editor.insert('cd');
editor.remove('left');
assert.equal(session.doc.getValue(), "var abc = 10;\nconsole.log(abc, abc);");
// Wait a little for the changes to enter the undo stack
setTimeout(function () {
p.cancel();
assert.equal(session.doc.getValue(), "var a = 10;\nconsole.log(a, a);");
next();
}, 80);
}
};

View File

@@ -0,0 +1,146 @@
/// <reference path="../ace.d.ts" />
exports = {
name: "ACE range.js",
"test: create range": function () {
var range = new AceAjax.Range(1, 2, 3, 4);
assert.equal(range.start.row, 1);
assert.equal(range.start.column, 2);
assert.equal(range.end.row, 3);
assert.equal(range.end.column, 4);
},
"test: create from points": function () {
var range = AceAjax.Range.fromPoints({ row: 1, column: 2 }, { row: 3, column: 4 });
assert.equal(range.start.row, 1);
assert.equal(range.start.column, 2);
assert.equal(range.end.row, 3);
assert.equal(range.end.column, 4);
},
"test: clip to rows": function () {
assert.range(new AceAjax.Range(0, 20, 100, 30).clipRows(10, 30), 10, 0, 31, 0);
assert.range(new AceAjax.Range(0, 20, 30, 10).clipRows(10, 30), 10, 0, 30, 10);
var range = new AceAjax.Range(0, 20, 3, 10);
var range = range.clipRows(10, 30);
assert.ok(range.isEmpty());
assert.range(range, 10, 0, 10, 0);
},
"test: isEmpty": function () {
var range = new AceAjax.Range(1, 2, 1, 2);
assert.ok(range.isEmpty());
var range = new AceAjax.Range(1, 2, 1, 6);
assert.notOk(range.isEmpty());
},
"test: is multi line": function () {
var range = new AceAjax.Range(1, 2, 1, 6);
assert.notOk(range.isMultiLine());
var range = new AceAjax.Range(1, 2, 2, 6);
assert.ok(range.isMultiLine());
},
"test: clone": function () {
var range = new AceAjax.Range(1, 2, 3, 4);
var clone = range.clone();
assert.position(clone.start, 1, 2);
assert.position(clone.end, 3, 4);
clone.start.column = 20;
assert.position(range.start, 1, 2);
clone.end.column = 20;
assert.position(range.end, 3, 4);
},
"test: contains for multi line ranges": function () {
var range = new AceAjax.Range(1, 10, 5, 20);
assert.ok(range.contains(1, 10));
assert.ok(range.contains(2, 0));
assert.ok(range.contains(3, 100));
assert.ok(range.contains(5, 19));
assert.ok(range.contains(5, 20));
assert.notOk(range.contains(1, 9));
assert.notOk(range.contains(0, 0));
assert.notOk(range.contains(5, 21));
},
"test: contains for single line ranges": function () {
var range = new AceAjax.Range(1, 10, 1, 20);
assert.ok(range.contains(1, 10));
assert.ok(range.contains(1, 15));
assert.ok(range.contains(1, 20));
assert.notOk(range.contains(0, 9));
assert.notOk(range.contains(2, 9));
assert.notOk(range.contains(1, 9));
assert.notOk(range.contains(1, 21));
},
"test: extend range": function () {
var range = new AceAjax.Range(2, 10, 2, 30);
var range = range.extend(2, 5);
assert.range(range, 2, 5, 2, 30);
var range = range.extend(2, 35);
assert.range(range, 2, 5, 2, 35);
var range = range.extend(2, 15);
assert.range(range, 2, 5, 2, 35);
var range = range.extend(1, 4);
assert.range(range, 1, 4, 2, 35);
var range = range.extend(6, 10);
assert.range(range, 1, 4, 6, 10);
},
"test: collapse rows": function () {
var range = new AceAjax.Range(0, 2, 1, 2);
assert.range(range.collapseRows(), 0, 0, 1, 0);
var range = new AceAjax.Range(2, 2, 3, 1);
assert.range(range.collapseRows(), 2, 0, 3, 0);
var range = new AceAjax.Range(2, 2, 3, 0);
assert.range(range.collapseRows(), 2, 0, 2, 0);
var range = new AceAjax.Range(2, 0, 2, 0);
assert.range(range.collapseRows(), 2, 0, 2, 0);
},
"test: to screen range": function () {
var session = new AceAjax.EditSession([
"juhu",
"12\t\t34",
"ぁぁa",
"\t\t34",
]);
var range = new AceAjax.Range(0, 0, 0, 3);
assert.range(range.toScreenRange(session), 0, 0, 0, 3);
var range = new AceAjax.Range(1, 1, 1, 3);
assert.range(range.toScreenRange(session), 1, 1, 1, 4);
var range = new AceAjax.Range(2, 1, 2, 2);
assert.range(range.toScreenRange(session), 2, 2, 2, 4);
var range = new AceAjax.Range(3, 0, 3, 4);
assert.range(range.toScreenRange(session), 3, 0, 3, 10);
}
};

View File

@@ -0,0 +1,117 @@
/// <reference path="../ace.d.ts" />
function flatten(rangeList) {
var points = [];
rangeList.ranges.forEach(function (r) {
points.push(r.start.row, r.start.column, r.end.row, r.end.column)
})
return points;
}
function testRangeList(rangeList, points) {
assert.equal("" + flatten(rangeList), "" + points);
}
exports = {
name: "ACE range_list.js",
"test: rangeList pointIndex": function() {
var rangeList = new AceAjax.RangeList();
rangeList.ranges = [
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(8, 8, 9, 9)
];
assert.equal(rangeList.pointIndex({ row: 0, column: 1 }), -1);
assert.equal(rangeList.pointIndex({ row: 1, column: 2 }), 0);
assert.equal(rangeList.pointIndex({ row: 1, column: 3 }), 0);
assert.equal(rangeList.pointIndex({ row: 3, column: 4 }), 0);
assert.equal(rangeList.pointIndex({ row: 4, column: 1 }), -2);
assert.equal(rangeList.pointIndex({ row: 5, column: 1 }), 1);
assert.equal(rangeList.pointIndex({ row: 8, column: 9 }), 2);
assert.equal(rangeList.pointIndex({ row: 18, column: 9 }), -4);
} ,
"test: rangeList add": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(9, 0, 9, 1),
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(8, 8, 9, 9),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(3, 20, 3, 24),
new AceAjax.Range(6, 6, 7, 7)
]);
assert.equal(rangeList.ranges.length, 5);
rangeList.add(new AceAjax.Range(1, 2, 3, 5));
assert.range(rangeList.ranges[0], 1, 2, 3, 5);
assert.equal(rangeList.ranges.length, 5);
rangeList.add(new AceAjax.Range(7, 7, 7, 7));
assert.range(rangeList.ranges[3], 7, 7, 7, 7);
rangeList.add(new AceAjax.Range(7, 8, 7, 8));
assert.range(rangeList.ranges[4], 7, 8, 7, 8);
} ,
"test: rangeList add empty": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(7, 10, 7, 10),
new AceAjax.Range(9, 10, 9, 10),
new AceAjax.Range(8, 10, 8, 10)
]);
assert.equal(rangeList.ranges.length, 3);
rangeList.add(new AceAjax.Range(9, 10, 9, 10));
testRangeList(rangeList, [7, 10, 7, 10, 8, 10, 8, 10, 9, 10, 9, 10]);
} ,
"test: rangeList merge": function() {
var rangeList = new AceAjax.RangeList();
rangeList.addList([
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(6, 6, 7, 7),
new AceAjax.Range(8, 8, 9, 9)
]);
var removed = [];
assert.equal(rangeList.ranges.length, 4);
rangeList.ranges[1].end.row = 7;
removed = rangeList.merge();
assert.equal(removed.length, 1);
assert.range(rangeList.ranges[1], 4, 2, 7, 7);
assert.equal(rangeList.ranges.length, 3);
rangeList.ranges[0].end.row = 10;
removed = rangeList.merge();
assert.range(rangeList.ranges[0], 1, 2, 10, 4);
assert.equal(removed.length, 2);
assert.equal(rangeList.ranges.length, 1);
rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10));
rangeList.ranges.push(new AceAjax.Range(10, 10, 10, 10));
removed = rangeList.merge();
assert.equal(rangeList.ranges.length, 2);
} ,
"test: rangeList remove": function() {
var rangeList = new AceAjax.RangeList();
var list = [
new AceAjax.Range(1, 2, 3, 4),
new AceAjax.Range(4, 2, 5, 4),
new AceAjax.Range(6, 6, 7, 7),
new AceAjax.Range(8, 8, 9, 9)
];
rangeList.addList(list);
assert.equal(rangeList.ranges.length, 4);
rangeList.substractPoint({ row: 1, column: 2 });
assert.equal(rangeList.ranges.length, 3);
rangeList.substractPoint({ row: 6, column: 7 });
assert.equal(rangeList.ranges.length, 2);
}
};

View File

@@ -0,0 +1,416 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: configure the search object": function () {
var search = new AceAjax.Search();
search.set({
needle: "juhu"
});
},
"test: find simple text in document": function () {
var session = new AceAjax.EditSession(["juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: find simple text in next line": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: find text starting at cursor position": function () {
var session = new AceAjax.EditSession(["juhu kinners", "juhu kinners 123"]);
session.getSelection().moveCursorTo(0, 6);
var search = new AceAjax.Search().set({
needle: "kinners"
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search is on by default": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "kinners"
});
assert.notEqual(search.find(session), null);
},
"test: wrap search should wrap at file end": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "kinners",
wrap: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search should find needle even if it starts inside it": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(6, 1);
var search = new AceAjax.Search().set({
needle: "kinners",
wrap: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: wrap search with no match should return 'null'": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
session.getSelection().moveCursorTo(2, 1);
var search = new AceAjax.Search().set({
needle: "xyz",
wrap: true
});
assert.equal(search.find(session), null);
},
"test: case sensitive is by default off": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "JUHU"
});
assert.range(search.find(session), 1, 0, 1, 4);
},
"test: case sensitive search": function () {
var session = new AceAjax.EditSession(["abc", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "KINNERS",
caseSensitive: true
});
var range = search.find(session);
assert.equal(range, null);
},
"test: whole word search should not match inside of words": function () {
var session = new AceAjax.EditSession(["juhukinners", "juhu kinners 123", "456"]);
var search = new AceAjax.Search().set({
needle: "kinners",
wholeWord: true
});
var range = search.find(session);
assert.position(range.start, 1, 5);
assert.position(range.end, 1, 12);
},
"test: find backwards": function () {
var session = new AceAjax.EditSession(["juhu juhu juhu juhu"]);
session.getSelection().moveCursorTo(0, 10);
var search = new AceAjax.Search().set({
needle: "juhu",
backwards: true
});
var range = search.find(session);
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 9);
},
"test: find in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(1, 0);
session.getSelection().selectTo(3, 5);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
},
"test: find backwards in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
backwards: true,
range: session.getSelection().getRange()
});
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
range: session.getSelection().getRange()
});
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(1, 2);
var range = search.find(session);
assert.position(range.start, 1, 0);
assert.position(range.end, 1, 4);
},
"test: edge case - match directly before the cursor": function () {
var session = new AceAjax.EditSession(["123", "123", "juhu"]);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true
});
session.getSelection().moveCursorTo(2, 5);
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
},
"test: edge case - match backwards directly after the cursor": function () {
var session = new AceAjax.EditSession(["123", "123", "juhu"]);
var search = new AceAjax.Search().set({
needle: "juhu",
wrap: true,
backwards: true
});
session.getSelection().moveCursorTo(2, 0);
var range = search.find(session);
assert.position(range.start, 2, 0);
assert.position(range.end, 2, 4);
},
"test: find using a regular expression": function () {
var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]);
var search = new AceAjax.Search().set({
needle: "\\d+",
regExp: true
});
var range = search.find(session);
assert.position(range.start, 0, 3);
assert.position(range.end, 0, 6);
},
"test: find using a regular expression and whole word": function () {
var session = new AceAjax.EditSession(["abc123 123 cd", "abc"]);
var search = new AceAjax.Search().set({
needle: "\\d+\\b",
regExp: true,
wholeWord: true
});
var range = search.find(session);
assert.position(range.start, 0, 7);
assert.position(range.end, 0, 10);
},
"test: use regular expressions with capture groups": function () {
var session = new AceAjax.EditSession([" ab: 12px", " <h1 abc"]);
var search = new AceAjax.Search().set({
needle: "(\\d+)",
regExp: true
});
var range = search.find(session);
assert.position(range.start, 0, 6);
assert.position(range.end, 0, 8);
},
"test: find all matches in selection": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
session.getSelection().setSelectionAnchor(0, 2);
session.getSelection().selectTo(3, 2);
var search = new AceAjax.Search().set({
needle: "uh",
wrap: true,
range: session.getSelection().getRange()
});
var ranges = search.findAll(session);
assert.equal(ranges.length, 2);
assert.position(ranges[0].start, 1, 1);
assert.position(ranges[0].end, 1, 3);
assert.position(ranges[1].start, 2, 1);
assert.position(ranges[1].end, 2, 3);
},
"test: find all multiline matches": function () {
var session = new AceAjax.EditSession(["juhu", "juhu", "juhu", "juhu"]);
var search = new AceAjax.Search().set({
needle: "hu\nju",
wrap: true
});
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[0].start, 0, 2);
assert.position(ranges[0].end, 1, 2);
assert.position(ranges[1].start, 1, 2);
assert.position(ranges[1].end, 2, 2);
},
"test: replace() should return the replacement if the input matches the needle": function () {
var search = new AceAjax.Search().set({
needle: "juhu"
});
assert.equal(search.replace("juhu", "kinners"), "kinners");
assert.equal(search.replace("", "kinners"), null);
assert.equal(search.replace(" juhu", "kinners"), null);
// case sensitivity
assert.equal(search.replace("Juhu", "kinners"), "kinners");
search.set({ caseSensitive: true });
assert.equal(search.replace("Juhu", "kinners"), null);
// regexp replacement
},
"test: replace with a RegExp search": function () {
var search = new AceAjax.Search().set({
needle: "\\d+",
regExp: true
});
assert.equal(search.replace("123", "kinners"), "kinners");
assert.equal(search.replace("01234", "kinners"), "kinners");
assert.equal(search.replace("", "kinners"), null);
assert.equal(search.replace("a12", "kinners"), null);
assert.equal(search.replace("12a", "kinners"), null);
},
"test: replace with RegExp match and capture groups": function () {
var search = new AceAjax.Search().set({
needle: "ab(\\d\\d)",
regExp: true
});
assert.equal(search.replace("ab12", "cd$1"), "cd12");
assert.equal(search.replace("ab12", "-$&-"), "-ab12-");
assert.equal(search.replace("ab12", "$$"), "$");
},
"test: find all using regular expresion containing $": function () {
var session = new AceAjax.EditSession(["a", " b", "c ", "d"]);
var search = new AceAjax.Search().set({
needle: "[ ]+$",
regExp: true,
wrap: true
});
session.getSelection().moveCursorTo(1, 2);
var ranges = search.findAll(session);
assert.equal(ranges.length, 1);
assert.position(ranges[0].start, 2, 1);
assert.position(ranges[0].end, 2, 2);
},
"test: find all matches in a line": function () {
var session = new AceAjax.EditSession("foo bar foo baz foobar foo");
var search = new AceAjax.Search().set({
needle: "foo",
wrap: true,
wholeWord: true
});
session.getSelection().moveCursorTo(0, 4);
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[0].start, 0, 0);
assert.position(ranges[0].end, 0, 3);
assert.position(ranges[1].start, 0, 8);
assert.position(ranges[1].end, 0, 11);
assert.position(ranges[2].start, 0, 23);
assert.position(ranges[2].end, 0, 26);
},
"test: find all matches in a line backwards": function () {
var session = new AceAjax.EditSession("foo bar foo baz foobar foo");
var search = new AceAjax.Search().set({
needle: "foo",
wrap: true,
wholeWord: true,
backwards: true
});
session.getSelection().moveCursorTo(0, 13);
var ranges = search.findAll(session);
assert.equal(ranges.length, 3);
assert.position(ranges[2].start, 0, 23);
assert.position(ranges[2].end, 0, 26);
assert.position(ranges[1].start, 0, 8);
assert.position(ranges[1].end, 0, 11);
assert.position(ranges[0].start, 0, 0);
assert.position(ranges[0].end, 0, 3);
},
};

View File

@@ -0,0 +1,411 @@
/// <reference path="../ace.d.ts" />
exports = {
createSession: function (rows, cols) {
var line = new Array(cols + 1).join("a");
var text = new Array(rows).join(line + "\n") + line;
return new AceAjax.EditSession(text);
},
"test: move cursor to end of file should place the cursor on last row and column": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorFileEnd();
assert.position(selection.getCursor(), 199, 10);
},
"test: moveCursor to start of file should place the cursor on the first row and column": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorFileStart();
assert.position(selection.getCursor(), 0, 0);
},
"test: move selection lead to end of file": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorTo(100, 5);
selection.selectFileEnd();
var range = selection.getRange();
assert.position(range.start, 100, 5);
assert.position(range.end, 199, 10);
},
"test: move selection lead to start of file": function () {
var session = this.createSession(200, 10);
var selection = session.getSelection();
selection.moveCursorTo(100, 5);
selection.selectFileStart();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 100, 5);
},
"test: move cursor word right": function () {
var session = new AceAjax.EditSession([
"ab",
" Juhu Kinners (abc, 12)",
" cde"
].join("\n"));
var selection = session.getSelection();
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 0);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 5);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 13);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 18);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 1, 22);
// wrap line
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 2, 4);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 2, 4);
},
"test: select word right if cursor in word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 2);
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 4);
},
"test: moveCursor word left": function () {
var session = new AceAjax.EditSession([
"ab",
" Juhu Kinners (abc, 12)",
" cde"
].join("\n"));
var selection = session.getSelection();
selection.moveCursorDown();
selection.moveCursorLineEnd();
assert.position(selection.getCursor(), 1, 23);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 20);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 15);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 6);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 1, 1);
// wrap line
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
},
"test: moveCursor word left with umlauts": function () {
var session = new AceAjax.EditSession(" Fuß Füße");
var selection = session.getSelection();
selection.moveCursorTo(0, 9)
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 5);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 1);
},
"test: select word left if cursor in word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 5);
},
"test: select word right and select": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 0);
selection.selectWordRight();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 4);
},
"test: select word left and select": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 3);
selection.selectWordLeft();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 3);
},
"test: select word with cursor in word should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners 123");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: select word with cursor in word including right whitespace should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners 123");
var selection = session.getSelection();
selection.moveCursorTo(0, 8);
selection.selectAWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 18);
},
"test: select word with cursor betwen white space and word should select the word": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 0);
assert.position(range.end, 0, 4);
selection.moveCursorTo(0, 5);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 5);
assert.position(range.end, 0, 12);
},
"test: select word with cursor in white space should select white space": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
selection.selectWord();
var range = selection.getRange();
assert.position(range.start, 0, 4);
assert.position(range.end, 0, 6);
},
"test: moving cursor should fire a 'changeCursor' event": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
var called = false;
selection.addEventListener("changeCursor", function () {
called = true;
});
selection.moveCursorTo(0, 6);
assert.ok(called);
},
"test: calling setCursor with the same position should not fire an event": function () {
var session = new AceAjax.EditSession("Juhu Kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 5);
var called = false;
selection.addEventListener("changeCursor", function () {
called = true;
});
selection.moveCursorTo(0, 5);
assert.notOk(called);
},
"test: moveWordright should move past || and [": function () {
var session = new AceAjax.EditSession("||foo[");
var selection = session.getSelection();
// Move behind ||foo
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 5);
// Move behind [
selection.moveCursorWordRight();
assert.position(selection.getCursor(), 0, 6);
},
"test: moveWordLeft should move past || and [": function () {
var session = new AceAjax.EditSession("||foo[");
var selection = session.getSelection();
selection.moveCursorTo(0, 6);
// Move behind [foo
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 2);
// Move behind ||
selection.moveCursorWordLeft();
assert.position(selection.getCursor(), 0, 0);
},
"test: move cursor to line start should move cursor to end of the indentation first": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 6);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
"test: move cursor to line start when the cursor is at the end of the indentation should move cursor to column 0": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 4);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 0);
},
"test: move cursor to line start when the cursor is at column 0 should move cursor to the end of the indentation": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 0);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
// Eclipse style
"test: move cursor to line start when the cursor is before the initial indentation should move cursor to the end of the indentation": function () {
var session = new AceAjax.EditSession("12\n Juhu\n12");
var selection = session.getSelection();
selection.moveCursorTo(1, 2);
selection.moveCursorLineStart();
assert.position(selection.getCursor(), 1, 4);
},
"test go line up when in the middle of the first line should go to document start": function () {
var session = new AceAjax.EditSession("juhu kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorUp();
assert.position(selection.getCursor(), 0, 0);
},
"test: (wrap) go line up when in the middle of the first line should go to document start": function () {
var session = new AceAjax.EditSession("juhu kinners");
session.setWrapLimitRange(5, 5);
session.adjustWrapLimit(80);
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorUp();
assert.position(selection.getCursor(), 0, 0);
},
"test go line down when in the middle of the last line should go to document end": function () {
var session = new AceAjax.EditSession("juhu kinners");
var selection = session.getSelection();
selection.moveCursorTo(0, 4);
selection.moveCursorDown();
assert.position(selection.getCursor(), 0, 12);
},
"test (wrap) go line down when in the middle of the last line should go to document end": function () {
var session = new AceAjax.EditSession("juhu kinners");
session.setWrapLimitRange(8, 8);
session.adjustWrapLimit(80);
var selection = session.getSelection();
selection.moveCursorTo(0, 10);
selection.moveCursorDown();
assert.position(selection.getCursor(), 0, 12);
},
"test go line up twice and then once down when in the second should go back to the previous column": function () {
var session = new AceAjax.EditSession("juhu\nkinners");
var selection = session.getSelection();
selection.moveCursorTo(1, 4);
selection.moveCursorUp();
selection.moveCursorUp();
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 4);
},
"test (keyboard navigation) when curLine is not EOL and targetLine is all whitespace new column should be current column": function () {
var session = new AceAjax.EditSession("function (a) {\n\
\n\
}");
var selection = session.getSelection();
selection.moveCursorTo(2, 0);
selection.moveCursorUp();
assert.position(selection.getCursor(), 1, 0);
},
"test (keyboard navigation) when curLine is EOL and targetLine is shorter dan current column, new column should be targetLine's EOL": function () {
var session = new AceAjax.EditSession("function (a) {\n\
\n\
}");
var selection = session.getSelection();
selection.moveCursorTo(0, 14);
selection.moveCursorDown();
assert.position(selection.getCursor(), 1, 4);
}
};

View File

@@ -0,0 +1,166 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: token iterator initialization in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var iterator = new AceAjax.TokenIterator(session, 0, 0);
assert.equal(iterator.getCurrentToken().value, "function");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, " ");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 8);
var iterator = new AceAjax.TokenIterator(session, 0, 4);
assert.equal(iterator.getCurrentToken().value, "function");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, " ");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 8);
var iterator = new AceAjax.TokenIterator(session, 2, 18);
assert.equal(iterator.getCurrentToken().value, "items");
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 14);
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "[");
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 19);
var iterator = new AceAjax.TokenIterator(session, 4, 0);
assert.equal(iterator.getCurrentToken().value, "}");
assert.equal(iterator.getCurrentTokenRow(), 4);
assert.equal(iterator.getCurrentTokenColumn(), 0);
iterator.stepBackward();
assert.equal(iterator.getCurrentToken().value, "// Real Tab.");
assert.equal(iterator.getCurrentTokenRow(), 3);
assert.equal(iterator.getCurrentTokenColumn(), 6);
var iterator = new AceAjax.TokenIterator(session, 5, 0);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator initialization in text document": function () {
var lines = [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
"sed do eiusmod tempor incididunt ut labore et dolore magna",
"aliqua. Ut enim ad minim veniam, quis nostrud exercitation",
"ullamco laboris nisi ut aliquip ex ea commodo consequat."
];
var session = new AceAjax.EditSession(lines.join("\n"));
var iterator = new AceAjax.TokenIterator(session, 0, 0);
assert.equal(iterator.getCurrentToken().value, lines[0]);
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 0, 4);
assert.equal(iterator.getCurrentToken().value, lines[0]);
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 2, 18);
assert.equal(iterator.getCurrentToken().value, lines[2]);
assert.equal(iterator.getCurrentTokenRow(), 2);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 3, lines[3].length - 1);
assert.equal(iterator.getCurrentToken().value, lines[3]);
assert.equal(iterator.getCurrentTokenRow(), 3);
assert.equal(iterator.getCurrentTokenColumn(), 0);
var iterator = new AceAjax.TokenIterator(session, 4, 0);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator step forward in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var tokens = [];
var len = session.getLength();
for (var i = 0; i < len; i++)
tokens = tokens.concat(session.getTokens(i));
var iterator = new AceAjax.TokenIterator(session, 0, 0);
for (var i = 1; i < tokens.length; i++)
assert.equal(iterator.stepForward(), tokens[i]);
assert.equal(iterator.stepForward(), null);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator step backward in JavaScript document": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var tokens = [];
var len = session.getLength();
for (var i = 0; i < len; i++)
tokens = tokens.concat(session.getTokens(i));
var iterator = new AceAjax.TokenIterator(session, 4, 0);
for (var i = tokens.length - 2; i >= 0; i--)
assert.equal(iterator.stepBackward(), tokens[i]);
assert.equal(iterator.stepBackward(), null);
assert.equal(iterator.getCurrentToken(), null);
},
"test: token iterator reports correct row and column": function () {
var lines = [
"function foo(items) {",
" for (var i=0; i<items.length; i++) {",
" alert(items[i] + \"juhu\");",
" } // Real Tab.",
"}"
];
var session = new AceAjax.EditSession(lines.join("\n"), new JavaScriptMode());
var iterator = new AceAjax.TokenIterator(session, 0, 0);
iterator.stepForward();
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "foo");
assert.equal(iterator.getCurrentTokenRow(), 0);
assert.equal(iterator.getCurrentTokenColumn(), 9);
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
iterator.stepForward();
assert.equal(iterator.getCurrentToken().value, "for");
assert.equal(iterator.getCurrentTokenRow(), 1);
assert.equal(iterator.getCurrentTokenColumn(), 4);
}
};

View File

@@ -0,0 +1,40 @@
/// <reference path="../ace.d.ts" />
exports = {
"test: screen2text the column should be rounded to the next character edge": function () {
var el = document.createElement("div");
if (!el.getBoundingClientRect) {
console.log("Skipping test: This test only runs in the browser");
return;
}
el.style.left = "20px";
el.style.top = "30px";
el.style.width = "300px";
el.style.height = "100px";
document.body.appendChild(el);
var renderer = new AceAjax.VirtualRenderer(el);
renderer.setPadding(0);
renderer.setSession(new AceAjax.EditSession("1234"));
var r = renderer.scroller.getBoundingClientRect();
function testPixelToText(x, y, row, column) {
assert.position(renderer.screenToTextCoordinates(x + r.left, y + r.top), row, column);
}
renderer.characterWidth = 10;
renderer.lineHeight = 15;
testPixelToText(4, 0, 0, 0);
testPixelToText(5, 0, 0, 1);
testPixelToText(9, 0, 0, 1);
testPixelToText(10, 0, 0, 1);
testPixelToText(14, 0, 0, 1);
testPixelToText(15, 0, 0, 2);
document.body.removeChild(el);
}
// change tab size after setDocument (for text layer)
};

2346
amcharts/AmCharts.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -24,7 +24,7 @@ module ng {
debug(obj: any): string;
// see http://docs.angularjs.org/api/angular.mock.inject
inject(...fns: Function[]): void;
inject(...fns: Function[]): any;
// see http://docs.angularjs.org/api/angular.mock.module
module(...modules: any[]): any;
@@ -71,7 +71,7 @@ module ng {
// see http://docs.angularjs.org/api/ngMock.$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
flush(count: number): void;
flush(count?: number): void;
resetExpectations(): void;
verifyNoOutstandingExpectation(): void;
verifyNoOutstandingRequest(): void;

View File

@@ -1,66 +1,82 @@
// Type definitions for Angular JS 1.0 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngResource module (angular-resource.js)
///////////////////////////////////////////////////////////////////////////////
module ng.resource {
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see http://docs.angularjs.org/api/ngResource.$resource
// Most part of the following definitions were achieved by analyzing the
// actual implementation, since the documentation doesn't seem to cover
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any, actionDescriptors?: any): IResourceClass;
}
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
method: string;
isArray?: bool;
params?: any;
headers?: any;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
interface IResourceClass {
get: IActionCall;
save: IActionCall;
query: IActionCall;
remove: IActionCall;
delete: IActionCall;
}
// In case of passing the first argument as anything but a function,
// it's gonna be considered data if the action method is POST, PUT or
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
interface IActionCall {
(): IResource;
(dataOrParams: any): IResource;
(dataOrParams: any, success: Function): IResource;
(success: Function, error?: Function): IResource;
(params: any, data: any, success?: Function, error?: Function): IResource;
}
interface IResource {
$save: IActionCall;
$remove: IActionCall;
$delete: IActionCall;
// No documented, but they are there, just as any custom action will be
$query: IActionCall;
$get: IActionCall;
}
}
// Type definitions for Angular JS 1.0 (ngResource module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
///////////////////////////////////////////////////////////////////////////////
// ngResource module (angular-resource.js)
///////////////////////////////////////////////////////////////////////////////
module ng.resource {
///////////////////////////////////////////////////////////////////////////
// ResourceService
// see http://docs.angularjs.org/api/ngResource.$resource
// Most part of the following definitions were achieved by analyzing the
// actual implementation, since the documentation doesn't seem to cover
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actionDescriptors?: any): IResourceClass;
}
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
method: string;
isArray?: bool;
params?: any;
headers?: any;
}
// Baseclass for everyresource with default actions.
// If you define your new actions for the resource, you will need
// to extend this interface and typecast the ResourceClass to it.
interface IResourceClass {
get: IActionCall;
save: IActionCall;
query: IActionCall;
remove: IActionCall;
delete: IActionCall;
}
// In case of passing the first argument as anything but a function,
// it's gonna be considered data if the action method is POST, PUT or
// PATCH (in other words, methods with body). Otherwise, it's going
// to be considered as parameters to the request.
interface IActionCall {
(): IResource;
(dataOrParams: any): IResource;
(dataOrParams: any, success: Function): IResource;
(success: Function, error?: Function): IResource;
(params: any, data: any, success?: Function, error?: Function): IResource;
}
interface IResource {
$save: IActionCall;
$remove: IActionCall;
$delete: IActionCall;
// No documented, but they are there, just as any custom action will be
$query: IActionCall;
$get: IActionCall;
}
/** when creating a resource factory via IModule.factory */
interface IResourceServiceFactoryFunction {
($resource: ng.resource.IResourceService): ng.resource.IResourceClass;
}
}
/** extensions to base ng based on using angular-resource */
module ng {
interface IModule {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: ng.resource.IResourceServiceFactoryFunction): IModule;
}
}

140
angularjs/angular-tests.ts Normal file
View File

@@ -0,0 +1,140 @@
/// <reference path="angular.d.ts" />
// issue: https://github.com/borisyankov/DefinitelyTyped/issues/369
https://github.com/witoldsz/angular-http-auth/blob/master/src/angular-http-auth.js
/**
* @license HTTP Auth Interceptor Module for AngularJS
* (c) 2012 Witold Szczerba
* License: MIT
*/
angular.module('http-auth-interceptor', [])
.provider('authService', function () {
/**
* Holds all the requests which failed due to 401 response,
* so they can be re-requested in future, once login is completed.
*/
var buffer = [];
/**
* Required by HTTP interceptor.
* Function is attached to provider to be invisible for regular users of this service.
*/
this.pushToBuffer = function (config: ng.IRequestConfig, deferred: ng.IDeferred) {
buffer.push({
config: config,
deferred: deferred
});
}
this.$get = ['$rootScope', '$injector', <any>function ($rootScope: ng.IScope, $injector: ng.auto.IInjectorService) {
var $http: ng.IHttpService; //initialized later because of circular dependency problem
function retry(config: ng.IRequestConfig, deferred: ng.IDeferred) {
$http = $http || $injector.get('$http');
$http(config).then(function (response) {
deferred.resolve(response);
});
}
function retryAll() {
for (var i = 0; i < buffer.length; ++i) {
retry(buffer[i].config, buffer[i].deferred);
}
buffer = [];
}
return {
loginConfirmed: function () {
$rootScope.$broadcast('event:auth-loginConfirmed');
retryAll();
}
}
}]
})
/**
* $http interceptor.
* On 401 response - it stores the request and broadcasts 'event:angular-auth-loginRequired'.
*/
.config(['$httpProvider', 'authServiceProvider', <any>function ($httpProvider: ng.IHttpProvider, authServiceProvider) {
var interceptor = ['$rootScope', '$q', <any>function ($rootScope: ng.IScope, $q: ng.IQService) {
function success(response: ng.IHttpPromiseCallbackArg) {
return response;
}
function error(response: ng.IHttpPromiseCallbackArg) {
if (response.status === 401) {
var deferred = $q.defer();
authServiceProvider.pushToBuffer(response.config, deferred);
$rootScope.$broadcast('event:auth-loginRequired');
return deferred.promise;
}
// otherwise
return $q.reject(response);
}
return function (promise: ng.IHttpPromise) {
return promise.then(success, error);
}
}];
$httpProvider.responseInterceptors.push(interceptor);
}]);
module HttpAndRegularPromiseTests {
interface Person {
firstName: string;
lastName: string;
}
interface ExpectedResponse extends Person {}
interface SomeControllerScope extends ng.IScope {
person: Person;
theAnswer: number;
letters: string[];
}
interface OurApiPromiseCallbackArg extends ng.IHttpPromiseCallbackArg {
data?: ExpectedResponse;
}
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
$http.get("http://somewhere/some/resource")
.success((data: ExpectedResponse) => {
$scope.person = data;
});
$http.get("http://somewhere/some/resource")
.then((response: ng.IHttpPromiseCallbackArg) => {
// typing lost, so something like
// var i: number = response.data
// would type check
$scope.person = response.data;
});
$http.get("http://somewhere/some/resource")
.then((response: OurApiPromiseCallbackArg) => {
// typing lost, so something like
// var i: number = response.data
// would NOT type check
$scope.person = response.data;
});
var aPromise: ng.IPromise = $q.when({firstName: "Jack", lastName: "Sparrow"});
aPromise.then((person: Person) => {
$scope.person = person;
});
var bPromise: ng.IPromise = $q.when(42);
bPromise.then((answer: number) => {
$scope.theAnswer = answer;
});
var cPromise: ng.IPromise = $q.when(["a", "b", "c"]);
cPromise.then((letters: string[]) => {
$scope.letters = letters;
});
}
}

1301
angularjs/angular.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -156,14 +156,16 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
var filename = '';
async.auto({
get_data: function (callback) { },
make_folder: function (callback) { },
write_file: ['get_data', 'make_folder', function (callback) {
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback) {
callback(null, filename);
}],
email_link: ['write_file', function (callback, results) { }]
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback, results) { }]
});
@@ -174,7 +176,7 @@ async.parallel([
function (results) {
async.series([
function (callback) { },
email_link: function(callback) { }
function email_link(callback) { }
]);
});

View File

@@ -105,6 +105,7 @@ function test_collection() {
});
var alphabetical = Books.sortBy(function (book) {
return null;
});
}

493
backbone/backbone.d.ts vendored
View File

@@ -1,246 +1,247 @@
// Type definitions for Backbone 0.9
// Project: http://backbonejs.org/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module Backbone {
export interface AddOptions extends Silenceable {
at: number;
}
export interface CreateOptions extends Silenceable {
wait: bool;
}
export interface HistoryOptions extends Silenceable {
pushState: bool;
root: string;
}
export interface NavigateOptions {
trigger: bool;
}
export interface RouterOptions {
routes: any;
}
export interface Silenceable {
silent: bool;
}
interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface off { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
interface trigger { (eventName: string, ...args: any[]): any; }
interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
declare class Events {
on(eventName: string, callback: (...args:any[]) => void, context?: any): any;
off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
trigger(eventName: string, ...args: any[]): any;
bind(eventName: string, callback: (...args:any[]) => void, context?: any): any;
unbind(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
}
export class ModelBase extends Events {
fetch(options?: JQueryAjaxSettings);
url(): string;
parse(response);
toJSON(): any;
}
export class Model extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
attributes: any;
changed: any[];
cid: string;
id: any;
idAttribute: string;
urlRoot() : string;
constructor (attributes?: any, options?: any);
initialize(attributes?: any);
get(attributeName: string): any;
set(attributeName: string, value: any);
set(obj: any);
change();
changedAttributes(attributes?: any): any[];
clear(options?: Silenceable);
clone(): Model;
defaults(): any;
destroy(options?: JQueryAjaxSettings);
escape(attribute: string);
has(attribute: string): bool;
hasChanged(attribute?: string): bool;
isNew(): bool;
isValid(): string;
previous(attribute: string): any;
previousAttributes(): any[];
save(attributes?: any, options?: JQueryAjaxSettings);
unset(attribute: string, options?: Silenceable);
validate(attributes: any): any;
}
export class Collection extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
model: Model;
models: any;
collection: Model;
length: number;
constructor (models?: any, options?: any);
comparator(element: Model): number;
comparator(element: Model): string;
comparator(compare: Model, to?: Model): number;
add(model: Model, options?: AddOptions);
add(models: Model[], options?: AddOptions);
at(index: number): Model;
get(id: any): Model;
getByCid(cid): Model;
create(attributes: any, options?: CreateOptions): Model;
pluck(attribute: string): any[];
push(model: Model, options?: AddOptions);
pop(options?: Silenceable);
remove(model: Model, options?: Silenceable);
remove(models: Model[], options?: Silenceable);
reset(models?: Model[], options?: Silenceable);
shift(options?: Silenceable);
sort(options?: Silenceable);
unshift(model: Model, options?: AddOptions);
where(properies: any): Model[];
all(iterator: (element: Model, index: number) => bool, context?: any): bool;
any(iterator: (element: Model, index: number) => bool, context?: any): bool;
collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
compact(): Model[];
contains(value: any): bool;
countBy(iterator: (element: Model, index: number) => any): any[];
countBy(attribute: string): any[];
detect(iterator: (item: any) => bool, context?: any): any; // ???
difference(...model: Model[]): Model[];
drop(): Model;
drop(n: number): Model[];
each(iterator: (element: Model, index: number, list?: any) => void, context?: any);
every(iterator: (element: Model, index: number) => bool, context?: any): bool;
filter(iterator: (element: Model, index: number) => bool, context?: any): Model[];
find(iterator: (element: Model, index: number) => bool, context?: any): Model;
first(): Model;
first(n: number): Model[];
flatten(shallow?: bool): Model[];
foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: Model, index: number, list?: any) => void, context?: any);
include(value: any): bool;
indexOf(element: Model, isSorted?: bool): number;
initial(): Model;
initial(n: number): Model[];
inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
intersection(...model: Model[]): Model[];
isEmpty(object: any): bool;
invoke(methodName: string, arguments?: any[]);
last(): Model;
last(n: number): Model[];
lastIndexOf(element: Model, fromIndex?: number): number;
map(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
max(iterator?: (element: Model, index: number) => any, context?: any): Model;
min(iterator?: (element: Model, index: number) => any, context?: any): Model;
object(...values: any[]): any[];
reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
select(iterator: any, context?: any): any[];
size(): number;
shuffle(): any[];
some(iterator: (element: Model, index: number) => bool, context?: any): bool;
sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[];
sortBy(attribute: string, context?: any): Model[];
sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number;
range(stop: number, step?: number);
range(start: number, stop: number, step?: number);
reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: Model, index: number) => bool, context?: any): Model[];
rest(): Model;
rest(n: number): Model[];
tail(): Model;
tail(n: number): Model[];
toArray(): any[];
union(...model: Model[]): Model[];
uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[];
without(...values: any[]): Model[];
zip(...model: Model[]): Model[];
}
export class Router extends Events {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
routes: any;
constructor (options?: RouterOptions);
initialize (options?: RouterOptions);
route(route: string, name: string, callback?: (...parameter: any[]) => void);
navigate(fragment: string, options?: NavigateOptions);
}
export var history: History;
export class History {
start(options?: HistoryOptions);
navigate(fragment: string, options: any);
pushSate();
}
export interface ViewOptions {
model?: Backbone.Model;
collection?: Backbone.Collection;
el?: Element;
id?: string;
className?: string;
tagName?: string;
attributes?: any[];
}
export class View extends Events {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
constructor (options?: ViewOptions);
$(selector: string): any;
model: Model;
make(tagName: string, attrs?, opts?): View;
setElement(element: HTMLElement, delegate?: bool);
tagName: string;
events: any;
el: HTMLElement;
$el;
setElement(element);
attributes;
$(selector);
render();
remove();
make(tagName, attributes?, content?);
//delegateEvents: any;
delegateEvents(events?: any): any;
undelegateEvents();
}
// SYNC
function sync(method, model, options?: JQueryAjaxSettings);
var emulateHTTP: bool;
var emulateJSONBackbone: bool;
// Utility
function noConflict(): Backbone;
function setDomLibrary(jQueryNew);
}
// Type definitions for Backbone 0.9.10
// Project: http://backbonejs.org/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module Backbone {
export interface AddOptions extends Silenceable {
at: number;
}
export interface CreateOptions extends Silenceable {
wait: bool;
}
export interface HistoryOptions extends Silenceable {
pushState?: bool;
root?: string;
}
export interface NavigateOptions {
trigger: bool;
}
export interface RouterOptions {
routes: any;
}
export interface Silenceable {
silent?: bool;
}
interface on { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface off { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
interface trigger { (eventName: string, ...args: any[]): any; }
interface bind { (eventName: string, callback: (...args: any[]) => void, context?: any): any; }
interface unbind { (eventName?: string, callback?: (...args: any[]) => void, context?: any): any; }
declare class Events {
on(eventName: string, callback: (...args:any[]) => void, context?: any): any;
off(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
trigger(eventName: string, ...args: any[]): any;
bind(eventName: string, callback: (...args:any[]) => void, context?: any): any;
unbind(eventName?: string, callback?: (...args:any[]) => void, context?: any): any;
}
export class ModelBase extends Events {
fetch(options?: JQueryAjaxSettings);
url: any;
parse(response);
toJSON(): any;
}
export class Model extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
attributes: any;
changed: any[];
cid: string;
id: any;
idAttribute: string;
urlRoot() : string;
constructor (attributes?: any, options?: any);
initialize(attributes?: any);
get(attributeName: string): any;
set(attributeName: string, value: any, options?: Silenceable);
set(obj: any, options?: Silenceable);
change();
changedAttributes(attributes?: any): any[];
clear(options?: Silenceable);
clone(): Model;
defaults(): any;
destroy(options?: JQueryAjaxSettings);
escape(attribute: string);
has(attribute: string): bool;
hasChanged(attribute?: string): bool;
isNew(): bool;
isValid(): string;
previous(attribute: string): any;
previousAttributes(): any[];
save(attributes?: any, options?: JQueryAjaxSettings);
unset(attribute: string, options?: Silenceable);
validate(attributes: any): any;
}
export class Collection extends ModelBase {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
model: Model;
models: any;
collection: Model;
length: number;
constructor (models?: any, options?: any);
comparator(element: Model): number;
comparator(element: Model): string;
comparator(compare: Model, to?: Model): number;
add(model: Model, options?: AddOptions);
add(models: Model[], options?: AddOptions);
at(index: number): Model;
get(id: any): Model;
create(attributes: any, options?: CreateOptions): Model;
pluck(attribute: string): any[];
push(model: Model, options?: AddOptions);
pop(options?: Silenceable);
remove(model: Model, options?: Silenceable);
remove(models: Model[], options?: Silenceable);
reset(models?: Model[], options?: Silenceable);
shift(options?: Silenceable);
sort(options?: Silenceable);
unshift(model: Model, options?: AddOptions);
where(properies: any): Model[];
all(iterator: (element: Model, index: number) => bool, context?: any): bool;
any(iterator: (element: Model, index: number) => bool, context?: any): bool;
collect(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
compact(): Model[];
contains(value: any): bool;
countBy(iterator: (element: Model, index: number) => any): any[];
countBy(attribute: string): any[];
detect(iterator: (item: any) => bool, context?: any): any; // ???
difference(...model: Model[]): Model[];
drop(): Model;
drop(n: number): Model[];
each(iterator: (element: Model, index: number, list?: any) => void, context?: any);
every(iterator: (element: Model, index: number) => bool, context?: any): bool;
filter(iterator: (element: Model, index: number) => bool, context?: any): Model[];
find(iterator: (element: Model, index: number) => bool, context?: any): Model;
first(): Model;
first(n: number): Model[];
flatten(shallow?: bool): Model[];
foldl(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
forEach(iterator: (element: Model, index: number, list?: any) => void, context?: any);
include(value: any): bool;
indexOf(element: Model, isSorted?: bool): number;
initial(): Model;
initial(n: number): Model[];
inject(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
intersection(...model: Model[]): Model[];
isEmpty(object: any): bool;
invoke(methodName: string, arguments?: any[]);
last(): Model;
last(n: number): Model[];
lastIndexOf(element: Model, fromIndex?: number): number;
map(iterator: (element: Model, index: number, context?: any) => any[], context?: any): any[];
max(iterator?: (element: Model, index: number) => any, context?: any): Model;
min(iterator?: (element: Model, index: number) => any, context?: any): Model;
object(...values: any[]): any[];
reduce(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any;
select(iterator: any, context?: any): any[];
size(): number;
shuffle(): any[];
some(iterator: (element: Model, index: number) => bool, context?: any): bool;
sortBy(iterator: (element: Model, index: number) => number, context?: any): Model[];
sortBy(attribute: string, context?: any): Model[];
sortedIndex(element: Model, iterator?: (element: Model, index: number) => number): number;
range(stop: number, step?: number);
range(start: number, stop: number, step?: number);
reduceRight(iterator: (memo: any, element: Model, index: number) => any, initialMemo: any, context?: any): any[];
reject(iterator: (element: Model, index: number) => bool, context?: any): Model[];
rest(): Model;
rest(n: number): Model[];
tail(): Model;
tail(n: number): Model[];
toArray(): any[];
union(...model: Model[]): Model[];
uniq(isSorted?: bool, iterator?: (element: Model, index: number) => bool): Model[];
without(...values: any[]): Model[];
zip(...model: Model[]): Model[];
}
export class Router extends Events {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
routes: any;
constructor (options?: RouterOptions);
initialize (options?: RouterOptions);
route(route: string, name: string, callback?: (...parameter: any[]) => void);
navigate(fragment: string, options?: NavigateOptions);
}
export var history: History;
export class History {
start(options?: HistoryOptions);
navigate(fragment: string, options: any);
pushSate();
getFragment(fragment?: string, forcePushState?: bool): string;
getHash(window?: Window): string;
}
export interface ViewOptions {
model?: Backbone.Model;
collection?: Backbone.Collection;
el?: Element;
id?: string;
className?: string;
tagName?: string;
attributes?: any[];
}
export class View extends Events {
static extend(properties: any, classProperties?: any): any; // do not use, prefer TypeScript's extend functionality
constructor (options?: ViewOptions);
$(selector: string): any;
model: Model;
make(tagName: string, attrs?, opts?): View;
setElement(element: HTMLElement, delegate?: bool);
tagName: string;
events: any;
el: HTMLElement;
$el;
setElement(element);
attributes;
$(selector);
render();
remove();
make(tagName, attributes?, content?);
//delegateEvents: any;
delegateEvents(events?: any): any;
undelegateEvents();
}
// SYNC
function sync(method, model, options?: JQueryAjaxSettings);
var emulateHTTP: bool;
var emulateJSONBackbone: bool;
// Utility
function noConflict(): Backbone;
function setDomLibrary(jQueryNew);
}

33
bgiframe/typescript.bgiframe.d.ts vendored Normal file
View File

@@ -0,0 +1,33 @@
// Type definitions for typescript.bgiframe 1.0
// Project: https://github.com/sumegizoltan/BgiFrame
// Definitions by: Zoltan Sumegi <https://github.com/sumegizoltan>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/*! The plugin based on:
*
* bgiframe for IE6
* https://github.com/brandonaaron/bgiframe
*
* Copyrights for the jQuery plugin:
* Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
*/
module BgiFrame {
interface ISettings {
top: string;
left: string;
width: string;
height: string;
opacity: bool;
src: string;
conditional: bool;
}
interface IBgiframe {
s: ISettings;
createIframe(): HTMLElement;
fire(element: HTMLElement): void;
getIframe(element: HTMLElement): HTMLElement;
prop(n: any): string;
}
}

68
bootstrap-notify/bootstrap-notify.d.ts vendored Normal file
View File

@@ -0,0 +1,68 @@
// Type definitions for bootstrap-notify
// Project: https://github.com/Nijikokun/bootstrap-notify
// Definitions by: Blake Niemyjski <https://github.com/niemyjski/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface NotifyOptions {
/**
Alert style, omit alert- from style name.
@param {string} type
*/
type?: string;
/**
Allow alert to be closable through a close icon.
@param {bool} closable
*/
closable?: bool;
/**
Alert transition, pretty sure only fade is supported, you can try others if you wish.
@param {string} transition
*/
transition?: string;
/**
Fade alert out after a certain delay (in ms)
@param {string} fadeOut
*/
fadeOut?: NotifyFadeOutSettings;
/**
Text to show on alert, you can use either html or text. HTML will override text.
@param {MessageOptions} message
*/
message?: MessageOptions;
/**
Called before alert closes.
@param {function} onClose
*/
onClose?: () => void;
/**
Called after alert closes.
@param {function} onClosed
*/
onClosed?: () => void;
}
interface NotifyFadeOutSettings {
enabled?: bool;
delay?: number;
}
interface MessageOptions {
html?: string;
text?: string;
}
interface Notification {
show();
hide();
}
interface JQuery {
/**
Creates a notification instance with default options.
@constructor
@param {NotifyOptions} options
*/
notify(options: NotifyOptions): Notification;
}

1787
box2d/box2dweb.d.ts vendored

File diff suppressed because it is too large Load Diff

787
breeze/breeze-1.0-tests.ts Normal file
View File

@@ -0,0 +1,787 @@
/// <reference path="breeze-1.0.d.ts" />
import breeze = module(Breeze);
import core = module(BreezeCore);
function test_dataType() {
var typ = breeze.DataType.DateTime;
var nm = typ.getName();
var isNumber = typ.isNumeric;
var dv = typ.defaultValue;
var symbs = breeze.DataType.getSymbols();
var x = typ.parentEnum === <BreezeCore.IEnum> breeze.DataType;
var isFalse = breeze.DataType.contains(breeze.DataType.Double);
var dt = breeze.DataType.fromName("Decimal");
}
function test_dataProperty() {
var lastNameProp = new breeze.DataProperty({
name: "lastName",
dataType: breeze.DataType.String,
isNullable: true,
maxLength: 20
});
var personEntityType: breeze.EntityType;
personEntityType.addProperty(lastNameProp);
}
function test_dataService() {
var ds = new breeze.DataService({
serviceName: "api/NorthwindIBModel",
hasServerMetadata: true
});
var em = new breeze.EntityManager({
dataService: ds
});
}
function test_entityAspect() {
var order: breeze.Entity;
order.entityAspect.acceptChanges();
var entityKey = order.entityAspect.getKey();
var valErrors = order.entityAspect.getValidationErrors();
var orderDateErrors = order.entityAspect.getValidationErrors("OrderDate");
var orderDateProperty = order.entityType.getProperty("OrderDate");
var orderDateErrors = order.entityAspect.getValidationErrors(orderDateProperty);
order.entityAspect.loadNavigationProperty("Orders").then(function (data) {
var orders = data.results;
}).fail(function (exception) { });
order.entityAspect.rejectChanges();
order.entityAspect.setDeleted();
order.entityAspect.setModified();
order.entityAspect.setUnchanged();
var isOk = order.entityAspect.validateEntity();
if (!isOk) {
var errors = order.entityAspect.getValidationErrors();
}
var isOk = order.entityAspect.validateProperty("Order");
var orderDateProperty = order.entityType.getProperty("OrderDate");
//var isOk = order.entityAspect.validateProperty(OrderDateProperty);
order.entityAspect.propertyChanged.subscribe(function (propertyChangedArgs) {
var entity = propertyChangedArgs.entity;
var propertyNameChanged = propertyChangedArgs.propertyName;
var oldValue = propertyChangedArgs.oldValue;
var newValue = propertyChangedArgs.newValue;
});
order.entityAspect.validationErrorsChanged.subscribe(function (validationChangeArgs) {
var entity = validationChangeArgs.entity;
var errorsAdded = validationChangeArgs.added;
var errorsCleared = validationChangeArgs.removed;
});
}
function test_entityKey() {
var em1: breeze.EntityManager;
var employee1: breeze.Entity;
var empType = em1.metadataStore.getEntityType("Employee");
var entityKey = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var empKey = employee1.entityAspect.getKey();
var empTerrType = em1.metadataStore.getEntityType("EmployeeTerritory");
var empTerrKey = new breeze.EntityKey(<breeze.EntityType> empTerrType, [1, 77]);
var empType = em1.metadataStore.getEntityType("Employee");
var empKey1 = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var empKey2 = employee1.entityAspect.getKey();
if (empKey1.equals(empKey2)) { }
if (breeze.EntityKey.equals(empKey1, empKey2)) { }
}
function test_metadataStore() {
var ms = new breeze.MetadataStore();
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
metadataStore: ms
});
var em1: breeze.EntityManager;
em1.setProperties({ metadataStore: ms });
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = new breeze.MetadataStore();
newMetadataStore.importMetadata(metadataFromStorage);
var ms = new breeze.MetadataStore();
ms.fetchMetadata("api/NorthwindIBModel")
.then(function (rawMetadata) { })
.fail(function (exception) { });
var odType = em1.metadataStore.getEntityType("OrderDetail");
var badType = em1.metadataStore.getEntityType("Foo", false);
var allTypes = em1.metadataStore.getEntityTypes();
if (!em1.metadataStore.hasMetadataFor("api/NorthwindIBModel")) { }
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = breeze.MetadataStore.importMetadata(metadataFromStorage);
var metadataAsString = ms.exportMetadata();
window.localStorage.setItem("metadata", metadataAsString);
var metadataFromStorage = window.localStorage.getItem("metadata");
var newMetadataStore = new breeze.MetadataStore();
newMetadataStore.importMetadata(metadataFromStorage);
if (em1.metadataStore.isEmpty()) { }
var Customer = function () {
this.miscData = "asdf";
}
em1.metadataStore.registerEntityTypeCtor("Customer", Customer);
}
function test_entityManager() {
var entityManager = new breeze.EntityManager("api/NorthwindIBModel");
var entityManager = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
var metadataStore = new breeze.MetadataStore();
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
metadataStore: metadataStore
});
return new breeze.QueryOptions({
mergeStrategy: null,
fetchStrategy: this.fetchStrategy
});
var queryOptions = new breeze.QueryOptions({
mergeStrategy: breeze.MergeStrategy.OverwriteChanges,
fetchStrategy: breeze.FetchStrategy.FromServer
});
var validationOptions = new breeze.ValidationOptions({
validateOnAttach: true,
validateOnSave: true,
validateOnQuery: false
});
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
queryOptions: queryOptions,
validationOptions: validationOptions
});
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);
em1.attachEntity(cust1, breeze.EntityState.Added);
em1.clear();
var em2 = em1.createEmptyCopy();
em1.detachEntity(cust1);
var serviceName: string;
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query,
function (data) {
var orders = data.results;
},
function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
var orders = em.executeQueryLocally(query);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(breeze.FetchStrategy.FromLocalCache);
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
var em2 = new breeze.EntityManager({
serviceName: em1.serviceName,
metadataStore: em1.metadataStore
});
em2.importEntities(bundleFromStorage);
var entitiesToExport: breeze.Entity[];
var bundle = em1.exportEntities(entitiesToExport);
em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
var em1 = new breeze.EntityManager("api/NorthwindIBModel");
em1.fetchMetadata()
.then(function () {
var metadataStore = em1.metadataStore;
})
.fail(function (exception) {
});
var employeeType = em1.metadataStore.getEntityType("Employee");
var employeeKey = new breeze.EntityKey(<breeze.EntityType> employeeType, 1);
var employee = em1.fetchEntityByKey(employeeKey);
var emp2 = em1.fetchEntityByKey("Employee", 6);
var emp3 = em1.fetchEntityByKey("Entityee", [6]);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var custumer = custType.createEntity();
var customerId = em.generateTempKeyValue(custumer);
em1.saveChanges()
.then(function (data) {
var sameCust1 = data.results[0];
});
var changedEntities = em1.getChanges();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var changedCustomers = em1.getChanges(custType);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var changedCustomersAndOrders = em1.getChanges([custType, orderType]);
var entities = em1.getEntities();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customers = em1.getEntities(custType);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var customersAndOrders = em1.getChanges([custType, orderType]);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var addedCustomersAndOrders = em1.getEntities([custType, orderType], breeze.EntityState.Added);
if (em1.hasChanges()) { }
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
if (em1.hasChanges(custType)) { }
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
if (em1.hasChanges([custType, orderType])) { }
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
var em2 = breeze.EntityManager.importEntities(bundleFromStorage);
var bundle = em1.exportEntities();
var em2 = new breeze.EntityManager({
serviceName: em1.serviceName,
metadataStore: em1.metadataStore
});
em2.importEntities(bundle);
var bundle = em1.exportEntities();
em2.importEntities(bundle, { mergeStrategy: breeze.MergeStrategy.PreserveChanges });
em.saveChanges().then(function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
});
var saveOptions = new breeze.SaveOptions({ allowConcurrentSaves: true });
var entitiesToSave: breeze.Entity[];
em.saveChanges(entitiesToSave, saveOptions).then(function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}).fail(function (e) {
});
em.saveChanges(entitiesToSave, null,
function (saveResult) {
var savedEntities = saveResult.entities;
var keyMappings = saveResult.keyMappings;
}, function (e) { }
);
em1.setProperties({
serviceName: "api/foo",
});
var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
em.entityChanged.subscribe(function (changeArgs) {
var action = changeArgs.entityAction;
var entity = changeArgs.entity;
});
var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
em.hasChangesChanged.subscribe(function (args) {
var hasChangesChanged = args.hasChanges;
var entityManager = args.entityManager;
});
}
function test_entityQuery() {
var query = new breeze.EntityQuery("Customers");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.orderBy("Region");
var serviceName: string;
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute()
.then(function (data) { })
.fail(function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders").using(em);
query.execute(
function (data) {
var orders = data.results;
},
function (err) { });
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders");
em.executeQuery(query)
.then(function (data) {
var orders = data.results;
}).fail(function (err) {
});
var query = new breeze.EntityQuery("Orders").using(em);
var orders = query.executeLocally();
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.expand("Orders");
var query = new breeze.EntityQuery("Orders")
.expand("Customer, Employee");
var query = new breeze.EntityQuery("Orders")
.expand("Customer, OrderDetails, OrderDetails.Product");
var query = breeze.EntityQuery.from("Customers");
var query = new breeze.EntityQuery("Customers");
var query = new breeze.EntityQuery().from("Customers");
var customer: breeze.Entity;
var customers: breeze.Entity[];
var customersQuery = breeze.EntityQuery.fromEntities(customers);
var customersQuery = breeze.EntityQuery.fromEntities(customers)
.where("Region", breeze.FilterQueryOp.NotEquals, null);
var customerQuery = breeze.EntityQuery.fromEntities(customer);
var metadataStore: breeze.MetadataStore;
var empType = metadataStore.getEntityType("Employee");
var entityKey = new breeze.EntityKey(<breeze.EntityType> empType, 1);
var query = breeze.EntityQuery.fromEntityKey(entityKey);
var employee: breeze.Entity;
var entityKey = employee.entityAspect.getKey();
var query = breeze.EntityQuery.fromEntityKey(entityKey);
var ordersNavProp = employee.entityType.getProperty("Orders");
var query = breeze.EntityQuery.fromEntityNavigation(employee, <breeze.NavigationProperty> ordersNavProp);
var query = new breeze.EntityQuery("Customers")
.orderBy("CompanyName");
var query = new breeze.EntityQuery("Customers")
.orderBy("Region, CompanyName");
var query = new breeze.EntityQuery("Products")
.orderBy("Category.CategoryName");
var query = new breeze.EntityQuery("Customers")
.orderBy("CompanyName desc");
var query = new breeze.EntityQuery("Customers")
.orderBy("Region desc, CompanyName desc");
var query = new breeze.EntityQuery("Customers")
.orderByDesc("CompanyName");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("CompanyName");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("Orders");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.select("CompanyName, Orders");
var query = new breeze.EntityQuery("Orders")
.where("Customer.CompanyName", "startsWith", "C")
.select("Customer.CompanyName, Customer, OrderDate");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C")
.skip(5);
var query = new breeze.EntityQuery("Customers")
.take(5);
var query = new breeze.EntityQuery("Customers")
.top(5);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(em);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(breeze.MergeStrategy.PreserveChanges);
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(breeze.FetchStrategy.FromLocalCache);
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C");
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", breeze.FilterQueryOp.StartsWith, "C");
var pred = new breeze.Predicate("CompanyName", breeze.FilterQueryOp.StartsWith, "C");
var query = new breeze.EntityQuery("Customers")
.where(pred);
var pred = breeze.Predicate.create("CompanyName", "startswith", "C").and("Region", breeze.FilterQueryOp.Equals, null);
var query = new breeze.EntityQuery("Customers")
.where(pred);
var query = new breeze.EntityQuery("Products")
.where("Category.CategoryName", "startswith", "S");
var query = new breeze.EntityQuery("Customers")
.where("toLower(CompanyName)", "startsWith", "c");
var query = new breeze.EntityQuery("Customers")
.where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM");
}
function test_entityState() {
var anEntity: breeze.Entity;
var es = anEntity.entityAspect.entityState;
return es.isAdded();
return es === breeze.EntityState.Added;
var es = anEntity.entityAspect.entityState;
return es.isAddedModifiedOrDeleted();
return es === breeze.EntityState.Added || es === breeze.EntityState.Modified || es === breeze.EntityState.Deleted;
var es = anEntity.entityAspect.entityState;
return es.isDeleted();
return es === breeze.EntityState.Deleted;
var es = anEntity.entityAspect.entityState;
return es.isDetached();
return es === breeze.EntityState.Detached;
var es = anEntity.entityAspect.entityState;
return es.isModified();
return es === breeze.EntityState.Modified;
var es = anEntity.entityAspect.entityState;
return es.isUnchanged();
return es === breeze.EntityState.Unchanged;
var es = anEntity.entityAspect.entityState;
return es.isUnchangedOrModified();
return es === breeze.EntityState.Unchanged || es === breeze.EntityState.Modified;
}
function test_entityType() {
var myMetadataStore: breeze.MetadataStore;
var myEntityType: breeze.EntityType;
var dataProperty1, dataProperty2, navigationProperty1: breeze.DataProperty;
var em1: breeze.EntityManager;
var entityManager = new breeze.EntityType({
metadataStore: myMetadataStore,
serviceName: "api/NorthwindIBModel",
name: "person",
namespace: "myAppNamespace"
});
myEntityType.addProperty(dataProperty1);
myEntityType.addProperty(dataProperty2);
myEntityType.addProperty(navigationProperty1);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var countryProp = custType.getProperty("Country");
var valFn = function (v) {
if (v == null) return true;
return (v.substring(0,2) === "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn,
{ displayName: "Country", messageTemplate: "'%displayName%' must start with 'US'" });
custType.addValidator(countryValidator, countryProp);
countryProp.validators.push(countryValidator);
var someEntityLevelValidator: breeze.Validator;
custType.addValidator(someEntityLevelValidator);
custType.validators.push(someEntityLevelValidator);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerNameDataProp = custType.getDataProperty("CustomerName");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerOrdersNavProp = custType.getDataProperty("Orders");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var arrayOfProps = custType.getProperties();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var companyNameProp = custType.getProperty("CompanyName");
var orderDetailType = <breeze.EntityType> em1.metadataStore.getEntityType("OrderDetail");
var companyNameProp2 = orderDetailType.getProperty("Order.Customer.CompanyName");
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var arrayOfPropNames = custType.getPropertyNames();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
custType.setProperties({
autoGeneratedKeyType: breeze.AutoGeneratedKeyType.Identity,
defaultResourceName: "CustomersAndIncludedOrders"
});
}
//function test_enum() {
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// var symbol = DayOfWeek.Friday;
// if (DayOfWeek.contains(symbol)) { }
// var dayOfWeek = DayOfWeek.from("Thursday");
// var symbols = DayOfWeek.getNames();
// var symbols = DayOfWeek.getSymbols();
// if (core.Enum.isSymbol(DayOfWeek.Wednesday)) { };
// DayOfWeek.seal();
// var name = DayOfWeek.Monday.getName();
// var name = DayOfWeek.Monday.toString();
// var prototype = {
// nextDay: function () {
// var nextIndex = (this.dayIndex + 1) % 7;
// return DayOfWeek.getSymbols()[nextIndex];
// }
// };
// var DayOfWeek = new core.Enum("DayOfWeek", prototype);
// DayOfWeek.Monday = DayOfWeek.addSymbol({ dayIndex: 0 });
// DayOfWeek.Tuesday = DayOfWeek.addSymbol({ dayIndex: 1 });
// DayOfWeek.Wednesday = DayOfWeek.addSymbol({ dayIndex: 2 });
// DayOfWeek.Thursday = DayOfWeek.addSymbol({ dayIndex: 3 });
// DayOfWeek.Friday = DayOfWeek.addSymbol({ dayIndex: 4 });
// DayOfWeek.Saturday = DayOfWeek.addSymbol({ dayIndex: 5, isWeekend: true });
// DayOfWeek.Sunday = DayOfWeek.addSymbol({ dayIndex: 6, isWeekend: true });
// DayOfWeek.seal();
// DayOfWeek.Monday.nextDay() === DayOfWeek.Tuesday;
// DayOfWeek.Sunday.nextDay() === DayOfWeek.Monday;
// DayOfWeek.Tuesday.isWeekend === undefined;
// DayOfWeek.Saturday.isWeekend == true;
// DayOfWeek instanceof core.Enum;
// core.Enum.isSymbol(DayOfWeek.Wednesday);
// DayOfWeek.contains(DayOfWeek.Thursday);
// DayOfWeek.Tuesday.parentEnum == DayOfWeek;
// DayOfWeek.getSymbols().length === 7;
// DayOfWeek.Friday.toString() === "Friday";
//}
function test_event() {
var myEntityManager: breeze.EntityManager;
var myEntity, person: breeze.Entity;
var salaryEvent = new core.Event("salaryEvent", person);
core.Event.enable("propertyChanged", myEntityManager, false);
core.Event.enable("propertyChanged", myEntityManager, true);
core.Event.enable("propertyChanged", myEntity.entityAspect, false);
core.Event.enable("propertyChanged", myEntity.entityAspect, <Function> null);
core.Event.enable("validationErrorsChanged", myEntityManager, function (em) {
return em.customTag === "blue";
});
core.Event.isEnabled("propertyChanged", myEntityManager);
salaryEvent.publish({ eventType: "payRaise", amount: 100 });
salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true);
salaryEvent.publish({ eventType: "payRaise", amount: 100 }, true, function (error) { });
salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 });
salaryEvent.publishAsync({ eventType: "payRaise", amount: 100 }, function (error) { });
salaryEvent.subscribe(function (eventArgs) {
if (eventArgs.eventType === "payRaise") { }
});
var order: breeze.Entity;
order.entityAspect.propertyChanged.subscribe(function (pcEvent) {
if (pcEvent.propertyName === "OrderDate") { }
});
var token = order.entityAspect.propertyChanged.subscribe(function (pcEvent) { });
order.entityAspect.propertyChanged.unsubscribe(token);
}
function test_localQueryComparisonOptions() {
var lqco = new breeze.LocalQueryComparisonOptions({
name: "caseSensitive-nonSQL",
isCaseSensitive: true,
usesSql92CompliantStringComparison: false
});
lqco.setAsDefault();
var ms = new breeze.MetadataStore({ localQueryComparisonOptions: lqco });
var em = new breeze.EntityManager({ metadataStore: ms });
var lqco = new breeze.LocalQueryComparisonOptions({
isCaseSensitive: false,
usesSql92CompliantStringComparison: true
});
lqco.setAsDefault();
}
function test_namingConventions() {
var namingConv = new breeze.NamingConvention({
serverPropertyNameToClient: function (serverPropertyName) {
return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1);
},
clientPropertyNameToServer: function (clientPropertyName) {
return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1);
}
});
var nc = new breeze.NamingConvention({
serverPropertyNameToClient: function (x) {
return "xxx";
}
});
var ms = new breeze.MetadataStore({ namingConvention: namingConv });
var em = new breeze.EntityManager({ metadataStore: ms });
var namingConv = new breeze.NamingConvention({
serverPropertyNameToClient: function (serverPropertyName) {
return serverPropertyName.substr(0, 1).toLowerCase() + serverPropertyName.substr(1);
},
clientPropertyNameToServer: function (clientPropertyName) {
return clientPropertyName.substr(0, 1).toUpperCase() + clientPropertyName.substr(1);
}
});
namingConv.setAsDefault();
}
function test_navigationProperty() {
var homeAddressProp = new breeze.NavigationProperty({
name: "homeAddress",
entityTypeName: "Address:#myNamespace",
isScalar: true,
associationName: "address_person",
foreignKeyNames: ["homeAddressId"]
});
var homeAddressIdProp = new breeze.DataProperty({
name: "homeAddressId",
dataType: breeze.DataType.Int32
});
var personEntityType: breeze.EntityType;
personEntityType.addProperty(homeAddressProp);
personEntityType.addProperty(homeAddressIdProp);
}
function test_predicate() {
var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B");
var p1a = breeze.Predicate.create("CompanyName", "==", "City");
var p2a = p1a.and(p1a.not());
var query = new breeze.EntityQuery("Customers").where(p1);
var p2 = new breeze.Predicate("Region", breeze.FilterQueryOp.Equals, null);
var query = new breeze.EntityQuery("Customers").where(p2);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = p1.and(p2, p3);
var preds = [p2, p3];
var newPred = p1.and(preds);
var p4 = breeze.Predicate.create("ShipCity", "startswith", "F")
.and("Size", "gt", 2000);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = breeze.Predicate.and(p1, p2, p3);
var preds = [p1, p2, p3];
var newPred = breeze.Predicate.and(preds);
var p1 = breeze.Predicate.create("Freight", "gt", 100);
var predArgs: any[] = ["Freight", "gt", 100];
var p1 = breeze.Predicate.create(predArgs);
var p1 = new breeze.Predicate("Freight", "gt", 100);
var p1 = new breeze.Predicate("CompanyName", "StartsWith", "B");
if (breeze.Predicate.isPredicate(p1)) { }
var p1 = breeze.Predicate.create("Freight", "gt", 100);
var not_p1 = breeze.Predicate.not(p1);
var not_p1 = p1.not();
var not_p1 = breeze.Predicate.create("Freight", "le", 100);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = breeze.Predicate.or(p1, p2, p3);
var preds = [p1, p2, p3];
var newPred = breeze.Predicate.or(preds);
var dt = new Date(88, 9, 12);
var p1 = breeze.Predicate.create("OrderDate", "ne", dt);
var p2 = breeze.Predicate.create("ShipCity", "startsWith", "C");
var p3 = breeze.Predicate.create("Freight", ">", 100);
var newPred = p1.and(p2, p3);
var preds = [p2, p3];
var newPred = p1.and(preds);
var p4 = breeze.Predicate.create("ShipCity", "startswith", "F")
.or("Size", "gt", 2000);
}
function test_queryOptions() {
var em1: breeze.EntityManager;
var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
em1.setProperties({ queryOptions: newQo });
var newQo = new breeze.QueryOptions({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
newQo.setAsDefault();
var queryOptions = em1.queryOptions.using(breeze.MergeStrategy.PreserveChanges);
var queryOptions = em1.queryOptions.using(breeze.FetchStrategy.FromLocalCache);
var queryOptions = em1.queryOptions.using({ mergeStrategy: breeze.MergeStrategy.OverwriteChanges });
}
function test_validationOptions() {
var newVo = new breeze.ValidationOptions({ validateOnSave: false, validateOnAttach: false });
var em1: breeze.EntityManager;
em1.setProperties({ validationOptions: newVo });
var validationOptions = new breeze.ValidationOptions()
var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false });
newOptions.setAsDefault();
var validationOptions = new breeze.ValidationOptions();
var newOptions = validationOptions.using({ validateOnQuery: true, validateOnSave: false });
}
function test_validator() {
var valFn = function (v) {
if (v == null) return true;
return ( v.substr(0,2)=== "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn, {
displayName: "Country",
messageTemplate: "'%displayName%' must start with 'US'"
});
var metadataStore: breeze.MetadataStore;
var custType = <breeze.EntityType> metadataStore.getEntityType("Customer");
var countryProp = custType.getProperty("Country");
countryProp.validators.push(countryValidator);
function isValidZipCode(value) {
var re = /^\d{5}([\-]\d{4})?$/;
return (re.test(value));
}
var valFn = function (v) {
if (v.getProperty("Country") === "USA") {
var postalCode = v.getProperty("PostalCode");
return isValidZipCode(postalCode);
}
return true;
};
var zipCodeValidator = new breeze.Validator("zipCodeValidator", valFn,
{ messageTemplate: "For the US, this is not a valid PostalCode" });
var em1: breeze.EntityManager;
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
custType.validators.push(zipCodeValidator);
var numericRangeValidator = function (context) {
var valFn = function (v, ctx) {
if (v == null) return true;
if (typeof (v) !== "number") return false;
if (ctx.min != null && v < ctx.min) return false;
if (ctx.max != null && v > ctx.max) return false;
return true;
};
return new breeze.Validator("numericRange", valFn, {
messageTemplate: "'%displayName%' must be an integer between the values of %min% and %max%",
min: context.min,
max: context.max
});
};
freightProperty.validators.push(numericRangeValidator({ min: 100, max: 500 }));
var productType = <breeze.EntityType> em1.metadataStore.getEntityType("Product");
var discontinuedProperty = productType.getProperty("Discontinued");
discontinuedProperty.validators.push(breeze.Validator.bool());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
regionProperty.validators.push(breeze.Validator.byte());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var orderDateProperty = orderType.getProperty("OrderDate");
orderDateProperty.validators.push(breeze.Validator.date());
var v0 = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" });
v0.validate("adasdfasdf");
var errMessage = v0.getMessage();
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var customerIdProperty = custType.getProperty("CustomerID");
customerIdProperty.validators.push(breeze.Validator.guid());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int16());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int32());
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.int64());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.maxLength({ maxLength: 5 }));
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
var freightProperty = orderType.getProperty("Freight");
freightProperty.validators.push(breeze.Validator.number());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.required());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.string());
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var regionProperty = custType.getProperty("Region");
regionProperty.validators.push(breeze.Validator.stringLength({ minLength: 2, maxLength: 5 }));
var validator = breeze.Validator.maxLength({ maxLength: 5, displayName: "City" });
var result = validator.validate("asdf");
var ok = result === null;
result = validator.validate("adasdfasdf");
var errMsg = result.errorMessage;
var context = result.context;
var sameValidator = result.validator;
var valFn = function (v) {
if (v == null) return true;
return (v.substr(0,2) === "US");
};
var countryValidator = new breeze.Validator("countryIsUS", valFn, { displayName: "Country" });
breeze.Validator.messageTemplates["countryIsUS"] = "'%displayName%' must start with 'US'";
}
function test_demo() {
var manager = new breeze.EntityManager('api/northwind');
var query = new breeze.EntityQuery()
.from("Employees");
manager.executeQuery(query).then(function (data) { });
}

731
breeze/breeze-1.0.d.ts vendored Normal file
View File

@@ -0,0 +1,731 @@
// Type definitions for Breeze 1.0
// Project: http://www.breezejs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Updated Jan 14 2011 - Jay Traband (www.ideablade.com)
declare module BreezeCore {
interface ErrorCallback {
(error: Error): void;
}
interface IEnum {
contains(object: any): bool;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
}
class Enum implements IEnum {
constructor (name: string, methodObj?: any);
addSymbol(propertiesObj?: any): EnumSymbol;
contains(object: any): bool;
fromName(name: string): EnumSymbol;
getNames(): string[];
getSymbols(): EnumSymbol[];
static isSymbol(object: any): bool;
seal(): void;
}
class EnumSymbol {
parentEnum: IEnum;
getName(): string;
toString(): string;
}
class Event {
constructor (name: string, publisher: any, defaultErrorCallback?: ErrorCallback);
static enable(eventName: string, target: any): void;
static enable(eventName: string, target: any, isEnabled: bool): void;
static enable(eventName: string, target: any, isEnabled: Function): void;
static isEnabled(eventName: string, target: any): bool;
publish(data: any, publishAsync?: bool, errorCallback?: ErrorCallback): void;
publishAsync(data: any, errorCallback?: ErrorCallback): void;
subscribe(callback?: (data: any) => void ): number;
unsubscribe(unsubKey: number): bool;
}
}
declare module Breeze {
interface Entity {
entityAspect: EntityAspect;
entityType: EntityType;
}
interface ComplexObject {
complexAspect: ComplexAspect;
complexType: ComplexType;
}
interface IProperty {
name: string;
parentEntityType: EntityType;
validators: Validator[];
isDataProperty: bool;
isNavigationProperty: bool;
}
interface IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
namespace: string;
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
}
class AutoGeneratedKeyType {
static Identity: AutoGeneratedKeyType;
static KeyGenerator: AutoGeneratedKeyType;
static None: AutoGeneratedKeyType;
}
class ComplexAspect {
complexObject: ComplexObject;
entityAspect: EntityAspect;
parent: Object;
parentProperty: DataProperty;
propertyPath: string;
originalValues: Object;
}
class ComplexType implements IStructuralType {
complexProperties: DataProperty[];
dataProperties: DataProperty[];
name: string;
namespace: string;
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
addProperty(dataProperty: DataProperty);
getProperties(): DataProperty[];
}
class DataProperty implements IProperty {
complexTypeName: string;
concurrencyMode: string;
dataType: DataTypeSymbol;
defaultValue: any;
fixedLength: bool;
isComplexProperty: bool;
isDataProperty: bool;
isNavigationProperty: bool;
isNullable: bool;
isPartOfKey: bool;
isUnmapped: bool;
maxLength: number;
name: string;
nameOnServer: string;
parentEntityType: EntityType;
relatedNavigationProperty: NavigationProperty;
validators: Validator[];
constructor (config: DataPropertyOptions);
}
interface DataPropertyOptions {
complexTypeName?: string;
concurrencyMode?: string;
dataType?: DataTypeSymbol;
defaultValue?: any;
fixedLength?: bool;
isNullable?: bool;
isPartOfKey?: bool;
isUnmapped?: bool;
maxLength?: number;
name?: string;
nameOnServer?: string;
validators?: Validator[];
}
class DataService {
adapterName: string;
hasServerMetadata: bool;
serviceName: string;
constructor(config: DataServiceOptions);
}
interface DataServiceOptions {
adapterName?: string;
hasServerMetadata?: bool;
serviceName?: string;
}
class DataTypeSymbol extends BreezeCore.EnumSymbol {
defaultValue: any;
isNumeric: bool;
}
interface DataType extends BreezeCore.IEnum {
Binary: DataTypeSymbol;
Boolean: DataTypeSymbol;
Byte: DataTypeSymbol;
DateTime: DataTypeSymbol;
Decimal: DataTypeSymbol;
Double: DataTypeSymbol;
Guid: DataTypeSymbol;
Int16: DataTypeSymbol;
Int32: DataTypeSymbol;
Int64: DataTypeSymbol;
Single: DataTypeSymbol;
String: DataTypeSymbol;
Time: DataTypeSymbol;
Undefined: DataTypeSymbol;
toDataType(typeName: string): DataTypeSymbol;
parseDateFromServer(date: any): Date;
}
declare var DataType: DataType;
class EntityActionSymbol extends BreezeCore.EnumSymbol {
}
interface EntityAction extends BreezeCore.IEnum {
AcceptChanges: EntityActionSymbol;
Attach: EntityActionSymbol;
AttachOnImport: EntityActionSymbol;
AttachOnQuery: EntityActionSymbol;
Clear: EntityActionSymbol;
Detach: EntityActionSymbol;
EntityStateChange: EntityActionSymbol;
MergeOnImport: EntityActionSymbol;
MergeOnSave: EntityActionSymbol;
MergeOnQuery: EntityActionSymbol;
PropertyChange: EntityActionSymbol;
RejectChanges: EntityActionSymbol;
}
var EntityAction: EntityAction;
class EntityAspect {
entity: Entity;
entityManager: EntityManager;
entityState: EntityStateSymbol;
isBeingSaved: bool;
originalValues: any;
propertyChanged: PropertyChangedEvent;
validationErrorsChanged: ValidationErrorsChangedEvent;
acceptChanges(): void;
addValidationError(validationError: ValidationError): void;
clearValidationErrors(): void;
getKey(forceRefresh?: bool): EntityKey;
getValidationErrors(): ValidationError[];
getValidationErrors(property: string): ValidationError[];
getValidationErrors(property: IProperty): ValidationError[];
loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): Promise;
loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): Promise;
rejectChanges(): void;
removeValidationError(validator: Validator): void;
removeValidationError(validator: Validator, property: DataProperty): void;
removeValidationError(validator: Validator, property: NavigationProperty): void;
setDeleted(): void;
setModified(): void;
setUnchanged(): void;
validateEntity(): bool;
validateProperty(property: string, context?: any): bool;
validateProperty(property: DataProperty, context?: any): bool;
validateProperty(property: NavigationProperty, context?: any): bool;
}
class PropertyChangedEventArgs {
entity: Entity;
propertyName: string;
oldValue: any;
newValue: any;
}
class PropertyChangedEvent extends BreezeCore.Event {
subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number;
}
class ValidationErrorsChangedEventArgs {
entity: Entity;
added: ValidationError[];
removed: ValidationError[];
}
class ValidationErrorsChangedEvent extends BreezeCore.Event {
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number;
}
class EntityKey {
constructor (entityType: EntityType, keyValue: any);
constructor (entityType: EntityType, keyValues: any[]);
equals(entityKey: EntityKey): bool;
static equals(k1: EntityKey, k2: EntityKey): bool;
}
class EntityManager {
dataService: DataService;
keyGeneratorCtor: Function;
metadataStore: MetadataStore;
queryOptions: QueryOptions;
saveOptions: SaveOptions;
serviceName: string;
validationOptions: ValidationOptions;
entityChanged: EntityChangedEvent;
hasChangesChanged: BreezeCore.Event;
constructor (config?: EntityManagerOptions);
constructor (config?: string);
addEntity(entity: Entity): Entity;
attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity;
clear(): void;
createEmptyCopy(): EntityManager;
detachEntity(entity: Entity): bool;
createEntity(entityTypeName: string, propertyInitializer: {}): Entity;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQueryLocally(query: EntityQuery): Entity[];
exportEntities(entities?: Entity[]): string;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(entityKey: EntityKey): Entity;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
generateTempKeyValue(entity: Entity): any;
getChanges(): Entity[];
getChanges(entityTypeName: string): Entity[];
getChanges(entityTypeNames: string[]): Entity[];
getChanges(entityType: EntityType): Entity[];
getChanges(entityTypes: EntityType[]): Entity[];
getEntities(entityTypeName: string, entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypeNames?: string[], entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypeName?: string, entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityTypeNames?: string[], entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityType: EntityType, entityState?: EntityStateSymbol): Entity[];
getEntities(entityTypes?: EntityType[], entityState?: EntityStateSymbol): Entity[];
getEntities(entityType?: EntityType, entityStates?: EntityStateSymbol[]): Entity[];
getEntities(entityTypes?: EntityType[], entityStates?: EntityStateSymbol[]): Entity[];
getEntityByKey(typeName: string, keyValue: any): Entity;
getEntityByKey(typeName: string, keyValues: any[]): Entity;
getEntityByKey(entityKey: EntityKey): Entity;
hasChanges(): bool;
hasChanges(entityTypeName: string): bool;
hasChanges(entityTypeNames: string[]): bool;
hasChanges(entityType: EntityType): bool;
hasChanges(entityTypes: EntityType[]): bool;
static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; }): EntityManager;
rejectChanges(): Entity[];
saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): Promise;
setProperties(config: EntityManagerProperties): void;
}
interface EntityManagerOptions {
serviceName?: string;
dataService?: DataService;
metadataStore?: MetadataStore;
queryOptions?: QueryOptions;
saveOptions?: SaveOptions;
validationOptions?: ValidationOptions;
keyGeneratorCtor?: Function;
}
interface EntityManagerProperties {
serviceName?: string;
dataService?: DataService;
queryOptions?: QueryOptions;
saveOptions?: SaveOptions;
validationOptions?: ValidationOptions;
keyGeneratorCtor?: Function;
}
interface ExecuteQuerySuccessCallback {
(data: { results: Entity[]; query: EntityQuery; XHR: XMLHttpRequest; }): void;
}
interface ExecuteQueryErrorCallback {
(error: { query: EntityQuery; XHR: XMLHttpRequest; }): void;
}
interface SaveChangesSuccessCallback {
(saveResult: { entities: Entity[]; keyMappings: any; XHR: XMLHttpRequest; }): void;
}
interface SaveChangesErrorCallback {
(error: { XHR: XMLHttpRequest; }): void;
}
class EntityChangedEventArgs {
entity: Entity;
entityAction: EntityActionSymbol;
args: Object;
}
class EntityChangedEvent extends BreezeCore.Event {
subscribe(callback?: (data: EntityChangedEventArgs) => void ): number;
}
class EntityQuery {
entityManager: EntityManager;
orderByClause: OrderByClause;
parameters: Object;
queryOptions: QueryOptions;
resourceName: string;
skipCount: number;
takeCount: number;
wherePredicate: Predicate;
constructor (resourceName?: string);
execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeLocally(): Entity[];
expand(propertyPaths: string[]): EntityQuery;
expand(propertyPaths: string): EntityQuery;
static from(resourceName: string): EntityQuery;
from(resourceName: string): EntityQuery;
static fromEntities(entity: Entity): EntityQuery;
static fromEntities(entities: Entity[]): EntityQuery;
static fromEntityKey(entityKey: EntityKey): EntityQuery;
static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery;
inlineCount(enabled?: bool): EntityQuery;
orderBy(propertyPaths: string): EntityQuery;
orderBy(propertyPaths: string[]): EntityQuery;
orderByDesc(propertyPaths: string): EntityQuery;
orderByDesc(propertyPaths: string[]): EntityQuery;
select(propertyPaths: string): EntityQuery;
select(propertyPaths: string[]): EntityQuery;
skip(count: number): EntityQuery;
take(count: number): EntityQuery;
top(count: number): EntityQuery;
using(obj: EntityManager): EntityQuery;
using(obj: MergeStrategySymbol): EntityQuery;
using(obj: FetchStrategySymbol): EntityQuery;
where(predicate: Predicate): EntityQuery;
where(property: string, operator: string, value: any): EntityQuery;
where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery;
where(predicate: FilterQueryOpSymbol): EntityQuery;
withParameters(params: Object): EntityQuery;
}
interface OrderByClause {
}
class EntityStateSymbol extends BreezeCore.EnumSymbol {
isAdded(): bool;
isAddedModifiedOrDeleted(): bool;
isDeleted(): bool;
isDetached(): bool;
isModified(): bool;
isUnchanged(): bool;
isUnchangedOrModified(): bool;
}
interface EntityState extends BreezeCore.IEnum {
Added: EntityStateSymbol;
Deleted: EntityStateSymbol;
Detached: EntityStateSymbol;
Modified: EntityStateSymbol;
Unchanged: EntityStateSymbol;
}
var EntityState: EntityState;
class EntityType implements IStructuralType {
autoGeneratedKeyType: AutoGeneratedKeyType;
complexProperties: DataProperty[];
concurrencyProperties: DataProperty[];
dataProperties: DataProperty[];
defaultResourceName: string;
foreignKeyProperties: DataProperty[];
keyProperties: DataProperty[];
metadataStore: MetadataStore;
name: string;
namespace: string;
navigationProperties: NavigationProperty[];
shortName: string;
unmappedProperties: DataProperty[];
validators: Validator[];
constructor (config: MetadataStore);
constructor (config: EntityTypeOptions);
addProperty(property: IProperty): void;
addValidator(validator: Validator, property?: IProperty): void;
createEntity(initialValues?: Object): Entity;
getDataProperty(propertyName: string): DataProperty;
getEntityCtor(): Function;
getNavigationProperty(propertyName: string): NavigationProperty;
getProperties(): IProperty[];
getProperty(propertyPath: string, throwIfNotFound?: bool): IProperty;
getPropertyNames(): string[];
setProperties(config: EntityTypeProperties): void;
toString(): string;
}
interface EntityTypeOptions {
shortName?: string;
namespace?: string;
autogeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
}
interface EntityTypeProperties {
autogeneratedKeyType?: AutoGeneratedKeyType;
defaultResourceName?: string;
}
class FetchStrategySymbol extends BreezeCore.EnumSymbol {
}
interface FetchStrategy extends BreezeCore.IEnum {
FromLocalCache: FetchStrategySymbol;
FromServer: FetchStrategySymbol;
}
var FetchStrategy: FetchStrategy;
class FilterQueryOpSymbol extends BreezeCore.EnumSymbol {
}
interface FilterQueryOp extends BreezeCore.IEnum {
Contains: FilterQueryOpSymbol;
EndsWith: FilterQueryOpSymbol;
Equals: FilterQueryOpSymbol;
GreaterThan: FilterQueryOpSymbol;
GreaterThanOrEqual: FilterQueryOpSymbol;
LessThan: FilterQueryOpSymbol;
LessThanOrEqual: FilterQueryOpSymbol;
NotEquals: FilterQueryOpSymbol;
StartsWith: FilterQueryOpSymbol;
}
var FilterQueryOp: FilterQueryOp;
class LocalQueryComparisonOptions {
static caseInsensitiveSQL: LocalQueryComparisonOptions;
static defaultInstance: LocalQueryComparisonOptions;
constructor (config: { name?: string; isCaseSensitive?: bool; usesSql92CompliantStringComparison?: bool; });
setAsDefault(): void;
}
class MergeStrategySymbol extends BreezeCore.EnumSymbol {
}
interface MergeStrategy extends BreezeCore.IEnum {
OverwriteChanges: MergeStrategySymbol;
PreserveChanges: MergeStrategySymbol;
}
var MergeStrategy: MergeStrategy;
class MetadataStore {
namingConvention: NamingConvention;
constructor (config?: MetadataStoreOptions);
addDataService(dataService: DataService): void;
addEntityType(structuralType: IStructuralType): void;
exportMetadata(): string;
fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
getDataService(serviceName: string): DataService;
getEntityType(entityTypeName: string, okIfNotFound?: bool): IStructuralType;
getEntityTypes(): IStructuralType[];
hasMetadataFor(serviceName: string): bool;
static importMetadata(exportedString: string): MetadataStore;
importMetadata(exportedString: string): MetadataStore;
isEmpty(): bool;
registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) =>void ): void;
trackUnmappedType(entityCtor: Function, interceptor?: Function);
}
interface MetadataStoreOptions {
namingConvention?: NamingConvention;
localQueryComparisonOptions?: LocalQueryComparisonOptions;
}
class NamingConvention {
static camelCase: NamingConvention;
static defaultInstance: NamingConvention;
static none: NamingConvention;
constructor (config: NamingConventionOptions);
clientPropertyNameToServer(clientPropertyName: string): string;
clientPropertyNameToServer(clientPropertyName: string, property: IProperty): string;
serverPropertyNameToClient(serverPropertyName: string): string;
serverPropertyNameToClient(serverPropertyName: string, property: IProperty): string;
setAsDefault();
}
interface NamingConventionOptions {
serverPropertyNameToClient?: (name: string) => string;
clientPropertyNameToServer?: (name: string) => string;
}
class NavigationProperty implements IProperty {
associationName: string;
entityType: EntityType;
foreignKeyNames: string[];
inverse: NavigationProperty;
isDataProperty: bool;
isNavigationProperty: bool;
isScalar: bool;
name: string;
parentEntityType: EntityType;
relatedDataProperties: DataProperty[];
validators: Validator[];
constructor (config: NavigationPropertyOptions);
}
interface NavigationPropertyOptions {
name?: string;
nameOnServer?: string;
entityTypeName: string;
isScalar?: bool;
associationName?: string;
foreignKeyNames?: string[];
foreignKeyNamesOnServer?: string[];
validators?: Validator[];
}
class Predicate {
constructor (property: string, operator: string, value: any, valueIsLiteral?: bool);
constructor (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool);
and: PredicateMethod;
static and: PredicateMethod;
static create: PredicateMethod;
static isPredicate(o: any): bool;
static not(predicate: Predicate): Predicate;
not(): Predicate;
static or: PredicateMethod;
or: PredicateMethod;
toFunction(): Function;
toString(): string;
validate(entityType: EntityType): void;
}
interface PredicateMethod {
(predicates: Predicate[]): Predicate;
(...predicates: Predicate[]): Predicate;
(property: string, operator: string, value: any, valueIsLiteral?: bool): Predicate;
(property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: bool): Predicate;
}
class Promise {
fail(errorCallback: Function): Promise;
fin(finallyCallback: Function): Promise;
then(callback: Function): Promise;
}
class QueryOptions {
static defaultInstance: QueryOptions;
fetchStrategy: FetchStrategySymbol;
mergeStrategy: MergeStrategySymbol;
constructor (config?: QueryOptionsConfiguration);
setAsDefault(): void;
using(config: QueryOptionsConfiguration): QueryOptions;
using(config: MergeStrategySymbol): QueryOptions;
using(config: FetchStrategySymbol): QueryOptions;
}
interface QueryOptionsConfiguration {
fetchStrategy?: FetchStrategySymbol;
mergeStrategy?: MergeStrategySymbol;
}
class SaveOptions {
allowConcurrentSaves: bool;
static defaultInstance: SaveOptions;
constructor (config?: { allowConcurrentSaves?: bool; });
setAsDefault(): SaveOptions;
}
class ValidationError {
context: any;
errorMessage: string;
property: IProperty;
propertyName: string;
validator: Validator;
constructor (validator: Validator, context: any, errorMessage: string);
}
class ValidationOptions {
static defaultInstance: ValidationOptions;
validateOnAttach: bool;
validateOnPropertyChange: bool;
validateOnQuery: bool;
validateOnSave: bool;
constructor (config?: ValidationOptionsConfiguration);
setAsDefault(): ValidationOptions;
using(config: ValidationOptionsConfiguration): ValidationOptions;
}
interface ValidationOptionsConfiguration {
validateOnAttach?: bool;
validateOnSave?: bool;
validateOnQuery?: bool;
validateOnPropertyChange?: bool;
}
class Validator {
static messageTemplates: any;
constructor (name: string, validatorFn: ValidatorFunction, context?: any);
static bool(): Validator;
static byte(): Validator;
static date(): Validator;
static duration(): Validator;
getMessage(): string;
static guid(): Validator;
static int16(): Validator;
static int32(): Validator;
static int64(): Validator;
static maxLength(context: { maxLength: number; }): Validator;
static number(): Validator;
static required(): Validator;
static string(): Validator;
static stringLength(context: { maxLength: number; minLength: number; }): Validator;
validate(value: any, context?: any): ValidationError;
}
interface ValidatorFunction {
(value: any, context: ValidatorFunctionContext): void;
}
interface ValidatorFunctionContext {
value: any;
validatorName: string;
displayName: string;
messageTemplate: string;
message?: string;
}
}

View File

@@ -1,7 +1,6 @@
/// <reference path="breeze.d.ts" />
import breeze = module(Breeze);
import core = module(BreezeCore);
import core = module(breezeCore);
function test_dataType() {
var typ = breeze.DataType.DateTime;
@@ -9,9 +8,10 @@ function test_dataType() {
var isNumber = typ.isNumeric;
var dv = typ.defaultValue;
var symbs = breeze.DataType.getSymbols();
var x = typ.parentEnum === <BreezeCore.IEnum> breeze.DataType;
var x = typ.parentEnum === <breezeCore.IEnum> breeze.DataType;
var isFalse = breeze.DataType.contains(breeze.DataType.Double);
var dt = breeze.DataType.fromName("Decimal");
}
function test_dataProperty() {
@@ -33,6 +33,7 @@ function test_dataService() {
var em = new breeze.EntityManager({
dataService: ds
});
}
function test_entityAspect() {
@@ -125,12 +126,13 @@ function test_metadataStore() {
function test_entityManager() {
var entityManager = new breeze.EntityManager("api/NorthwindIBModel");
var entityManager = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
var em1 = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
var metadataStore = new breeze.MetadataStore();
var entityManager = new breeze.EntityManager({
serviceName: "api/NorthwindIBModel",
metadataStore: metadataStore
});
return new breeze.QueryOptions({
mergeStrategy: null,
fetchStrategy: this.fetchStrategy
@@ -152,6 +154,10 @@ function test_entityManager() {
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var cust1 = custType.createEntity();
em1.addEntity(cust1);
var cust2 = em1.createEntity("Customer", { companyName: "foo" });
var cust3 = em1.createEntity("foo", { xxx: 3 }, breeze.EntityState.Added);
em1.attachEntity(cust1, breeze.EntityState.Added);
em1.clear();
var em2 = em1.createEmptyCopy();
@@ -239,7 +245,8 @@ function test_entityManager() {
if (em1.hasChanges(custType)) { }
var custType = <breeze.EntityType> em1.metadataStore.getEntityType("Customer");
var orderType = <breeze.EntityType> em1.metadataStore.getEntityType("Order");
if (em1.hasChanges([custType, orderType])) { }
if (em1.hasChanges([custType, orderType])) { };
var bundle = em1.exportEntities();
window.localStorage.setItem("myEntityManager", bundle);
var bundleFromStorage = window.localStorage.getItem("myEntityManager");
@@ -279,10 +286,10 @@ function test_entityManager() {
var entity = changeArgs.entity;
});
var em = new breeze.EntityManager({ serviceName: "api/NorthwindIBModel" });
//em.hasChanges.subscribe(function (args) {
// var hasChanges = args.hasChanges;
// var entityManager = args.entityManager;
//});
em.hasChangesChanged.subscribe(function (args) {
var hasChanges = args.hasChanges;
var entityManager = args.entityManager;
});
}
function test_entityQuery() {
@@ -377,6 +384,8 @@ function test_entityQuery() {
var em = new breeze.EntityManager(serviceName);
var query = new breeze.EntityQuery("Orders")
.using(breeze.FetchStrategy.FromLocalCache);
var adapter = new breeze.JsonResultsAdapter({ name: "foo", visitNode: function (x) { return x; } });
var q2 = query.using(adapter);
var query = new breeze.EntityQuery("Customers")
.where("CompanyName", "startsWith", "C");
var query = new breeze.EntityQuery("Customers")
@@ -393,6 +402,7 @@ function test_entityQuery() {
.where("toLower(CompanyName)", "startsWith", "c");
var query = new breeze.EntityQuery("Customers")
.where("toUpper(substring(CompanyName, 1, 2))", breeze.FilterQueryOp.Equals, "OM");
var q2 = query.toType("foo").orderBy("foo2");
}
function test_entityState() {

99
breeze/breeze.d.ts vendored
View File

@@ -1,12 +1,13 @@
// Type definitions for Breeze 1.0
// Type definitions for Breeze 1.2.7
// Project: http://www.breezejs.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions by: Boris Yankov <https://github.com/borisyankov/>,
// IdeaBlade <https://github.com/IdeaBlade/Breeze/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Updated Jan 14 2011 - Jay Traband (www.ideablade.com)
// Updated March 27 2013 - John Lantz (www.ideablade.com)
declare module BreezeCore {
declare module breezeCore {
interface ErrorCallback {
(error: Error): void;
@@ -53,7 +54,7 @@ declare module BreezeCore {
}
}
declare module Breeze {
declare module breeze {
interface Entity {
entityAspect: EntityAspect;
@@ -151,6 +152,7 @@ declare module Breeze {
adapterName: string;
hasServerMetadata: bool;
serviceName: string;
jsonResultsAdapter: JsonResultsAdapter;
constructor(config: DataServiceOptions);
}
@@ -158,13 +160,38 @@ declare module Breeze {
adapterName?: string;
hasServerMetadata?: bool;
serviceName?: string;
jsonResultsAdapter?: JsonResultsAdapter;
}
class DataTypeSymbol extends BreezeCore.EnumSymbol {
class JsonResultsAdapter {
name: string;
extractResults: (data: {}) => {};
visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: bool; };
constructor(config: {
name: string;
extractResults?: (data: {}) => {};
visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: bool; };
});
}
interface QueryContext {
query: any; // how to also say it could be an EntityQuery or a string
entityManager: EntityManager;
jsonResultsAdapter: JsonResultsAdapter;
mergeStrategy: MergeStrategy;
}
interface NodeContext {
nodeType: string;
}
class DataTypeSymbol extends breezeCore.EnumSymbol {
defaultValue: any;
isNumeric: bool;
}
interface DataType extends BreezeCore.IEnum {
interface DataType extends breezeCore.IEnum {
Binary: DataTypeSymbol;
Boolean: DataTypeSymbol;
Byte: DataTypeSymbol;
@@ -185,9 +212,9 @@ declare module Breeze {
}
declare var DataType: DataType;
class EntityActionSymbol extends BreezeCore.EnumSymbol {
class EntityActionSymbol extends breezeCore.EnumSymbol {
}
interface EntityAction extends BreezeCore.IEnum {
interface EntityAction extends breezeCore.IEnum {
AcceptChanges: EntityActionSymbol;
Attach: EntityActionSymbol;
AttachOnImport: EntityActionSymbol;
@@ -248,7 +275,7 @@ declare module Breeze {
newValue: any;
}
class PropertyChangedEvent extends BreezeCore.Event {
class PropertyChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: PropertyChangedEventArgs) => void ): number;
}
@@ -258,7 +285,7 @@ declare module Breeze {
removed: ValidationError[];
}
class ValidationErrorsChangedEvent extends BreezeCore.Event {
class ValidationErrorsChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void ): number;
}
@@ -280,7 +307,7 @@ declare module Breeze {
validationOptions: ValidationOptions;
entityChanged: EntityChangedEvent;
// hasChanges: BreezeCore.Event;
hasChangesChanged: HasChangesChangedEvent;
constructor (config?: EntityManagerOptions);
constructor (config?: string);
@@ -289,17 +316,17 @@ declare module Breeze {
attachEntity(entity: Entity, entityState?: EntityStateSymbol): Entity;
clear(): void;
createEmptyCopy(): EntityManager;
createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol) : Entity;
detachEntity(entity: Entity): bool;
executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): Promise;
executeQueryLocally(query: EntityQuery): Entity[];
exportEntities(entities?: Entity[]): string;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Entity;
fetchEntityByKey(entityKey: EntityKey): Entity;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: bool): Promise;
fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: bool): Promise;
fetchEntityByKey(entityKey: EntityKey): Promise;
fetchMetadata(callback?: (schema: any) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
generateTempKeyValue(entity: Entity): any;
getChanges(): Entity[];
getChanges(entityTypeName: string): Entity[];
@@ -376,10 +403,19 @@ declare module Breeze {
args: Object;
}
class EntityChangedEvent extends BreezeCore.Event {
class EntityChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: EntityChangedEventArgs) => void ): number;
}
class HasChangesChangedEventArgs {
entityManager: EntityManager;
hasChanges: bool;
}
class HasChangesChangedEvent extends breezeCore.Event {
subscribe(callback?: (data: HasChangesChangedEventArgs) => void ): number;
}
class EntityQuery {
entityManager: EntityManager;
orderByClause: OrderByClause;
@@ -412,10 +448,13 @@ declare module Breeze {
skip(count: number): EntityQuery;
take(count: number): EntityQuery;
top(count: number): EntityQuery;
toType(typeName: string): EntityQuery;
toType(type: EntityType): EntityQuery;
using(obj: EntityManager): EntityQuery;
using(obj: MergeStrategySymbol): EntityQuery;
using(obj: FetchStrategySymbol): EntityQuery;
using(obj: FetchStrategySymbol): EntityQuery;
using(obj: JsonResultsAdapter): EntityQuery;
where(predicate: Predicate): EntityQuery;
where(property: string, operator: string, value: any): EntityQuery;
@@ -427,7 +466,7 @@ declare module Breeze {
interface OrderByClause {
}
class EntityStateSymbol extends BreezeCore.EnumSymbol {
class EntityStateSymbol extends breezeCore.EnumSymbol {
isAdded(): bool;
isAddedModifiedOrDeleted(): bool;
isDeleted(): bool;
@@ -436,7 +475,7 @@ declare module Breeze {
isUnchanged(): bool;
isUnchangedOrModified(): bool;
}
interface EntityState extends BreezeCore.IEnum {
interface EntityState extends breezeCore.IEnum {
Added: EntityStateSymbol;
Deleted: EntityStateSymbol;
Detached: EntityStateSymbol;
@@ -489,17 +528,17 @@ declare module Breeze {
defaultResourceName?: string;
}
class FetchStrategySymbol extends BreezeCore.EnumSymbol {
class FetchStrategySymbol extends breezeCore.EnumSymbol {
}
interface FetchStrategy extends BreezeCore.IEnum {
interface FetchStrategy extends breezeCore.IEnum {
FromLocalCache: FetchStrategySymbol;
FromServer: FetchStrategySymbol;
}
var FetchStrategy: FetchStrategy;
class FilterQueryOpSymbol extends BreezeCore.EnumSymbol {
class FilterQueryOpSymbol extends breezeCore.EnumSymbol {
}
interface FilterQueryOp extends BreezeCore.IEnum {
interface FilterQueryOp extends breezeCore.IEnum {
Contains: FilterQueryOpSymbol;
EndsWith: FilterQueryOpSymbol;
Equals: FilterQueryOpSymbol;
@@ -521,9 +560,9 @@ declare module Breeze {
setAsDefault(): void;
}
class MergeStrategySymbol extends BreezeCore.EnumSymbol {
class MergeStrategySymbol extends breezeCore.EnumSymbol {
}
interface MergeStrategy extends BreezeCore.IEnum {
interface MergeStrategy extends breezeCore.IEnum {
OverwriteChanges: MergeStrategySymbol;
PreserveChanges: MergeStrategySymbol;
}
@@ -536,8 +575,8 @@ declare module Breeze {
addDataService(dataService: DataService): void;
addEntityType(structuralType: IStructuralType): void;
exportMetadata(): string;
fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: BreezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: string, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
fetchMetadata(dataService: DataService, callback?: (data) => void , errorCallback?: breezeCore.ErrorCallback): Promise;
getDataService(serviceName: string): DataService;
getEntityType(entityTypeName: string, okIfNotFound?: bool): IStructuralType;
getEntityTypes(): IStructuralType[];

267
casperjs/casperjs.d.ts vendored Normal file
View File

@@ -0,0 +1,267 @@
// Type definitions for CasperJS v1.0.0 API
// Project: http://casperjs.org/
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../phantomjs/phantomjs.d.ts" />
interface Casper {
constructor (options: CasperOptions);
// Properties
__utils__: ClientUtils;
// Methods
back();
base64encode(url: string, method?: string, data?: any);
click(selector: string);
clickLabel(label: string, tag?: string);
capture(targetFilePath: string, clipRect: ClipRect);
captureBase64(format: string);
captureBase64(format: string, area: string);
captureBase64(format: string, area: ClipRect);
captureBase64(format: string, area: any);
captureSelector(targetFile: string, selector: string);
clear();
debugHTML(selector?: string, outer?: bool);
debugPage();
die(message: string, status?: number);
download(url: string, target?: string, method?: string, data?: any);
each(array: Array, fn: (self, link) => void);
echo(message: string, style?: string);
evaluate(fn: Function, ...args: any[]);
evaluateOrDie(fn: Function, message?: string);
exit(status?: number);
exists(selector: string);
fetchText(selector: string);
forward();
log(message: string, level?: string, space?: string);
fill(selector: string, values: any, submit?: bool);
getCurrentUrl(): string;
getElementAttribute(selector: string, attribute: string): string;
getElementBounds(selector: string): ElementBounds;
getElementsBounds(selector: string): ElementBounds[];
getElementInfo(selector: string): ElementInfo;
getFormValues(selector: string): any;
getGlobal(name: string): any;
getHTML(selector?: string, outer?: bool): string;
getPageContent(): string;
getTitle(): string;
mouseEvent(type: string, selector: string);
open(location: string, settings: OpenSettings): Casper;
reload(then?: (response: HttpResponse) => void);
repeat(times: number, then: Function);
resourceExists(test: Function);
resourceExists(test: string);
run(onComplete: Function, time?: number);
sendKeys(selector: string, keys: string, options?: any);
setHttpAuth(username: string, password: string);
start(url?: string, then?: (response: HttpResponse) => void): Casper;
status(asString: bool): any;
then(fn: (self?: Casper) => void);
thenClick(selector: string);
thenEvaluate(fn: Function, ...args: any[]);
thenOpen(location: string, then?: (response: HttpResponse) => void);
thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void);
thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]);
toString();
userAgent(agent: string);
viewport(width: number, height: number);
visible(selector: string);
wait(timeout: number, then?: Function);
waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number);
waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number);
waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number);
waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number);
waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number);
waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number);
waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number);
waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number);
waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number);
waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number);
warn(message: string);
withFrame(frameInfo: string, then: Function);
withFrame(frameInfo: number, then: Function);
withPopup(popupInfo: string, step: Function);
withPopup(popupInfo: RegExp, step: Function);
zoom(factor: number);
}
interface HttpResponse {
contentType: string;
headers: any[];
id: number;
redirectURL: string;
stage: string;
status: number;
statusText: string;
time: string;
url: string;
}
interface OpenSettings {
method: string;
data: any;
headers: any;
}
interface ElementBounds {
top: number;
left: number;
width: number;
height: number;
}
interface ElementInfo {
nodeName: string;
attributes: any;
tag: string;
html: string;
text: string;
x: number;
y: number;
width: number;
height: number;
visible: bool;
}
interface CasperOptions {
clientScripts: Array;
exitOnError: bool;
httpStatusHandlers: any;
logLevel: string;
onAlert: Function;
onDie: Function;
onError: Function;
onLoadError: Function;
onPageInitialized: Function;
onResourceReceived: Function;
onResourceRequested: Function;
onStepComplete: Function;
onStepTimeout: Function;
onTimeout: Function;
onWaitTimeout: Function;
page: WebPage;
pageSettings: any;
remoteScripts: Array;
safeLogs: bool;
stepTimeout: number;
timeout: number;
verbose: bool;
viewportSize: any;
waitTimeout: number;
}
interface ClientUtils {
echo(message: string);
encode(contents: string);
exists(selector: string);
findAll(selector: string);
findOne(selector: string);
getBase64(url: string, method?: string, data?: any);
getBinary(url: string, method?: string, data?: any);
getDocumentHeight();
getElementBounds(selector: string);
getElementsBounds(selector: string);
getElementByXPath(expression: string, scope?: HTMLElement);
getElementsByXPath(expression: string, scope?: HTMLElement);
getFieldValue(inputName: string);
getFormValues(selector: string);
mouseEvent(type: string, selector: string);
removeElementsByXPath(expression: string);
sendAJAX(url: string, method?: string, data?: any, async?: bool);
visible(selector: string);
}
interface Colorizer {
colorize(text: string, styleName: string);
format(text: string, style: any);
}
interface Tester {
assert(condition: bool, message?: string);
assertDoesntExist(selector: string, message?: string);
assertEquals(testValue: any, expected: any, message?: string);
assertEval(fn: Function, message: string, arguments: any);
assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any);
assertExists(selector: string, message?: string);
assertFalsy(subject: any, message?: string);
assertField(inputName: string, expected: string, message?: string);
assertHttpStatus(status: number, message?: string);
assertMatch(subject: any, pattern: RegExp, message?: string);
assertNot(subject: any, message?: string);
assertNotEquals(testValue: any, expected: any, message?: string);
assertNotVisible(selector: string, message?: string);
assertRaises(fn: Function, args: Array, message?: string);
assertSelectorDoesntHaveText(selector: string, text: string, message?: string);
assertSelectorExists(selector: string, message?: string);
assertSelectorHasText(selector: string, text: string, message?: string);
assertResourceExists(testFx: Function, message?: string);
assertTextExists(expected: string, message?: string);
assertTextDoesntExist(unexpected: string, message: string);
assertTitle(expected: string, message?: string);
assertTitleMatch(pattern: RegExp, message?: string);
assertTruthy(subject: any, message?: string);
assertType(input: any, type: string, message?: string);
assertUrlMatch(pattern: RegExp, message?: string);
assertVisible(selector: string, message?: string);
colorize(message: string, style: string);
comment(message: string);
done(expected?: number);
error(message: string);
fail(message: string);
formatMessage(message: string, style: string);
getFailures(): Cases;
getPasses(): Cases;
info(message: string);
pass(message: string);
renderResults(exit: bool, status: number, save: string);
}
interface Cases {
length: number;
cases: Case[];
}
interface Case {
success: bool;
type: string;
standard: string;
file: string;
values: CaseValues;
}
interface CaseValues {
subject: bool;
expected: bool;
}
interface Utils {
betterTypeOf(input: any);
dump(value: any);
fileExt(file: string);
fillBlanks(text: string, pad: number);
format(f: string, ...args: any[]);
getPropertyPath(obj: any, path: string);
inherits(ctor: any, superCtor: any);
isArray(value: any);
isCasperObject(value: any);
isClipRect(value: any);
isFalsy(subject: any);
isFunction(value: any);
isJsFile(file: string);
isNull(value: any);
isNumber(value: any);
isObject(value: any);
isRegExp(value: any);
isString(value: any);
isTruthy(subject: any);
isType(what: any, type: string);
isUndefined(value: any);
isWebPage(what: any);
mergeObjects(origin: any, add: any);
node(name: string, attributes: any);
serialize(value: any);
unique(array: Array);
}

156
cheerio/cheerio.d.ts vendored
View File

@@ -1,75 +1,81 @@
declare interface Cheerio {
addClass(classNames: string): Cheerio;
hasClass(className: string): bool;
removeClass(className?: any): Cheerio;
attr(attributeName: string, value: any): Cheerio;
attr(attributeName: string): string;
removeAttr(attributeName: any): Cheerio;
find(selector: string): Cheerio;
parent(): Cheerio;
next(): Cheerio;
prev(): Cheerio;
siblings(): Cheerio;
children(selector?: any): Cheerio;
each(func: (index: any, elem: any) => Cheerio);
map(callback: (index: any, domElement: Element) =>any): Cheerio;
filter(selector: string): Cheerio;
filter(func: (index: any) =>any): Cheerio;
first(): Cheerio;
last(): Cheerio;
eq(index: number): Cheerio;
append(...content: any[]): Cheerio;
prepend(...content: any[]): Cheerio;
after(...content: any[]): Cheerio;
before(...content: any[]): Cheerio;
remove(selector: string): Cheerio;
replaceWith(content: string): Cheerio;
empty(): Cheerio;
html(htmlString: string): Cheerio;
html(): string;
text(textString: string): Cheerio;
text(): string;
toArray(): any[];
clone() : Cheerio;
root() : Cheerio;
dom(): any;
contains(container: Element, contained: Element): bool;
isArray(obj: any): bool;
inArray(value: any, array: any[], fromIndex?: number): number;
merge(first: any[], second: any[]): any[];
}
declare interface CheerioOptionsInterface {
ignoreWhitespace?: bool;
xmlMode?: bool;
lowerCaseTags?: bool;
}
declare interface CheerioStatic {
(...selectors: any[]): Cheerio;
(): Cheerio;
}
declare module "cheerio" {
export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic;
}
// Type definitions for Cheerio
// Project: https://github.com/MatthewMueller/cheerio
// Definitions by: Bret Little <https://github.com/blittle>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare interface Cheerio {
addClass(classNames: string): Cheerio;
hasClass(className: string): bool;
removeClass(className?: any): Cheerio;
attr(attributeName: string, value: any): Cheerio;
attr(attributeName: string): string;
removeAttr(attributeName: any): Cheerio;
find(selector: string): Cheerio;
parent(): Cheerio;
next(): Cheerio;
prev(): Cheerio;
siblings(): Cheerio;
children(selector?: any): Cheerio;
each(func: (index: any, elem: any) => Cheerio);
map(callback: (index: any, domElement: Element) =>any): Cheerio;
filter(selector: string): Cheerio;
filter(func: (index: any) =>any): Cheerio;
first(): Cheerio;
last(): Cheerio;
eq(index: number): Cheerio;
append(...content: any[]): Cheerio;
prepend(...content: any[]): Cheerio;
after(...content: any[]): Cheerio;
before(...content: any[]): Cheerio;
remove(selector: string): Cheerio;
replaceWith(content: string): Cheerio;
empty(): Cheerio;
html(htmlString: string): Cheerio;
html(): string;
text(textString: string): Cheerio;
text(): string;
toArray(): any[];
clone() : Cheerio;
root() : Cheerio;
dom(): any;
contains(container: Element, contained: Element): bool;
isArray(obj: any): bool;
inArray(value: any, array: any[], fromIndex?: number): number;
merge(first: any[], second: any[]): any[];
}
declare interface CheerioOptionsInterface {
ignoreWhitespace?: bool;
xmlMode?: bool;
lowerCaseTags?: bool;
}
declare interface CheerioStatic {
(...selectors: any[]): Cheerio;
(): Cheerio;
}
declare module "cheerio" {
export function load (html : string, options?: CheerioOptionsInterface) : CheerioStatic;
}

View File

@@ -0,0 +1,50 @@
///<reference path="commander.d.ts"/>
//
// TODO: improve tests
// [the code below was extracted from the documentation and examples, but does not seem to cover all cases]
//
import program = module("commander");
program
.version('0.0.1')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path [./deploy.conf]')
.option('-T, --no-tests', 'ignore test hook')
// $ deploy setup stage
// $ deploy setup
program
.command('setup [env]')
.description('run setup commands for all envs')
.action(function (env) {
env = env || 'all';
console.log('setup for %s env(s)', env);
});
// $ deploy stage
// $ deploy production
program
.command('*')
.action(function (env) {
console.log('deploying "%s"', env);
});
program.option('-p, --pepper', 'add pepper');
program.option('-C, --chdir <path>', 'change the working directory');
program.prompt('Username: ', function (name) {
console.log('hi %s', name);
});
program.prompt('Description:', function (desc) {
console.log('description was "%s"', desc.trim());
});
program.promptForNumber("Enter a number:", (n) => { });
program.confirm("Confirm? ", (f) => { });
program.choose(["a", "b", "c"], (i) => { });

228
commander/commander.d.ts vendored Normal file
View File

@@ -0,0 +1,228 @@
// Type definitions for commanderjs 1.1.1
// Project: https://github.com/visionmedia/commander.js
// Definitions by: Marcelo Dezem <http://github.com/mdezem>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "commander" {
export interface Command {
/**
* The command name.
*/
name: string;
//
//
// NOTE: the methods below are COPIED to the module
// as functions exports. If changes need to be made here,
// remember to re-paste the definitions in the module.
// Read below to know why such ugly thing is required.
//
//
/**
* Register callback fn for the command.
*/
action(fn: (...args: any[]) => any): Command;
/**
* Define option with flags, description and optional coercion function and default value.
* The flags string should contain both the short and long flags
* separated by comma, a pipe or space. The following are all valid
* all will output this way when --help is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @param flags the option flags.
* @param description the option description. The description is printed when "--help" is used.
* @param coerceFn (optional) specifies a callback function to coerce the option arg.
* @param defaultValue (optional) specifies a default value.
*/
option(flags: string, description: string, coerceFn?: (value: string) => any, defaultValue?: any): Command;
/**
* Sets the command version
*/
version(version: string): Command;
/**
* Parse the arguments array and invokes the commands passing the parsed options.
* @param argv the arguments array.
*/
parse(argv: string[]): Command;
/**
* Gets or sets the command description.
* @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command.
*/
description(description: string): Command;
description(): string;
/**
* Gets or sets the usage help string.
*/
usage(usage: string): Command;
usage(): string;
/*
* Prompt the user for a value, calling the callback function.
*
* Supports single-line and multi-line prompts.
* To issue a single-line prompt simply add a whitespace
* to the end of label, something like "name: ", whereas
* for a multi-line prompt omit this "description:".
* @param label the label string to be printed in console.
* @param callback a callback function to handle the inputed string.
*/
prompt(label: string, callback: (value: string) => any): void;
promptForNumber(label: string, callback: (value: number) => any): void;
promptForDate(label: string, callback: (value: Date) => any): void;
promptSingleLine(label: string, callback: (value: string) => any): void;
promptMultiLine(label: string, callback: (value: string) => any): void;
/**
* Prompt for password with a label, a optional mask char and callback function.
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
password(label: string, mask: string, callback: (value: string) => any): void;
password(label: string, callback: (value: string) => any): void;
/**
* Prompts the user for a confirmation.
*/
confirm(label: string, callback: (flag: bool) => any): void;
/**
* Prompt for password with str, mask char and callback fn(val).
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
choose(options: string[], callback: (idx: number) => any): void;
choose(options: any[], callback: (idx: number) => any): void;
/**
* Add command with the specified name. Returns a new instance of Command.
*
* The .action() callback is invoked when the
* command name is specified via ARGV,
* and the remaining arguments are applied to the
* function for access.
* When the name is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of ARGV remaining.
*
* @param name the name of the command. Pass "*" to trap un-matched commands.
*/
command(name: string): Command;
}
//
//
// since TypeScript (and ECMA6) does not supports module.exports,
// there is no way to set the default Command instance as the module itself.
// It's ugly but the only way is to copy all the methods from Command
// and paste it in the module as functions exports.
//
//
/**
* Register callback fn for the command.
*/
export function action(fn: (...args: any[]) => any): Command;
/**
* Define option with flags, description and optional coercion function and default value.
* The flags string should contain both the short and long flags
* separated by comma, a pipe or space. The following are all valid
* all will output this way when --help is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @param flags the option flags.
* @param description the option description. The description is printed when "--help" is used.
* @param coerceFn (optional) specifies a callback function to coerce the option arg.
* @param defaultValue (optional) specifies a default value.
*/
export function option(flags: string, description: string, coerceFn?: (value: string) => any, defaultValue?: any): Command;
/**
* Sets the command version
*/
export function version(version: string): Command;
/**
* Parse the arguments array and invokes the commands passing the parsed options.
* @param argv the arguments array.
*/
export function parse(argv: string[]): Command;
/**
* Gets or sets the command description.
* @param description the new description for the command. When ommited this returns the current description, otherwise returns the current Command.
*/
export function description(description: string): Command;
export function description(): string;
/**
* Gets or sets the usage help string.
*/
export function usage(usage: string): Command;
export function usage(): string;
/*
* Prompt the user for a value, calling the callback function.
*
* Supports single-line and multi-line prompts.
* To issue a single-line prompt simply add a whitespace
* to the end of label, something like "name: ", whereas
* for a multi-line prompt omit this "description:".
* @param label the label string to be printed in console.
* @param callback a callback function to handle the inputed string.
*/
export function prompt(label: string, callback: (value: string) => any): void;
export function promptForNumber(label: string, callback: (value: number) => any): void;
export function promptForDate(label: string, callback: (value: Date) => any): void;
export function promptSingleLine(label: string, callback: (value: string) => any): void;
export function promptMultiLine(label: string, callback: (value: string) => any): void;
/**
* Prompt for password with a label, a optional mask char and callback function.
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
export function password(label: string, mask: string, callback: (value: string) => any): void;
export function password(label: string, callback: (value: string) => any): void;
/**
* Prompts the user for a confirmation.
*/
export function confirm(label: string, callback: (flag: bool) => any): void;
/**
* Prompt for password with str, mask char and callback fn(val).
* The mask string defaults to '', aka no output is written while typing, you may want to use "*" etc.
*/
export function choose(options: string[], callback: (idx: number) => any): void;
export function choose(options: any[], callback: (idx: number) => any): void;
/**
* Add command with the specified name. Returns a new instance of Command.
*
* The .action() callback is invoked when the
* command name is specified via ARGV,
* and the remaining arguments are applied to the
* function for access.
* When the name is "*" an un-matched command
* will be passed as the first arg, followed by
* the rest of ARGV remaining.
*
* @param name the name of the command. Pass "*" to trap un-matched commands.
*/
export function command(name: string): Command;
}

View File

@@ -1,29 +1,731 @@
/// <reference path="d3.d.ts" />
d3.selectAll("p").style("color", "white");
d3.select("body").style("background-color", "black");
d3.selectAll("p").style("color", function () {
return "hsl(" + Math.random() * 360 + ",100%,50%)";
});
d3.selectAll("p").style("color", function (d, i) {
return i % 2 ? "#fff" : "#eee";
});
d3.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.style("font-size", function (d) { return d + "px"; });
d3.select("body").selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.enter().append("p")
.text(function (d) { return "Im number " + d + "!"; });
var p = d3.select("body").selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.text(String);
p.enter().append("p")
.text(String);
p.exit().remove();
d3.select("body").transition()
.style("background-color", "black");
d3.selectAll("circle").transition()
.duration(750)
.delay(function (d, i) { return i * 10; })
.attr("r", function (d) { return Math.sqrt(d * scale); });
/// <reference path="d3.d.ts" />
//Example from http://bl.ocks.org/3887235
function testPieChart() {
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function (d) { return d.population; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", function (error, data) {
data.forEach(function (d) {
d.population = +d.population;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function (d) { return color(d.data.age); });
g.append("text")
.attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function (d) { return d.data.age; });
});
}
//Example from http://bl.ocks.org/3887051
function groupedBarChart() => {
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x0 = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var x1 = d3.scale.ordinal();
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x0)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", function (error, data) {
var ageNames = d3.keys(data[0]).filter(function (key) { return key !== "State"; });
data.forEach(function (d) {
d.ages = ageNames.map(function (name) { return { name: name, value: +d[name] }; });
});
x0.domain(data.map(function (d) { return d.State; }));
x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
y.domain([0, d3.max(data, function (d) { return d3.max(d.ages, function (d) { return d.value; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) { return "translate(" + x0(d.State) + ",0)"; });
state.selectAll("rect")
.data(function (d) { return d.ages; })
.enter().append("rect")
.attr("width", x1.rangeBand())
.attr("x", function (d) { return x1(d.name); })
.attr("y", function (d) { return y(d.value); })
.attr("height", function (d) { return height - y(d.value); })
.style("fill", function (d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(ageNames.reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
});
}
//Example from http://bl.ocks.org/3886208
function stackedBarChart() {
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", function (error, data) {
color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; }));
data.forEach(function (d) {
var y0 = 0;
d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; });
d.total = d.ages[d.ages.length - 1].y1;
});
data.sort(function (a, b) { return b.total - a.total; });
x.domain(data.map(function (d) { return d.State; }));
y.domain([0, d3.max(data, function (d) { return d.total; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Population");
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "g")
.attr("transform", function (d) { return "translate(" + x(d.State) + ",0)"; });
state.selectAll("rect")
.data(function (d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function (d) { return y(d.y1); })
.attr("height", function (d) { return y(d.y0) - y(d.y1); })
.style("fill", function (d) { return color(d.name); });
var legend = svg.selectAll(".legend")
.data(color.domain().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function (d) { return d; });
});
}
// example from http://bl.ocks.org/3886394
function normalizedBarChart() {
var margin = { top: 20, right: 100, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear()
.rangeRound([height, 0]);
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".0%"));
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("data.csv", function (error, data) {
color.domain(d3.keys(data[0]).filter(function (key) { return key !== "State"; }));
data.forEach(function (d) {
var y0 = 0;
d.ages = color.domain().map(function (name) { return { name: name, y0: y0, y1: y0 += +d[name] }; });
d.ages.forEach(function (d) { d.y0 /= y0; d.y1 /= y0; });
});
data.sort(function (a, b) { return b.ages[0].y1 - a.ages[0].y1; });
x.domain(data.map(function (d) { return d.State; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var state = svg.selectAll(".state")
.data(data)
.enter().append("g")
.attr("class", "state")
.attr("transform", function (d) { return "translate(" + x(d.State) + ",0)"; });
state.selectAll("rect")
.data(function (d) { return d.ages; })
.enter().append("rect")
.attr("width", x.rangeBand())
.attr("y", function (d) { return y(d.y1); })
.attr("height", function (d) { return y(d.y0) - y(d.y1); })
.style("fill", function (d) { return color(d.name); });
var legend = svg.select(".state:last-child").selectAll(".legend")
.data(function (d) { return d.ages; })
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d) { return "translate(" + x.rangeBand() / 2 + "," + y((d.y0 + d.y1) / 2) + ")"; });
legend.append("line")
.attr("x2", 10);
legend.append("text")
.attr("x", 13)
.attr("dy", ".35em")
.text(function (d) { return d.name; });
});
}
// example from http://bl.ocks.org/3885705
function sortablebarChart() {
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1, 1);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(formatPercent);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", function (error, data) {
data.forEach(function (d) {
d.frequency = +d.frequency;
});
x.domain(data.map(function (d) { return d.letter; }));
y.domain([0, d3.max(data, function (d) { return d.frequency; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function (d) { return y(d.frequency); })
.attr("height", function (d) { return height - y(d.frequency); });
d3.select("input").on("change", change);
var sortTimeout = setTimeout(function () {
d3.select("input").property("checked", true).each(change);
}, 2000);
function change() {
clearTimeout(sortTimeout);
var x0 = x.domain(data.sort(this.checked
? function (a, b) { return b.frequency - a.frequency; }
: function (a, b) { return d3.ascending(a.letter, b.letter); })
.map(function (d) { return d.letter; }))
.copy();
var transition = svg.transition().duration(750),
delay = function (d, i) { return i * 50; };
transition.selectAll(".bar")
.delay(delay)
.attr("x", function (d) { return x0(d.letter); });
transition.select(".x.axis")
.call(xAxis)
.selectAll("g")
.delay(delay);
}
});
}
//example from http://bl.ocks.org/4063318
function callenderView() {
var width = 960,
height = 136,
cellSize = 17; // cell size
var day = d3.time.format("%w"),
week = d3.time.format("%U"),
percent = d3.format(".1%"),
format = d3.time.format("%Y-%m-%d");
var color = d3.scale.quantize()
.domain([-.05, .05])
.range(d3.range(11).map(function (d) { return "q" + d + "-11"; }));
var svg = d3.select("body").selectAll("svg")
.data(d3.range(1990, 2011))
.enter().append("svg")
.attr("width", width)
.attr("height", height)
.attr("class", "RdYlGn")
.append("g")
.attr("transform", "translate(" + ((width - cellSize * 53) / 2) + "," + (height - cellSize * 7 - 1) + ")");
svg.append("text")
.attr("transform", "translate(-6," + cellSize * 3.5 + ")rotate(-90)")
.style("text-anchor", "middle")
.text(function (d) { return d; });
var rect = svg.selectAll(".day")
.data(function (d) { return d3.time.days(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("x", function (d) { return parseInt(week(d)) * cellSize; })
.attr("y", function (d) { return parseInt(day(d)) * cellSize; })
.datum(format);
rect.append("title")
.text(function (d) { return d; });
svg.selectAll(".month")
.data(function (d) { return d3.time.months(new Date(d, 0, 1), new Date(d + 1, 0, 1)); })
.enter().append("path")
.attr("class", "month")
.attr("d", monthPath);
d3.csv("dji.csv", function (error, csv) {
var data = d3.nest()
.key(function (d) { return d.Date; })
.rollup(function (d) { return (d[0].Close - d[0].Open) / d[0].Open; })
.map(csv);
rect.filter(function (d) { return d in data; })
.attr("class", function (d) { return "day " + color(data[d]); })
.select("title")
.text(function (d) { return d + ": " + percent(data[d]); });
});
function monthPath(t0) {
var t1 = new Date(t0.getFullYear(), t0.getMonth() + 1, 0),
d0 = +day(t0), w0 = +week(t0),
d1 = +day(t1), w1 = +week(t1);
return "M" + (w0 + 1) * cellSize + "," + d0 * cellSize
+ "H" + w0 * cellSize + "V" + 7 * cellSize
+ "H" + w1 * cellSize + "V" + (d1 + 1) * cellSize
+ "H" + (w1 + 1) * cellSize + "V" + 0
+ "H" + (w0 + 1) * cellSize + "Z";
}
d3.select(self.frameElement).style("height", "2910px");
}
// example from http://bl.ocks.org/3883245
function lineChart {
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", function (error, data) {
data.forEach(function (d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain(d3.extent(data, function (d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
}
//example from http://bl.ocks.org/3884914
function bivariateAreaChart {
var margin = { top: 20, right: 20, bottom: 30, left: 50 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y%m%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var area = d3.svg.area()
.x(function (d) { return x(d.date); })
.y0(function (d) { return y(d.low); })
.y1(function (d) { return y(d.high); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.tsv("data.tsv", function (error, data) {
data.forEach(function (d) {
d.date = parseDate(d.date);
d.low = +d.low;
d.high = +d.high;
});
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain([d3.min(data, function (d) { return d.low; }), d3.max(data, function (d) { return d.high; })]);
svg.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Temperature (ºF)");
});
}
//Example from http://bl.ocks.org/mbostock/1557377
function dragMultiples {
var width = 238,
height = 123,
radius = 20;
var drag = d3.behavior.drag()
.origin(Object)
.on("drag", dragmove);
var svg = d3.select("body").selectAll("svg")
.data(d3.range(16).map(function () { return { x: width / 2, y: height / 2 }; }))
.enter().append("svg")
.attr("width", width)
.attr("height", height);
svg.append("circle")
.attr("r", radius)
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.call(drag);
function dragmove(d) {
d3.select(this)
.attr("cx", d.x = Math.max(radius, Math.min(width - radius, d3.event.x)))
.attr("cy", d.y = Math.max(radius, Math.min(height - radius, d3.event.y)));
}
}
//Example from http://bl.ocks.org/mbostock/3892919
function panAndZoom {
var margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([-width / 2, width / 2])
.range([0, width]);
var y = d3.scale.linear()
.domain([-height / 2, height / 2])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width);
var zoom = d3.behavior.zoom()
.x(x)
.y(y)
.scaleExtent([1, 10])
.on("zoom", zoomed);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
}
}
//Example from http://bl.ocks.org/mbostock/1125997
function chainedTransitions() {
var w = 960,
h = 500,
y = d3.scale.ordinal().domain(d3.range(50)).rangePoints([20, h - 20]),
t = Date.now();
var svg = d3.select("body").append("svg:svg")
.attr("width", w)
.attr("height", h);
var circle = svg.selectAll("circle")
.data(y.domain())
.enter().append("svg:circle")
.attr("r", 16)
.attr("cx", 20)
.attr("cy", y)
.each(slide(20, w - 20));
function slide(x0, x1) {
t += 50;
return function() {
d3.select(this).transition()
.duration(t - Date.now())
.attr("cx", x1)
.each("end", slide(x1, x0));
};
}
}

1661
d3/d3.d.ts vendored

File diff suppressed because it is too large Load Diff

438
durandal/durandal.d.ts vendored Normal file
View File

@@ -0,0 +1,438 @@
// Type definitions for durandal 1.1.1
// Project: http://durandaljs.com
// Definitions by: Evan Larsen <http://nouvosoft.com/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../knockout/knockout.d.ts" />
declare module "durandal/system" {
/**
* Returns the module id associated with the specified object
*/
export var getModuleId: (obj: any) => string;
/**
* Sets the module id on the module.
*/
export var setModuleId: (obj, id: string) => void;
/**
* Call this function to enable or disable Durandal's debug mode. Calling it with no parameters will return true if the framework is currently in debug mode, false otherwise.
*/
export var debug: (debug?: bool) => bool;
/**
* Checks if the obj is an array
*/
export var isArray: (obj: any) => bool;
/**
* Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode.
*/
export var log: (...msgs: any[]) => void;
/**
* Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise.
*/
export var defer: (action?: Function) => JQueryDeferred;
/**
* Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids.
*/
export var guid: () => string;
/**
* Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function. If more than one is passed, then the promise will resolve with one callback parameter per module.
*/
export var acquire: (...modules: string[]) => JQueryPromise;
}
declare module "durandal/app" {
/**
* Sets the title for the app. You must set this before calling start. This will set the document title and the default message box header. It is also used internally by the router to set the document title when pages change.
*/
export var title: string;
/**
* simple helper function that wraps a call to modalDialog.show()
*/
export var showModal: (obj, activationData?, context?) => JQueryPromise;
/**
* A simple helper function that translates to return modalDialog.show(new MessageBox(message, title, options));
*/
export var showMessage: (message: string, title?: string, options?: any) => JQueryPromise;
/**
* Call this function to bootstrap the Durandal framework. It returns a promise which is resolved when the framework is configured and the dom is ready. At that point you are ready to set your root.
*/
export var start: () => JQueryPromise;
/**
* This sets the root view or view model and displays the composed application in the specified application host.
* @param root parameter is required and can be anything that the composition module understands as a view or view model. This includes strings and objects.
* @param transition If you have a splash screen, you may want to specify an optional transition to animate from the splash to your main shell.
* @param applicationHost parameter is optional. If provided it should be an element id for the node into which the UI should be composed. If it is not provided the default is to look for an element with an id of "applicationHost".
*/
export var setRoot: (root: any, transition: string, applicationHost?: string) => void;
/**
* If you intend to run on mobile, you should also call app.adaptToDevice() before setting the root.
*/
export var adaptToDevice: () => void;
/**
* The events parameter is a space delimited string containing one or more event identifiers. When one of these events is triggered, the callback is called and passed the event data provided by the trigger. The special events value of "all" binds all events on the object to the callback. If a context is provided, it will be bound to this for the callback. If the callback is omitted, then a promise-like object is returned from on. This object represents a subscription and has a then function used to register callbacks.
*/
export var on: (events: string, callback: Function, context?) => any;
/**
* Unwires callbacks from events. If no context is specified, all callbacks with different contexts will be removed. If no callback is specified, all callbacks for the event will be removed. If no event is specified, all event callbacks on the object will be removed.
*/
export var off: (events: string, callback: Function, context?) => any;
/**
* Triggers an event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.
*/
export var trigger: (events: string, ...args: any[]) => any;
/**
* Provides a function which can be used as a callback to trigger the events. This is useful in combination with jQuery events which may need to trigger the aggregator's events.
*/
export var proxy: (events) => Function;
}
declare module "durandal/composition" {
/**
* sets activate: true on every compose binding
*/
export var activateDuringComposition: bool;
/**
* changes the convention for finding where transitions are located
*/
export var convertTransitionToModuleId: (name: string) => string;
/**
* sets a default transition for all compositions
*/
export var defaultTransitionName: string;
/**
* the default implementation for switching the content during composition
*/
export var switchContent: (parent: HTMLElement, newChild: HTMLElement, settings: any) => void;
/**
* the default implementation on binding and showing content during composition
*/
export var bindAndShow: (element: HTMLElement, view: HTMLElement, settings: any) => void;
/**
* the default strategy which is: return viewLocator.locateViewForObject(settings.model, settings.viewElements);
*/
export var defaultStrategy: (settings: any) => JQueryPromise;
/**
* the default method for getting settings from the binding handler compose.
*/
export var getSettings: (valueAccessor: any) => any;
/**
* the default method for executing a strategy during composition
*/
export var executeStrategy: (element: HTMLElement, settings: any) => void;
/**
* the default method for injecting during composition
*/
export var inject: (element: HTMLElement, settings: any) => void;
/**
* the default method for composing
*/
export var compose: (element: HTMLElement, settings: any, bindingContext: any) => void;
}
declare module "durandal/http" {
/**
* the default is 'callback'
*/
export var defaultJSONPCallbackParam: string;
/**
* Performs an HTTP GET request on the specified URL. This function returns a promise which resolves with the returned response data. You can optionally return a query object whose properties will be used to construct a query string.
*/
export var get: (url: string, query: Object) => JQueryPromise;
/**
* Performs a JSONP request to the specified url. You can optionally include a query object whose properties will be used to construct the query string. Also, you can pass the name of the API's callback parameter. If none is specified, it defaults to "callback". This api returns a promise. If you are using a callback parameter other than "callback" consistently throughout your application, then you may want to set the http module's defaultJSONPCallbackParam so that you don't need to specify it on every request.
*/
export var jsonp: (url: string, query: Object, callbackParam: string) => JQueryPromise;
/**
* Performs an HTTP POST request on the specified URL with the supplied data. The data object is converted to JSON and the request is sent with an application/json content type. Thie function returns a promise which resolves with the returned response data.
*/
export var post: (url: string, data: Object) => JQueryPromise;
}
declare module "durandal/modalDialog" {
/**
* the default is 1050
*/
export var currentZIndex: number;
/**
* This is a helper function which can be used in the creation of custom modal contexts. Each time it is called, it returns a successively higher zIndex value than the last time.
*/
export var getNextZIndex: () => number;
/**
* This is a helper function which will tell you if any modals are currently open.
*/
export var isModalOpen: () => bool;
/**
* You may wish to customize modal displays or add additional contexts in order to display modals in different ways. To alter the default context, you would acquire it by calling getContext() and then alter it's pipeline. If you don't provide a value for name it returns the default context.
*/
export var getContext: (name: string) => any;
/**
* Pass a name and an object which defines the proper modal display pipeline via the functions described in the next section. This creates a new modal context or "modal style."
*/
export var addContext: (name: string, modalContext: any) => JQueryPromise;
/**
* creates a settings obj from the supplied params
*/
export var createCompositionSettings: (obj: any, modalContext: any) => any;
/**
* This API uses the composition module to compose your obj into a modal popover. It also uses the viewModel module to check and enforce any screen lifecycle needs that obj may have. A promise is returned which will be resolved when the modal dialog is dismissed. The obj is the view model for your modal dialog, or a moduleId for the view model to load. Your view model instance will have a single property added to it by this mechanism called modal which represents the dialog infrastructure itself. This modal object has a single function called close which can be invoked to close the modal. You may also pass data to close which will be returned via the promise mechanism. The modal object also references it's owner, activator, the composition settings it was created with and its display context. Speaking of context, this parameter represents the display context or modal style. By default, there is one context registered with the system, named 'default'. If no context is specified, the default context with be used to display the modal. You can also specify activationData which is an arbitrary object that will be passed to your modal's activate function, if it has one.
*/
export var show: (obj: any, activationData: any, context: any) => JQueryPromise;
}
declare module "durandal/viewEngine" {
/**
* The file extension that view source files are expected to have.
*/
export var viewExtension: string;
/**
* The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path).
*/
export var viewPlugin: string;
/**
* Returns true if the potential string is a url for a view, according to the view engine.
*/
export var isViewUrl: (url: string) => bool;
/**
* Converts a view url into a view id.
*/
export var convertViewUrlToViewId: (url: string) => string;
/**
* Converts a view id into a full RequireJS path.
*/
export var convertViewIdToRequirePath: (viewId: string) => string;
/**
* Parses some markup and turns it into a dom element.
*/
export var parseMarkup: (markup: string) => HTMLElement;
/**
* Returns a promise for a dom element identified by the viewId parameter.
*/
export var createView: (viewId: string) => JQueryPromise;
}
declare module "durandal/viewLocator" {
/**
* Allows you to set up a convention for mapping module folders to view folders. modulesPath is a string in the path that will be replaced by viewsPath. Partial views will be mapped to the "views" folder unless an areasPath is specified. All parameters are optional. If none are specified, the convention will map modules in a "viewmodels" folder to views in a "views" folder.
*/
export var useConvention: (modulesPath?: string, viewsPath?: string, areasPath?: string) => string;
/**
* This function takes in an object instance, which it then maps to a view id. That id is then passed to the locateView function and it is processed as above. If elementsToSearch are provided, those are passed along to locateView. Following is a description of how locateViewForObject determines the view for a given object instance.
*/
export var locateViewForObject: (obj: {}, elementsToSearch: HTMLElement[]) => JQueryPromise;
/**
* This function does nothing by default which is why editCustomer.js is mapped to editCustomer.html (both have the same underlying id of editCustomer). Replace this function with your own implementation to easily create your own mapping logic based on moduleId.
*/
export var convertModuleIdToViewId: (moduleId: string) => string;
/**
* As mentioned above, if no view id can be determined, the system falls back to attempting to determine the object's type and then uses that. This function contains the implementation of that fallback behavior. Replace it if you desire something different. Under normal usage however, this function should not be called.
*/
export var determineFallbackViewId: (obj: any) => string;
/**
* When a view area is specified, it along with the requested view id will be passed to this function, allowing you to customize the path of your view. You can specify area as part of the locateView call, but more commonly you would specify it as part of a compose binding. Any compose binding that does not include a model, but only a view, has a default area of 'partial'.
*/
export var translateViewIdToArea: (viewId: string, area?: string) => string;
/**
* The viewOrUrlOrId parameter represents a url/id for the view. The file extension is not necessary (ie. .html). When this function is called, the viewEngine will be used to construct the view. The viewEngine is passed the finalized id and returns a constructed DOM sub-tree, which is returned from this function. If the viewOrUrlOrId is not a string but is actually a DOM node, then the DOM node will be immediately returned. Optionally, you can pass an area string and it along with the url will be passed to the view locator's translateViewIdToArea before constructing the final id to pass to the view engine. If you provide an array of DOM elements for elementsToSearch, before we call the view engine, we will search the existing array for a match and return it if found.
*/
export var locateView: (viewOrUrlOrId: any, area: string, elementsToSearch: HTMLElement[]) => JQueryPromise;
}
declare module "durandal/viewModel" {
/**
* A property which is the home to some basic settings and functions that control how all activators work. These are used to create the instance settings object for each activator. They can be overriden on a per-instance-basis by passing a settings object when creating an activator or by accessing the settings property of the activator. To change them for all activators, change them on the defaults property. The two most common customizations are presented below. See the source for additional information.
*/
export var defaults: IViewModelDefaults;
/**
* This creates a computed observable which enforces a lifecycle on all values the observable is set to. When creating the activator, you can specify an initialActiveItem to activate. You can also specify a settings object. Use of the settings object is for advanced scenarios and will not be detailed much here.
*/
export var activator: {
(): IDurandalViewModelActiveItem;
(initialActiveItem: any, settings?: IViewModelDefaults): IDurandalViewModelActiveItem;
}
}
declare module "durandal/viewModelBinder" {
/**
* Applies bindings to a view using a pre-existing bindingContext. This is used by the composition module when a view is supplied without a model. It allows the parent binding context to be preserved. If the optional obj parameter is supplied, a new binding context will be created that is a child of bindingContext with its model set to obj. This is used by the widget framework to provide the widget binding while allowing templated parts to access their surrounding scope.
*/
export var bindContext: (bindingContext: KnockoutBindingContext, view: HTMLElement, obj?: any) => void;
/**
* Databinds obj, which can be an arbitrary object, to view which is a dom sub-tree. If obj has a function called setView, then, following binding, this function will be called, providing obj with an opportunity to interact directly with the dom fragment that it is bound to.
*/
export var bind: (obj: any, view: HTMLElement) => void;
}
interface IViewModelDefaults {
/**
* When the activator attempts to activate an item as described below, it will only activate the new item, by default, if it is a different instance than the current. Overwrite this function to change that behavior.
*/
areSameItem(currentItem, newItem, activationData): bool;
/**
* default is true
*/
closeOnDeactivate: bool;
/**
* Interprets values returned from guard methods like canActivate and canDeactivate by transforming them into bools. The default implementation translates string values "Yes" and "Ok" as true...and all other string values as false. Non string values evaluate according to the truthy/falsey values of JavaScript. Replace this function with your own to expand or set up different values. This transformation is used by the activator internally and allows it to work smoothly in the common scenario where a deactivated item needs to show a message box to prompt the user before closing. Since the message box returns a promise that resolves to the button option the user selected, it can be automatically processed as part of the activator's guard check.
*/
interpretResponse(value: any): bool;
/**
* called before activating a module
*/
beforeActivate(newItem: any): any;
/**
* called after deactivating a module
*/
afterDeactivate(): any;
};
interface IDurandalViewModelActiveItem {
/**
* knockout observable
*/
(val?): any;
/**
* A property which is the home to some basic settings and functions that control how all activators work. These are used to create the instance settings object for each activator. They can be overriden on a per-instance-basis by passing a settings object when creating an activator or by accessing the settings property of the activator. To change them for all activators, change them on the defaults property. The two most common customizations are presented below. See the source for additional information.
*/
settings: IViewModelDefaults;
/**
* This observable is set internally by the activator during the activation process. It can be used to determine if an activation is currently happening.
*/
isActivating(val?: bool): bool;
/**
* Pass a specific item as well as an indication of whether it should be closed, and this function will tell you the answer.
*/
canDeactivateItem(item, close): JQueryPromise;
/**
* Deactivates the specified item (optionally closing it). Deactivation follows the lifecycle and thus only works if the item can be deactivated.
*/
deactivateItem(item, close): JQueryDeferred;
/**
* Determines if a specific item can be activated. You can pass an arbitrary object to this function, which will be passed to the item's canActivate function , if present. This is useful if you are manually controlling activation and you want to provide some context for the operation.
*/
canActivateItem(newItem, activationData?): JQueryPromise;
/**
* Activates a specific item. Activation follows the lifecycle and thus only occurs if possible. activationData functions as stated above.
*/
activateItem(newItem, activationData?): JQueryPromise;
/**
* Checks whether or not the activator itself can be activated...that is whether or not it's current item or initial value can be activated.
*/
canActivate(): JQueryPromise;
/**
* Activates the activator...that is..it activates it's current item or initial value.
*/
activate(): JQueryPromise;
/**
* Checks whether or not the activator itself can be deactivated...that is whether or not it's current item can be deactivated.
*/
canDeactivate(): JQueryPromise;
/**
* Deactivates the activator...interpreted as deactivating its current item.
*/
deactivate(): JQueryDeferred;
/**
* Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator.
*/
includeIn(includeIn: any): JQueryPromise;
/**
* Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them.
*/
forItems(items): IDurandalViewModelActiveItem;
};
declare module "durandal/plugins/router" {
interface routeInfo {
url: string;
moduleId: string;
name: string;
visible: bool;
};
/**
* observable that is called when the router is ready
*/
export var ready: KnockoutObservableBool;
/**
* An observable array containing all route info objects.
*/
export var allRoutes: KnockoutObservableArray;
/**
* An observable array containing route info objects configured with visible:true (or by calling the mapNav function).
*/
export var visibleRoutes: KnockoutObservableArray;
/**
* An observable boolean which is true while navigation is in process; false otherwise.
*/
export var isNavigating: KnockoutObservableBool;
/**
* An observable whose value is the currently active item/module/page.
*/
export var activeItem: IDurandalViewModelActiveItem;
/**
* An observable whose value is the currently active route.
*/
export var activeRoute: KnockoutObservableAny;
/**
* called after an a new module is composed
*/
export var afterCompose: () => void;
/**
* Causes the router to move backwards in page history.
*/
export var navigateBack: () => void;
/**
* Use router default convention.
*/
export var useConvention: () => void;
/**
* Causes the router to navigate to a specific url.
*/
export var navigateTo: (url: string) => void;
/**
* replaces the windows.location w/ the url
*/
export var replaceLocation: (url: string) => void;
/**
* akes a route in and returns a calculated name.
*/
export var convertRouteToName: (route: string) => string;
/**
* Takes a route in and returns a calculated moduleId. Simple transformations of this can be done via the useConvention function above. For more advanced transformations, you can override this function.
*/
export var convertRouteToModuleId: (url: string) => string;
/**
* This can be overwritten to provide your own convention for automatically converting routes to module ids.
*/
export var autoConvertRouteToModuleId: (url: string) => string;
/**
* This should not normally be overwritten. But advanced users can override this to completely transform the developer's routeInfo input into the final version used to configure the router.
*/
export var prepareRouteInfo: (info: routeInfo) => void;
/**
* This should not normally be overwritten. But advanced users can override this to completely transform the developer's routeInfo input into the final version used to configure the router.
*/
export var handleInvalidRoute: (route: routeInfo, parameters: any) => void;
/**
* Once the router is required, you can call router.mapAuto(). This is the most basic configuration option. When you call this function (with no parameters) it tells the router to directly correlate route parameters to module names in the viewmodels folder.
*/
export var mapAuto: (path?: string) => void;
/**
* Works the same as mapRoute except that routes are automatically added to the visibleRoutes array.
*/
export var mapNav: (url: string, moduleId?: string, name?: string) => routeInfo;
/**
* You can pass a single routeInfo to this function, or you can pass the basic configuration parameters. url is your url pattern, moduleId is the module path this pattern will map to, name is used as the document title and visible determines whether or not to include it in the router's visibleRoutes array for easy navigation UI binding.
*/
export var mapRoute: (urlOrRouteInfo: any, moduleId?: string, name?: string, visible?: bool) => routeInfo;
/**
* This function takes an array of routeInfo objects or a single routeInfo object and uses it to configure the router. The finalized routeInfo (or array of infos) is returned.
*/
export var map: {
(routeOrRouteArray: string): void;
(routeOrRouteArray: string[]): void;
};
/**
* After you've configured the router, you need to activate it. This is usually done in your shell. The activate function of the router returns a promise that resolves when the router is ready to start. To use the router, you should add an activate function to your shell and return the result from that. The application startup infrastructure of Durandal will detect your shell's activate function and call it at the appropriate time, waiting for it's promise to resolve. This allows Durandal to properly orchestrate the timing of composition and databinding along with animations and splash screen display.
*/
export var activate: (defaultRoute: string) => JQueryPromise;
}

View File

@@ -0,0 +1,41 @@
///<reference path="dustjs-linkedin.d.ts"/>
import dust = module("dustjs-linkedin");
//
// compilation
//
dust.compile("template", "template name", true);
dust.compile("template", "template name");
dust.compileFn("");
var template = dust.compileFn("template", "template name");
// registration
dust.register("template name", template);
dust.loadSource("template source");
// context
var context = dust.makeBase({ anyProperty: "anyvalue" });
context = dust.makeBase(context);
// render and renderSource overloads
dust.render("template name", { anyProperty: "anyvalue" }, (err, out) => { });
dust.render("template name", context, (err, out) => { });
dust.renderSource("template source", { anyProperty: "anyvalue" });
dust.renderSource("template source", { anyProperty: "anyvalue" }, (err, out) => { });
dust.renderSource("template source", context, (err, out) => { });
dust.renderSource("template source", context);
// stream
dust.stream("template name", { anyProperty: "anyvalue" });
dust.stream("template name", context);
// utils
var filter = dust.filters["someFilter"];
filter("value");
dust.escapeHtml("<html/>");
dust.escapeJs("['a', 124]");

168
dustjs-linkedin/dustjs-linkedin.d.ts vendored Normal file
View File

@@ -0,0 +1,168 @@
// Type definitions for linkedin dustjs 1.2.1
// Project: https://github.com/linkedin/dustjs
// Definitions by: Marcelo Dezem <http://github.com/mdezem>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//
// Due to a lack of documentation it's not possible
// to know which methods are intended to be public and which
// are intended to be used internally by the framework.
// All the interfaces definitions here exposes only the methods
// that are documented in some way (tutorials, guides, references, etc.).
//
// Fell free to include other methods. If possible let me know about.
//
declare module "dustjs-linkedin" {
/**
* A template compiled into a js function.
*/
export interface Template {
(chk: Chunk, ctx: Context): Chunk;
}
export interface Chunk {
/**
* Writes data to this chunk's buffer.
*/
write(data: string): Chunk;
/**
* Writes data to this chunk's buffer and marks it as flushable. This method must be called on any chunks created via chunk.map. Do not call this method on a handler's main chunk -- dust.render and dust.stream take care of this for you.
*/
end(data: string): Chunk;
/**
* Creates a new chunk and passes it to callback. Use map to wrap asynchronous functions and to partition the template for streaming.
*/
map(callback: (chunk: Chunk) => any): Chunk;
/**
* Convenience method to apply filters to a stream.
*/
tap(callback: (value: any) => any): Chunk;
/**
* Removes the head tap function from the list.
*/
untap(): Chunk;
/**
* Renders a template block, such as a default block or an else block.
*/
render(body: any, context: Context): Chunk;
/**
* Sets an error on this chunk and immediately flushes the output.
*/
setError(err: any): Chunk;
}
export interface Context {
/**
* Retrieves the value at key from the context stack.
*/
get (key: string): any;
/**
* Pushes an arbitrary value onto the context stack and returns a new context instance. Specify index and/or length to enable enumeration helpers.
*/
push(head: any, idx?: number, len?: number): Context;
/**
* Returns a new context instance consisting only of the value at head, plus any previously defined global object.
*/
rebase(head: any): Context;
/**
* Returns the head of the context stack.
*/
current(): any;
}
export interface Stream {
flush(): void;
emit(evt: string, data: any): void;
/*
* Registers an event listener. Streams accept a single listener for a given event.
* @param evt the event. Possible values are data, end, error (maybe more, look in the source).
*/
on(evt: string, callback: (data?: any) => any);
pipe(stream: Stream): Stream;
}
/**
* register a template into the cache.
* @param name the unique template name.
* @param tmpl the template function.
*/
export function register(name: string, tmpl: Template): void;
/**
* compile a template body into a string of JavaScript source code
* @param source the template string
* @param name the name used to register the compiled template into the internal cache. See render().
* @strip strip whitespaces from the output. Defaults to false.
*/
export function compile(source: string, name: string, strip?: bool): string;
/**
* Compiles source directly into a JavaScript function that takes a context and an optional callback (see dust.renderSource). Registers the template under [name] if this argument is supplied.
* @param source the template string
* @param name the template name (optional).
*/
export function compileFn(source: string, name?: string): Template;
/**
* Evaluates a compiled source string.
*/
export function loadSource(compiled: string): Template;
/**
* Renders the named template and calls callback on completion.context may be a plain object or an instance of dust.Context.
* @param name the template name.
* @param context a plain object or an instance of dust.Context.
*/
export function render(name: string, context: any, callback: (err: any, out: string) => any);
export function render(name: string, context: Context, callback: (err: any, out: string) => any);
/**
* Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required.
* @param source the template string.
* @param context a plain object or an instance of dust.Context.
* @param callback (optional). If supplied the callback will be called passing the result string. If omitted, renderSource() will return a dust.Stream object.
*/
export function renderSource(source: string, context: any): Stream;
export function renderSource(source: string, context: Context): Stream;
export function renderSource(source: string, context: any, callback: (err: any, out: string) => any): void;
export function renderSource(source: string, context: Context, callback: (err: any, out: string) => any): void;
/**
* Streams the named template. context may be a plain object or an instance of dust.Context. Returns an instance of dust.Stream.
* @param name the template name.
* @param context a plain object or an instance of dust.Context.
*/
export function stream(name: string, context: any): Stream;
export function stream(name: string, context: Context): Stream;
/**
* Manufactures a dust.Context instance with its global object set to object.
* @param global a plain object or an instance of dust.Context.
*/
export function makeBase(global: any): Context;
export function makeBase(global: Context): Context;
export function escapeHtml(html: string): string;
export function escapeJs(js: string): string;
declare var helpers: {
[key: string]: (chk: Chunk, ctx: Context, bodies?: any, params?: any) => any;
};
declare var filters: {
[key: string]: (value: string) => string;
};
}

View File

@@ -1,16 +1,19 @@
/// <reference path="easeljs.d.ts" />
var stage: any;
var myContext2D: any;
function test_simple() {
var canvas = document.getElementById('canvas');
var stage = new Stage(canvas);
var shape = new Shape();
var canvas = <HTMLCanvasElement>document.getElementById('canvas');
var stage = new createjs.Stage(canvas);
var shape = new createjs.Shape();
shape.graphics.beginFill('rgba(255,0,0,1)').drawRoundRect(0, 0, 120, 120, 10);
stage.addChild(shape);
stage.update();
}
function test_animation() {
var ss = new SpriteSheet({
var ss = new createjs.SpriteSheet({
"frames": {
"width": 200,
"numFrames": 64,
@@ -26,28 +29,28 @@ function test_animation() {
ss.getAnimation("run").next = "jump";
ss.getAnimation("jump").next = "run";
var bitmapAnimation = new BitmapAnimation(ss);
var bitmapAnimation = new createjs.BitmapAnimation(ss);
bitmapAnimation.scaleY = bitmapAnimation.scaleX = .4;
bitmapAnimation.gotoAndPlay("run");
Ticker.setFPS(60);
Ticker.addListener(stage);
createjs.Ticker.setFPS(60);
createjs.Ticker.addListener(stage);
stage.addChild(bitmapAnimation);
}
function test_graphics() {
var g = new Graphics();
var g = new createjs.Graphics();
g.setStrokeStyle(1);
g.beginStroke(Graphics.getRGB(0, 0, 0));
g.beginFill(Graphics.getRGB(255, 0, 0));
g.beginStroke(createjs.Graphics.getRGB(0, 0, 0));
g.beginFill(createjs.Graphics.getRGB(255, 0, 0));
g.drawCircle(0, 0, 3);
var s = new Shape(g);
var s = new createjs.Shape(g);
s.x = 100;
s.y = 100;
stage.addChild(s);
stage.update();
var myGraphics: Graphics;
var myGraphics: createjs.Graphics;
myGraphics.beginStroke("#F00").beginFill("#00F").drawRect(20, 20, 100, 50).draw(myContext2D);
}

154
easeljs/easeljs.d.ts vendored
View File

@@ -1,4 +1,4 @@
// Type definitions for EaselJS 0.5
// Type definitions for EaselJS 0.6
// Project: http://www.createjs.com/#!/EaselJS
// Definitions by: Pedro Ferreira <https://bitbucket.org/drk4>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -27,6 +27,7 @@ module createjs {
cacheCanvas: HTMLCanvasElement;
cacheID: number;
compositeOperation: string;
cursor: string;
filters: Filter[];
hitArea: DisplayObject;
id: number;
@@ -53,6 +54,7 @@ module createjs {
clone(): DisplayObject;
draw(ctx: CanvasRenderingContext2D, ignoreCache?: bool): void;
getCacheDataURL(): string;
getChildByName(name: string): DisplayObject;
getConcatenatedMatrix(mtx: Matrix2D): Matrix2D;
getMatrix(matrix: Matrix2D): Matrix2D;
getStage(): Stage;
@@ -61,6 +63,7 @@ module createjs {
isVisible(): bool;
localToGlobal(x: number, y: number): Point;
localToLocal(x: number, y: number, target: DisplayObject): Point;
set(props: Object): DisplayObject;
setTransform(x: number, y: number, scaleX: number, scaleY: number, rotation: number, skewX: number, skewY: number, regX: number, regY: number): DisplayObject;
setupContext(ctx: CanvasRenderingContext2D): void;
toString(): string;
@@ -68,12 +71,26 @@ module createjs {
updateCache(compositeOperation: string): void;
// events
onClick: (event: MouseEvent) => any;
onDoubleClick: (event: MouseEvent) => any;
onMouseOut: (event: MouseEvent) => any;
onMouseOver: (event: MouseEvent) => any;
onPress: (event: MouseEvent) => any;
onTick: () => any;
click: (event: MouseEvent) => any;
dblClick: (event: MouseEvent) => any;
mouseout: (event: MouseEvent) => any;
mouseover: (event: MouseEvent) => any;
mousedown: (event: MouseEvent) => any;
tick: () => any;
// EventDispatcher mixins
addEventListener(type: string, listener: (eventObj: Object) => bool): Function;
addEventListener(type: string, listener: (eventObj: Object) => void): Function;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object;
removeEventListener(type: string, listener: (eventObj: Object) => bool): void;
removeEventListener(type: string, listener: (eventObj: Object) => void): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void;
removeAllEventListeners(type: string): void;
dispatchEvent(eventObj: string, target: Object): bool;
dispatchEvent(eventObj: Object, target: Object): bool;
hasEventListener(type: string): bool;
}
@@ -142,6 +159,7 @@ module createjs {
advance(): void;
cache(): void;
clone(): BitmapAnimation;
getBounds(): Rectangle;
gotoAndPlay(frameOrAnimation: string): void;
gotoAndPlay(frameOrAnimation: number): void;
play(): void;
@@ -149,9 +167,23 @@ module createjs {
updateCache(): void;
// events
onAnimationEnd: (reference: BitmapAnimation, animationEnded: string) => any;
onAnimationEnd: (event: Object) => any;
}
export class ButtonHelper {
// properties
target: Object;
overLabel: string;
outLabel: string;
downLabel: string;
play: bool;
// methods
constructor(target: MovieClip, outLabel: string, overLabel: string, downLabel: string, play: bool, hitArea: DisplayObject, hitLabel: string);
constructor(target: BitmapAnimation, outLabel: string, overLabel: string, downLabel: string, play: bool, hitArea: DisplayObject, hitLabel: string);
setEnabled(value: bool);
toString(): string;
}
export class BoxBlurFilter extends Filter {
// properties
@@ -209,8 +241,7 @@ module createjs {
}
export class Command
{
export class Command {
// methods
constructor (f, params, path);
exec(scope: any): void;
@@ -252,6 +283,35 @@ module createjs {
}
export class EaselJS {
// properties
version: string;
buildDate: string;
}
export class EventDispatcher {
// properties
// methods
static initialize(target: Object): void;
addEventListener(type: string, listener: (eventObj: Object) => bool): Function;
addEventListener(type: string, listener: (eventObj: Object) => void): Function;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object;
removeEventListener(type: string, listener: (eventObj: Object) => bool): void;
removeEventListener(type: string, listener: (eventObj: Object) => void): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void;
removeAllEventListeners(type: string): void;
dispatchEvent(eventObj: string, target: Object): bool;
dispatchEvent(eventObj: Object, target: Object): bool;
hasEventListener(type: string): bool;
toString(): string;
}
export class Graphics {
// properties
BASE_64: Object;
@@ -263,7 +323,7 @@ module createjs {
// methods
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, anticlockwise: bool): Graphics;
arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): Graphics;
beginBitmapFill(image: Object, repetition?: string): Graphics;
beginBitmapFill(image: Object, repetition?: string, matrix?: Matrix2D): Graphics;
beginBitmapStroke(image: Object, repetition?: string): Graphics;
beginFill(color: string): Graphics;
beginLinearGradientFill(colors: string[], ratios: number[], x0: number, y0: number, x1: number, y1: number): Graphics;
@@ -285,20 +345,36 @@ module createjs {
drawRoundRectComplex(x: number, y: number, width: number, height: number, radiusTL: number, radiusTR: number, radiusBR: number, radisBL: number): Graphics;
endFill(): Graphics;
endStroke(): Graphics;
isEmpty(): bool;
static getHSL(hue: number, saturation: number, lightness: number, alpha?: number): string;
static getRGB(red: number, green: number, blue: number, alpha?: number): string;
lineTo(x: number, y: number): Graphics;
moveTo(x: number, y: number): Graphics;
quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): Graphics;
rect(x: number, y: number, width: number, height: number): Graphics;
setStrokeStyle(thickness: number, caps?: string, joints?: string, miter?: number): Graphics; // caps and joints can be a string or number
setStrokeStyle(thickness: number, caps?: number, joints?: string, miter?: number): Graphics;
setStrokeStyle(thickness: number, caps?: string, joints?: number, miter?: number): Graphics;
setStrokeStyle(thickness: number, caps?: number, joints?: number, miter?: number): Graphics;
setStrokeStyle(thickness: number, caps?: string, joints?: string, miter?: number, ignoreScale?: bool): Graphics; // caps and joints can be a string or number
setStrokeStyle(thickness: number, caps?: number, joints?: string, miter?: number, ignoreScale?: bool): Graphics;
setStrokeStyle(thickness: number, caps?: string, joints?: number, miter?: number, ignoreScale?: bool): Graphics;
setStrokeStyle(thickness: number, caps?: number, joints?: number, miter?: number, ignoreScale?: bool): Graphics;
toString(): string;
}
export class Log {
// properties
static NONE: number;
static ERROR: number;
static WARNING: number;
static TRACE: number;
static ALL: number;
static level: number;
// methods
static out(message: string, details: string, level: number);
static addKeys(keys: Object);
static log(message: string, details: string, level: number);
}
export class Matrix2D {
// properties
a: number;
@@ -354,6 +430,20 @@ module createjs {
clone(): MouseEvent;
toString(): string;
// EventDispatcher mixins
addEventListener(type: string, listener: (eventObj: Object) => bool): Function;
addEventListener(type: string, listener: (eventObj: Object) => void ): Function;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object;
addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object;
removeEventListener(type: string, listener: (eventObj: Object) => bool): void;
removeEventListener(type: string, listener: (eventObj: Object) => void ): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void;
removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void;
removeAllEventListeners(type: string): void;
dispatchEvent(eventObj: string, target: Object): bool;
dispatchEvent(eventObj: Object, target: Object): bool;
hasEventListener(type: string): bool;
// events
onMouseMove: (event: MouseEvent) => any;
onMouseUp: (event: MouseEvent) => any;
@@ -363,6 +453,8 @@ module createjs {
export class MovieClip extends Container {
// properties
actionsEnabled: bool;
autoReset: bool;
currentFrame: number;
static INDEPENDENT: string;
loop: bool;
mode: string;
@@ -453,6 +545,7 @@ module createjs {
getAnimation(name: string): SpriteSheetAnimation;
getAnimations(): string[];
getFrame(frameIndex: number): Object;
getFrameBounds(frameIndex: number);
getNumFrames(animation: string): number;
toString(): string;
@@ -467,22 +560,29 @@ module createjs {
maxWidth: number;
maxHeight: number;
padding: number;
progress: number;
spriteSheet: SpriteSheet;
timeSlice: number;
// methods
addFrame(source: DisplayObject, sourceRect?: Rectangle, scale?: number, setupFunction?: () => any, setupParams?: any[], setupScope?: Object): any; //HERE returns number or null
addMovieClip(source: MovieClip, sourceRect?: Rectangle, scale?: number): void;
build(): void;
buildAsync(callback?: (reference: SpriteSheetBuilder) => any, timeSlice?: number): void;
buildAsync(timeSlice?: number): void;
clone(): SpriteSheetBuilder;
stopAsync(): void;
toString(): string;
// events
complete: (event: Object) => any;
onProgress: (event: Object) => any;
}
export class SpriteSheetUtils {
static addFlippedFrames(spriteSheet: SpriteSheet, horizontal?: bool, vertical?: bool, both?: bool): void;
static extractFrame(spriteSheet: HTMLImageElement, frame: number): HTMLImageElement;
static extractFrame(spriteSheet: SpriteSheet, frame: number): HTMLImageElement;
static extractFrame(spriteSheet: SpriteSheet, animationName: string): HTMLImageElement;
static flip(spriteSheet: HTMLImageElement, flipData: Object): void;
static mergeAlpha(rgbImage: HTMLImageElement, alphaImage: HTMLImageElement, canvas?: HTMLCanvasElement): HTMLCanvasElement;
}
@@ -498,18 +598,22 @@ module createjs {
snapToPixelEnabled: bool;
tickOnUpdate: bool;
new (): Stage;
new (canvas: HTMLElement): Stage;
// methods
constructor (canvas: HTMLCanvasElement);
clone(): Stage;
enableMouseOver(frequency: number): void;
enableDOMEvents(enable: bool): void;
toDataURL(backgroundColor: string, mimeType: string): string;
update(): void;
clear(): void;
handleEvent(evt: Object): void;
// events
onMouseDown: (event: MouseEvent) => any;
onMouseMove: (event: MouseEvent) => any;
onMouseUp: (event: MouseEvent) => any;
stagemousemove: (event: MouseEvent) => any;
stagemouseup: (event: MouseEvent) => any;
}
@@ -553,6 +657,16 @@ module createjs {
static setInterval(interval: number): void;
static setPaused(value: bool): void;
// EventDispatcher mixins
static addEventListener(type: string, listener: (eventObj: Object) => bool): Function;
static addEventListener(type: string, listener: (eventObj: Object) => void): Function;
static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): Object;
static addEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): Object;
static removeEventListener(type: string, listener: (eventObj: Object) => bool): void;
static removeEventListener(type: string, listener: (eventObj: Object) => void): void;
static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => bool; }): void;
static removeEventListener(type: string, listener: { handleEvent: (eventObj: Object) => void; }): void;
// events
tick: (timeElapsed: number) => any;
}

View File

@@ -0,0 +1,79 @@
/// <reference path="epiceditor.d.ts" />
var editor = new EpicEditor().load();
editor.load(function () {
console.log("Editor loaded.")
});
editor.unload(function () {
console.log("Editor unloaded.")
});
editor.getElement('editor').body.innerHTML;
if (editor.is('loaded'))
editor.enterFullscreen();
editor.open('some-file');
editor.importFile('some-file', "#Imported markdown\nFancy, huh?");
var theContent = editor.exportFile();
var newName = prompt('What do you want to rename this file to?');
editor.rename('old-filename.md', newName);
editor.save();
editor.remove('example.md');
var files = editor.getFiles();
editor.on('unload', function () {
console.log('Editor was removed');
});
editor.emit('unload');
editor.removeListener('unload');
editor.preview();
editor.edit();
editor.enterFullscreen();
editor.exitFullscreen();
editor.reflow();
editor.reflow('height');
var marked;
var opts = {
container: 'epiceditor',
textarea: null,
basePath: 'epiceditor',
clientSideStorage: true,
localStorageName: 'epiceditor',
useNativeFullsreen: true,
parser: marked,
file: {
name: 'epiceditor',
defaultContent: '',
autoSave: 100
},
theme: {
base: '/themes/base/epiceditor.css',
preview: '/themes/preview/preview-dark.css',
editor: '/themes/editor/epic-dark.css'
},
focusOnLoad: false,
shortcut: {
modifier: 18,
fullscreen: 70,
preview: 80
},
string: {
togglePreview: 'Toggle Preview Mode',
toggleEdit: 'Toggle Edit Mode',
toggleFullscreen: 'Enter Fullscreen'
}
}
var editor2 = new EpicEditor(opts);

61
epiceditor/epiceditor.d.ts vendored Normal file
View File

@@ -0,0 +1,61 @@
// Type definitions for EpicEditor 0.2
// Project: http://epiceditor.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface EpicEditorOptions {
container?: any;
textarea?: any;
basePath?: string;
clientSideStorage?: bool;
localStorageName?: string;
useNativeFullsreen?: bool;
parser?: any;
file?: {
name: string;
defaultContent: string;
autoSave: any;
};
theme?: {
base: string;
preview: string;
editor: string;
};
focusOnLoad?: bool;
shortcut?: {
modifier: number;
fullscreen: number;
preview: number;
};
string?: {
togglePreview: string;
toggleEdit: string;
toggleFullscreen: string;
};
}
class EpicEditor {
constructor();
constructor(options: EpicEditorOptions);
load(callback?: Function): EpicEditor;
unload(callback?: Function): EpicEditor;
getElement(element: string): any;
is(state: string): bool;
open(filename: string);
importFile(filename?: string, content?: string): void;
exportFile(filename?: string, type?: string): any;
rename(oldName: string, newName: string): void;
save(): void;
remove(filename: string): void;
getFiles(filename?: string): any;
on(event: string, handler: Function): void;
emit(event: string): void;
removeListener(event: string, handler?: Function): void;
preview(): void;
edit(): void;
enterFullscreen(): void;
exitFullscreen(): void;
reflow(type?: string): void;
}

File diff suppressed because it is too large Load Diff

2054
express/express.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -758,6 +758,7 @@ declare module fabric {
fromURL(url: string): IImage;
fromURL(url: string, callback: (image: IImage) => any): IImage;
fromURL(url: string, callback: (image: IImage) => any, objObjects: IObjectOptions): IImage;
new (element: HTMLImageElement, objObjects: IObjectOptions): IImage;
prototype: any;
filters:

View File

@@ -0,0 +1,49 @@
/// <reference path="filesystem.d.ts" />
// http://www.w3.org/TR/file-system-api/
// 2. Introduction
declare function getAsText(file:File): void;
declare function writeDataToLogFile(fileWriter:FileWriterSync): void;
function useAsyncFS(fs:FileSystem):void {
// see getAsText example in [FILE-API-ED].
fs.root.getFile("already_there.txt", null, function (f:FileEntry): void{
// In the example of the specification, there is a following code:
//
// getAsText(f.file());
//
// It seems wrong because f is ASYNCRONOUS file system.
f.file(getAsText);
});
// But now we can also write to the file; see [FILE-WRITER-ED].
fs.root.getFile("logFile", {create: true}, function (f:FileEntry): void{
f.createWriter(writeDataToLogFile);
});
}
window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function(fs:FileSystem): void{
useAsyncFS(fs);
});
// In a worker:
var tempFS:FileSystemSync = window.requestFileSystemSync(window.TEMPORARY, 1024 * 1024);
var logFile:FileEntrySync = tempFS.root.getFile("logFile", {create: true});
var writer:FileWriterSync = logFile.createWriter();
writer.seek(writer.length);
writeDataToLogFile(writer);
// 5.2 The Flags dictionary
var fsSync:FileSystemSync = window.requestFileSystemSync(window.TEMPORARY, 1024 * 1024);
// Get the data directory, creating it if it doesn't exist.
var dataDir:DirectoryEntrySync = fsSync.root.getDirectory("data", {create: true});
// Create the lock file, if and only if it doesn't exist.
try {
var lockFile:FileEntrySync = dataDir.getFile("lockfile.txt", {create: true, exclusive: true});
} catch (ex) {
// It already exists, or something else went wrong.
}

528
filesystem/filesystem.d.ts vendored Normal file
View File

@@ -0,0 +1,528 @@
// Type Definitions for File API: Directories and System (File System API)
// Project: http://www.w3.org/TR/file-system-api/
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../filewriter/filewriter.d.ts" />
interface LocalFileSystem {
/**
* Used for storage with no guarantee of persistence.
*/
TEMPORARY:number;
/**
* Used for storage that should not be removed by the user agent without application or user permission.
*/
PERSISTENT:number;
/**
* Requests a filesystem in which to store application data.
* @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT.
* @param size This is an indicator of how much storage space, in bytes, the application expects to need.
* @param successCallback The callback that is called when the user agent provides a filesystem.
* @param errorCallback A callback that is called when errors happen, or when the request to obtain the filesystem is denied.
*/
requestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void;
/**
* Allows the user to look up the Entry for a file or directory referred to by a local URL.
* @param url A URL referring to a local file in a filesystem accessable via this API.
* @param successCallback A callback that is called to report the Entry to which the supplied URL refers.
* @param errorCallback A callback that is called when errors happen, or when the request to obtain the Entry is denied.
*/
resolveLocalFileSystemURL(url:string, successCallback:EntryCallback, errorCallback?:ErrorCallback):void;
/**
* see requestFileSystem.
*/
webkitRequestFileSystem(type:number, size:number, successCallback:FileSystemCallback, errorCallback?:ErrorCallback):void;
}
interface LocalFileSystemSync {
/**
* Used for storage with no guarantee of persistence.
*/
TEMPORARY:number;
/**
* Used for storage that should not be removed by the user agent without application or user permission.
*/
PERSISTENT:number;
/**
* Requests a filesystem in which to store application data.
* @param type Whether the filesystem requested should be persistent, as defined above. Use one of TEMPORARY or PERSISTENT.
* @param size This is an indicator of how much storage space, in bytes, the application expects to need.
*/
requestFileSystemSync(type:number, size:number):FileSystemSync;
/**
* Allows the user to look up the Entry for a file or directory referred to by a local URL.
* @param url A URL referring to a local file in a filesystem accessable via this API.
*/
resolveLocalFileSystemSyncURL(url:string):EntrySync;
/**
* see requestFileSystemSync
*/
webkitRequestFileSystemSync(type:number, size:number):FileSystemSync;
}
interface Metadata {
/**
* This is the time at which the file or directory was last modified.
* @readonly
*/
modificationTime:Date;
/**
* The size of the file, in bytes. This must return 0 for directories.
* @readonly
*/
size:number;
}
interface Flags {
/**
* Used to indicate that the user wants to create a file or directory if it was not previously there.
*/
create?:bool;
/**
* By itself, exclusive must have no effect. Used with create, it must cause getFile and getDirectory to fail if the target path already exists.
*/
exclusive?:bool;
}
/**
* This interface represents a file system.
*/
interface FileSystem{
/**
* This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems.
* @readonly
*/
name: string;
/**
* The root directory of the file system.
* @readonly
*/
root:any;
}
interface Entry {
/**
* Entry is a file.
*/
isFile:bool;
/**
* Entry is a directory.
*/
isDirectory:bool;
/**
* Look up metadata about this entry.
* @param successCallback A callback that is called with the time of the last modification.
* @param errorCallback ErrorCallback A callback that is called when errors happen.
*/
getMetadata(successCallback:MetadataCallback, errorCallback?:ErrorCallback):void;
/**
* The name of the entry, excluding the path leading to it.
*/
name:string;
/**
* The full absolute path from the root to the entry.
*/
fullPath:string;
/**
* The file system on which the entry resides.
*/
filesystem:FileSystem;
/**
* Move an entry to a different location on the file system. It is an error to try to:
*
* <ui>
* <li>move a directory inside itself or to any child at any depth;</li>
* <li>move an entry into its parent if a name different from its current one isn't provided;</li>
* <li>move a file to a path occupied by a directory;</li>
* <li>move a directory to a path occupied by a file;</li>
* <li>move any element to a path occupied by a directory which is not empty.</li>
* <ul>
*
* A move of a file on top of an existing file must attempt to delete and replace that file.
* A move of a directory on top of an existing empty directory must attempt to delete and replace that directory.
*/
moveTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string;
/**
* Copy an entry to a different location on the file system. It is an error to try to:
*
* <ul>
* <li> copy a directory inside itself or to any child at any depth;</li>
* <li> copy an entry into its parent if a name different from its current one isn't provided;</li>
* <li> copy a file to a path occupied by a directory;</li>
* <li> copy a directory to a path occupied by a file;</li>
* <li> copy any element to a path occupied by a directory which is not empty.</li>
* <li> A copy of a file on top of an existing file must attempt to delete and replace that file.</li>
* <li> A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory.</li>
* </ul>
*
* Directory copies are always recursive--that is, they copy all contents of the directory.
*/
copyTo(parent:DirectoryEntry, newName?:string, successCallback?:EntryCallback, errorCallback?:ErrorCallback):string;
/**
* Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists.
*/
toURL():string;
/**
* Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem.
* @param successCallback A callback that is called on success.
* @param errorCallback A callback that is called when errors happen.
*/
remove(successCallback:VoidCallback, errorCallback?:ErrorCallback):void;
/**
* Look up the parent DirectoryEntry containing this Entry. If this Entry is the root of its filesystem, its parent is itself.
* @param successCallback A callback that is called to return the parent Entry.
* @param errorCallback A callback that is called when errors happen.
*/
getParent(successCallback:EntryCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface represents a directory on a file system.
*/
interface DirectoryEntry extends Entry {
/**
* Creates a new DirectoryReader to read Entries from this Directory.
*/
createReader():DirectoryReader;
/**
* Creates or looks up a file.
* @param path Either an absolute path or a relative path from this DirectoryEntry to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist.
* @param options
* <ul>
* <li>If create and exclusive are both true, and the path already exists, getFile must fail.</li>
* <li>If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.</li>
* <li>If create is not true and the path doesn't exist, getFile must fail.</li>
* <li>If create is not true and the path exists, but is a directory, getFile must fail.</li>
* <li>Otherwise, if no other error occurs, getFile must return a FileEntry corresponding to path.</li>
* </ul>
* @param successCallback A callback that is called to return the File selected or created.
* @param errorCallback A callback that is called when errors happen.
*/
getFile(path:string, options?:Flags, successCallback?:EntryCallback, errorCallback?:ErrorCallback):void;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntry to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist.
* @param options
* <ul>
* <li>If create and exclusive are both true and the path already exists, getDirectory must fail.</li>
* <li>If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.</li>
* <li>If create is not true and the path doesn't exist, getDirectory must fail.</li>
* <li>If create is not true and the path exists, but is a file, getDirectory must fail.</li>
* <li>Otherwise, if no other error occurs, getDirectory must return a DirectoryEntry corresponding to path.</li>
* </ul>
* @param successCallback A callback that is called to return the DirectoryEntry selected or created.
* @param errorCallback A callback that is called when errors happen.
*
*/
getDirectory(path:string, options?:Flags, successCallback?:EntryCallback, errorCallback?:ErrorCallback):void;
/**
* Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem.
* @param successCallback A callback that is called on success.
* @param errorCallback A callback that is called when errors happen.
*/
removeRecursively(successCallback:VoidCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then:
* <ul>
* <li> A series of calls to readEntries must return each entry in the directory exactly once.</li>
* <li> Once all entries have been returned, the next call to readEntries must produce an empty array.</li>
* <li> If not all entries have been returned, the array produced by readEntries must not be empty.</li>
* <li> The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].</li>
* </ul>
*/
interface DirectoryReader {
/**
* Read the next block of entries from this directory.
* @param successCallback Called once per successful call to readEntries to deliver the next previously-unreported set of Entries in the associated Directory. If all Entries have already been returned from previous invocations of readEntries, successCallback must be called with a zero-length array as an argument.
* @param errorCallback A callback indicating that there was an error reading from the Directory.
*/
readEntries(successCallback:EntriesCallback, errorCallback?:ErrorCallback):void;
}
/**
* This interface represents a file on a file system.
*/
interface FileEntry extends Entry {
/**
* Creates a new FileWriter associated with the file that this FileEntry represents.
* @param successCallback A callback that is called with the new FileWriter.
* @param errorCallback A callback that is called when errors happen.
*/
createWriter(successCallback:FileWriterCallback, errorCallback?:ErrorCallback):void;
/**
* Returns a File that represents the current state of the file that this FileEntry represents.
* @param successCallback A callback that is called with the File.
* @param errorCallback A callback that is called when errors happen.
*/
file(successCallback:FileCallback, errorCallback?:ErrorCallback):void;
}
/**
* When requestFileSystem() succeeds, the following callback is made.
*/
interface FileSystemCallback {
/**
* @param filesystem The file systems to which the app is granted access.
*/
(filesystem:FileSystem):void;
}
/**
* This interface is the callback used to look up Entry objects.
*/
interface EntryCallback {
/**
* @param entry
*/
(entry:Entry):void;
}
/**
* When readEntries() succeeds, the following callback is made.
*/
interface EntriesCallback {
(entries:Entry[]):void;
}
/**
* This interface is the callback used to look up file and directory metadata.
*/
interface MetadataCallback {
(metadata:Metadata):void;
}
/**
* This interface is the callback used to create a FileWriter.
*/
interface FileWriterCallback {
(fileWriter:FileWriter):void;
}
/**
* This interface is the callback used to obtain a File.
*/
interface FileCallback {
(file:File):void;
}
/**
* This interface is the generic callback used to indicate success of an asynchronous method.
*/
interface VoidCallback {
():void;
}
/**
* When an error occurs, the following callback is made.
*/
interface ErrorCallback {
(err:DOMError):void;
}
/**
* This interface represents a file system.
*/
interface FileSystemSync {
/**
* This is the name of the file system. The specifics of naming filesystems is unspecified, but a name must be unique across the list of exposed file systems.
*/
name:string;
/**
* root The root directory of the file system.
*/
root:DirectoryEntrySync;
}
/**
* An abstract interface representing entries in a file system, each of which may be a FileEntrySync or DirectoryEntrySync.
*/
interface EntrySync{
/**
* EntrySync is a file.
* @readonly
*/
isFile:bool;
/**
* EntrySync is a directory.
* @readonly
*/
isDirectory:bool;
/**
* Look up metadata about this entry.
*/
getMetadata():Metadata;
/**
* The name of the entry, excluding the path leading to it.
*/
name:string;
/**
* The full absolute path from the root to the entry.
*/
fullPath:string;
/**
* The file system on which the entry resides.
*/
filesystem:FileSystemSync;
/**
* Move an entry to a different location on the file system. It is an error to try to:
* <ul>
* <li> move a directory inside itself or to any child at any depth;</li>
* <li> move an entry into its parent if a name different from its current one isn't provided;</li>
* <li> move a file to a path occupied by a directory;</li>
* <li> move a directory to a path occupied by a file;</li>
* <li> move any element to a path occupied by a directory which is not empty.</li>
* </ui>
* A move of a file on top of an existing file must attempt to delete and replace that file. A move of a directory on top of an existing empty directory must attempt to delete and replace that directory.
* @param parent The directory to which to move the entry.
* @param newName The new name of the entry. Defaults to the EntrySync's current name if unspecified.
*/
moveTo(parent:DirectoryEntrySync, newName?:string):EntrySync;
/**
* Copy an entry to a different location on the file system. It is an error to try to:
* <ul>
* <li> copy a directory inside itself or to any child at any depth;</li>
* <li> copy an entry into its parent if a name different from its current one isn't provided;</li>
* <li> copy a file to a path occupied by a directory;</li>
* <li> copy a directory to a path occupied by a file;</li>
* <li> copy any element to a path occupied by a directory which is not empty.</li>
* </ui>
* A copy of a file on top of an existing file must attempt to delete and replace that file.
* A copy of a directory on top of an existing empty directory must attempt to delete and replace that directory.
* Directory copies are always recursive--that is, they copy all contents of the directory.
*/
copyTo(parent:DirectoryEntrySync, newName?:string):EntrySync;
/**
* Returns a URL that can be used to identify this entry. Unlike the URN defined in [FILE-API-ED], it has no specific expiration; as it describes a location on disk, it should be valid at least as long as that location exists.
*/
toURL():string;
/**
* Deletes a file or directory. It is an error to attempt to delete a directory that is not empty. It is an error to attempt to delete the root directory of a filesystem.
*/
remove ():void;
/**
* Look up the parent DirectoryEntrySync containing this Entry. If this EntrySync is the root of its filesystem, its parent is itself.
*/
getParent():DirectoryEntrySync;
}
/**
* This interface represents a directory on a file system.
*/
interface DirectoryEntrySync extends EntrySync {
/**
* Creates a new DirectoryReaderSync to read EntrySyncs from this DirectorySync.
*/
createReader():DirectoryReaderSync;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntrySync to the file to be looked up or created. It is an error to attempt to create a file whose immediate parent does not yet exist.
* @param options
* <ul>
* <li> If create and exclusive are both true and the path already exists, getFile must fail.</li>
* <li> If create is true, the path doesn't exist, and no other error occurs, getFile must create it as a zero-length file and return a corresponding FileEntry.</li>
* <li> If create is not true and the path doesn't exist, getFile must fail.</li>
* <li> If create is not true and the path exists, but is a directory, getFile must fail.</li>
* <li> Otherwise, if no other error occurs, getFile must return a FileEntrySync corresponding to path.</li>
* </ul>
*/
getFile(path:string, options?:Flags):FileEntrySync;
/**
* Creates or looks up a directory.
* @param path Either an absolute path or a relative path from this DirectoryEntrySync to the directory to be looked up or created. It is an error to attempt to create a directory whose immediate parent does not yet exist.
* @param options
* <ul>
* <li> If create and exclusive are both true and the path already exists, getDirectory must fail.</li>
* <li> If create is true, the path doesn't exist, and no other error occurs, getDirectory must create and return a corresponding DirectoryEntry.</li>
* <li> If create is not true and the path doesn't exist, getDirectory must fail.</li>
* <li> If create is not true and the path exists, but is a file, getDirectory must fail.</li>
* <li> Otherwise, if no other error occurs, getDirectory must return a DirectoryEntrySync corresponding to path.</li>
* </ul>
*/
getDirectory(path:string, options?:Flags):DirectoryEntrySync;
/**
* Deletes a directory and all of its contents, if any. In the event of an error [e.g. trying to delete a directory that contains a file that cannot be removed], some of the contents of the directory may be deleted. It is an error to attempt to delete the root directory of a filesystem.
*/
removeRecursively():void;
}
/**
* This interface lets a user list files and directories in a directory. If there are no additions to or deletions from a directory between the first and last call to readEntries, and no errors occur, then:
* <ul>
* <li> A series of calls to readEntries must return each entry in the directory exactly once.</li>
* <li> Once all entries have been returned, the next call to readEntries must produce an empty array.</li>
* <li> If not all entries have been returned, the array produced by readEntries must not be empty.</li>
* <li> The entries produced by readEntries must not include the directory itself ["."] or its parent [".."].</li>
* </ul>
*/
interface DirectoryReaderSync {
/**
* Read the next block of entries from this directory.
*/
readEntries():EntrySync[];
}
/**
* This interface represents a file on a file system.
*/
interface FileEntrySync extends EntrySync {
/**
* Creates a new FileWriterSync associated with the file that this FileEntrySync represents.
*/
createWriter():FileWriterSync;
/**
* Returns a File that represents the current state of the file that this FileEntrySync represents.
*/
file():File;
}
interface Window extends LocalFileSystem, LocalFileSystemSync{
}
interface WorkerGlobalScope extends LocalFileSystem, LocalFileSystemSync{
}

View File

@@ -0,0 +1,16 @@
/// <reference path="filewriter.d.ts" />
// http://www.w3.org/TR/file-writer-api/
function writeFile(writer:FileWriter): void{
function done(evt:Event): void{
alert("Write completed.");
}
function error(evt:Event): void{
alert("Write failed:" + evt);
}
var b:Blob = new Blob();
writer.onwrite = done;
writer.onerror = error;
writer.write(b);
}

176
filewriter/filewriter.d.ts vendored Normal file
View File

@@ -0,0 +1,176 @@
// Type Definitions for File API: Writer
// Project: http://www.w3.org/TR/file-writer-api/
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* This interface provides methods to monitor the asynchronous writing of blobs to disk using progress events [PROGRESS-EVENTS] and event handler attributes.
* This interface is specified to be used within the context of the global object (Window [HTML5]) and within Web Workers (WorkerUtils [WEBWORKERS-ED]).
*/
interface FileSaver extends EventTarget {
/**
* When the abort method is called, user agents must run the steps below:
* <ol>
* <li> If readyState == DONE or readyState == INIT, terminate this overall series of steps without doing anything else. </li>
* <li> Set readyState to DONE. </li>
* <li> If there are any tasks from the object's FileSaver task source in one of the task queues, then remove those tasks. </li>
* <li> Terminate the write algorithm being processed. </li>
* <li> Set the error attribute to a DOMError object of type "AbortError". </li>
* <li> Fire a progress event called abort </li>
* <li> Fire a progress event called writeend </li>
* <li> Terminate this algorithm. </li>
* </ol>
*/
abort():void;
/**
* The blob is being written.
* @readonly
*/
INIT:number;
/**
* The object has been constructed, but there is no pending write.
* @readonly
*/
WRITING:number;
/**
* The entire Blob has been written to the file, an error occurred during the write, or the write was aborted using abort(). The FileSaver is no longer writing the blob.
* @readonly
*/
DONE:number;
/**
* The FileSaver object can be in one of 3 states. The readyState attribute, on getting, must return the current state, which must be one of the following values:
* <ul>
* <li>INIT</li>
* <li>WRITING</li>
* <li>DONE</li>
* <ul>
* @readonly
*/
readyState:number;
/**
* The last error that occurred on the FileSaver.
* @readonly
*/
error:DOMError;
/**
* Handler for writestart events
*/
onwritestart:Function;
/**
* Handler for progress events.
*/
onprogress:Function;
/**
* Handler for write events.
*/
onwrite:Function;
/**
* Handler for abort events.
*/
onabort:Function;
/**
* Handler for error events.
*/
onerror:Function;
/**
* Handler for writeend events.
*/
onwriteend:Function;
}
var FileSaver: {
/**
* When the FileSaver constructor is called, the user agent must return a new FileSaver object with readyState set to INIT.
* This constructor must be visible when the script's global object is either a Window object or an object implementing the WorkerUtils interface.
*/
new(data:Blob): FileSaver;
}
/**
* This interface expands on the FileSaver interface to allow for multiple write actions, rather than just saving a single Blob.
*/
interface FileWriter extends FileSaver {
/**
* The byte offset at which the next write to the file will occur. This must be no greater than length.
* A newly-created FileWriter must have position set to 0.
*/
position:number;
/**
* The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.
*/
length:number;
/**
* Write the supplied data to the file at position.
* @param data The blob to write.
*/
write(data:Blob):void;
/**
* Seek sets the file position at which the next write will occur.
* @param offset If nonnegative, an absolute byte offset into the file. If negative, an offset back from the end of the file.
*/
seek(offset:number):void;
/**
* Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.
* @param size The size to which the length of the file is to be adjusted, measured in bytes.
*/
truncate(size:number):void;
}
/**
* This interface lets users write, truncate, and append to files using simple synchronous calls.
* This interface is specified to be used only within Web Workers (WorkerUtils [WEBWORKERS]).
*/
interface FileWriterSync {
/**
* The byte offset at which the next write to the file will occur. This must be no greater than length.
*/
position:number;
/**
* The length of the file. If the user does not have read access to the file, this must be the highest byte offset at which the user has written.
*/
length:number;
/**
* Write the supplied data to the file at position. Upon completion, position will increase by data.size.
* @param data The blob to write.
*/
write(data:Blob):void;
/**
* Seek sets the file position at which the next write will occur.
* @param offset An absolute byte offset into the file. If offset is greater than length, length is used instead. If offset is less than zero, length is added to it, so that it is treated as an offset back from the end of the file. If it is still less than zero, zero is used.
*/
seek(offset:number):void;
/**
* Changes the length of the file to that specified. If shortening the file, data beyond the new length must be discarded. If extending the file, the existing data must be zero-padded up to the new length.
* Upon successful completion:
* <ul>
* <li>length must be equal to size.</li>
* <li>position must be the lesser of
* <ul>
* <li>its pre-truncate value,</li>
* <li>size.</li>
* </ul>
* </li>
* </ul>
* @param size The size to which the length of the file is to be adjusted, measured in bytes.
*/
truncate(size:number):void;
}

View File

@@ -0,0 +1,84 @@
/// <reference path="flexSlider.d.ts"/>
// Can also be used with $(document).ready()
$(window).load(function() {
$('.flexslider').flexslider({
animation: "slide"
});
});
// Can also be used with $(document).ready()
$(window).load(function() {
$('.flexslider').flexslider({
animation: "slide",
controlNav: "thumbnails"
});
});
$(window).load(function() {
// The slider being synced must be initialized first
$('#carousel').flexslider({
animation: "slide",
controlNav: false,
animationLoop: false,
slideshow: false,
itemWidth: 210,
itemMargin: 5,
asNavFor: '#slider'
});
$('#slider').flexslider({
animation: "slide",
controlNav: false,
animationLoop: false,
slideshow: false,
sync: "#carousel"
});
});
$(window).load(function() {
$('.flexslider').flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 210,
itemMargin: 5
});
});
// Can also be used with $(document).ready()
$(window).load(function() {
$('.flexslider').flexslider({
animation: "slide",
animationLoop: false,
itemWidth: 210,
itemMargin: 5,
minItems: 2,
maxItems: 4
});
});
// Can also be used with $(document).ready()
$(window).load(function() {
// Vimeo API nonsense
var player = document.getElementById('player_1');
$(player).on('ready', ready);
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false)
} else {
element.attachEvent(eventName, callback, false);
}
}
function ready(player_id) {
var froogaloop = $(player_id);
froogaloop.on('play', function(data) {
$('.flexslider').flexslider("pause");
});
froogaloop.on('pause', function(data) {
$('.flexslider').flexslider("play");
});
}
});

90
flexSlider/flexSlider.d.ts vendored Normal file
View File

@@ -0,0 +1,90 @@
// Type definitions for FlexSlider 2 jquery plugin
// Project: https://github.com/woothemes/FlexSlider
// Definitions by: Diullei Gomes <https://github.com/diullei>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface SliderObject { //Object: The slider element itself
container: Object; //Object: The ul.slides within the slider
slides: Object; //Object: The slides of the slider
count: number; //Int: The total number of slides in the slider
currentSlide: number; //Int: The slide currently being shown
animatingTo: number; //Int: Useful in .before(), the slide currently animating to
animating: bool; //Boolean: is slider animating?
atEnd: bool; //Boolean: is the slider at either end?
manualPause: bool; //Boolean: force slider to stay paused during pauseOnHover event
controlNav: Object; //Object: The slider controlNav
directionNav: Object; //Object: The slider directionNav
controlsContainer: Object; //Object: The controlsContainer element of the slider
manualControls: Object; //Object: The manualControls element of the slider
flexAnimate(target, pause?); //Function: Move slider - (target, pause) parameters
pause(); //Function: Pause slider slideshow interval
resume(); //Function: Resume slider slideshow interval
canAdvance(target); //Function: returns boolean if slider can advance - (target) parameter
getTarget(dir); //Function: get target given a direction - "next" or "prev" parameter
}
interface FlexSliderOptions {
namespace?: string; //{NEW} String: Prefix string attached to the class of every element generated by the plugin
selector?: string; //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
animation?: string; //String: Select your animation type, "fade" or "slide"
easing?: string; //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
direction?: string; //String: Select the sliding direction, "horizontal" or "vertical"
reverse?: bool; //{NEW} Boolean: Reverse the animation direction
animationLoop?: bool; //Boolean: Should the animation loop? If bool; directionNav will received "disable" classes at either end
smoothHeight?: bool; //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
startAt?: number; //Integer: The slide that the slider should start on. Array notation (0 = first slide)
slideshow?: bool; //Boolean: Animate slider automatically
slideshowSpeed?: number; //Integer: Set the speed of the slideshow cycling, in milliseconds
animationSpeed?: number; //Integer: Set the speed of animations, in milliseconds
initDelay?: number; //{NEW} Integer: Set an initialization delay, in milliseconds
randomize?: bool; //Boolean: Randomize slide order
// Usability features
pauseOnAction?: bool; //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
pauseOnHover?: bool; //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
useCSS?: bool; //{NEW} Boolean: Slider will use CSS3 transitions if available
touch?: bool; //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
video?: bool; //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches
// Primary Controls
controlNav?: any; //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
directionNav?: bool; //Boolean: Create navigation for previous/next navigation? (true/false)
prevText?: string; //String: Set the text for the "previous" directionNav item
nextText?: string; //String: Set the text for the "next" directionNav item
// Secondary Navigation
keyboard?: bool; //Boolean: Allow slider navigating via keyboard left/right keys
multipleKeyboard?: bool; //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
mousewheel?: bool; //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
pausePlay?: bool; //Boolean: Create pause/play dynamic element
pauseText?: string; //String: Set the text for the "pause" pausePlay item
playText?: string; //String: Set the text for the "play" pausePlay item
// Special properties
controlsContainer?: string; //{UPDATED} Selector: USE CLASS SELECTOR. Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be ".flexslider-container". Property is ignored if given element is not found.
manualControls?: string; //Selector: Declare custom control navigation. Examples would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
sync?: string; //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
asNavFor?: string; //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider
// Carousel Options
itemWidth?: number; //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
itemMargin?: number; //{NEW} Integer: Margin between carousel items.
minItems?: number; //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
maxItems?: number; //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
move?: number; //{NEW} Integer: Number of carousel items that should move on animation. If number; slider will move all visible items.
// Callback API
start?: (slider: SliderObject) => any; //Callback: function(slider) - Fires when the slider loads the first slide
before?: (slider: SliderObject) => any; //Callback: function(slider) - Fires asynchronously with each slider animation
after?: () => any; //Callback: function(slider) - Fires after each slider animation completes
end?: () => any; //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
added?: () => any; //{NEW} Callback: function(slider) - Fires after a slide is added
removed?: () => any;
}
interface JQuery {
flexslider(options?: FlexSliderOptions);
}

View File

@@ -31,10 +31,33 @@ interface RevealOptions {
animationSpeed?: number;
closeOnBackgroundClick?: bool;
dismissModalClass?: string;
/**
* The class of the modals background.
*/
bgClass?: string;
open?: () => void;
opened?: () => void;
close?: () => void;
closed?: () => void;
/**
* The modals background object.
*/
bg: JQuery;
/**
* The css property for when the modal is opened and closed.
*/
css: {
open: {
opacity?: number;
visibility?: string;
display: string;
};
close: {
opacity: number;
visibility: string;
display: string;
};
};
}
interface JoyrideOptions {

72
gamepad/gamepad-tests.ts Normal file
View File

@@ -0,0 +1,72 @@
/// <reference path="gamepad.d.ts" />
()=>{
function runAnimation()
{
window.requestAnimationFrame(runAnimation);
var gamepads = navigator.getGamepads();
for (var i = 0; i < gamepads.length; ++i)
{
var pad = gamepads[i];
// todo; simple demo of displaying pad.axes and pad.buttons
}
}
window.requestAnimationFrame(runAnimation);
};
()=>{
window.addEventListener('GamepadConnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('GamepadDisconnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('webkitGamepadConnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('webkitGamepadDisconnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('mozGamepadConnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('mozGamepadDisconnected', (e: GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
var requestAnimationFrame = window.requestAnimationFrame || window["mozRequestAnimationFrame"];
var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads;
if(getGamepads){
function runAnimation()
{
requestAnimationFrame.call(window, runAnimation);
var gamepads: GamepadList = getGamepads.call(navigator);
for(var i = 0; i < gamepads.length; i++){
var pad: Gamepad = gamepads[i];
if(pad){
for (var k = 0; k < pad.buttons.length; k++)
{
var button = pad.buttons[k];
if(button !== 0){
console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button);
}
}
for (var k = 0; k < pad.axes.length; k++)
{
var axis = pad.axes[k];
if(Math.abs(axis) > 0.1){
console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" axis[' + k + '] = ' + axis);
}
}
}
}
}
runAnimation();
}
}();

78
gamepad/gamepad.d.ts vendored Normal file
View File

@@ -0,0 +1,78 @@
// Type definitions for Gamepad API
// Project: http://www.w3.org/TR/gamepad/
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* This interface defines an individual gamepad device.
*/
interface Gamepad{
/**
* An identification string for the gamepad. This string identifies the brand or style of connected gamepad device. Typically, this will include the USB vendor and a product ID.
* @readonly
*/
id:string;
/**
* The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices must be assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned indices must not be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected, and subsequently the same or a different gamepad is then connected, index entries must be reused.
* @readonly
*/
index:number;
/**
* Last time the data for this gamepad was updated. Timestamp is a monotonically increasing value that allows the author to determine if the axes and button data have been updated from the hardware, relative to a previously saved timestamp.
* @readonly
*/
timestamp:number;
/**
* Array of values for all axes of the gamepad. All axis values must be linearly normalized to the range [-1.0 .. 1.0]. As appropriate, -1.0 should correspond to "up" or "left", and 1.0 should correspond to "down" or "right". Axes that are drawn from a 2D input device should appear next to each other in the axes array, X then Y. It is recommended that axes appear in decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional stick.
* @readonly
*/
axes:number[];
/**
* Array of values for all buttons of the gamepad. All button values must be linearly normalized to the range [0.0 .. 1.0]. 0.0 must mean fully unpressed, and 1.0 must mean fully pressed. It is recommended that buttons appear in decreasing importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1, 2, ... in the buttons array.
* @readonly
*/
buttons:number[];
}
/**
*
*/
interface GamepadEvent extends Event{
/**
* The single gamepad attribute provides access to the associated gamepad data for this event.
* @readonly
*/
gamepad:Gamepad;
}
interface GamepadList{
[index: number]: Gamepad;
length: number;
}
interface Navigator{
/**
* The currently connected and interacted-with gamepads. Gamepads must only appear in the list if they are currently connected to the user agent, and have been interacted with by the user. Otherwise, they must not appear in the list to avoid a malicious page from fingerprinting the user based on connected devices.
* @readonly
*/
getGamepads(): Gamepad[];
webkitGetGamepads(): GamepadList;
// Not supported yet :(
// mozGetGamepads(): Gamepad[];
}
/*
* @event gamepadconnected
* A user agent must dispatch this event type to indicate the user has connected a gamepad. If a gamepad was already connected when the page was loaded, the gamepadconnected event will be dispatched when the user presses a button or moves an axis.
*/
/*
* @event gamepaddisconnected
* When a gamepad is disconnected from the user agent, if the user agent has previously dispatched a gamepadconnected event, a gamepaddisconnected event must be dispatched.
*/

View File

@@ -0,0 +1,282 @@
/// <reference path="gamequery.d.ts" />
//Original examples: https://github.com/onaluf/gameQuery/tree/master/tests/human
$(function () {
var simpleVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL, numberOfFrame: 4, delta: 32, rate: 300 });
var simpleHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 });
var multiVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 });
var multiHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "mh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 });
var simpleOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "sov.png", type: $.gameQuery.ANIMATION_VERTICAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 });
var simpleOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "soh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300 });
var multiOffsetVerticalAnimation = new $.gameQuery.Animation({ imageURL: "mov.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 });
var multiOffsetHorizontalAnimation = new $.gameQuery.Animation({ imageURL: "moh.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI, offsetx: 100, offsety: 100, numberOfFrame: 4, delta: 32, rate: 300, distance: 32 });
var pingpongAnimation = new $.gameQuery.Animation({ imageURL: "rebound.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG, numberOfFrame: 9, delta: 64, rate: 60 });
var multiPingpongAnimation = new $.gameQuery.Animation({ imageURL: "reboundm.png", type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG | $.gameQuery.ANIMATION_MULTI, numberOfFrame: 9, delta: 64, rate: 60, distance: 64 });
var callbackAnim = new $.gameQuery.Animation({ imageURL: "sv.png", type: $.gameQuery.ANIMATION_VERTICAL | $.gameQuery.ANIMATION_ONCE | $.gameQuery.ANIMATION_CALLBACK, numberOfFrame: 4, delta: 32, rate: 300 });
var counter = 0;
$("#playground").playground({ height: 64, width: 500 });
$.playground()
.addSprite("simpleVertical", { animation: simpleVerticalAnimation, posx: 0 })
.addSprite("simpleHorizontal", { animation: simpleHorizontalAnimation, posx: 34 })
.addSprite("multiVertical", { animation: multiVerticalAnimation, posx: 75 })
.addSprite("multiHorizontal", { animation: multiHorizontalAnimation, posx: 109 })
.addSprite("simpleOffsetVertical", { animation: simpleOffsetVerticalAnimation, posx: 150 })
.addSprite("simpleOffsetHorizontal", { animation: simpleOffsetHorizontalAnimation, posx: 184 })
.addSprite("multiOffsetVertical", { animation: multiOffsetVerticalAnimation, posx: 225 })
.addSprite("multiOffsetHorizontal", { animation: multiOffsetHorizontalAnimation, posx: 259 })
.addSprite("pingpong", { animation: pingpongAnimation, posx: 286, width: 64, height: 64 })
.addSprite("multiPingpong", { animation: multiPingpongAnimation, posx: 350, width: 64, height: 64 })
.addSprite("callback", {
animation: callbackAnim, posx: 414, callback: function () {
counter++;
if (counter > 1) {
$("#callback").remove();
}
}
});
$("#multiVertical").setAnimation(1);
$("#multiHorizontal").setAnimation(1);
$("#multiOffsetVertical").setAnimation(1);
$("#multiOffsetHorizontal").setAnimation(1);
$("#multiPingpong").setAnimation(1);
$.playground().startGame();
});
$(function () {
var red = new $.gameQuery.Animation({
imageURL: "red.png",
type: $.gameQuery.ANIMATION_HORIZONTAL
});
var blue = new $.gameQuery.Animation({
imageURL: "blue.png",
type: $.gameQuery.ANIMATION_HORIZONTAL
});
$("#playground").playground({ height: 450, width: 350 });
// no group, no translation, no transformation
$.playground()
.addSprite("a1", { animation: red, width: 30, height: 30, posx: 0, posy: 0 })
.addSprite("b1", { animation: red, width: 30, height: 30, posx: 15, posy: 15 });
// one group, no translation, no transformation
$.playground()
.addSprite("a2", { animation: red, width: 30, height: 30, posx: 0, posy: 50 })
.addGroup("g1", { width: 100, height: 100, posx: -55, posy: -5 })
.addSprite("b2", { animation: red, width: 30, height: 30, posx: 70, posy: 70 });
// no group, absolute translation, no rotation
$.playground()
.addSprite("a3", { animation: red, width: 30, height: 30, posx: 0, posy: 100 })
.addSprite("b3", { animation: red, width: 30, height: 30, posx: 100, posy: 131 });
$("#b3").x(15).y(115);
// no group, relative translation, scale
$.playground()
.addSprite("a4", { animation: red, width: 30, height: 30, posx: 0, posy: 150 })
.addSprite("b4", { animation: red, width: 30, height: 30, posx: 100, posy: 181 });
$("#b4").x(-85, true).y(-16, true);
// no group, no translation, flip
$.playground()
.addSprite("a5", { animation: red, width: 30, height: 30, posx: 0, posy: 200 })
.addSprite("b5", { animation: red, width: 30, height: 30, posx: 15, posy: 215 });
$("#a5").flipv();
$("#b5").fliph();
// no group, no translation, rotation
$.playground()
.addSprite("a6", { animation: red, width: 30, height: 30, posx: 0, posy: 250 })
.addSprite("b6", { animation: red, width: 30, height: 30, posx: 30, posy: 265 });
$("#b6").rotate(45);
// no group, no translation, scale
$.playground()
.addSprite("a7", { animation: red, width: 30, height: 30, posx: 0, posy: 300 })
.addSprite("b7", { animation: red, width: 30, height: 30, posx: 30, posy: 315 });
$("#b7").scale(1.5);
// no group, no translation, override
$.playground()
.addSprite("a8", { animation: red, width: 30, height: 30, posx: 0, posy: 370 })
.addSprite("b8", { animation: red, width: 30, height: 30, posx: 40, posy: 385 });
// now we try to turn every b* sprites blue
$("#a1").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a2").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a3").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a4").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a5").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a6").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a7").collision().each(function () {
$(this).setAnimation(blue);
});
$("#a8").collision({ x: 35 }).each(function () {
$(this).setAnimation(blue);
});
$.playground().startGame();
});
$(function () {
var multiAnimation = new $.gameQuery.Animation({
imageURL: "m.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI,
numberOfFrame: 3,
delta: 10,
distance: 10,
rate: 300
});
var multiAnimationPingpong = new $.gameQuery.Animation({
imageURL: "m.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI | $.gameQuery.ANIMATION_PINGPONG,
numberOfFrame: 3,
delta: 10,
distance: 10,
rate: 300
});
var animations = [];
animations[0] = new $.gameQuery.Animation({
imageURL: "s1.png",
type: $.gameQuery.ANIMATION_HORIZONTAL,
numberOfFrame: 3,
delta: 10,
rate: 300
});
animations[1] = new $.gameQuery.Animation({
imageURL: "s2.png",
type: $.gameQuery.ANIMATION_HORIZONTAL,
numberOfFrame: 3,
delta: 10,
rate: 300
});
animations[2] = new $.gameQuery.Animation({
imageURL: "s3.png",
type: $.gameQuery.ANIMATION_HORIZONTAL,
numberOfFrame: 3,
delta: 10,
rate: 300
});
var animationsPingpong = [];
animationsPingpong[0] = new $.gameQuery.Animation({
imageURL: "s1.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG,
numberOfFrame: 3,
delta: 10,
rate: 300
});
animationsPingpong[1] = new $.gameQuery.Animation({
imageURL: "s2.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG,
numberOfFrame: 3,
delta: 10,
rate: 300
});
animationsPingpong[2] = new $.gameQuery.Animation({
imageURL: "s3.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_PINGPONG,
numberOfFrame: 3,
delta: 10,
rate: 300
});
var tileDef = [[1, 2, 3], [2, 3, 1], [3, 1, 2]];
var tileFun = function (i, j) { return 1 + (i + j) % 3; };
$("#playground").playground({ height: 64, width: 350 });
$.playground()
.addTilemap("multiArray", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 }).end()
.addTilemap("multiFunction", tileFun, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 40 }).end()
.addTilemap("arrayArray", tileDef, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 80 }).end()
.addTilemap("arrayFunction", tileFun, animations, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 120 }).end()
.addTilemap("multiArrayPingpong", tileDef, multiAnimationPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 160 }).end()
.addTilemap("arrayArrayPingpong", tileDef, animationsPingpong, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 200 }).end()
.addGroup("testGroup", { height: 30, width: 30, posx: -40 }).addTilemap("outside", tileDef, multiAnimation, { width: 10, height: 10, sizex: 3, sizey: 3, posx: 0 });
$("#testGroup").x(240);
$.playground().startGame();
});
$(function () {
var multiAnimation = new $.gameQuery.Animation({
imageURL: "m.png",
type: $.gameQuery.ANIMATION_HORIZONTAL | $.gameQuery.ANIMATION_MULTI,
numberOfFrame: 3,
delta: 10,
distance: 10,
rate: 300
});
var tileDef = [[1, 2, 3, 1, 2, 3, 1, 2, 3],
[2, 3, 1, 2, 3, 1, 2, 3, 1],
[3, 1, 2, 3, 1, 2, 3, 1, 2]];
$("#playground").playground({ height: 60, width: 90 });
$.playground()
.addGroup("testGroup1", { height: 60, width: 180, posx: 0 })
.addTilemap("map1", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 }).end()
.addTilemap("map2", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 90 }).end()
.end()
.addGroup("testGroup2", { height: 60, width: 90, posy: 60 })
.addTilemap("map3", tileDef, multiAnimation, { width: 10, height: 10, sizex: 9, sizey: 3, posx: 0 });
$("#testGroup1").x(-45);
$("#testGroup2").y(30);
$.playground().startGame();
});
$(function () {
var animation = new $.gameQuery.Animation({ imageURL: "sh.png", type: $.gameQuery.ANIMATION_HORIZONTAL, numberOfFrame: 4, delta: 32, rate: 300 });
$("#playground").playground({ height: 64, width: 480 });
$.playground()
.addSprite("rotate", { animation: animation, posx: 0, posy: 16 })
.addSprite("scale", { animation: animation, posx: 80, posy: 16 })
.addSprite("rotateScale", { animation: animation, posx: 160, posy: 16 })
.addSprite("scaleRotate", { animation: animation, posx: 240, posy: 16 })
.addSprite("flipH", { animation: animation, posx: 320, posy: 16 })
.addSprite("flipV", { animation: animation, posx: 400, posy: 16 })
$("#rotate").rotate(45);
$("#scale").scale(4);
$("#scale").scale(0.5, true);
$("#rotateScale").rotate(45).scale(2);
$("#scaleRotate").scale(2).rotate(45);
$("#flipV").flipv(true);
$("#flipH").fliph(true);
$.playground().startGame();
});

171
gamequery/gamequery.d.ts vendored Normal file
View File

@@ -0,0 +1,171 @@
// Type definitions for gameQuery 0.7.0
// Project: http://gamequeryjs.com/
// Definitions by: David Laubreiter <https://github.com/Laubi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface PlaygroundOptions{
height?: number;
width?: number;
refreshRate?: number;
keyTracker?: bool;
mouseTracker?: bool;
position?: string;
disableCollision?: bool;
}
interface Coordinate3D{
x: number;
y: number;
z: number;
}
interface Size{
w: number;
h: number;
}
interface SpriteOptions{
animation?: any;
height?: number;
width?: number;
posx?: number;
posy?: number;
callback?: () => any;
}
interface GroupOptions{
overflow?: string;
height?: number;
width?: number;
posx?: number;
posy?: number;
}
interface TileMapOptions{
sizex?: number;
sizey?: number;
height?: number;
width?: number;
posx?: number;
posy?: number;
buffer?: number;
}
interface AnimationOptions{
imageURL: string;
numberOfFrame?: number;
delta?: number;
rate?: number;
type?: number;
distance?: number;
offsetx?: number;
offsety?: number;
}
interface Animation{
imageURL: string;
numberOfFrame: number;
delta: number;
rate: number;
type: number;
distance: number;
offsetx: number;
offsety: number;
new (options: AnimationOptions): Animation;
}
interface GameQuery {
ANIMATION_VERTICAL: number;
ANIMATION_HORIZONTAL: number;
ANIMATION_ONCE: number;
ANIMATION_CALLBACK: number;
ANIMATION_MULTI: number;
ANIMATION_PINGPONG: number;
Animation: Animation;
keyTracker: bool[];
spriteCssClass: string;
groupCssClass: string;
tilemapCssClass: string;
tileCssClass: string;
tileTypePrefix: string;
tileIdPrefix: string;
}
interface JQuery{
playground(options?: PlaygroundOptions): JQuery;
collision(query?: any): JQuery;
startGame(callback?: () => void): JQuery;
pauseGame(): JQuery;
resumeGame(callback?: () => void ): JQuery;
registerCallback(callback: () => void , rate: number): JQuery;
registerCallback(callback: () => number , rate: number): JQuery;
registerCallback(callback: () => bool , rate: number): JQuery;
clearScenegraph(): JQuery;
clearAll(clearCallbacks?: bool): JQuery;
loadCallback(callback: (percent: number) => void ): JQuery;
rotate(angle: number, relative?: bool): JQuery;
scale(ratio: number, relative?: bool): JQuery;
flipv(flip?: bool): JQuery;
fliph(flip?: bool): JQuery;
xyz(x: number, y: number, z: number, relative?: bool): JQuery;
xyz(): Coordinate3D;
xy(x: number, y: number, relative?: bool): JQuery;
xy(): Coordinate3D;
x(value: number, relative?: bool): JQuery;
x(): number;
y(value: number, relative?: bool): JQuery;
y(): number;
z(value: number, relative?: bool): JQuery;
z(): number;
wh(width: number, height: number, relative?: bool): JQuery;
wh(): Size;
w(value: number, relative?: bool): JQuery;
w(): number;
h(value: number, relative?: bool): JQuery;
h(): number;
addSprite(name: string, options: SpriteOptions): JQuery;
addGroup(name: string, options: GroupOptions): JQuery;
addTilemap(name: string, tileDescription: number[][], animationList : Animation[], options: TileMapOptions) : JQuery;
addTilemap(name: string, tileDescription: number[][], animation : Animation, options: TileMapOptions) : JQuery;
addTilemap(name: string, tileDescription: (i: number, j: number) => number, animationList : Animation[], options: TileMapOptions) : JQuery;
addTilemap(name: string, tileDescription: (i: number, j: number) => number, animation : Animation, options: TileMapOptions) : JQuery;
gQ: GameQuery;
setAnimation(animation: Animation, callback?: () => any): JQuery;
setAnimation(animation: number, callback?: () => any): JQuery;
setAnimation(): JQuery;
pauseAnimation(): JQuery;
resumeAnimation(): JQuery;
}
interface JQueryStatic{
playground(): JQuery;
gQ: GameQuery;
gameQuery: GameQuery;
}

View File

@@ -110,11 +110,11 @@ class GlobalizeStatic {
addCultureInfo(cultureName, baseCultureName, info? );
findClosestCulture(cultureSelector: string);
format(value, format, cultureSelector? );
localize(key, cultureSelector);
localize(key, cultureSelector?);
parseDate(value: string, formats? , cultureSelector?: string): Date;
parseInt(value: string, radix? , cultureSelector?: string): number;
parseFloat(value: string, radix? , cultureSelector?: string): number;
}
declare var Globalize: GlobalizeStatic;
declare var Globalize: GlobalizeStatic;

View File

@@ -0,0 +1,76 @@
/// <reference path="ga.d.ts" />
/// <reference path="../jasmine/jasmine.d.ts" />
describe("tester Google Analytics Tracker _gat object", () => {
it("can set ga script element", () => {
ga = <HTMLScriptElement>document.createElement("script");
});
it("can set aync to true", () => {
ga.async = true;
});
it("can set src to string url", () => {
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';;
});
it("can set type", () => {
ga.type = 'text/javascript';
});
});
describe("tester Google Analytics Tracker _gat object", () => {
it("can create _createTracker", () => {
_gat._createTracker('UA-65432-1');
_gat._createTracker('UA-65432-2', 't2');
});
it("can create _getTrackerByName", () => {
_gat._getTrackerByName();
_gat._getTrackerByName('t2');
});
it("can create _anonymizeIp", () => {
_gat._anonymizeIp();
});
});
describe("tester Google Analytics Code _gaq object", () => {
it("can create _push", () => {
_gaq.push(['_setAccount', 'UA-XXXXXXX-YY']);
_gaq.push(['_gat._anonymizeIp']);
_gaq.push(['_trackPageview']);
_gaq.push(() => {
var tracker = _gat._getTrackerByName('UA-65432-1');
tracker._trackPageview();
}
);
});
});
describe("tester Google Analytics Code Tracker object", () => {
it("can create Tracker object and call methods", () => {
var tracker = _gat._getTrackerByName('UA-65432-1');
tracker._trackPageview();
tracker._getName();
tracker._getAccount();
tracker._getVersion();
tracker._getVisitorCustomVar(0);
tracker._setAccount();
tracker._setCustomVar(0, "name", "value", 1);
tracker._setSampleRate("80");
tracker._setSessionCookieTimeout(1800000);
tracker._setSiteSpeedSampleRate(5);
tracker._setVisitorCookieTimeout(63072000000);
tracker._trackPageLoadTime();
});
});

41
google.analytics/ga.d.ts vendored Normal file
View File

@@ -0,0 +1,41 @@
// Type definitions for Google Analytics
// Project: https://developers.google.com/analytics/devguides/collection/gajs/
// Definitions by: Ronnie Haakon Hegelund <http://ronniehegelund.blogspot.dk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
class Tracker {
_trackPageview(): void;
_getName(): string;
_getAccount(): string;
_getVersion(): string;
_getVisitorCustomVar(index: number); string;
_setAccount(): string;
_setCustomVar(index: number, name: string, value: string, opt_scope?: number): bool;
_setSampleRate(newRate: string): void;
_setSessionCookieTimeout(cookieTimeoutMillis: number): void;
_setSiteSpeedSampleRate(sampleRate: number): void;
_setVisitorCookieTimeout(milliseconds: number): void;
_trackPageLoadTime(): void;
}
interface GoogleAnalyticsCode {
push(commandArray: string[]): void;
push(Function): void;
}
interface GoogleAnalyticsTracker {
_getTracker(account: string): Tracker;
_createTracker(opt_account: string, opt_name?: string): Tracker;
_getTrackerByName(opt_name?: string): Tracker;
_anonymizeIp(): void;
}
interface GoogleAnalytics {
type: string;
src: string;
async: bool;
}
declare var ga: GoogleAnalytics;
declare var _gaq: GoogleAnalyticsCode;
declare var _gat: GoogleAnalyticsTracker;

79
google.feeds/google.feed.api.d.ts vendored Normal file
View File

@@ -0,0 +1,79 @@
//Project Google Feed Apis
// Project: https://developers.google.com/feed/
// Definitions by: https://github.com/RodneyJT
declare module google.feeds {
export class feed {
constructor();
constructor(url: string);
findFeeds(query?: string, callback?: (result: findResult) => void ): void;
getElementsByTagNameNS(node: string, ns: string, localName: string): any[];
includeHistoricalEntries(): void;
load(callback?: (result: feedResult) => void ): void;
setNumEntries(num: number): void;
setResultFormat(format: string): void;
}
}
interface feedResult {
error?: feedError;
xmlDocument?: string;
feed: feedJSON;
}
interface findResult {
error?: feedError;
xmlDocument?: string;
findEntries: findEntry[];
}
interface feedError {
code: string;
message: string;
}
interface feedJSON {
feedURL: string;
link: string;
author: string;
description: string;
entries: feedEntry[];
}
interface feedEntry {
mediaGroup: MediaGroup[];
title: string;
link: string;
content: string;
contentSnippet: string;
publishedDate: string;
categories: string[];
}
interface findEntry {
title: string;
link: string;
contentSnippet: string;
url: string;
}
interface MediaGroup {
content: MediaContent[];
}
interface MediaContent {
url: string;
fileSize: number;
type: string;
medium: string;
isDefault: bool;
expression: string;
bitrate: number;
framerate: number;
samplingrate: number;
channels: string;
duration: number;
height: number;
width: number;
lang: string;
}

View File

@@ -0,0 +1,18 @@
// Test files for Geolocation Definition file
/// <reference path="google.geolocation.d.ts" />
//determine if the handset has client side geo location capabilities
var isInit: bool = geo_position_js.init();
if(isInit){
geo_position_js.getCurrentPosition(success_callback, error_callback);
} else {
alert("Functionality not available");
}
function success_callback(position: Position): void {
geo_position_js.showMap(position.coords.latitude, position.coords.longitude);
}
function error_callback(positionError: PositionError): void {
console.log(positionError.code);
}

View File

@@ -0,0 +1,12 @@
// Type definitions for Google Geolocation 0.4.8
// Project: https://code.google.com/p/geo-location-javascript/
// Definitions by: Vincent Bortone <https://github.com/vbortone/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface GeolocationStatic {
init(): bool;
getCurrentPosition(success: (position: Position) => void, error?: (positionError: PositionError) => void, opts?: PositionOptions): void;
showMap(latitude: number, longitude: number): void;
}
declare var geo_position_js: GeolocationStatic;

View File

@@ -1123,7 +1123,7 @@ declare module google.maps {
worldSize?: Size;
}
export interface StreetViewService {
export class StreetViewService {
getPanoramaById(pano: string, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void );
getPanoramaByLocation(latlng: LatLng, radius: number, callback: (streetViewPanoramaData: StreetViewPanoramaData, streetViewStatus: StreetViewStatus) => void );
}

View File

@@ -960,8 +960,8 @@ interface HighchartsOptions {
subtitle?: HighchartsSubtitleOptions;
title?: HighchartsTitleOptions;
tooltip?: HighchartsTooltipOptions;
xAxis?: HighchartsAxisOptions[];
yAxis?: HighchartsAxisOptions[];
xAxis?: HighchartsAxisOptions;
yAxis?: HighchartsAxisOptions;
}

267
jake/jake-tests.ts Normal file
View File

@@ -0,0 +1,267 @@
// https://github.com/mde/jake
/// <reference path="jake.d.ts" />
import path = module("path");
desc('This is the default task.');
task('default', function (params) {
console.log('This is the default task.');
});
desc('This task has prerequisites.');
task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
console.log('Ran some prereqs first.');
});
desc('This is an asynchronous task.');
task('asyncTask', {async: true}, function () {
setTimeout(complete, 1000);
});
desc('This builds a minified JS file for production.');
file('foo-minified.js', ['bar', 'foo-bar.js', 'foo-baz.js'], function () {
// Code to concat and minify goes here
});
desc('This creates the bar directory for use with the foo-minified.js file-task.');
directory('bar');
desc('This is the default task.');
task('default', function () {
console.log('This is the default task.');
});
namespace('foo', function () {
desc('This the foo:bar task');
task('bar', function () {
console.log('doing foo:bar task');
});
desc('This the foo:baz task');
task('baz', ['default', 'foo:bar'], function () {
console.log('doing foo:baz task');
});
});
desc('This is an awesome task.');
task('awesome', function (a, b, c) {
console.log(a, b, c);
});
desc('This is an awesome task.');
task('awesome', function (a, b, c) {
console.log(a, b, c);
console.log(process.env.qux, process.env.frang);
});
jake.addListener('complete', function () {
process.exit();
});
desc('Calls the foo:bar task and its prerequisites.');
task('invokeFooBar', function () {
// Calls foo:bar and its prereqs
jake.Task['foo:bar'].invoke();
});
desc('Calls the foo:bar task and its prerequisites.');
task('invokeFooBar', function () {
// Calls foo:bar and its prereqs
jake.Task['foo:bar'].invoke();
// Does nothing
jake.Task['foo:bar'].invoke();
});
desc('Calls the foo:bar task without its prerequisites.');
task('executeFooBar', function () {
// Calls foo:bar without its prereqs
jake.Task['foo:baz'].execute();
});
desc('Calls the foo:bar task without its prerequisites.');
task('executeFooBar', function () {
// Calls foo:bar without its prereqs
jake.Task['foo:baz'].execute();
// Can keep running this over and over
jake.Task['foo:baz'].execute();
jake.Task['foo:baz'].execute();
});
desc('Calls the foo:bar task and its prerequisites.');
task('invokeFooBar', function () {
// Calls foo:bar and its prereqs
jake.Task['foo:bar'].invoke();
// Does nothing
jake.Task['foo:bar'].invoke();
// Only re-runs foo:bar, but not its prerequisites
jake.Task['foo:bar'].reenable();
jake.Task['foo:bar'].invoke();
});
desc('Calls the foo:bar task and its prerequisites.');
task('invokeFooBar', function () {
// Calls foo:bar and its prereqs
jake.Task['foo:bar'].invoke();
// Does nothing
jake.Task['foo:bar'].invoke();
// Re-runs foo:bar and all of its prerequisites
jake.Task['foo:bar'].reenable(true);
jake.Task['foo:bar'].invoke();
});
desc('Passes params on to other tasks.');
task('passParams', function () {
var t = jake.Task['foo:bar'];
// Calls foo:bar, passing along current args
t.invoke.apply(t, arguments);
});
desc('Calls the async foo:baz task and its prerequisites.');
task('invokeFooBaz', {async: true}, function () {
var t = jake.Task['foo:baz'];
t.addListener('complete', function () {
console.log('Finished executing foo:baz');
// Maybe run some other code
// ...
// Complete the containing task
complete();
});
// Kick off foo:baz
t.invoke();
});
namespace('vronk', function () {
task('groo', function () {
var t = jake.Task['vronk:zong'];
t.addListener('error', function (e) {
console.log(e.message);
});
t.invoke();
});
task('zong', function () {
throw new Error('OMFGZONG');
});
});
desc('This task fails.');
task('failTask', function () {
fail('Yikes. Something back happened.');
});
desc('This task fails with an exit-status of 42.');
task('failTaskQuestionCustomStatus', function () {
fail('What is the answer?', 42);
});
declare var sourceDir:string;
declare var currentDir:string;
jake.mkdirP('app/views/layouts');
jake.cpR(path.join(sourceDir, '/templates'), currentDir);
jake.readdirR('pkg');
jake.rmRf('pkg');
desc('Runs the Jake tests.');
task('test', {async: true}, function () {
var cmds = [
'node ./tests/parseargs.js'
, 'node ./tests/task_base.js'
, 'node ./tests/file_task.js'
];
jake.exec(cmds, function () {
console.log('All tests passed.');
complete();
}, {printStdout: true});
});
var ex = jake.createExec(['do_thing.sh'], {printStdout: true});
ex.addListener('error', function (msg, code) {
if (code == 127) {
console.log("Couldn't find do_thing script, trying do_other_thing");
ex.append('do_other_thing.sh');
}
else {
fail('Fatal error: ' + msg, code);
}
});
ex.run();
task('echo', {async: true}, function () {
jake.exec(['echo "hello"'], function () {
jake.logger.log('Done.');
complete();
}, {printStdout: !jake.program.opts.quiet});
});
function hoge(){
var t = new jake.PackageTask('fonebone', 'v0.1.2112', function () {
var fileList = [
'Jakefile'
, 'README.md'
, 'package.json'
, 'lib/*'
, 'bin/*'
, 'tests/*'
];
this.packageFiles.include(fileList);
this.needTarGz = true;
this.needTarBz2 = true;
});
}
var list = new jake.FileList();
list.include('foo/*.txt');
list.include(['bar/*.txt', 'README.md']);
list.include('Makefile', 'package.json');
list.exclude('foo/zoobie.txt');
list.exclude(/foo\/src.*.txt/);
console.log(list.toArray());
var t = new jake.TestTask('fonebone', function () {
var fileList = [
'tests/*'
, 'lib/adapters/**/test.js'
];
this.testFiles.include(fileList);
this.testFiles.exclude('tests/helper.js');
this.testName = 'testMainAndAdapters';
});
var assert = require('assert')
, tests;
tests = {
'sync test': function () {
// Assert something
assert.ok(true);
}
, 'async test': function (next) {
// Assert something else
assert.ok(true);
// Won't go next until this is called
next();
}
, 'another sync test': function () {
// Assert something else
assert.ok(true);
}
};
//module.exports = tests;
var p = new jake.NpmPublishTask('jake', [
'Makefile'
, 'Jakefile'
, 'README.md'
, 'package.json'
, 'lib/*'
, 'bin/*'
, 'tests/*'
]);

388
jake/jake.d.ts vendored Normal file
View File

@@ -0,0 +1,388 @@
// Type definitions for jake
// Project: https://github.com/mde/jake
// Definitions by: Kon <http://phyzkit.net/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/**
* Complets an asynchronous task, allowing Jake's execution to proceed to the next task
*/
function complete(): void;
/**
* Creates a description for a Jake Task (or FileTask, DirectoryTask). When invoked, the description that iscreated will be associated with whatever Task is created next.
* @param description The description for the Task
*/
function desc(description:string): void;
/**
* Creates a Jake DirectoryTask. Can be used as a prerequisite for FileTasks, or for simply ensuring a directory exists for use with a Task's action.
* @param name The name of the DiretoryTask
*/
function directory(name:string): jake.DirectoryTask;
/**
* Causes Jake execution to abort with an error. Allows passing an optional error code, which will be used to set the exit-code of exiting process.
* @param err The error to thow when aborting execution. If this argument is an Error object, it will simply be thrown. If a String, it will be used as the error-message. (If it is a multi-line String, the first line will be used as the Error message, and the remaining lines will be used as the error-stack.)
*/
function fail(...err:string[]): void;
function fail(...err:Error[]): void;
function fail(...err:any[]): void;
/**
* Creates a Jake FileTask.
* @name name The name of the Task
* @param prereqs Prerequisites to be run before this task
* @param action The action to perform for this task
* @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task.
*/
function file(name:string, prereqs?:string[], action?:()=>void, opts?:jake.FileTaskOptions): jake.FileTask;
/**
* Creates a namespace which allows logical grouping of tasks, and prevents name-collisions with task-names. Namespaces can be nested inside of other namespaces.
* @param name The name of the namespace
* @param scope The enclosing scope for the namespaced tasks
*/
function namespace(name:string, scope:()=>void): void;
/**
* @param name The name of the Task
* @param prereqs Prerequisites to be run before this task
* @param action The action to perform for this task
* @param opts
*/
function task(name:string, prereqs?:string[], action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task;
function task(name:string, action?:(...params:any[])=>any, opts?:jake.TaskOptions): jake.Task;
function task(name:string, opts?:jake.TaskOptions, action?:(...params:any[])=>any): jake.Task;
module jake{
////////////////////////////////////////////////////////////////////////////////////
// File-utils //////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
interface UtilOptions{
silent?: bool;
}
/**
* The jake.mkdirP utility recursively creates a set of nested directories. It will not throw an error if any of the directories already exists.
* https://github.com/substack/node-mkdirp
*/
export function mkdirP(name:string, mode?:string, f?:(er:Error, made:any)=>void): void;
export function mkdirP(name:string, f?:(er:Error, made:any)=>void): void;
/**
* The jake.cpR utility does a recursive copy of a file or directory.
* Note that this command can only copy files and directories; it does not perform globbing (so arguments like '*.txt' are not possible).
* @param path the file/directory to copy,
* @param destination the destination.
*/
export function cpR(path:string, destination:string, opts?:UtilOptions, callback?:()=>void): void;
export function cpR(path:string, destination:string, callback?:(err:Error)=>void): void;
/**
* The jake.readdirR utility gives you a recursive directory listing, giving you output somewhat similar to the Unix find command. It only works with a directory name, and does not perform filtering or globbing.
* @return an array of filepaths for all files in the 'pkg' directory, and all its subdirectories.
*/
export function readdirR(name:string, opts?:UtilOptions): string[];
/**
* The jake.rmRf utility recursively removes a directory and all its contents.
*/
export function rmRf(name:string, opts?:UtilOptions): void;
//////////////////////////////////////////////////////////////////////////////////////////////
// Running shell-commands ////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
interface ExecOptions{
/**
* print to stdout, default false
*/
printStdout?:bool;
/**
* print to stderr, default false
*/
printStderr?:bool;
/**
* stop execution on error, default true
*/
breakOnError?:bool;
}
export function exec(cmds:string[], callback?:()=>void, opts?:ExecOptions);
/**
* @event cmdStart When a new command begins to run. Passes one arg, the command being run.
* @event cmdEnd When a command finishes. Passes one arg, the command being run.
* @event stdout When the stdout for the child-process recieves data. This streams the stdout data. Passes one arg, the chunk of data.
* @event stderr When the stderr for the child-process recieves data. This streams the stderr data. Passes one arg, the chunk of data.
* @event error When a shell-command
*/
export interface Exec extends EventEmitter{
constructor(cmds:string[], callback?:()=>void, opts?:ExecOptions);
constructor(cmds:string[], opts?:ExecOptions, callback?:()=>void);
constructor(cmds:string, callback?:()=>void, opts?:ExecOptions);
constructor(cmds:string, opts?:ExecOptions, callback?:()=>void);
append(cmd:string): void;
run(): void;
}
export function createExec(cmds:string[], callback?:()=>void, opts?:ExecOptions ):Exec;
export function createExec(cmds:string[], opts?:ExecOptions, callback?:()=>void):Exec;
export function createExec(cmds:string, callback?:()=>void, opts?:ExecOptions ):Exec;
export function createExec(cmds:string, opts?:ExecOptions, callback?:()=>void):Exec;
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Logging and output ////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
interface Logger{
log(value:any): void;
error(value:any): void;
}
export var logger: Logger;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// program ////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
export var program: {
opts: {
[name:string]: any;
quiet: bool;
};
taskNames: string[];
taskArgs: string[];
envVars: { [key:string]: string; };
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tasks /////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
export interface TaskOptions{
/**
* Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task.
* @default false
*/
asyc?: bool;
}
/**
* A Jake Task
*
* @event complete
*/
export class Task implements EventEmitter{
/**
* @name name The name of the Task
* @param prereqs Prerequisites to be run before this task
* @param action The action to perform for this task
* @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task.
*/
constructor(name:string, prereqs?:string[], action?:()=>void, opts?:TaskOptions);
/**
* Runs prerequisites, then this task. If the task has already been run, will not run the task again.
*/
invoke(): void;
/**
* Runs this task, without running any prerequisites. If the task has already been run, it will still run it again.
*/
reenable(): void;
addListener(event: string, listener: Function);
on(event: string, listener: Function);
once(event: string, listener: Function): void;
removeListener(event: string, listener: Function): void;
removeAllListener(event: string): void;
setMaxListeners(n: number): void;
listeners(event: string): { Function; }[];
emit(event: string, arg1?: any, arg2?: any): void;
}
export class DirectoryTask{
/**
* @param name The name of the directory to create.
*/
constructor(name:string);
}
export interface FileTaskOptions{
/**
* Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task.
* @default false
*/
asyc?: bool;
}
export class FileTask{
/**
* @param name The name of the Task
* @param prereqs Prerequisites to be run before this task
* @param action The action to perform to create this file
* @param opts Perform this task asynchronously. If you flag a task with this option, you must call the global `complete` method inside the task's action, for execution to proceed to the next task.
*/
constructor(name:string, prereqs?:string[], action?:()=>void, opts?:FileTaskOptions);
}
interface FileFilter{
(filename:string): bool;
}
export class FileList{
constructor();
/**
* Includes file-patterns in the FileList. Should be called with one or more
* pattern for finding file to include in the list. Arguments should be strings
* for either a glob-pattern or a specific file-name, or an array of them
*/
include(files:string[]): void;
include(...files:string[]): void;
/**
* Indicates whether a particular file would be filtered out by the current
* exclusion rules for this FileList.
* @param name The filename to check
* @return Whether or not the file should be excluded
*/
shouldExclude(name:string): bool;
/**
* Excludes file-patterns from the FileList. Should be called with one or more
* pattern for finding file to include in the list. Arguments can be:
* 1. Strings for either a glob-pattern or a specific file-name
* 2. Regular expression literals
* 3. Functions to be run on the filename that return a true/false
*/
exclude(file:string[]): void;
exclude(...file:string[]): void;
exclude(file:RegExp[]): void;
exclude(...file:RegExp[]): void;
exclude(file:FileFilter[]): void;
exclude(...file:FileFilter[]): void;
/**
* Populates the FileList from the include/exclude rules with a list of
* actual files
*/
resolve(): void;
/**
* Convert to a plain-jane array
*/
toArray(): string[];
/**
* Get rid of any current exclusion rules
*/
clearExclude(): void;
}
export class PackageTask{
/**
* Instantiating a PackageTask creates a number of Jake Tasks that make packaging and distributing your software easy.
* @param name The name of the project
* @param version The current project version (will be appended to the project-name in the package-archive
* @param definition Defines the contents of the package, and format of the package-archive. Will be executed on the instantiated PackageTask (i.e., 'this', will be the PackageTask instance), to set the various instance-propertiess.
*/
constructor(name:string, version:string, definition:()=>void);
/**
* Equivalent to the '-C' command for the `tar` and `jar` commands. ("Change to this directory before adding files.")
*/
archiveChangeDir: string;
/**
* Specifies the files and directories to include in the package-archive. If unset, this will default to the main package directory -- i.e., name + version.
*/
archiveContentDir: string;
/**
* The shell-command to use for creating jar archives.
*/
jarCommand: string;
/**
* Can be set to point the `jar` utility at a manifest file to use in a .jar archive. If unset, one will be automatically created by the `jar` utility. This path should be relative to the root of the package directory (this.packageDir above, likely 'pkg')
*/
manifestFile: string;
/**
* The name of the project
*/
name: string;
/**
* If set to true, uses the `jar` utility to create a .jar archive of the pagckage
*/
needJar: bool;
/**
* If set to true, uses the `tar` utility to create a gzip .tgz archive of the pagckage
*/
needTar: bool;
/**
* If set to true, uses the `tar` utility to create a bzip2 .bz2 archive of the pagckage
*/
needTarBz2: bool;
/**
* If set to true, uses the `zip` utility to create a .zip archive of the pagckage
*/
needZip: bool;
/**
* The list of files and directories to include in the package-archive
*/
packageFiles: FileList;
/**
* The shell-command to use for creating tar archives.
*/
tarCommand: string;
/**
* The project version-string
*/
version: string;
/**
* The shell-command to use for creating zip archives.
*/
zipCommand: string;
}
export class TestTask{
constructor(name:string, definition?:()=>void);
}
export class NpmPublishTask{
constructor(name:string, packageFiles:string[]);
}
export function addListener(event: string, listener: Function);
export function on(event: string, listener: Function);
export function once(event: string, listener: Function): void;
export function removeListener(event: string, listener: Function): void;
export function removeAllListener(event: string): void;
export function setMaxListeners(n: number): void;
export function listeners(event: string): { Function; }[];
export function emit(event: string, arg1?: any, arg2?: any): void;
}

View File

@@ -60,7 +60,7 @@ describe("Included matchers:", () => {
foo: 'foo'
};
expect(a.foo).toBeDefined();
expect(a.bar).not.toBeDefined();
expect((<any>a).bar).not.toBeDefined();
});
it("The `toBeUndefined` matcher compares against `undefined`", () => {
@@ -68,7 +68,7 @@ describe("Included matchers:", () => {
foo: 'foo'
};
expect(a.foo).not.toBeUndefined();
expect(a.bar).toBeUndefined();
expect((<any>a).bar).toBeUndefined();
});
it("The 'toBeNull' matcher compares against null", () => {
@@ -120,7 +120,7 @@ describe("Included matchers:", () => {
return 1 + 2;
};
var bar = () => {
return a + 1;
//return a + 1;
};
expect(foo).not.toThrow();
expect(bar).toThrow();
@@ -439,7 +439,7 @@ describe("Asynchronous specs", () => {
currentWindowOnload(null);
}
document.querySelector('.version').innerHTML = jasmineEnv.versionString();
(<HTMLElement>document.querySelector('.version')).innerHTML = jasmineEnv.versionString();
execJasmine();
};

View File

@@ -7,7 +7,8 @@
declare function describe(description: string, specDefinitions: Function): void;
declare function xdescribe(description: string, specDefinitions: Function): void;
declare function it(expectation: string, assertion: Function): void;
declare function it(expectation: string, assertion: () => void ): void;
declare function it(expectation: string, assertion: (done: (err?) => void) => void ): void;
declare function xit(expectation: string, assertion: Function): void;
declare function beforeEach(action: Function): void;
@@ -23,7 +24,6 @@ declare function runs(asyncMethod: Function): void;
declare function waitsFor(latchMethod: () => bool, failureMessage: string, timeout?: number): void;
declare function waits(timeout?: number): void;
declare module jasmine {
var Clock: Clock;
@@ -165,6 +165,8 @@ declare module jasmine {
toBeLessThan(expected): bool;
toBeGreaterThan(expected): bool;
toBeCloseTo(expected, precision): bool;
toContainHtml(expected: string): bool;
toContainText(expected: string): bool;
toThrow(expected? ): bool;
not: Matchers;
@@ -291,4 +293,6 @@ declare module jasmine {
Clock: Clock;
util: Util;
}
export var HtmlReporter: any;
}

View File

@@ -94,7 +94,10 @@ $("#formatterExample").dateRangeSlider({
formatter: (val: Date) => {
var days = val.getDay(),
month = val.getMonth() + 1,
year = val.getYear();
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getYear#Description
// getYear is no longer used and has been replaced by the getFullYear method.
// year = val.getYear();
year = val.getFullYear();
return days + "/" + month + "/" + year;
}
});

File diff suppressed because it is too large Load Diff

View File

@@ -1,42 +1,160 @@
// Type definitions for jquery.bbq 1.2
// Project: http://benalman.com/projects/jquery-bbq-plugin/
// Definitions by: https://github.com/sunetos
// Definitions by: Adam R. Smith <https://github.com/sunetos>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface JQueryBBQ {
pushState(params?: any, merge_mode?: number): void;
getState(key?: string, coerce?: bool): any;
removeState(...key: any[]): void;
/// <reference path="../jquery/jquery.d.ts" />
module JQueryBbq {
interface JQuery {
/**
* Adds a 'state' into the browser history at the current position, setting
* location.hash and triggering any bound <hashchange event> callbacks
* (provided the new state is different than the previous state).
*
* @name params A serialized params string or a hash string beginning with # to merge into location.hash.
* @name merge_mode Merge behavior defaults to 0 if merge_mode is not specified (unless a hash string beginning with # is specified, in which case merge behavior defaults to 2)
*/
pushState(params?: string, merge_mode?: number): void;
pushState(params?: any, merge_mode?: number): void;
/**
* Retrieves the current 'state' from the browser history, parsing
* location.hash for a specific key or returning an object containing the
* entire state, optionally coercing numbers, booleans, null and undefined
* values.
*
* @name key An optional state key for which to return a value.
* @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false
*/
getState(key?: string, coerce?: bool): any;
getState(coerce?: bool): any;
/**
* Remove one or more keys from the current browser history 'state', creating
* a new state, setting location.hash and triggering any bound
* <hashchange event> callbacks (provided the new state is different than
* the previous state).
*
* @name key One or more key values to remove from the current state.
*/
removeState(...key: any[]): void;
}
interface ParamFragment {
(url?: string): string;
(url: string, params: any, merge_mode?: number): string;
/**
* Specify characters that will be left unescaped when fragments are created
* or merged using <jQuery.param.fragment>, or when the fragment is modified
* using <jQuery.bbq.pushState>. This option only applies to serialized data
* object fragments, and not set-as-string fragments. Does not affect the
* query string. Defaults to ",/" (comma, forward slash).
*
* @name chars The characters to not escape in the fragment. If unspecified, defaults to empty string (escape all characters).
*/
noEscape: (chars?: string) => void;
/**
* TODO: DESCRIBE
*
* @name state TODO: DESCRIBE
*/
ajaxCrawlable(state?: bool): bool;
}
interface JQueryDeparam {
/**
* Deserialize a params string into an object, optionally coercing numbers,
* booleans, null and undefined values; this method is the counterpart to the
* internal jQuery.param method.
*
* @name params A params string to be parsed.
* @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted.
*/
(params: string, coerce?: bool): any;
/**
* Parse the query string from a URL or the current window.location.href,
* deserializing it into an object, optionally coercing numbers, booleans,
* null and undefined values.
*
* @name url An optional params string or URL containing query string params to be parsed. If url is omitted, the current window.location.href is used.
* @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted.
*/
querystring(url?: string, coerce?: bool): any;
/**
* Parse the fragment (hash) from a URL or the current window.location.href,
* deserializing it into an object, optionally coercing numbers, booleans,
* null and undefined values.
*
* @name url An optional params string or URL containing fragment (hash) params to be parsed. If url is omitted, the current window.location.href is used.
* @name coerce If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted.
*/
fragment(url?: string, coerce?: bool): any;
}
interface EventObject extends JQueryEventObject {
fragment: string;
getState( key?: string, coerce? :bool );
}
}
interface JQueryParam {
(obj: any): string;
(obj: any, traditional: bool): string;
/**
* Parse the query string from a URL or the current window.location.href,
* deserializing it into an object, optionally coercing numbers, booleans,
* null and undefined values.
*
* @name url An optional params string or URL containing query string params to be parsed. If url is omitted, the current window.location.href is used.
* @name coerce (Boolean) If true, coerces any numbers or true, false, null, and undefined to their actual value. Defaults to false if omitted.
* @name merge_mode An object representing the deserialized params string.
*/
querystring(url?: string, coerce?: bool, merge_mode?: number): string;
querystring(url?: string): string;
querystring(url: string, params: any, merge_mode?: number): string;
fragment: {
noEscape: (chars?: string) => void;
(url?: string): string;
(url: string, params: any, merge_mode?: number): string;
};
}
querystring(url?: string, coerce?: any, merge_mode?: number): string;
interface JQueryDeparam {
(params: string, coerce?: bool): any;
querystring(url?: string, coerce?: bool): any;
fragment(url?: string, coerce?: bool): any;
fragment: JQueryBbq.ParamFragment;
/**
* Returns a params string equivalent to that returned by the internal
* jQuery.param method, but sorted, which makes it suitable for use as a
* cache key.
*
* @name obj An object to be serialized.
* @name traditional Params deep/shallow serialization mode. See the documentation at http://api.jquery.com/jQuery.param/ for more detail.
*/
sorted(obj: any, traditional?: bool): string;
}
interface JQueryStatic {
bbq: JQueryBBQ;
param: JQueryParam;
deparam: JQueryDeparam;
bbq: JQueryBbq.JQuery;
elemUrlAttr(tag_attr: any): any;
deparam: JQueryBbq.JQueryDeparam;
/**
* Get the internal "Default URL attribute per tag" list, or augment the list
* with additional tag-attribute pairs, in case the defaults are insufficient.
*
* @name tag_attr An object containing a list of tag names and their associated default attribute names in the format { tag: 'attr', ... } to be merged into the internal tag-attribute list.
*/
elemUrlAttr(tag_attr?: any): any;
}
interface JQuery {
querystring(attr?: any, params?: any, merge_mode?: number): JQuery;
fragment(attr?: any, params?: any, merge_mode?: number): JQuery;
querystring(attr?: any, params?: any, merge_mode?: number): JQuery;
fragment(attr?: any, params?: any, merge_mode?: number): JQuery;
hashchange(eventData?: any, handler?: (eventObject: JQueryBbq.EventObject) => any): JQuery;
hashchange(handler: (eventObject: JQueryBbq.EventObject) => any): JQuery;
}

View File

@@ -0,0 +1,17 @@
///<reference path="jquery.clientSideLogging.d.ts" />
$.clientSideLogging({
log_level: 3,
client_info: {
location:true,
screen_size:true,
user_agent:true,
window_size:false
}
});
$.info({msg:$(this).parents('li').find('input:text').val()});
$.error({msg:$(this).parents('li').find('input:text').val()});
$.log($(this).parents('li').find('input:text').val());
$.post('/log?type=error&msg=YOUR_ERROR_MESSAGE');

Some files were not shown because too many files have changed in this diff Show More