Merge remote-tracking branch 'remotes/upstream/master'

This commit is contained in:
Igor Oleinikov
2014-03-19 17:22:35 +04:00
79 changed files with 6851 additions and 1624 deletions
+7 -1
View File
@@ -54,6 +54,7 @@ List of Definitions
* [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))
* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay))
* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik))
* [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon))
* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem))
* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat))
@@ -62,6 +63,7 @@ List of Definitions
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com))
* [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton))
* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton))
* [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter))
@@ -137,6 +139,7 @@ List of Definitions
* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny))
* [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix))
* [jQuery.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald))
* [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.form](http://malsup.com/jquery/form/) (by [François Guillot](http://fguillot.developpez.com/))
@@ -144,6 +147,7 @@ List of Definitions
* [jQuery.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts))
* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone))
* [jQuery.jSignature] (https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/))
* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb))
* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/))
@@ -155,6 +159,7 @@ List of Definitions
* [jQuery.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl))
* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.tooltipster] (https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee))
* [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))
@@ -238,7 +243,7 @@ List of Definitions
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin))
* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley))
* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
* [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n))
* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev))
@@ -264,6 +269,7 @@ List of Definitions
* [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))
* [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds))
* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade))
* [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient))
* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov))
+1 -1
View File
@@ -1 +1 @@
tsc runner.ts --target ES5 --out runner.js --module commonjs
tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap
+13 -12
View File
@@ -850,7 +850,7 @@ var DT;
var Promise = require('bluebird');
var endDts = /\w\.ts$/i;
var endDts = /\w\.d\.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
@@ -1035,9 +1035,6 @@ var DT;
// add a closure to queue
this.queue.push(function () {
// when activate, add test to active list
_this.active.push(test);
// run it
var p = test.run();
p.then(defer.resolve.bind(defer), defer.reject.bind(defer));
@@ -1048,6 +1045,9 @@ var DT;
}
_this.step();
});
// return it
return test;
});
this.step();
@@ -1056,13 +1056,9 @@ var DT;
};
TestQueue.prototype.step = function () {
var _this = this;
// setTimeout to make it flush
setTimeout(function () {
while (_this.queue.length > 0 && _this.active.length < _this.concurrent) {
_this.queue.pop().call(null);
}
}, 1);
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.active.push(this.queue.pop().call(null));
}
};
return TestQueue;
})();
@@ -1297,10 +1293,12 @@ var DT;
process.exit(0);
}
var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false;
new TestRunner(dtPath, {
concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2),
tscVersion: argv['tsc-version'],
testChanges: argv['test-changes'],
testChanges: testFull ? false : argv['test-changes'],
skipTests: argv['skip-tests'],
printFiles: argv['print-files'],
printRefMap: argv['print-refmap'],
@@ -1314,4 +1312,7 @@ var DT;
process.exit(2);
});
})(DT || (DT = {}));
//grunt-start
/// <reference path="../runner.ts" />
//grunt-end
//# sourceMappingURL=runner.js.map
+8 -9
View File
@@ -75,8 +75,6 @@ module DT {
var defer = Promise.defer();
// add a closure to queue
this.queue.push(() => {
// when activate, add test to active list
this.active.push(test);
// run it
var p = test.run();
p.then(defer.resolve.bind(defer), defer.reject.bind(defer));
@@ -87,6 +85,8 @@ module DT {
}
this.step();
});
// return it
return test;
});
this.step();
// defer it
@@ -94,12 +94,9 @@ module DT {
}
private step(): void {
// setTimeout to make it flush
setTimeout(() => {
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.queue.pop().call(null);
}
}, 1);
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.active.push(this.queue.pop().call(null));
}
}
}
@@ -339,10 +336,12 @@ module DT {
process.exit(0);
}
var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false;
new TestRunner(dtPath, {
concurrent: argv['single-thread'] ? 1 : Math.max(cpuCores, 2),
tscVersion: argv['tsc-version'],
testChanges: argv['test-changes'],
testChanges: testFull ? false : argv['test-changes'], // allow magic branch
skipTests: argv['skip-tests'],
printFiles: argv['print-files'],
printRefMap: argv['print-refmap'],
+1 -1
View File
@@ -6,7 +6,7 @@ module DT {
var Promise: typeof Promise = require('bluebird');
var endDts = /\w\.ts$/i;
var endDts = /\w\.d\.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
+5 -3
View File
@@ -885,7 +885,9 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
/** AmChart is a base class of all charts. It can not be instantiated explicitly. AmCoordinateChart, AmPieChart and AmMap extend AmChart class. */
class AmChart {
/** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */
/** used when constructing a chart with a theme */
constructor(theme: any);
/** Background color. You should set backgroundAlpha to >0 value in order background to be visible. We recommend setting background color directly on a chart's DIV instead of using this property. #FFFFFF */
backgroundColor: string;
/** The chart creates AmBalloon class itself. If you want to customize balloon, get balloon instance using this property, and then change balloon's properties. AmBalloon */
balloon: AmBalloon;
@@ -943,7 +945,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
@param legend
@param legendDivId - Id of the legend div (optional).
*/
addLegend(legend: AmLegend, legendDivId: string);
addLegend(legend: AmLegend, legendDivId?: string);
/** Adds a legend to the chart.
By default, you don't need to create div for your legend, however if you want it to be positioned in some different way, you can create div anywhere you want and pass id or reference to your div as a second parameter.
(NOTE: This method will not work on StockPanel.)
@@ -1437,7 +1439,7 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val
chart.write("chartdiv");
*/
class AmSerialChart extends AmRectangularChart {
/** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */
/** Read-only. Chart creates category axis itself. If you want to change some properties, you should get this axis from the chart and set properties to this object. */
categoryAxis: CategoryAxis;
/** Category field name tells the chart the name of the field in your dataProvider object which will be used for category axis values. */
categoryField: string;
+1
View File
@@ -51,6 +51,7 @@ declare module ng.resource {
// to be considered as parameters to the request.
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L461-L465
interface IResourceClass<T> {
new(dataOrParams? : any) : T;
get(): T;
get(dataOrParams: any): T;
get(dataOrParams: any, success: Function): T;
+1
View File
@@ -41,6 +41,7 @@ declare module ng.route {
resolve?: any;
redirectTo?: any;
reloadOnSearch?: boolean;
caseInsensitiveMatch?: boolean;
}
// see http://docs.angularjs.org/api/ng.$route#current
+7
View File
@@ -94,6 +94,7 @@ module HttpAndRegularPromiseTests {
person: Person;
theAnswer: number;
letters: string[];
snack: string;
}
var someController: Function = ($scope: SomeControllerScope, $http: ng.IHttpService, $q: ng.IQService) => {
@@ -132,6 +133,12 @@ module HttpAndRegularPromiseTests {
cPromise.then((letters: string[]) => {
$scope.letters = letters;
});
// When $q.when is passed an IPromise<T>, it returns an IPromise<T>
var dPromise: ng.IPromise<string> = $q.when($q.when("ALBATROSS!"));
dPromise.then((snack: string) => {
$scope.snack = snack;
});
}
// Test that we can pass around a type-checked success/error Promise Callback
+2 -1
View File
@@ -430,7 +430,7 @@ declare module ng {
// DocumentService
// see http://docs.angularjs.org/api/ng.$document
///////////////////////////////////////////////////////////////////////////
interface IDocumentService extends Document {}
interface IDocumentService extends IAugmentedJQuery {}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
@@ -455,6 +455,7 @@ declare module ng {
all(promises: {[id: string]: IPromise<any>;}): IPromise<{[id: string]: any}>;
defer<T>(): IDeferred<T>;
reject(reason?: any): IPromise<void>;
when<T>(value: IPromise<T>): IPromise<T>;
when<T>(value: T): IPromise<T>;
}
+2
View File
@@ -53,6 +53,8 @@ interface Async {
series<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
parallel<T>(tasks: T, callback?: AsyncMultipleResultsCallback<T>): void;
parallelLimit<T>(tasks: T[], limit: number, callback?: AsyncMultipleResultsCallback<T>): void;
parallelLimit<T>(tasks: T, limit: number, callback?: AsyncMultipleResultsCallback<T>): void;
whilst(test: Function, fn: Function, callback: Function): void;
until(test: Function, fn: Function, callback: Function): void;
waterfall<T>(tasks: T[], callback?: AsyncMultipleResultsCallback<T>): void;
+772 -209
View File
File diff suppressed because it is too large Load Diff
+417 -248
View File
@@ -3,27 +3,44 @@
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Note: these are preliminary non-generic typings using `any`: the generic versions are ready but need (tsc >= v1.0.0) due to issues in the compiler
// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
// - https://github.com/borisyankov/DefinitelyTyped/tree/def/bluebird/bluebird
// ES6 model with generics overload was sourced and trans-multiplied from es6-promises.d.ts
// By: Campredon <https://github.com/fdecampredon/>
declare class Promise {
// Warning: recommended to use `tsc > v0.9.7` (critical bugs in earlier generic code):
// - https://github.com/borisyankov/DefinitelyTyped/issues/1563
// Note: replicate changes to all overloads in both definition and test file
// Note: keep both static and instance members inline (so similar)
// TODO fix remaining TODO annotations in both definition and test
// TODO verify support to have no return statement in handlers to get a Promise<void> (more overloads?)
declare class Promise<R> implements Promise.Thenable<R> {
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
*/
constructor(resolver: (resolve: (value: any) => void, reject: (reason: any) => any) => void);
constructor(callback: (resolve: (thenable: Promise.Thenable<R>) => void, reject: (error: any) => void) => void);
constructor(callback: (resolve: (result: R) => void, reject: (error: any) => void) => void);
/**
* Promises/A+ `.then()` with progress handler. Returns a new promise chained from this promise. The new promise will be rejected or resolved dedefer on the passed `fulfilledHandler`, `rejectedHandler` and the state of this promise.
*/
then(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any):Promise;
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => Promise.Thenable<U>, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* This is a catch-all exception handler, shortcut for calling `.then(null, handler)` on this promise. Any exception happening in a `.then`-chain will propagate to nearest `.catch` handler.
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
catch(handler: (reason: any) => any):Promise;
caught(handler: (reason: any) => any):Promise;
catch<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(onReject?: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(onReject?: (error: any) => U): Promise<U>;
caught<U>(onReject?: (error: any) => U): Promise<U>;
/**
* This extends `.catch` to work more like catch-clauses in languages like Java or C#. Instead of manually checking `instanceof` or `.name === "SomeError"`, you may specify a number of error constructors which are eligible for this catch handler. The catch handler that is first met that has eligible constructors specified, is the one that will be called.
@@ -32,64 +49,78 @@ declare class Promise {
*
* Alias `.caught();` for compatibility with earlier ECMAScript version.
*/
//TODO expand this complex overload (weird)
catch(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise;
caught(predicate: (reason: any) => boolean, handler: (reason: any) => any): Promise;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch(ErrorClass: Function, handler: (reason: any) => any): Promise;
caught(ErrorClass: Function, handler: (reason: any) => any): Promise;
catch<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
caught<U>(predicate: (error: any) => boolean, onReject: (error: any) => U): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => Promise.Thenable<U>): Promise<U>;
catch<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
caught<U>(ErrorClass: Function, onReject: (error: any) => U): Promise<U>;
/**
* Like `.catch` but instead of catching all types of exceptions, it only catches those that don't originate from thrown errors but rather from explicit rejections.
*/
error(rejectedHandler: (reason: any) => any): Promise;
error<U>(onReject: (reason: any) => Promise.Thenable<U>): Promise<U>;
error<U>(onReject: (reason: any) => U): Promise<U>;
/**
* Pass a handler that will be called regardless of this promise's fate. Returns a new promise chained from this promise. There are special semantics for `.finally()` in that the final value cannot be modified from the handler.
*
* Alias `.lastly();` for compatibility with earlier ECMAScript version.
*/
finally(handler: (value: any) => any): Promise;
lastly(handler: (value: any) => any): Promise;
finally(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
finally(handler: (value: R) => R): Promise<R>;
finally(handler: (value: R) => void): Promise<R>;
lastly(handler: (value: R) => Promise.Thenable<R>): Promise<R>;
lastly(handler: (value: R) => R): Promise<R>;
lastly(handler: (value: R) => void): Promise<R>;
/**
* Create a promise that follows this promise, but is bound to the given `thisArg` value. A bound promise will call its handlers with the bound value set to `this`. Additionally promises derived from a bound promise will also be bound promises with the same `thisArg` binding as the original promise.
*/
bind(thisArg: any): Promise;
bind(thisArg: any): Promise<R>;
/**
* Like `.then()`, but any unhandled rejection that ends up here will be thrown as an error.
*/
done(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
done<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Shorthand for `.then(null, null, handler);`. Attach a progress handler that will be called if this promise is progressed. Returns a new promise chained from this promise.
*/
progressed(handler: (note: any) => any): Promise;
progressed(handler: (note: any) => any): Promise<R>;
/**
* Same as calling `Promise.delay(this, ms)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
delay(ms: number): Promise;
delay(ms: number): Promise<R>;
/**
* Returns a promise that will be fulfilled with this promise's fulfillment value or rejection reason. However, if this promise is not fulfilled or rejected within `ms` milliseconds, the returned promise is rejected with a `Promise.TimeoutError` instance.
*
* You may specify a custom error message with the `message` parameter.
*/
timeout(ms: number, message?: string): Promise;
timeout(ms: number, message?: string): Promise<R>;
/**
* Register a node-style callback on this promise. When this promise is is either fulfilled or rejected, the node callback will be called back with the node.js convention where error reason is the first argument and success value is the second argument. The error argument will be `null` in case of success.
* Returns back this promise instead of creating a new one. If the `callback` argument is not a function, this method does not do anything.
*/
nodeify(callback?: Function): Promise;
nodeify(callback: (err: any, value?: R) => void): Promise<R>;
nodeify(...sink: any[]): void;
/**
* Marks this promise as cancellable. Promises by default are not cancellable after v0.11 and must be marked as such for `.cancel()` to have any effect. Marking a promise as cancellable is infectious and you don't need to remark any descendant promise.
*/
cancellable(): Promise;
cancellable(): Promise<R>;
/**
* Cancel this promise. The cancellation will propagate to farthest cancellable ancestor promise which is still pending.
@@ -100,17 +131,21 @@ declare class Promise {
*
* Promises are by default not cancellable. Use `.cancellable()` to mark a promise as cancellable.
*/
cancel(): Promise;
// TODO what to do with this?
cancel<U>(): Promise<U>;
/**
* Like `.then()`, but cancellation of the the returned promise or any of its descendant will not propagate cancellation to this promise or this promise's ancestors.
*/
fork(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any, progressHandler?: (note: any) => any): Promise;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => Promise.Thenable<U>, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Promise.Thenable<U>, onProgress?: (note: any) => any): Promise<U>;
fork<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U, onProgress?: (note: any) => any): Promise<U>;
/**
* Create an uncancellable promise based on this promise.
*/
uncancellable(): Promise;
uncancellable(): Promise<R>;
/**
* See if this promise can be cancelled.
@@ -138,62 +173,65 @@ declare class Promise {
isResolved(): boolean;
/**
* Synchronously inspect the state of this `promise`. The `Promise.Inspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
* Synchronously inspect the state of this `promise`. The `PromiseInspection` will represent the state of the promise as snapshotted at the time of calling `.inspect()`.
*/
inspect(): Promise.Inspection;
inspect(): Promise.Inspection<R>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName].call(obj, arg...);
* });
* return obj[propertyName].call(obj, arg...);
* });
* </code>
*/
call(propertyName: string, ...args: any[]): Promise;
call(propertyName: string, ...args: any[]): Promise<any>;
/**
* This is a convenience method for doing:
*
* <code>
* promise.then(function(obj){
* return obj[propertyName];
* });
* return obj[propertyName];
* });
* </code>
*/
get(propertyName: string): Promise;
// TODO find way to fix get()
// get<U>(propertyName: string): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* return value;
* });
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return(value: any): Promise;
thenReturn(): Promise;
return(): Promise<any>;
thenReturn(): Promise<any>;
return<U>(value: U): Promise<U>;
thenReturn<U>(value: U): Promise<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason: any): Promise;
thenThrow(): Promise;
throw(reason: Error): Promise<R>;
thenThrow(reason: Error): Promise<R>;
/**
* Convert to String.
@@ -205,64 +243,376 @@ declare class Promise {
*/
toJSON(): Object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
// TODO how to model instance.spread()? like Q?
spread<U>(onFulfill: Function, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U>(onFulfill: Function, onReject?: (reason: any) => U): Promise<U>;
/*
// TODO or something like this?
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => Promise.Thenable<U>, onReject?: (reason: any) => U): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => Promise.Thenable<U>): Promise<U>;
spread<U, W>(onFulfill: (...values: W[]) => U, onReject?: (reason: any) => U): Promise<U>;
*/
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all(): Promise;
// TODO type inference from array-resolving promise?
all<U>(): Promise<U[]>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
props(): Promise;
// TODO how to model instance.props()?
props(): Promise<Object>;
/**
* Same as calling `Promise.settle(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
settle(): Promise;
// TODO type inference from array-resolving promise?
settle<U>(): Promise<Promise.Inspection<U>[]>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any(): Promise;
// TODO type inference from array-resolving promise?
any<U>(): Promise<U>;
/**
* Same as calling `Promise.race(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some(count: number): Promise;
// TODO type inference from array-resolving promise?
some<U>(count: number): Promise<U[]>;
/**
* Same as calling `Promise.some(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race(): Promise;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
*/
spread(fulfilledHandler?: (value: any) => any, rejectedHandler?: (reason: any) => any): Promise;
// TODO type inference from array-resolving promise?
race<U>(): Promise<U>;
/**
* Same as calling `Promise.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
map(mapper: (item: any, index: number, arrayLength: number) => any): Promise;
// TODO type inference from array-resolving promise?
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U>;
map<Q, U>(mapper: (item: Q, index: number, arrayLength: number) => U): Promise<U>;
/**
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
reduce(reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise;
// TODO type inference from array-resolving promise?
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
reduce<Q, U>(reducer: (memo: U, item: Q, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
filter(filterer: (item: any, index: number, arrayLength: number) => any): Promise;
// TODO type inference from array-resolving promise?
filter<U>(filterer: (item: U, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<U>;
filter<U>(filterer: (item: U, index: number, arrayLength: number) => boolean): Promise<U>;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
static try<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static try<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => Promise.Thenable<R>, args?: any[], ctx?: any): Promise<R>;
static attempt<R>(fn: () => R, args?: any[], ctx?: any): Promise<R>;
/**
* Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
static method(fn: Function): Function;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
static resolve(): Promise<void>;
static resolve<R>(value: Promise.Thenable<R>): Promise<R>;
static resolve<R>(value: R): Promise<R>;
/**
* Create a promise that is rejected with the given `reason`.
*/
static reject(reason: any): Promise<any>;
static reject<R>(reason: any): Promise<R>;
/**
* Create a promise with undecided fate and return a `PromiseResolver` to control it. See resolution?: Promise(#promise-resolution).
*/
static defer<R>(): Promise.Resolver<R>;
/**
* Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
static cast<R>(value: Promise.Thenable<R>): Promise<R>;
static cast<R>(value: R): Promise<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
static bind(thisArg: any): Promise<void>;
/**
* See if `value` is a trusted Promise.
*/
static is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
static longStackTraces(): void;
/**
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
// TODO enable more overloads
static delay<R>(value: Promise.Thenable<R>, ms: number): Promise<R>;
static delay<R>(value: R, ms: number): Promise<R>;
static delay(ms: number): Promise<void>;
/**
* Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
// TODO how to model promisify?
static promisify(nodeFunction: Function, receiver?: any): Function;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
// TODO how to model promisifyAll?
static promisifyAll(target: Object): Object;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix coroutine GeneratorFunction
static coroutine<R>(generatorFunction: Function): Function;
/**
* Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
// TODO fix spawn GeneratorFunction
static spawn<R>(generatorFunction: Function): Promise<R>;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else.
*/
static noConflict(): typeof Promise;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
static onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
// TODO enable more overloads
// promise of array with promises of value
static all<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R[]>;
// promise of array with values
static all<R>(values: Promise.Thenable<R[]>): Promise<R[]>;
// array with promises of value
static all<R>(values: Promise.Thenable<R>[]): Promise<R[]>;
// array with values
static all<R>(values: R[]): Promise<R[]>;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
// TODO verify this is correct
// trusted promise for object
static props(object: Promise<Object>): Promise<Object>;
// object
static props(object: Object): Promise<Object>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``PromiseInspection`` instances at respective positions in relation to the input array.
*
* *original: The array is not modified. The input array sparsity is retained in the resulting array.*
*/
// promise of array with promises of value
static settle<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<Promise.Inspection<R>[]>;
// promise of array with values
static settle<R>(values: Promise.Thenable<R[]>): Promise<Promise.Inspection<R>[]>;
// array with promises of value
static settle<R>(values: Promise.Thenable<R>[]): Promise<Promise.Inspection<R>[]>;
// array with values
static settle<R>(values: R[]): Promise<Promise.Inspection<R>[]>;
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
// promise of array with promises of value
static any<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static any<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static any<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static any<R>(values: R[]): Promise<R>;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
// promise of array with promises of value
static race<R>(values: Promise.Thenable<Promise.Thenable<R>[]>): Promise<R>;
// promise of array with values
static race<R>(values: Promise.Thenable<R[]>): Promise<R>;
// array with promises of value
static race<R>(values: Promise.Thenable<R>[]): Promise<R>;
// array with values
static race<R>(values: R[]): Promise<R>;
/**
* Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static some<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, count: number): Promise<R[]>;
// promise of array with values
static some<R>(values: Promise.Thenable<R[]>, count: number): Promise<R[]>;
// array with promises of value
static some<R>(values: Promise.Thenable<R>[], count: number): Promise<R[]>;
// array with values
static some<R>(values: R[], count: number): Promise<R[]>;
/**
* Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments.
*/
// variadic array with promises of value
static join<R>(...values: Promise.Thenable<R>[]): Promise<R[]>;
// variadic array with values
static join<R>(...values: R[]): Promise<R[]>;
/**
* Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
// promise of array with promises of value
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// promise of array with values
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R[]>, mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with promises of value
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: Promise.Thenable<R>[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
// array with values
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => Promise.Thenable<U>): Promise<U[]>;
static map<R, U>(values: R[], mapper: (item: R, index: number, arrayLength: number) => U): Promise<U[]>;
/**
* Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
// promise of array with promises of value
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<Promise.Thenable<R>[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// promise of array with values
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R[]>, reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with promises of value
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: Promise.Thenable<R>[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
// array with values
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => Promise.Thenable<U>, initialValue?: U): Promise<U>;
static reduce<R, U>(values: R[], reducer: (total: U, current: R, index: number, arrayLength: number) => U, initialValue?: U): Promise<U>;
/**
* Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
// promise of array with promises of value
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<Promise.Thenable<R>[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// promise of array with values
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R[]>, filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with promises of value
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: Promise.Thenable<R>[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
// array with values
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => Promise.Thenable<boolean>): Promise<R[]>;
static filter<R>(values: R[], filterer: (item: R, index: number, arrayLength: number) => boolean): Promise<R[]>;
}
declare module Promise {
export interface RangeError extends Error {
}
export interface CancellationError extends Error {
}
export interface TimeoutError extends Error {
}
export interface TypeError extends Error {
}
export interface RejectionError extends Error {
}
export interface Thenable<R> {
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled: (value: R) => Thenable<U>, onRejected?: (error: any) => U): Thenable<U>;
then<U>(onFulfilled: (value: R) => U, onRejected: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfilled?: (value: R) => U, onRejected?: (error: any) => U): Thenable<U>;
}
export interface Resolver<R> {
/**
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise: Promise<R>;
interface Resolver {
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value: any): void;
resolve(value: R): void;
resolve(): void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
@@ -275,14 +625,15 @@ declare module Promise {
progress(value: any): void;
/**
* Gives you a callback representation of the `Promise.Resolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property. The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fullfills its promise with an array of the values.
*/
callback:Function;
// TODO specify resolver callback
callback: (err: any, value: R, ...values: R[]) => void;
}
interface Inspection {
export interface Inspection<R> {
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
@@ -303,7 +654,7 @@ declare module Promise {
*
* throws `TypeError`
*/
value(): any;
value(): R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
@@ -312,190 +663,8 @@ declare module Promise {
*/
error(): any;
}
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call. Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
*/
// function try(fn: () => any, args?: any[], ctx?: any): Promise;
function attempt(fn: () => any, args?: any[], ctx?: any): Promise;
/**
* Returns a new function that wraps the given function `fn`. The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
*/
function method(fn: Function): Function;
/**
* Create a promise that is resolved with the given `value`. If `value` is a thenable or promise, the returned promise will assume its state.
*/
function resolve(value: any): Promise;
/**
* Create a promise that is rejected with the given `reason`.
*/
function reject(reason: any): Promise;
/**
* Create a promise with undecided fate and return a `Promise.Resolver` to control it. See resolution?:Promise(#promise-resolution).
*/
function defer(): Promise.Resolver;
/**
* Cast the given `value` to a trusted promise. If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is:Promise returned with `value` as its fulfillment value. If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that:Promise assimilates the state of the thenable.
*/
function cast(value: any): Promise;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
function bind(thisArg: any): Promise;
/**
* See if `value` is a trusted Promise.
*/
function is(value: any): boolean;
/**
* Call this right after the library is loaded to enabled long stack traces. Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have alread been created. Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
function longStackTraces(): void;
/**
* Returns a promise that will be fulfilled with `value` (or `undefined`) after given `ms` milliseconds. If `value` is a promise, the delay will start counting down when it is fulfilled and the returned promise will be fulfilled with the fulfillment value of the `value` promise.
*/
function delay(value: Promise, ms: number): Promise;
function delay(value: any, ms: number): Promise;
function delay(ms: number): Promise;
/**
* Returns a function that will wrap the given `nodeFunction`. Instead of taking a callback, the returned function will return a promise whose fate is decided by the callback behavior of the given node function. The node function should conform to node.js convention of accepting a callback as last argument and calling that callback with error as the first argument and success value on the second argument.
*
* If the `nodeFunction` calls its callback with multiple success values, the fulfillment value will be an array of them.
*
* If you pass a `receiver`, the `nodeFunction` will be called as a method on the `receiver`.
*/
function promisify(nodeFunction: Function, receiver?: any): Function;
/**
* This overload has been **deprecated**. The overload will continue working for now. The recommended method for promisifying multiple methods at once is ``Promise.promisifyAll(Object target)``
*/
function promisify(target: Object): Object;
/**
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain. The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example, if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
*/
function promisifyAll(target: Object): Object;
/**
* Returns a function that can use `yield` to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
function coroutine(generatorFunction: Function): Function;
/**
* Spawn a coroutine which may yield promises to run asynchronous code synchronously. This feature requires the support of generators which are drafted in the next version of the language. Node version greater than `0.11.2` is required and needs to be executed with the `--harmony-generators` (or `--harmony`) command-line switch.
*/
function spawn(generatorFunction: Function): Promise;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the `Promise` namespace to whatever it was before this library was loaded. Returns a reference to the library namespace so you can attach it to something else.
*/
function noConflict(): Object;
/**
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
*/
function onPossiblyUnhandledRejection(handler: (reason: any) => any): void;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled. The promise's fulfillment value is an array with fulfillment values at respective positions to the original array. If any promise in the array rejects, the returned promise is rejected with the rejection reason.
*/
function all(values: any[]): Promise;
/**
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled. The promise's fulfillment value is an object with fulfillment values at respective keys to the original object. If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties. All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
*
* *The original object is not modified.*
*/
function props(object: Promise): Promise;
function props(object: Object): Promise;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are either fulfilled or rejected. The fulfillment value is an array of ``Promise.Inspection`` instances at respective positions in relation to the input array.
*
* *original:The array is not modified. The input array sparsity is retained in the resulting array.*
*/
function settle(values: any[]): Promise;
/**
* Like `Promise.some()`, with 1 as `count`. However, if the promise fulfills, the fulfillment value is not an array of 1 but the value directly.
*/
function any(values: any[]): Promise;
/**
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled or rejected as soon as a promise in the array is fulfilled or rejected with the respective rejection reason or fulfillment value.
*
* **Note** If you pass empty array or a sparse array with no values, or a promise/thenable for such, it will be forever pending.
*/
function race(values: any[]): Promise;
/**
* Initiate a competetive race between multiple promises or values (values will become immediately fulfilled promises). When `count` amount of promises have been fulfilled, the returned promise is fulfilled with an array that contains the fulfillment values of the winners in order of resolution.
*
* If too many promises are rejected so that the promise can never become fulfilled, it will be immediately rejected with an array of rejection reasons in the order they were thrown in.
*
* *The original array is not modified.*
*/
function some(values: any[], count: number): Promise;
/**
* Like `Promise.all()` but instead of having to pass an array, the array is generated from the passed variadic arguments.
*/
function join(...values: any[]): Promise;
/**
* Map an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
function map(values: any[], mapper: (item: any, index: number, arrayLength: number) => any): Promise;
/**
* Reduce an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `intialValue` is given and the array doesn't contain at least 2 items, the callback will not be called and `undefined` is returned. If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
*/
function reduce(values: any[], reducer: (total: number, current: any, index: number, arrayLength: number) => any, initialValue?: any): Promise;
/**
* Filter an array, or a promise of an array, which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)` where `item` is the resolved value of a respective promise in the input array. If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
function filter(values: any[], filterer: (item: any, index?: number, arrayLength?: number) => any): Promise;
}
declare module 'bluebird' {
export = Promise;
export = Promise;
}
+3 -3
View File
@@ -8,11 +8,11 @@
interface DatepickerOptions {
format?: string;
weekStart?: number;
startDate?: Date;
endDate?: Date;
startDate?: any;
endDate?: any;
autoclose?: boolean;
startView?: number;
todayBtn?: boolean;
todayBtn?: any;
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
+2 -1
View File
@@ -14,10 +14,11 @@ interface PaginatorOptions{
totalPages?: number;
pageUrl?: (type, page, current) => string;
shouldShowPage?: boolean;
itemText?: (type, page, current) => any;
itemTexts?: (type:string, page:number, current:number) => string;
tooltipTitles?: (type, page, current) => string;
useBootstrapTooltip?: boolean;
bootstrapTooltipOptions?: {};
bootstrapMajorVersion?: number;
onPageClicked?: (event, originalEvent, type, page) => void;
onPageChanged?: (event, originalEvent, type, page) => void;
}
+254
View File
@@ -0,0 +1,254 @@
/// <reference path="ckeditor.d.ts" />
function test_CKEDITOR() {
CKEDITOR.basePath = 'test';
CKEDITOR.replaceClass = 'rich_editor';
CKEDITOR.skinName = 'moono';
CKEDITOR.skinName = 'myskin,/customstuff/myskin/';
var editor = new CKEDITOR.editor();
if (editor.getSelection().getType() == CKEDITOR.SELECTION_ELEMENT)
if (editor.getSelection().getType() == CKEDITOR.SELECTION_NONE)
if (editor.getSelection().getType() == CKEDITOR.SELECTION_TEXT)
alert(CKEDITOR.basePath);
if (CKEDITOR.currentInstance)
alert(CKEDITOR.currentInstance.name);
alert(CKEDITOR.document.getBody().getName());
alert(CKEDITOR.instances[0].name);
CKEDITOR.loadFullCoreTimeout = 5;
alert(CKEDITOR.revision);
alert(CKEDITOR.rnd);
if (CKEDITOR.status == 'loaded') {
CKEDITOR.loadFullCore();
}
alert(CKEDITOR.timestamp);
CKEDITOR.addCss('.cke_editable h1,.cke_editable h2,.cke_editable h3 { border-bottom: 1px dotted red }');
CKEDITOR.appendTo('editorSpace');
alert(CKEDITOR.getUrl('skins/default/editor.css'));
alert(CKEDITOR.getUrl('/skins/default/editor.css'));
alert(CKEDITOR.getUrl('http://www.somesite.com/skins/default/editor.css'));
CKEDITOR.inline('content');
if (CKEDITOR.loadFullCore)
CKEDITOR.loadFullCore();
CKEDITOR.replace('myfield');
var textarea = document.createElement('textarea');
CKEDITOR.replace(textarea);
CKEDITOR.replaceAll();
CKEDITOR.replaceAll('myClassName');
CKEDITOR.replaceAll((textarea, config) => false);
}
function test_dom_comment() {
var type = CKEDITOR.NODE_COMMENT;
var nativeNode = document.createComment('Example');
var comment = new CKEDITOR.dom.comment(nativeNode);
var comment2 = new CKEDITOR.dom.comment('Example');
}
function test_dom_document() {
var document = new CKEDITOR.dom.document(window.document);
var type = CKEDITOR.NODE_DOCUMENT;
CKEDITOR.document.appendStyleSheet('/mystyles.css');
var element = CKEDITOR.document.getBody();
alert(element.getName());
var element2 = CKEDITOR.document.getById('myElement');
alert(element.getId());
var element3 = CKEDITOR.document.getHead();
alert(element.getName());
var selection = CKEDITOR.instances[0].document.getSelection();
alert(selection.getType());
document.write(
'<html>' +
'<head><title>Sample Doc</title></head>' +
'<body>Document contents created by code</body>' +
'</html>'
);
}
function test_dom_documentFragment() {
var type = CKEDITOR.NODE_DOCUMENT_FRAGMENT;
}
function test_dom_domObject() {
var element = new CKEDITOR.dom.element('span');
alert(element.$.nodeType);
var nativeElement = element.$;
var doc = new CKEDITOR.dom.document(document);
alert(doc.equals(CKEDITOR.document));
alert(doc == CKEDITOR.document);
var element2 = new CKEDITOR.dom.element('span');
alert(element.getCustomData('hasCustomData'));
alert(element.getCustomData('nonExistingKey'));
var elementA = new CKEDITOR.dom.element(nativeElement);
elementA.getPrivate().value = 1;
var elementB = new CKEDITOR.dom.element(nativeElement).getPrivate().value;
var element3 = new CKEDITOR.dom.element('span');
element.setCustomData('hasCustomData', true);
}
function test_dom_element() {
var element = new CKEDITOR.dom.element('span');
alert(element.$.nodeType);
element.addClass('classA');
element.addClass('classB');
element.addClass('classA');
var p = new CKEDITOR.dom.element('p');
var strong = new CKEDITOR.dom.element('strong');
p.append(strong);
var em = p.append('em');
var p = new CKEDITOR.dom.element('p');
p.appendText('This is');
p.appendText(' some text');
element.breakParent(strong);
element.data('extra-info', 'test');
alert(element.data('extra-info'));
element.data('extra-info', false);
var element5 = CKEDITOR.document.getById('myTextarea');
element.focus();
element.focusNext();
element.focusPrevious();
element.forEach(node=> {
console.log(node);
});
var element2 = CKEDITOR.dom.element.createFromHtml('<input type="text" />');
alert(element.getAttribute('type'));
alert(element.getComputedStyle('display'));
element.appendTo(CKEDITOR.document.getBody());
alert(element.getEditor().name);
var first = element.getFirst();
alert(element.getHtml());
alert(element.getId());
alert(element.getName());
alert('<b>' + element.getNameAtt() + '</b>');
alert(element.getOuterHtml());
alert(element.getTabIndex());
alert(element.getText());
alert(element.hasAttributes());
alert(element.hasAttributes());
element.hide();
alert(element.is('span'));
alert(element.is('p', 'span'));
alert(element.is('p'));
alert(element.is('p', 'div'));
alert(element.is({ p: 1, span: 1 }));
element.removeAttribute('class');
element.addClass('classA');
element.addClass('classB');
element.removeClass('classA');
element.removeClass('classB');
element.removeStyle('display');
element.setAttribute('class', 'myClass');
element.setAttribute('title', 'This is an example');
element.setAttributes({
'class': 'myClass',
title: 'This is an example'
});
p.setHtml('<b>Inner</b> HTML');
element.setOpacity(0.75);
element.setStyle('background-color', '#ff0000');
element.setStyle('margin-top', '10px');
element.setStyle('float', 'right');
element.setStyles({
position: 'absolute',
float: 'right'
});
element.setText('A > B & C < D');
element.show();
element.unselectable();
alert(element.getName());
alert(element == CKEDITOR.dom.element.get(element));
var htmlElement = document.getElementById('myElement');
alert(CKEDITOR.dom.element.get(htmlElement).getName());
}
function test_dom_event() {
var event = new CKEDITOR.dom.event(new Event());
alert(event.getKey());
alert(event.getKeystroke() == 65);
alert(event.getKeystroke() == CKEDITOR.CTRL + 65);
alert(event.getKeystroke() == CKEDITOR.CTRL + CKEDITOR.SHIFT + 65);
var element = new CKEDITOR.dom.element('div');
element.on('mousemouse', ev=> {
var pageOffset = ev.data.getPageOffset();
alert(pageOffset.x);
alert(pageOffset.y);
});
element.on('click', ev=> {
var domEvent = ev.data;
domEvent.getTarget().addClass('clicked');
});
element.on('click', ev=> {
var domEvent = ev.data;
domEvent.preventDefault();
});
}
function test_dom_iterator() {
var range = new CKEDITOR.dom.range(new CKEDITOR.dom.element('div'));
var iterator = range.createIterator();
iterator.getNextParagraph();
iterator.getNextParagraph();
}
function test_dom_node() {
var p = new CKEDITOR.dom.element('p');
var strong = new CKEDITOR.dom.element('strong');
strong.appendTo(p);
var node = new CKEDITOR.dom.node(new Node());
node = node.getAscendant('b');
node = node.getAscendant('b', true);
var element = CKEDITOR.document.getById('example');
alert(element.getDocument().equals(CKEDITOR.document));
element.getIndex();
element.getIndex(true);
var last = element.getFirst().getNext();
var parent = node.getParent();
alert(parent.getName());
var parents = node.getParents();
var em = new CKEDITOR.dom.element('em');
strong.insertAfter(em);
strong.insertBefore(em);
strong.insertBeforeMe(em);
element.isReadOnly();
}
function test_dom_nodeList() {
var nodeList = CKEDITOR.document.getBody().getChildren();
alert(nodeList.count());
}
function test_dom_range() {
var editor = new CKEDITOR.editor();
var range = new CKEDITOR.dom.range(editor.document);
range.selectNodeContents(editor.document.getBody());
range.deleteContents();
range.selectNodeContents(editor.document.getBody());
alert(range.collapsed);
range.collapse();
alert(range.collapsed);
range.selectNodeContents(range.document.getBody());
range.selectNodeContents(editor.document.getBody());
alert(range.endContainer.getName());
range.selectNodeContents(editor.document.getBody());
alert(range.endOffset);
range.selectNodeContents(editor.document.getBody());
alert(range.startContainer.getName());
range.selectNodeContents(editor.document.getBody());
alert(range.startOffset);
}
function test_dom_text() {
var nativeNode = document.createTextNode('Example');
var text = new CKEDITOR.dom.text(nativeNode);
var text2 = new CKEDITOR.dom.text('Example');
}
function test_dom_window() {
var document = new CKEDITOR.dom.window(window);
var win = new CKEDITOR.dom.window(window);
var pos = win.getScrollPosition();
alert(pos.x);
alert(pos.y);
var size = win.getViewPaneSize();
alert(size.width);
alert(size.height);
}
+954
View File
@@ -0,0 +1,954 @@
// Type definitions for CKEditor
// Project: http://ckeditor.com/
// Definitions by: Ondrej Sevcik <https://github.com/ondrejsevcik/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// WORK-IN-PROGRESS: Any contribution support welcomed.
// See https://github.com/borisyankov/DefinitelyTyped/issues/1827 for more informations.
declare module CKEDITOR {
// Config options
var disableAutoInline: boolean;
var replaceClass: string;
var skinName: string;
// Properties
var ALT: number;
var CTRL: number;
var DIALOG_RESIZE_BOTH: number;
var DIALOG_RESIZE_HEIGHT: number;
var DIALOG_RESIZE_NONE: number;
var DIALOG_RESIZE_WIDTH: number;
var ELEMENT_MODE_APPENDTO: number;
var ELEMENT_MODE_INLINE: number;
var ELEMENT_MODE_NONE: number;
var ELEMENT_MODE_REPLACE: number;
var END: number;
var ENTER_BR: number;
var ENTER_P: number;
var EVENT_PHASE_AT_TARGET: number;
var EVENT_PHASE_BUBBLING: number;
var EVENT_PHASE_CAPTURING: number;
var LINEUTILS_AFTER: number;
var LINEUTILS_BEFORE: number;
var LINEUTIS_INSIDE: number;
var NODE_COMMENT: number;
var NODE_DOCUMENT: number;
var NODE_DOCUMENT_FRAGMENT: number;
var NODE_ELEMENT: number;
var NODE_TEXT: number;
var SELECTION_ELEMENT: number;
var SELECTION_NONE: number;
var SELECTION_TEXT: number;
var SHIFT: number;
var SHRINK_ELEMENT: number;
var SHRINK_TEXT: number;
var START: number;
var TRISTATE_DISABLED: number;
var TRISTATE_OFF: number;
var TRISTATE_ON: number;
var UI_BUTTON: string;
var UI_MENUBUTTON: string;
var UI_PANEL: string;
var UI_PANELBUTTON: string;
var UI_RICHCOMBO: string;
var UI_SEPARATOR: string;
var basePath: string;
var currentInstance: editor;
var document: dom.document;
var instances: editor[];
var loadFullCoreTimeout: number;
var revision: string;
var rnd: number;
var status: string;
var timestamp: string;
var version: string;
// Methods
function add(editor: editor): void;
function addCss(css: string): void;
function addTemplate(name: string, source: string): template;
function appendTo(element: string, config?: config, data?: string): editor;
function appendTo(element: HTMLTextAreaElement, config?: config, data?: string): editor;
function domReady(): void;
function editorConfig(config: config): void;
function getCss(): string;
function getTemplate(name: string): template;
function getUrl(resource: string): string;
function inline(element: string, instanceConfig?: config): editor;
function inline(element: HTMLTextAreaElement, instanceConfig?: config): editor;
function inlineAll(): void;
function loadFullCore(): void;
function replace(element: string, config?: config): editor;
function replace(element: HTMLTextAreaElement, config?: config): editor;
function replaceAll(className?: string): void;
function replaceAll(assertionFunction: (textarea: HTMLTextAreaElement, config: config) => boolean): void;
module dom {
class comment {
// Properties
type: number;
// Methods
constructor(comment: string, ownerDocument?: document);
constructor(comment: Object, ownerDocument?: document);
getOuterHtml(): string;
}
class document extends domObject {
// Properties
type: number;
// Methods
constructor(domDocument: Object);
appendStyleSheet(cssFileUrl: string): void;
appendStyleText(cssStyleText: string): Object;
createElement(name: string, attribsAndStyles?: { attributes: Object; styles: Object; }): element;
createText(text: string): element;
find(selector: string): nodeList;
findOne(selector: string): element;
focus(): void;
getActive(): element;
getBody(): element;
getByAddress(address: any[], normalized?: boolean): node;
getById(elementId: string): element;
getDocumentElement(): element;
getElementsByTag(tagName: string): nodeList;
getHead(): element;
getSelection(): selection;
getWindow(): window;
write(html: string): void;
}
class documentFragment {
// Properties
type: number;
// Methods
constructor(nodeOrDoc: Object);
insertAfterNode(node: node): void;
}
class domObject extends event {
// Properties
$: HTMLElement;
// Methods
constructor(nativeDomObject: Object);
clearCustomData(): void;
equals(object: any): boolean;
getCustomData(key: string): any;
getPrivate(): any;
getUniqueId(): number;
removeAllListeners(): void;
removeCustomData(key: string): Object;
setCustomData(key: string, value: Object): domObject;
}
class element extends node {
// Properties
type: number;
// Methods
constructor(element: string, ownerDocument?: document);
constructor(element: HTMLElement, ownerDocument?: document);
addClass(className: string): void;
append(node: node, toStart?: boolean): node;
append(node: string, toStart?: boolean): node;
appendBogus(force: boolean): void;
appendHtml(html: string): void;
appendText(text: string): node;
breakParent(parent: element): void;
contains(node: node): boolean;
copyAttributes(dest: element, skipAttributes: Object): void;
data(name: string): string;
data(name: string, value: string): void;
data(name: string, value: boolean): void;
disableContextMenu(): void;
find(selector: string): nodeList;
findOne(selector: string): element;
focus(defer?: boolean): void;
focusNext(ignoreChildren?: boolean, indexToUse?: number): void;
focusPrevious(ignoreChildren?: boolean, indexToUse?: number): void;
forEach(callback: (node: node) => void, type?: number, skipRoot?: boolean): void;
getAttribute(name: string): string;
getBogus(): Object;
getChild(indices: number): node;
getChild(indices: number[]): node;
getChildCount(): number;
getChildren(): nodeList;
getClientRect(): any;
getComputedStyle(propertyName: string): string;
getDirection(useComputed: boolean): string;
getDocumentPosition(refDocument: document): position;
getDtd(): any;
getEditor(): editor;
getElementsByTag(tagName: string): nodeList;
getFirst(evaluator?: Function): node;
getFrameDocument(): document;
getHtml(): string;
getId(): string;
getLast(evaluator?: Function): node;
getName(): string;
getNameAtt(): string;
getOuterHtml(): string;
getPositionedAncestor(): element;
getSize(type: string, isBorderBox: boolean): void;
getStyle(name: string): string;
getTabIndex(): number;
getText(): string;
getValue(): string;
getWindow(): window;
hasAttributes(): boolean;
hasAttribute(name: string): boolean;
hasClass(className: string): boolean;
hide(): void;
is(...name: string[]): boolean;
is(name: any): boolean;
isBlockBoundary(customNodeNames: Object): boolean;
isEditable(textCursor?: boolean): boolean;
isEmptyInlineRemoveable(): boolean;
isIdentical(otherElement: element): boolean;
isVisible(): boolean;
mergeSiblings(inlineOnly?: boolean): void;
moveChildren(target: element, toStart?: boolean): void;
removeAttribute(name: string): void;
removeAttributes(attributes?: string[]): void;
removeClass(className: string): void;
removeStyle(name: string): void;
renameNode(newTag: string): void;
scrollIntoParent(parent: element, alignToTop: boolean, hscroll: boolean): void;
scrollIntoParent(parent: window, alignToTop: boolean, hscroll: boolean): void;
scrollIntoView(alignToTop?: boolean): void;
setAttribute(name: string, value: string): element;
setAttributes(attributesPairs: Object): element;
setHtml(html: string): string;
setOpacity(opacity: number): void;
setSize(type: string, size: number, isBorderBox: boolean): void;
setState(state: number, base?: Object, useAria?: Object): void;
setStyle(name: string, value: string): element;
setStyles(stylesPair: Object): element;
setText(text: string): string;
setValue(value: string): element;
show(): void;
unselectable(): void;
//static method
static clearAllMarkers(database: Object): Object;
static clearMarkers(database: Object, element: Object, removeFromDatabase: Object): void;
static createFromHtml(html: string): element;
static get(element: string): element;
static get(element: any): element;
static setMarker(database: Object, element: Object, name: Object, value: Object): domObject;
}
class elementPath {
constructor(startNode: element, root: element);
block: element;
blockLimit: element;
root: element;
elements: element[];
compare(otherPath: elementPath): boolean;
contains(query: string, excludeRoot: boolean, fromTop: boolean): element;
contains(query: string[], excludeRoot: boolean, fromTop: boolean): element;
contains(query: (element: element) => boolean, excludeRoot: boolean, fromTop: boolean): element;
contains(query: Object, excludeRoot: boolean, fromTop: boolean): element;
contains(query: element, excludeRoot: boolean, fromTop: boolean): element;
isContextFor(tag: string): boolean;
direction(): string;
}
class range {
constructor(root: element);
constructor(root: document);
startContainer: any;
startOffset: number;
endContainer: any;
endOffset: number;
collapsed: boolean;
isDocRoot: boolean;
document: document;
root: element;
clone(): range;
collapse(toStart?: boolean): Boolean;
cloneContents(): documentFragment;
deleteContents(mergeThen?: boolean): void;
extractContents(mergeThen?: boolean): documentFragment;
createBookmark(serializable: boolean): Object;
createBookmark2(normalized: boolean): Object;
createIterator(): iterator;
moveToBookmark(bookmark: Object): void;
getBoundaryNodes(): { startNode: node; endNode: node; };
getCommonAncestor(includeSelf: boolean, ignoreTextNode: boolean): element;
optimize(): void;
optimizeBookmark(): void;
trim(ignoreStart?: boolean, ignoreEnd?: boolean): void;
enlarge(unit: number, excludeBrs?: boolean): void;
shrink(mode: number, selectContents: boolean): void;
insertNode(node: node): void;
moveToPosition(node: node, position: Object): void;
moveToRange(range: range): void;
selectNodeContents(node: node): void;
setStart(startNode: node, startOffset: number): void;
setEnd(endNode: node, endOffset: number): void;
setStartAfter(node: node): void;
setStartBefore(node: node): void;
setStartAt(node: node, position: number): void;
setEndAt(node: node, position: number): void;
fixBlock(isStart: boolean, blockTag: Object): Object;
splitBlock(blockTag: Object): Object;
splitElement(toSplit: element): element;
removeEmptyBlocksAtEnd(atEnd: boolean): void;
startPath(): elementPath;
endPath(): elementPath;
checkBoundaryOfElement(element: element, checkType: number): boolean;
checkStartOfBlock(): boolean;
checkEndOfBlock(): boolean;
getPreviousNode(evaluator: Function, guard: Function, boundary: element): element;
getNextNode(evaluator: Function, guard: Function, boundary: element): element;
checkReadOnly(): boolean;
moveToElementEditablePosition(element: element, isMoveToEnd: boolean): boolean;
movetoClosestEditablePosition(element: element, isMoveToEnd: boolean): boolean;
moveToElementEditStart(target: Object): boolean;
moveToElementEditEnd(target: Object): boolean;
getEnclosedNode(): node;
getTouchedStartNode(): node;
getTouchedEndNode(): node;
getNextEditableNode(): Object;
getPreviousEditableNode(): Object;
scrollIntoView(): void;
}
interface rangeListIterator {
}
class selection {
document: document;
isFake: boolean;
isLocked: boolean;
rev: number;
root: element;
constructor(target: document);
constructor(target: element);
constructor(target: selection);
createBookmarks(serializable: Object): any[];
createBookmarks2(normalized?: Object): any[];
fake(element: element): void;
getCommonAncestor(): element;
getNative(): Object;
getRanges(onlyEditables?: boolean): any[];
getSelectedElement(): element;
getSelectedText(): string;
getStartElement(): element;
getType(): number;
isHidden(): boolean;
lock(): void;
removeAllRanges(): void;
reset(): void;
scrollIntoView(): void;
selectBookmarks(bookmarks: any[]): selection;
selectElement(element: element): void;
selectRanges(ranges: any[]): void;
unlock(restore: Object): void;
}
class rangeList {
constructor(ranges: range[]);
constructor(range: range);
createIterator(): rangeListIterator;
createBokmark(serializable: boolean): Object[];
createBookmark2(normalized: boolean): Object[];
moveToBookmark(bookmarks: Object[]): void;
}
class iterator {
constructor(range: range);
getNextParagraph(blockTag?: string): element;
activeFilter: filter;
enforceRealBlocks: Boolean;
enlargeBr: Boolean;
filter: filter;
}
class node extends domObject {
constructor(domNode: Node);
appendTo(element: element): element;
clone(includeChildren: boolean, cloneId: boolean): node;
hasPrevious(): boolean;
hasNext(): boolean;
insertAfter(node: node): node;
insertBefore(node: node): node;
insertBeforeMe(node: node): node;
getAddress(normalized: boolean): Object[];
getDocument(): document;
getIndex(normalized?: boolean): number;
getNextSourceNode(startFromSibling: Object, nodeType: Object, guard: Object): void;
getPreviousSourceNode(startFromSibling: Object, nodeType: Object, guard: Object): void;
getPrevious(evaluator?: Function): node;
getNext(evaluator?: Function): node;
getParent(allowFragmentParent?: boolean): element;
getParents(closerFirst?: boolean): node[];
getCommonAncestor(node: Object): void;
getPosition(otherNode: Object): void;
getAscendant(reference: string, includeSelf?: boolean): node;
hasAscendant(name: Object, includeSelf: any): boolean;
move(preserveChildren?: boolean): node;
replace(nodeToReplace: node): void;
trim(): void;
ltrim(): void;
rtrim(): void;
isReadOnly(): boolean;
}
class nodeList {
constructor(nativeList: Object);
count(): number;
getItem(index: number): node;
}
class event {
constructor(domEvent: Event);
getKey(): number;
getKeystroke(): number;
preventDefault(stopPropagation: boolean): void;
stopPropagation(): void;
getTarget(): node;
getPhase(): number;
getPhaseOffset(): position;
on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): Object;
}
interface position {
x: number;
y: number;
}
interface widthAndHeight {
width: number;
height: number;
}
class text extends node {
constructor(text: Text, ownerDocument?: document);
constructor(text: string, ownerDocument?: document);
type: number;
getLength(): number;
getText(): string;
setText(text: string): void;
split(offset: number): text;
substring(indexA: number, indexB: number): void;
}
class window extends domObject {
constructor(domWindow: Object);
focus(): void;
getViewPaneSize(): widthAndHeight;
getScrollPosition(): position;
getFrame(): element;
}
class walker {
constructor(range: range);
end(): void;
next(): node;
previous(): node;
checkForward(): boolean;
checkBackward(): boolean;
lastForward(): node;
lastBackward(): node;
reset(): void;
//static methods till the end
blockBoundary(customNodeNames: Object): Function;
listItemBoundary(): Function;
bookmark(contentOnly?: boolean, isReject?: boolean): Function;
whitespaces(isReject?: boolean): Function;
invisible(isReject?: boolean): Function;
nodeType(type: number, isReject?: boolean): Function;
bogus(isReject?: boolean): Function;
temp(isReject?: boolean): Function;
ignored(isReject?: boolean): Function;
editable(isReject?: boolean): Function;
}
}
module ajax {
// Methods
function load(url: string, callback?: Function): string;
function loadXml(url: string, callback?: Function): xml;
}
interface xml {
}
class command extends event {
// Properties
contextSensitive: boolean;
editorFocus: boolean;
modes: any;
previousState: number;
state: number;
uiItems: any[];
// Methods
constructor(editor: editor, commandDefinition: commandDefinition);
checkAllowed(noCache: boolean): boolean;
disable(): void;
enable(): void;
exec(data?: Object): boolean;
refresh(editor: editor, path: dom.elementPath): void;
setState(newState: number): boolean;
toggleState(): void;
}
interface focusManager {
}
interface keystrokeHandler {
}
interface config {
startupMode: string;
removeButtons: string;
toolbar?: any;
}
interface feature {
}
interface style {
}
interface editable {
}
class menu {
constructor();
add(item: any): void;
addListener(listenerFn: (startElement: dom.element, selection: dom.selection, path: dom.elementPath) => any): void;
hide(returnFocus?: boolean): void;
removeAll(): void;
show(offsetParent: dom.element, corner?: number, offsetX?: number, offsetY?: number): void;
}
module plugins {
class contextMenu extends menu {
constructor(editor: editor);
addTarget(element: dom.element, nativeContextMenuOnCtrl?: boolean): void;
open(offsetParent: dom.element, corner?: number, offsetX?: number, offsetY?: number): void;
}
module link {
var emptyAnchorFix: boolean;
var fakeAnchor: boolean;
var synAnchorSelector: boolean;
function getEditorAnchors(editor: editor): dom.element[];
function getSelectedLink(editor: editor): dom.elementPath;
function tryRestoreFakeAnchor(editor: editor, element: dom.element): dom.element;
}
module widget {
class repository {
}
}
}
class editor extends event {
activeEnterMode: number;
activeFilter: filter;
activeShiftEnterMode: number;
blockless: boolean;
config: config;
container: dom.element;
contextMenu: plugins.contextMenu;
dataProcessor: dataProcessor;
document: dom.document;
element: dom.element;
elementMode: number;
enterMode: number;
filter: filter;
focusManager: focusManager;
id: string;
keystrokeHandler: keystrokeHandler;
lang: any;
langCode: string;
mode: string;
name: string;
plugins: Object;
readOnly: boolean;
shiftEnterMode: number;
status: string;
tabIndex: number;
templates: Object;
title: any;
toolbar: Object;
ui: ui;
widgets: plugins.widget.repository;
window: dom.window;
constructor(instanceConfig?: Object, element?: dom.element, mode?: number);
addCommand(commandName: string, commandDefinition: commandDefinition): void;
addFeature(feature: feature): boolean;
addMenuGroup(name: string, order?: number): void;
addMenuItem(name: string, definition?: any): void;
addMenuItems(definitions: any[]): void;
addMode(mode: string, exec: () => void): void;
addRemoveFormatFilter(func: Function): void;
applyStyle(style: style): void;
attachStyleStateChange(style: style, callback: Function): void;
checkDirty(): boolean;
createFakeElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void;
createFakeParserElement(realElement: Object, className: Object, realElementType: Object, isResizable: Object): void;
createRange(): dom.range;
destroy(noUpdate?: boolean): void;
editable(elementOrEditable: dom.element): void;
editable(elementOrEditable: editable): void;
elementPath(startNode?: dom.node): dom.elementPath;
execCommand(commandName: string, data?: Object): boolean;
focus(): void;
forceNextSelectionCheck(): void;
getClipboardData(options: Object, callback: Function): void;
getColorFromDialog(callback: Function, scope?: Object): void;
getCommand(commandName: string): command;
getData(noEvents: Object): string;
getMenuItem(name: string): Object;
getResizable(forContents: boolean): dom.element;
getSelection(forceRealSelection?: boolean): dom.selection;
getSnapshot(): string;
getStylesSet(callback: Function): void;
getUiColor(): string;
insertElement(element: dom.element): void;
insertHtml(html: string, mode?: string): void;
insertText(text: string): void;
loadSnapshot(snapshot: Object): void;
lockSelection(sel?: dom.selection): boolean;
openDialog(dialogName: string, callback: Function): dialog;
popup(url: string, width?: number, height?: number, options?: string): void;
popup(url: string, width?: string, height?: number, options?: string): void;
popup(url: string, width?: number, height?: string, options?: string): void;
popup(url: string, width?: string, height?: string, options?: string): void;
removeMenuItem(name: string): void;
removeStyle(style: style): void;
resetDirty(): void;
resetUndo(): void;
resize(width: number, height: number, isContentHeight?: boolean, resizeInner?: boolean): void;
resize(width: string, height: number, isContentHeight?: boolean, resizeInner?: boolean): void;
resize(width: number, height: string, isContentHeight?: boolean, resizeInner?: boolean): void;
resize(width: string, height: string, isContentHeight?: boolean, resizeInner?: boolean): void;
restoreRealElement(fakeElement: Object): dom.element;
selectionChange(checkNow?: boolean): void;
setActiveEnterMode(enterMode: number, shiftEnterMode: number): void;
setActiveFilter(filter: filter): void;
setData(data: string, callback: Function, internal: boolean): void;
setKeystroke(keystroke: number, behavior?: string): void;
setKeystroke(keystroke: any[], behavior?: string): void;
setKeystroke(keystroke: number, behavior?: boolean): void;
setKeystroke(keystroke: any[], behavior?: boolean): void;
setMode(newMode: string, callback: Function): void;
setReadOnly(isReadOnly?: boolean): void;
setUiColor(color: string): void;
unlockSelection(restore?: boolean): void;
updateElement(): void;
}
interface eventInfo {
data: any;
editor: editor;
listenerData: any;
name: string;
sender: any;
cancel(): void;
removeListener(): void;
stop(): void;
}
class filter {
}
interface template {
}
interface dataProcessor {
toDataFormat(html: string, fixForBody: string): void;
toHtml(data: string, fixForBody?: string): void;
}
class event {
constructor();
useCapture: boolean;
capture(): void;
define(name: string, meta: Object): void;
fire(eventName: string, data?: Object, editor?: editor): any;
fireOnce(eventName: string, data?: Object, editor?: editor): any;
hasListeners(eventName: string): boolean;
on(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void;
once(eventName: string, listenerFunction: (eventInfo: eventInfo) => void, scopeObj?: Object, listenerData?: Object, priority?: number): void;
removeAllListeners(): void;
removeListener(eventName: string, listenerFunction: (eventInfo: eventInfo) => void): void;
static implementOn(targetObject: Object): void;
}
interface commandDefinition {
async?: boolean;
canUndo?: boolean;
context?: boolean;
contextSensitive?: boolean;
editorFocus?: boolean;
modes?: Object;
startDisabled?: boolean;
exec(editor: editor, data?: Object): boolean;
refresh? (editor: editor, path: dom.elementPath): void;
}
class dtd {
}
class ui extends event {
constructor(editor: editor);
add(name: string, type: Object, definition: Object): void;
addButton(name: string, definition: dialog.definition.button): void;
addHandler(type: Object, handler: Object): void;
}
module dialog {
module definition {
interface button extends uiElement {
disabled?: boolean;
label?: string;
}
interface uiElement {
align?: string;
className?: string;
commit?: Function;
id?: string;
onHide?: Function;
onLoad?: Function;
requiredcontent?: any;
setup?: Function;
style?: string;
title?: string;
type?: string;
}
}
}
module htmlParser {
class basicWriter {
constructor();
openTag(tagName: string, attributes: Object): void;
openTagClose(tagName: string, isSelfClose: boolean): void;
attribute(attName: string, attValue: string): void;
closeTag(tagName: string): void;
text(text: string): void;
comment(comment: string): void;
write(data: string): void;
reset(): void;
getHtml(reset: boolean): string;
}
class node {
constructor();
remove(preserveChildren?: boolean): node;
replaceWith(node: node): void;
insertAfter(node: node): void;
insertBefore(node: node): void;
getAscendant(condition: string): element;
getAscendant(condition: Object): element;
getAscendant(condition: Function): element;
wrapWith(wrapper: element): element;
getIndex(): number;
}
class filter {
constructor(rules?: filterRulesDefinition);
id: number;
elementNameRules: filterRulesGroup;
attributeNameRules: filterRulesGroup;
elementsRules: Object;
attributesRules: Object;
textRules: filterRulesGroup;
commentRules: filterRulesGroup;
rootRules: filterRulesGroup;
addRules(rules: filterRulesDefinition, options?: number): void;
addRules(rules: filterRulesDefinition, options?: { priority?: number; applyToAll?: boolean; }): void;
applyTo(node: node): void;
}
interface filterRulesDefinition {
}
class filterRulesGroup {
rules: Object[];
add(rule: Function, priority: number, options: Object): void;
add(rule: Object[], priority: number, options: Object): void;
addMany(rules: Object[], priority: number, options: Object): void;
findIndex(priority: number): number;
exec(currentValue: Object): Object;
execOnName(currentName: string): string;
}
class cdata extends node {
constructor(value: string);
type: number;
writeHtml(writer: basicWriter): void;
}
class comment extends node {
constructor(value: string);
type: number;
filter(filter: filter): boolean;
writeHtml(writer: basicWriter, filter: filter): void;
}
class element extends node {
constructor(name: string, attributes: Object);
name: string;
attributes: Object;
children: Object[];
type: number;
add(node: node): number;
clone(): element;
filter(filter: filter): boolean;
filterChildren(filter: filter): void;
writeHtml(writer: basicWriter, filter: filter): void;
writeChildrenHtml(writer: basicWriter, filter: filter): void;
replaceWithChildren(): void;
forEach(callback: (node: node, type?: number) => boolean): void;
getFirst(condition: string): node;
getFirst(condition: Object): node;
getFirst(condition: Function): node;
getHtml(): string;
setHtml(html: string): void;
getOuterHtml(): string;
split(index: number): element;
removeClass(className: string): void;
hasClass(className: string): boolean;
}
class fragment {
constructor();
children: Object[];
parent: Object;
type: number;
fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: string): void;
fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: string): void;
fromHtml(fragmentHtml: string, parent?: element, fixingBlock?: boolean): void;
fromHtml(fragmentHtml: string, parent?: string, fixingBlock?: boolean): void;
add(node: node, index?: number): void;
filter(filter: filter): void;
filterChildren(filter: filter, filterRoot?: boolean): void;
writeHtml(writer: basicWriter, filter?: filter): void;
writeChildrenHtml(writer: basicWriter, filter?: filter, filterRoot?: boolean): void;
forEach(callback: (node: node, type?: number) => boolean, type?: number, skipRoot?: boolean): void;
}
class cssStyle {
constructor(element: element);
constructor(styleText: string);
populate(obj: element): void;
populate(obj: dom.element): void;
populate(obj: Object): void;
}
class text extends node {
constructor(value: string);
type: number;
filter(filter: filter): boolean;
writeHtml(writer: basicWriter, filter?: filter): void;
}
}
interface dialog {
addFocusable(element: CKEDITOR.dom.element, index: number): void;
}
}
+121 -2
View File
@@ -1160,7 +1160,7 @@ function azimuthalEquidistant() {
}
//Example from http://bl.ocks.org/mbostock/4060366
function voroniTesselation() {
function voronoiTesselation() {
var width = 960,
height = 500;
@@ -1168,6 +1168,9 @@ function voroniTesselation() {
return [Math.random() * width, Math.random() * height];
} );
var voronoi = d3.geom.voronoi()
.clipExtent([[0, 0], [width, height]]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
@@ -1185,13 +1188,129 @@ function voroniTesselation() {
redraw();
function redraw() {
path = path.data(d3.geom.voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String);
path = path.data(voronoi(vertices).map(function (d) { return "M" + d.join("L") + "Z"; } ), String);
path.exit().remove();
path.enter().append("path").attr("class", function (d, i) { return "q" + (i % 9) + "-9"; } ).attr("d", String);
path.order();
}
}
// Example from https://gist.github.com/christophermanning/1734663
function forceDirectedVoronoi() {
var w = window.innerWidth > 960 ? 960 : (window.innerWidth || 960),
h = window.innerHeight > 500 ? 500 : (window.innerHeight || 500),
radius = 5.25,
links = [],
simulate = true,
zoomToAdd = true,
color = d3.scale.quantize().domain([10000, 7250]).range(["#dadaeb","#bcbddc","#9e9ac8","#807dba","#6a51a3","#54278f","#3f007d"])
var numVertices = (w*h) / 3000;
var vertices = d3.range(numVertices).map(function(i) {
var angle = radius * (i+10);
return <D3.Layout.GraphNode>{x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)};
});
var d3_geom_voronoi = d3.geom.voronoi<D3.Layout.GraphNode>()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
var prevEventScale = 1;
var zoom = d3.behavior.zoom().on("zoom", function(d,i) {
if (zoomToAdd){
if (d3.event.scale > prevEventScale) {
var angle = radius * vertices.length;
vertices.push(<D3.Layout.GraphNode>{x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)})
} else if (vertices.length > 2 && d3.event.scale != prevEventScale) {
vertices.pop();
}
force.nodes(vertices).start()
} else {
if (d3.event.scale > prevEventScale) {
radius+= .01
} else {
radius -= .01
}
vertices.forEach(function(d, i) {
var angle = radius * (i+10);
vertices[i] = <D3.Layout.GraphNode>{x: angle*Math.cos(angle)+(w/2), y: angle*Math.sin(angle)+(h/2)};
});
force.nodes(vertices).start()
}
prevEventScale = d3.event.scale;
});
d3.select(window)
.on("keydown", function() {
// shift
if(d3.event.keyCode == 16) {
zoomToAdd = false
}
// s
if(d3.event.keyCode == 83) {
simulate = !simulate
if(simulate) {
force.start()
} else {
force.stop()
}
}
})
.on("keyup", function() {
zoomToAdd = true
})
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h)
.call(zoom)
var force = d3.layout.force()
.charge(-300)
.size([w, h])
.on("tick", update);
force.nodes(vertices).start();
var circle = <D3.UpdateSelection>svg.selectAll("circle");
var path = <D3.UpdateSelection>svg.selectAll("path");
var link = <D3.UpdateSelection>svg.selectAll("line");
function update() {
path = path.data(d3_geom_voronoi(vertices));
path.enter().append("path")
// drag node by dragging cell
.call(d3.behavior.drag()
.on("drag", function(d, i) {
vertices[i] = <D3.Layout.GraphNode>{x: vertices[i].x + d3.event.dx, y: vertices[i].y + d3.event.dy}
})
)
.style("fill", function(d, i) { return color(0) })
path.attr("d", function(d) { return "M" + d.join("L") + "Z"; })
.transition().duration(150).style("fill", function(d, i) { return color(d3.geom.polygon(d).area()) })
path.exit().remove();
circle = circle.data(vertices)
circle.enter().append("circle")
.attr("r", 0)
.transition().duration(1000).attr("r", 5);
circle.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
circle.exit().transition().attr("r", 0).remove();
link = link.data(d3_geom_voronoi.links(vertices))
link.enter().append("line")
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; })
link.exit().remove()
if(!simulate) force.stop()
}
}
//Example from http://bl.ocks.org/mbostock/4341156
function delaunayTesselation() {
var width = 960,
Vendored
+85 -15
View File
@@ -812,6 +812,8 @@ declare module D3 {
select: (selector: string) => Selection;
empty: () => boolean;
node: () => Element;
call: (callback: (selection: EnterSelection) => void) => EnterSelection;
size: () => number;
}
export interface UpdateSelection extends Selection {
@@ -1148,17 +1150,17 @@ declare module D3 {
};
startAngle: {
(): number;
(angle: number): D3.Svg.Arc;
(angle: () => number): D3.Svg.Arc;
(angle: (d : any) => number): D3.Svg.Arc;
(angle: (d : any, i: number) => number): D3.Svg.Arc;
(angle: number): PieLayout;
(angle: () => number): PieLayout;
(angle: (d : any) => number): PieLayout;
(angle: (d : any, i: number) => number): PieLayout;
};
endAngle: {
(): number;
(angle: number): D3.Svg.Arc;
(angle: () => number): D3.Svg.Arc;
(angle: (d : any) => number): D3.Svg.Arc;
(angle: (d : any, i: number) => number): D3.Svg.Arc;
(angle: number): PieLayout;
(angle: () => number): PieLayout;
(angle: (d : any) => number): PieLayout
(angle: (d : any, i: number) => number): PieLayout;
};
}
@@ -3211,10 +3213,11 @@ declare module D3 {
// Geometry
export module Geom {
export interface Geom {
voronoi<T>(): Voronoi<T>;
/**
* compute the Voronoi diagram for the specified points.
*/
voronoi: Voronoi
voronoi(vertices: Array<Vertice>): Array<Polygon>;
/**
* compute the Delaunay triangulation for the specified points.
*/
@@ -3295,15 +3298,82 @@ declare module D3 {
y: number;
}
export interface Voronoi {
(vertices?: Array<Vertice>): Array<Polygon>;
export interface Voronoi<T> {
/**
* Compute the Voronoi diagram for the specified data.
*/
(data: Array<T>): Array<Polygon>;
/**
* Compute the graph links for the Voronoi diagram for the specified data.
*/
links(data: Array<T>): Array<Layout.GraphLink>;
/**
* Compute the triangles for the Voronoi diagram for the specified data.
*/
triangles(data: Array<T>): Array<Array<number>>;
x: {
(): (d: any) => any;
(accesor: (d: any) => any): any;
/**
* Get the x-coordinate accessor.
*/
(): (data: T, index ?: number) => number;
/**
* Set the x-coordinate accessor.
*
* @param accessor The new accessor function
*/
(accessor: (data: T, index: number) => number): Voronoi<T>;
/**
* Set the x-coordinate to a constant.
*
* @param constant The new constant value.
*/
(constant: number): Voronoi<T>;
}
y: {
(): (d: any) => any;
(accesor: (d: any) => any): any;
/**
* Get the y-coordinate accessor.
*/
(): (data: T, index ?: number) => number;
/**
* Set the y-coordinate accessor.
*
* @param accessor The new accessor function
*/
(accessor: (data: T, index: number) => number): Voronoi<T>;
/**
* Set the y-coordinate to a constant.
*
* @param constant The new constant value.
*/
(constant: number): Voronoi<T>;
}
clipExtent: {
/**
* Get the clip extent.
*/
(): Array<Array<number>>;
/**
* Set the clip extent.
*
* @param extent The new clip extent.
*/
(extent: Array<Array<number>>): Voronoi<T>;
}
size: {
/**
* Get the size.
*/
(): Array<number>;
/**
* Set the size, equivalent to a clip extent starting from (0,0).
*
* @param size The new size.
*/
(size: Array<number>): Voronoi<T>;
}
}
+242
View File
@@ -0,0 +1,242 @@
///<reference path="../d3/d3.d.ts" />
///<reference path="../crossfilter/crossfilter.d.ts" />
///<reference path="dc.d.ts" />
interface IYelpData {
city: string;
review_count: number;
name: string;
neighborhoods: string[];
type: string;
business_id: string;
full_address: string;
state: string;
longitude: number;
stars: number;
latitude: number;
open: boolean;
categories: string[]
}
interface IYelpDataExtended {
count: number;
review_sum: number;
star_sum: number;
review_avg: number;
star_avg: number;
}
/********************************************************
* *
* dj.js example using Yelp Kaggle Test Dataset *
* Eamonn O'Loughlin 9th May 2013 *
* *
********************************************************/
/********************************************************
* *
* Step0: Load data from json file *
* *
********************************************************/
d3.json("data/yelp_test_set_business.json", function (yelp_data:IYelpData[]) {
/********************************************************
* *
* Step1: Create the dc.js chart objects & ling to div *
* *
********************************************************/
var bubbleChart = dc.bubbleChart("#dc-bubble-graph");
var pieChart = dc.pieChart("#dc-pie-graph");
var volumeChart = dc.barChart("#dc-volume-chart");
var lineChart = dc.lineChart("#dc-line-chart");
var dataTable = dc.dataTable("#dc-table-graph");
var rowChart = dc.rowChart("#dc-row-graph");
/********************************************************
* *
* Step2: Run data through crossfilter *
* *
********************************************************/
var ndx = crossfilter(yelp_data);
/********************************************************
* *
* Step3: Create Dimension that we'll need *
* *
********************************************************/
// for volumechart
var cityDimension = ndx.dimension(function (d) { return d.city; });
var cityGroup = cityDimension.group();
var cityDimensionGroup = cityDimension.group().reduce(
//add
function(p: IYelpDataExtended,v:IYelpData){
++p.count;
p.review_sum += v.review_count;
p.star_sum += v.stars;
p.review_avg = p.review_sum / p.count;
p.star_avg = p.star_sum / p.count;
return p;
},
//remove
function(p: IYelpDataExtended,v:IYelpData){
--p.count;
p.review_sum -= v.review_count;
p.star_sum -= v.stars;
p.review_avg = p.review_sum / p.count;
p.star_avg = p.star_sum / p.count;
return p;
},
//init
function(){
return {count:0, review_sum: 0, star_sum: 0, review_avg: 0, star_avg: 0};
}
);
// for pieChart
var startValue = ndx.dimension(function (d) {
return d.stars*1.0;
});
var startValueGroup = startValue.group();
// For datatable
var businessDimension = ndx.dimension(function (d) { return d.business_id; });
/********************************************************
* *
* Step4: Create the Visualisations *
* *
********************************************************/
bubbleChart.width(650)
.height(300)
.dimension(cityDimension)
.group(cityDimensionGroup)
.transitionDuration(1500)
.colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"])
.colorDomain([-12000, 12000])
.x(d3.scale.linear().domain([0, 5.5]))
.y(d3.scale.linear().domain([0, 5.5]))
.r(d3.scale.linear().domain([0, 2500]))
.keyAccessor(function (p) {
return p.value.star_avg;
})
.valueAccessor(function (p) {
return p.value.review_avg;
})
.radiusValueAccessor(function (p) {
return p.value.count;
})
.transitionDuration(1500)
.elasticY(true)
.yAxisPadding(1)
.xAxisPadding(1)
.label(function (p) {
return p.key;
})
.renderLabel(true)
.renderlet(function (chart) {
rowChart.filter(chart.filter());
})
.on("postRedraw", function (chart) {
dc.events.trigger(function () {
rowChart.filter(chart.filter());
});
});
;
pieChart.width(200)
.height(200)
.transitionDuration(1500)
.dimension(startValue)
.group(startValueGroup)
.radius(90)
.minAngleForLabel(0)
.label(function(d) { return d.data.key; })
.on("filtered", function (chart) {
dc.events.trigger(function () {
if(chart.filter()) {
console.log(chart.filter());
volumeChart.filter([chart.filter()-.25,chart.filter()-(-0.25)]);
}
else volumeChart.filterAll();
});
});
volumeChart.width(230)
.height(200)
.dimension(startValue)
.group(startValueGroup)
.transitionDuration(1500)
.centerBar(true)
.gap(17)
.x(d3.scale.linear().domain([0.5, 5.5]))
.elasticY(true)
.on("filtered", function (chart) {
dc.events.trigger(function () {
if(chart.filter()) {
console.log(chart.filter());
lineChart.filter(chart.filter());
}
else
{lineChart.filterAll()}
});
})
.xAxis().tickFormat(function(v) {return v;});
console.log(startValueGroup.top(1)[0].value);
lineChart.width(230)
.height(200)
.dimension(startValue)
.group(startValueGroup)
.x(d3.scale.linear().domain([0.5, 5.5]))
.valueAccessor(function(d) {
return d.value;
})
.renderHorizontalGridLines(true)
.elasticY(true)
.xAxis().tickFormat(function(v) {return v;}); ;
rowChart.width(340)
.height(850)
.dimension(cityDimension)
.group(cityGroup)
.renderLabel(true)
.colors(["#a60000","#ff0000", "#ff4040","#ff7373","#67e667","#39e639","#00cc00"])
.colorDomain([0, 0])
.renderlet(function (chart) {
bubbleChart.filter(chart.filter());
})
.on("filtered", function (chart) {
dc.events.trigger(function () {
bubbleChart.filter(chart.filter());
});
});
dataTable.width(800).height(800)
.dimension(businessDimension)
.group(function(d:Object) { return "List of all Selected Businesses"
})
.size(100)
.columns([
function(d) { return d.name; },
function(d) { return d.city; },
function(d) { return d.stars; },
function(d) { return d.review_count; },
function(d) { return '<a href=\"http://maps.google.com/maps?z=12&t=m&q=loc:' + d.latitude + '+' + d.longitude +"\" target=\"_blank\">Map</a>"}
])
.sortBy(function(d){ return d.stars; })
// (optional) sort order, :default ascending
.order(d3.ascending);
/********************************************************
* *
* Step6: Render the Charts *
* *
********************************************************/
dc.renderAll();
});
+198
View File
@@ -0,0 +1,198 @@
// Type definitions for DCJS
// Project: https://github.com/dc-js
// Definitions by: hans windhoff
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// this makes only sense together with d3 and crossfilter so you need the d3.d.ts and crossfilter.d.ts files
///<reference path="../d3/d3.d.ts" />
///<reference path="../crossfilter/crossfilter.d.ts" />
declare module dc {
// helper for get/set situation
interface IGetSet<T, V> {
(): T;
(t:T): V;
}
export interface ILegendwidget {
x: IGetSet<number, number>;
y: IGetSet<number, number>;
gap: IGetSet<number, number>;
itemHeight: IGetSet<number, number>;
horizontal: IGetSet<boolean, boolean>;
legendWidth: IGetSet<number, number>;
itemWidth: IGetSet<number, number>;
}
export interface IBaseChart<T> {
width: IGetSet<number, T>;
height: IGetSet<number, T>;
minWidth: IGetSet<number, T>;
minHeight: IGetSet<number, T>;
dimension: IGetSet<any, T>;
group: IGetSet<any, T>; // not sure here
transitionDuration: IGetSet<number, T>;
colors: IGetSet<string[], T>;
keyAccessor: IGetSet<(d:any) => number, T>;
valueAccessor: IGetSet<(d:any) => number, T>;
label: IGetSet<(l:any) => string, T>;
renderLabel: IGetSet<boolean, T>;
renderlet: (fnctn: (t:T) => void) => T;
title: IGetSet<(t:string) => string, T>;
filter: IGetSet<any, T>;
filterAll: () => void;
expireCache: () => void;
legend: (l:ILegendwidget) => T;
chartID: () => number;
options: (o:Object)=>void ;
select: (selector: D3.Selection) => D3.Selection;
selectAll: (selector: D3.Selection) => D3.Selection;
}
export interface IEvents {
trigger(fnctn: () => void, delay?: number):void;
}
export var events: IEvents;
export interface IListener<T> {
on: (eventName: string, fnctn: (c:T) => void) => T;
}
export interface ImarginObj {
top: number;
right: number;
bottom: number;
left: number;
}
export interface IMarginable<T> {
margins: IGetSet<ImarginObj, T>;
}
// abstract interfaces
export interface IAbstractColorChart<T> {
colorDomain: IGetSet<number[], T>;
}
export interface IAbstractStackableChart<T> {
stack: (group: IChartGroup, name?:string, retriever?: (d:Object)=>number) => T;
}
export interface IAbstractCoordinateGridChart<T> {
x: IGetSet<any, T>;
y: IGetSet<any, T>;
elasticY: IGetSet<boolean, T>;
xAxis: IGetSet<D3.Svg.Axis, T>;
yAxis: IGetSet<D3.Svg.Axis, T>;
yAxisPadding: IGetSet<number, T>;
xAxisPadding: IGetSet<number, T>;
renderHorizontalGridLines: IGetSet<boolean, T>;
}
export interface IAbstractBubblechart<T> {
r: IGetSet<any, T>;
radiusValueAccessor: IGetSet<(d:any) => number, T>;
}
// function interfaces
export interface columnFunction {
(rowinfo:any): string;
}
export interface sortbyFunction {
(rowinfo:any): any;
}
export interface orderFunction {
<T>(a: T, b: T): number;
}
// chart interfaces
export interface IBubblechart extends
IBaseChart<IBubblechart>,
IAbstractColorChart<IBubblechart>,
IAbstractBubblechart<IBubblechart>,
IAbstractCoordinateGridChart<IBubblechart>,
IMarginable<IBubblechart>,
IListener<IBubblechart> {
}
export interface IPiechart extends
IBaseChart<IPiechart>,
IAbstractColorChart<IPiechart>,
IAbstractBubblechart<IPiechart>,
IAbstractCoordinateGridChart<IPiechart>,
IMarginable<IPiechart>,
IListener<IPiechart> {
radius: IGetSet<number, IPiechart>;
minAngleForLabel: IGetSet<number, IPiechart>;
}
export interface IBarchart extends
IBaseChart<IBarchart>,
IAbstractStackableChart<IBarchart>,
IAbstractCoordinateGridChart<IBarchart>,
IMarginable<IBarchart>,
IListener<IBarchart> {
centerBar: (b:boolean) => IBarchart;
gap: (gapBetweenBars: number) => IBarchart;
}
export interface ILinechart extends
IBaseChart<ILinechart>,
IAbstractStackableChart<ILinechart>,
IAbstractCoordinateGridChart<ILinechart>,
IMarginable<ILinechart>,
IListener<ILinechart> {
}
export interface IDatachart extends
IBaseChart<IDatachart>,
IAbstractStackableChart<IDatachart>,
IAbstractCoordinateGridChart<IDatachart>,
IMarginable<IDatachart>,
IListener<IDatachart> {
size: IGetSet<number, IDatachart>;
columns: IGetSet<columnFunction[], IDatachart>;
sortBy: IGetSet<sortbyFunction, IDatachart>;
order: IGetSet<orderFunction, IDatachart>;
}
export interface IRowchart extends
IBaseChart<IRowchart>,
IAbstractColorChart<IRowchart>,
IAbstractStackableChart<IRowchart>,
IAbstractCoordinateGridChart<IRowchart>,
IMarginable<IRowchart>,
IListener<IRowchart> {
}
// utilities
export interface IChartGroup { }
export function filterAll(chartGroup?: IChartGroup): void;
export function renderAll(chartGroup?: IChartGroup): void;
export function redrawAll(chartGroup?: IChartGroup): void;
export function bubbleChart(cssSel: string): IBubblechart;
export function pieChart(cssSel: string): IPiechart;
export function barChart(cssSel: string): IBarchart;
export function lineChart(cssSel: string): ILinechart;
export function dataTable(cssSel: string): IDatachart;
export function rowChart(cssSel: string): IRowchart;
}
+22
View File
@@ -0,0 +1,22 @@
/// <reference path="dock-spawn.d.ts" />
var dockManagerDiv = document.createElement('div'),
panelDiv1 = document.createElement('div'),
panelDiv2 = document.createElement('div'),
panelDiv3 = document.createElement('div');
document.body.appendChild(dockManagerDiv);
var dockManager = new dockspawn.DockManager(dockManagerDiv);
dockManager.initialize();
var panelContainer1 = new dockspawn.PanelContainer(panelDiv1, dockManager),
panelContainer2 = new dockspawn.PanelContainer(panelDiv2, dockManager),
panelContainer3 = new dockspawn.PanelContainer(panelDiv3, dockManager);
var documentNode = dockManager.context.model.documentManagerNode;
var panelNode1 = dockManager.dockLeft(documentNode, panelContainer1, 0.33),
panelNode2 = dockManager.dockRight(documentNode, panelContainer2, 0.33),
panelNode3 = dockManager.dockFill(documentNode, panelContainer3);
+180
View File
@@ -0,0 +1,180 @@
// Type definitions for Dock Spawn
// Project: http://dockspawn.com
// https://github.com/coderespawn/dock-spawn
// Definitions by: Drew Noakes <https://drewnoakes.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped/dock-spawn
declare module dockspawn
{
/**
* Dock manager manages all the dock panels in a hierarchy, similar to Visual Studio.
* It owns an HTMLDivElement inside which all panels are docked.
* Initially the document manager takes up the central space and acts as the root node.
*/
class DockManager
{
context: DockManagerContext;
constructor(element: HTMLDivElement);
initialize(): void;
rebuildLayout(node: DockNode): void;
invalidate(): void;
resize(width: number, height: number): void;
/**
* Reset the dock model. This happens when state is loaded from JSON.
*/
setModel(model: DockModel): void;
setRootNode(node: DockNode): void;
/** Dock the [dialog] to the left of the [referenceNode] node */
dockDialogLeft(referenceNode: DockNode, dialog: Dialog): DockNode;
/** Dock the [dialog] to the right of the [referenceNode] node */
dockDialogRight(referenceNode: DockNode, dialog: Dialog): DockNode;
/** Dock the [dialog] above the [referenceNode] node */
dockDialogUp(referenceNode: DockNode, dialog: Dialog): DockNode;
/** Dock the [dialog] below the [referenceNode] node */
dockDialogDown(referenceNode: DockNode, dialog: Dialog): DockNode;
/** Dock the [dialog] as a tab inside the [referenceNode] node */
dockDialogFill(referenceNode: DockNode, container: PanelContainer): DockNode;
/** Dock the [container] to the left of the [referenceNode] node */
dockLeft(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode;
/** Dock the [container] to the right of the [referenceNode] node */
dockRight(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode;
/** Dock the [container] above the [referenceNode] node */
dockUp(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode;
/** Dock the [container] below the [referenceNode] node */
dockDown(referenceNode: DockNode, container: PanelContainer, ratio: number): DockNode;
/** Dock the [container] as a tab inside the [referenceNode] node */
dockFill(referenceNode: DockNode, container: PanelContainer): DockNode;
suspendLayout(): void;
resumeLayout(): void;
saveState(): string;
loadState(state: string): void;
}
class DockManagerContext
{
dockManager: DockManager;
model: DockModel;
documentManagerView: DocumentManagerContainer;
constructor(dockManager: DockManager);
}
class DockModel
{
rootNode: DockNode;
documentManagerNode: DockNode;
}
class DockNode
{
constructor(container: PanelContainer);
detachFromParent(): void;
}
/**
* Tab Host control contains tabs known as TabPages.
* The tab strip can be aligned in different orientations
*/
class TabHost
{
tabStripDirection: TabStripDirection;
displayCloseButton: boolean;
pages: TabPage[];
hostElement: HTMLDivElement;
tabListElement: HTMLDivElement;
separatorElement: HTMLDivElement;
contentElement: HTMLDivElement;
constructor(tabStripDirection?: TabStripDirection, displayCloseButton?: boolean)
setActiveTab(container: PanelContainer): void;
/** Set the selected TabPage. */
onTabPageSelected(page: TabPage): void;
resize(width: number, height: number): void;
}
class TabPage
{
constructor(host: TabHost, container: PanelContainer);
}
enum TabStripDirection
{
DIRECTION_TOP = 0,
DIRECTION_BOTTOM = 1,
DIRECTION_LEFT = 2,
DIRECTION_RIGHT = 3
}
class FillDockContainer
{
tabOrientation: TabStripDirection;
element: HTMLDivElement;
tabHost: TabHost;
dockManager: DockManager;
name: string;
containerType: string;
minimumAllowedChildNodes: number;
constructor(dockManager: DockManager, tabStripDirection?: TabStripDirection)
}
/**
* The document manager is then central area of the dock layout hierarchy.
* This is where more important panels are placed (e.g. the text editor in an IDE,
* 3D view in a modelling package etc
*/
class DocumentManagerContainer extends FillDockContainer
{
selectedTab: TabPage;
constructor(dockManager: DockManager);
saveState(state: string): void;
}
class PanelContainer
{
width: number;
height: number;
constructor(element: HTMLElement, dockManager: DockManager, title?: string);
setTitle(title: string): void;
setTitleIcon(iconName: string): void;
}
class Dialog
{
static fromElement(id: string, dockManager: DockManager): Dialog;
constructor(panel: PanelContainer, dockManager: DockManager);
setPosition(x: number, y: number): void;
resize(width: number, height: number): void;
setTitle(title: string): void;
setTitleIcon(iconName: string): void;
bringToFront(): void;
}
}
@@ -26,8 +26,11 @@ function test_bubble() {
var map: google.maps.Map;
var marker: google.maps.Marker;
var bubble: google.maps.infobubble.InfoBubble;
var position: google.maps.LatLng;
bubble.open(map, marker);
var isOpen = bubble.isOpen();
bubble.close();
position = bubble.getPosition();
}
+5
View File
@@ -57,6 +57,11 @@ declare module google.maps.infobubble {
* @marker The marker used for anchoring the infobubble to
*/
open(map: google.maps.Map, marker: google.maps.Marker) : void;
/**
* Returns the position of the InfoBubble
*/
getPosition(): google.maps.LatLng;
}
export interface InfoBubbleOptions {
+1 -1
View File
@@ -367,7 +367,7 @@ declare module google.maps {
getEditable(): boolean;
getMap(): Map;
getPath(): MVCArray;
getPaths(): MVCArray[];
getPaths(): MVCArray;
getVisible(): boolean;
setDraggable(draggable: boolean): void;
setEditable(editable: boolean): void;
+8 -8
View File
@@ -393,7 +393,8 @@ declare module grunt {
* @param contents If `contents` is a Buffer, encoding is ignored.
* @param options If an encoding is not specified, default to grunt.file.defaultEncoding.
*/
write(filepath: string, contents: NodeBuffer, options?: IFileEncodedOption): void
write(filepath: string, contents: string, options?: IFileEncodedOption): void
write(filepath: string, contents: NodeBuffer): void
/**
* Copy a source file to a destination path, creating intermediate directories if necessary.
@@ -809,6 +810,12 @@ declare module grunt {
* This method is used internally by the multi task system this.files / grunt.task.current.files property.
*/
normalizeMultiTaskFiles(data: grunt.config.IProjectConfig, targetname?: string): Array<grunt.file.IFileMap>
/**
* The currently running task or multitask.
* @see http://gruntjs.com/api/inside-tasks
*/
current: grunt.task.IMultiTask<any>
}
interface AsyncResultCatcher {
@@ -1232,13 +1239,6 @@ declare module grunt {
}
interface ITaskComponents extends grunt.task.CommonTaskModule {
/**
* The currently running task or multitask.
* @see IMultiTask for when to cast
*/
current: grunt.task.ITask
/**
* Load task-related files from the specified directory, relative to the Gruntfile.
* This method can be used to load task-related files from a local Grunt plugin by
+20 -11
View File
@@ -73,15 +73,15 @@ var barArr: Bar[];
var fooStream: Highland.Stream<Foo>;
var barStream: Highland.Stream<Bar>;
var fooStreamStream: Highland.Stream<Highland.Stream<Foo>>;
var barStreamStream: Highland.Stream<Highland.Stream<Bar>>;
var fooArrStream: Highland.Stream<Foo[]>;
var barArrStream: Highland.Stream<Bar[]>;
var fooStreamArr: Highland.Stream<Foo>[];
var barStreamArr: Highland.Stream<Bar>[];
var fooStreamArr: Highland.Stream<Foo>[];
var barStreamArr: Highland.Stream<Bar>[];
var strFooArrMapStream: Highland.Stream<StrFooArrMap>;
var strBarArrMapStream: Highland.Stream<StrBarArrMap>;
@@ -184,13 +184,13 @@ strStream = _.keys(obj);
anyArrStream = _.pairs(obj);
anyArrStream = _.pairs(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
obj = _.extend(obj, obj);
objCurObj = _.extend(obj);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
x = _.get(str, obj);
@@ -200,26 +200,26 @@ obj = _.set(str, foo, obj);
objCurAny = _.set(str, foo);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
_.log(str);
_.log(str, num, foo);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
f = _.wrapCallback(func);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
num = _.add(num, num);
numCurNum = _.add(num);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// instance methods
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooStream.pause();
fooStream.resume();
@@ -323,6 +323,10 @@ fooStream = fooStream.flatFilter((x: Foo) => {
return boolStream;
});
fooStream = fooStream.reject((x: Foo) => {
return bool;
});
fooStream = fooStream.find((x: Foo) => {
return bool;
});
@@ -343,6 +347,7 @@ fooStream = fooStream.where(obj);
fooStream = fooStream.zip(fooStream);
fooStream = fooStream.zip([foo, foo]);
fooStream = fooStream.head();
fooStream = fooStream.take(num);
fooStream = fooStream.last();
@@ -383,6 +388,10 @@ fooStream = fooStream.concat(fooArr);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fooStream = fooStream.merge(fooStreamStream);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barStream = fooStream.invoke<Bar>(str, anyArr);
fooStream = fooStream.throttle(num);
@@ -393,4 +402,4 @@ fooStream = fooStream.debounce(num);
fooStream = fooStream.latest();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+67 -2
View File
@@ -8,6 +8,7 @@
// TODO export the top-level functions
// TODO figure out curry arguments
// TODO create more overloads for nested data, like streams-of-streams or streams-of-array-of-streams etc
// TODO use externalised Thenable
// TODO use externalised Readable/Writable (not node's)
@@ -19,7 +20,6 @@
* Copyright (c) Caolan McMahon
*
*/
interface HighlandStatic {
/**
* The Stream constructor, accepts an array of values or a generator function
@@ -320,8 +320,9 @@ interface HighlandStatic {
* @api public
*/
add(a: number, b: number): number;
add(a: number): (b: number) => number;
not<R>(a: any): boolean;
}
declare module Highland {
@@ -660,6 +661,21 @@ declare module Highland {
*/
flatFilter(f: (x: R) => Stream<boolean>): Stream<R>;
/**
* The inverse of [filter](#filter).
*
* @id reject
* @section Streams
* @name Stream.reject(f)
* @param {Function} f - the truth test function
* @api public
*
* var odds = _([1, 2, 3, 4]).reject(function (x) {
* return x % 2 === 0;
* });
*/
reject(f: (x: R) => boolean): Stream<R>;
/**
* A convenient form of filter, which returns the first object from a
* Stream that passes the provided truth test
@@ -733,6 +749,18 @@ declare module Highland {
*/
take(n: number): Stream<R>;
/**
* Creates a new Stream with only the first value from the source.
*
* @id head
* @section Streams
* @name Stream.head()
* @api public
*
* _([1, 2, 3, 4]).head() // => 1
*/
head(): Stream<R>;
/**
* Drops all values from the Stream apart from the last one (if any).
*
@@ -871,6 +899,20 @@ declare module Highland {
*/
scan<U>(memo: U, x: (memo: U, x: R) => U): Stream<U>;
/**
* Same as [scan](#scan), but uses the first element as the initial
* state instead of passing in a `memo` value.
*
* @id scan1
* @section Streams
* @name Stream.scan1(iterator)
* @param {Function} iterator - the function which reduces the values
* @api public
*
* _([1, 2, 3, 4]).scan1(add) // => 1, 3, 6, 10
*/
scan1<U>(memo: U, x: (memo: U, x: R) => U): Stream<U>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
@@ -889,6 +931,29 @@ declare module Highland {
concat(ys: Stream<R>): Stream<R>;
concat(ys: R[]): Stream<R>;
/**
* Takes a Stream of Streams and merges their values and errors into a
* single new Stream. The merged stream ends when all source streams have
* ended.
*
* Note that no guarantee is made with respect to the order in which
* values for each stream end up in the merged stream. Values in the
* merged stream will, however, respect the order they were emitted from
* their respective streams.
*
* @id merge
* @section Streams
* @name Stream.merge()
* @api public
*
* var txt = _(['foo.txt', 'bar.txt']).map(readFile)
* var md = _(['baz.md']).map(readFile)
*
* _([txt, md]).merge();
* // => contents of foo.txt, bar.txt and baz.txt in the order they were read
*/
merge (ys: Stream<Stream<R>>): Stream<R>;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
+3 -1
View File
@@ -16,7 +16,9 @@ describe("Jasmine jQuery extension", () => {
expect($('<span></span>').addClass('js-something')).toBeMatchedBy('.js-something');
expect($('<span></span>')).toExist();
expect($('<div id="some-id"></div>')).toHaveAttr('id', 'some-id');
expect($('<input type="checkbox" checked="checked"/>')).toHaveAttr('type');
expect($('<div id="some-id"></div>')).toHaveProp('id', 'some-id');
expect($('<input type="checkbox" checked="checked"/>')).toHaveProp('checked');
expect($('')).toHaveBeenTriggered();
expect($('')).toHaveBeenTriggeredOn('#some-id');
expect($('')).toHaveBeenTriggeredOnAndWith('#some-id', 'eventParam');
@@ -132,4 +134,4 @@ describe("Jasmine jQuery extension", () => {
expect(spyEvent).toHaveBeenStopped();
});
});
})
});
+109 -109
View File
@@ -3,142 +3,142 @@
// Definitions by: Gregor Stamac <https://github.com/gstamac/>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jasmine/jasmine.d.ts"/>
/// <reference path="../jquery/jquery.d.ts"/>
declare function sandbox(attributes?: any): string;
declare function readFixtures(...uls: string[]): string;
declare function preloadFixtures(...uls: string[]);
declare function loadFixtures(...uls: string[]);
declare function appendLoadFixtures(...uls: string[]);
declare function setFixtures(html: string): string;
declare function appendSetFixtures(html: string);
declare function preloadStyleFixtures(...uls: string[]);
declare function loadStyleFixtures(...uls: string[]);
declare function appendLoadStyleFixtures(...uls: string[]);
declare function setStyleFixtures(html: string);
declare function appendSetStyleFixtures(html: string);
declare function loadJSONFixtures(...uls: string[]): jasmine.JSONFixtures;
declare function getJSONFixture(url: string): any;
/// <reference path="../jasmine/jasmine.d.ts"/>
/// <reference path="../jquery/jquery.d.ts"/>
declare function sandbox(attributes?: any): string;
declare function readFixtures(...uls: string[]): string;
declare function preloadFixtures(...uls: string[]);
declare function loadFixtures(...uls: string[]);
declare function appendLoadFixtures(...uls: string[]);
declare function setFixtures(html: string): string;
declare function appendSetFixtures(html: string);
declare function preloadStyleFixtures(...uls: string[]);
declare function loadStyleFixtures(...uls: string[]);
declare function appendLoadStyleFixtures(...uls: string[]);
declare function setStyleFixtures(html: string);
declare function appendSetStyleFixtures(html: string);
declare function loadJSONFixtures(...uls: string[]): jasmine.JSONFixtures;
declare function getJSONFixture(url: string): any;
declare function spyOnEvent(selector: string, eventName: string): jasmine.JQueryEventSpy;
declare function spyOnEvent(selector: string, eventName: string): jasmine.JQueryEventSpy;
declare module jasmine {
function spiedEventsKey(selector: JQuery, eventName: string): string;
function spiedEventsKey(selector: JQuery, eventName: string): string;
function getFixtures(): Fixtures;
function getStyleFixtures(): StyleFixtures;
function getJSONFixtures(): JSONFixtures;
function getFixtures(): Fixtures;
function getStyleFixtures(): StyleFixtures;
function getJSONFixtures(): JSONFixtures;
interface Fixtures {
fixturesPath: string;
containerId: string;
set(html: string): string;
appendSet(html: string);
preload(...uls: string[]);
load(...uls: string[]);
appendLoad(...uls: string[]);
read(...uls: string[]): string;
clearCache();
cleanUp();
sandbox(attributes?: any): string;
createContainer_(html: string);
addToContainer_(html: string);
getFixtureHtml_(url: string): string;
loadFixtureIntoCache_(relativeUrl: string);
makeFixtureUrl_(relativeUrl: string): string;
proxyCallTo_(methodName: string, passedArguments): any;
set(html: string): string;
appendSet(html: string);
preload(...uls: string[]);
load(...uls: string[]);
appendLoad(...uls: string[]);
read(...uls: string[]): string;
clearCache();
cleanUp();
sandbox(attributes?: any): string;
createContainer_(html: string);
addToContainer_(html: string);
getFixtureHtml_(url: string): string;
loadFixtureIntoCache_(relativeUrl: string);
makeFixtureUrl_(relativeUrl: string): string;
proxyCallTo_(methodName: string, passedArguments): any;
}
interface StyleFixtures {
fixturesPath: string;
set(html: string): string;
appendSet(html: string);
preload(...uls: string[]);
load(...uls: string[]);
appendLoad(...uls: string[]);
read_(...uls: string[]): string;
clearCache();
cleanUp();
createStyle_(html: string);
getFixtureHtml_(url: string): string;
loadFixtureIntoCache_(relativeUrl: string);
makeFixtureUrl_(relativeUrl: string): string;
proxyCallTo_(methodName: string, passedArguments): any;
set(html: string): string;
appendSet(html: string);
preload(...uls: string[]);
load(...uls: string[]);
appendLoad(...uls: string[]);
read_(...uls: string[]): string;
clearCache();
cleanUp();
createStyle_(html: string);
getFixtureHtml_(url: string): string;
loadFixtureIntoCache_(relativeUrl: string);
makeFixtureUrl_(relativeUrl: string): string;
proxyCallTo_(methodName: string, passedArguments): any;
}
interface JSONFixtures {
fixturesPath: string;
load(...uls: string[]);
read(...uls: string[]): string;
clearCache();
getFixtureData_(url: string): any;
loadFixtureIntoCache_(relativeUrl: string);
load(...uls: string[]);
read(...uls: string[]): string;
clearCache();
getFixtureData_(url: string): any;
loadFixtureIntoCache_(relativeUrl: string);
proxyCallTo_(methodName: string, passedArguments): any;
}
interface Matchers {
toHaveClass(className: string): boolean;
toHaveCss(css): boolean;
toBeVisible(): boolean;
toBeHidden(): boolean;
toBeSelected(): boolean;
toBeChecked(): boolean;
toBeEmpty(): boolean;
toExist(): boolean;
toHaveLength(length: number): boolean;
toHaveAttr(attributeName: string, expectedAttributeValue): boolean;
toHaveProp(propertyName: string, expectedPropertyValue): boolean;
toHaveId(id: string): boolean;
toHaveHtml(html: string): boolean;
//toContainHtml(html: string): boolean;
toHaveText(text: string): boolean;
//toContainText(text: string): boolean;
toHaveValue(value): boolean;
toHaveData(key, expectedValue): boolean;
toBe(selector: JQuery): boolean;
toContain(selector: JQuery): boolean;
toBeMatchedBy(selector: string): boolean;
toBeDisabled(): boolean;
toBeFocused(): boolean;
toHandle(event): boolean;
toHandleWith(eventName: string, eventHandler): boolean;
toHaveBeenTriggered(): boolean;
toHaveBeenTriggeredOn(selector: string): boolean;
toHaveBeenTriggeredOnAndWith(selector: string, ...args: any[]): boolean;
toHaveBeenPrevented(): boolean;
toHaveBeenPreventedOn(selector: string): boolean;
toHaveBeenStopped(): boolean;
toHaveBeenStoppedOn(selector: string): boolean;
toHaveCss(css): boolean;
toBeVisible(): boolean;
toBeHidden(): boolean;
toBeSelected(): boolean;
toBeChecked(): boolean;
toBeEmpty(): boolean;
toExist(): boolean;
toHaveLength(length: number): boolean;
toHaveAttr(attributeName: string, expectedAttributeValue?): boolean;
toHaveProp(propertyName: string, expectedPropertyValue?): boolean;
toHaveId(id: string): boolean;
toHaveHtml(html: string): boolean;
//toContainHtml(html: string): boolean;
toHaveText(text: string): boolean;
//toContainText(text: string): boolean;
toHaveValue(value): boolean;
toHaveData(key, expectedValue): boolean;
toBe(selector: JQuery): boolean;
toContain(selector: JQuery): boolean;
toBeMatchedBy(selector: string): boolean;
toBeDisabled(): boolean;
toBeFocused(): boolean;
toHandle(event): boolean;
toHandleWith(eventName: string, eventHandler): boolean;
toHaveBeenTriggered(): boolean;
toHaveBeenTriggeredOn(selector: string): boolean;
toHaveBeenTriggeredOnAndWith(selector: string, ...args: any[]): boolean;
toHaveBeenPrevented(): boolean;
toHaveBeenPreventedOn(selector: string): boolean;
toHaveBeenStopped(): boolean;
toHaveBeenStoppedOn(selector: string): boolean;
}
interface JQueryEventSpy {
selector: string;
eventName: string;
handler(eventObject: JQueryEventObject): any;
selector: string;
eventName: string;
handler(eventObject: JQueryEventObject): any;
reset(): any;
}
interface JasmineJQuery {
browserTagCaseIndependentHtml(html: string): string;
elementToString(element: JQuery): string;
matchersClass: any;
events: JasmineJQueryEvents;
}
interface JasmineJQueryEvents {
spyOn(selector: string, eventName: string): JQueryEventSpy;
args(selector: string, eventName: string): any;
wasTriggered(selector: string, eventName: string): boolean;
wasTriggeredWith(selector: string, eventName: string, expectedArgs: any, env: jasmine.Env): boolean;
wasPrevented(selector: string, eventName: string): boolean;
wasStopped(selector: string, eventName: string): boolean;
cleanUp();
}
browserTagCaseIndependentHtml(html: string): string;
elementToString(element: JQuery): string;
matchersClass: any;
events: JasmineJQueryEvents;
}
interface JasmineJQueryEvents {
spyOn(selector: string, eventName: string): JQueryEventSpy;
args(selector: string, eventName: string): any;
wasTriggered(selector: string, eventName: string): boolean;
wasTriggeredWith(selector: string, eventName: string, expectedArgs: any, env: jasmine.Env): boolean;
wasPrevented(selector: string, eventName: string): boolean;
wasStopped(selector: string, eventName: string): boolean;
cleanUp();
}
var JQuery: JasmineJQuery;
}
+7 -2
View File
@@ -5,10 +5,13 @@
declare function describe(description: string, specDefinitions: () => void): void;
declare function ddescribe(description: string, specDefinitions: () => void): void;
declare function xdescribe(description: string, specDefinitions: () => void): void;
declare function it(expectation: string, assertion?: () => void): void;
declare function it(expectation: string, assertion?: (done: () => void) => void): void;
declare function iit(expectation: string, assertion?: () => void): void;
declare function iit(expectation: string, assertion?: (done: () => void) => void): void;
declare function xit(expectation: string, assertion?: () => void): void;
declare function xit(expectation: string, assertion?: (done: () => void) => void): void;
@@ -95,11 +98,13 @@ declare module jasmine {
addReporter(reporter: Reporter): void;
execute(): void;
describe(description: string, specDefinitions: () => void): Suite;
ddescribe(description: string, specDefinitions: () => void): Suite;
beforeEach(beforeEachFunction: () => void): void;
currentRunner(): Runner;
afterEach(afterEachFunction: () => void): void;
xdescribe(desc: string, specDefinitions: () => void): XSuite;
it(description: string, func: () => void): Spec;
iit(description: string, func: () => void): Spec;
xit(desc: string, func: () => void): XSpec;
compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean;
compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean;
@@ -349,7 +354,7 @@ declare module jasmine {
identity: string;
and: SpyAnd;
calls: any[];
calls: any;
mostRecentCall: { args: any[]; };
argsForCall: any[];
wasCalled: boolean;
@@ -362,7 +367,7 @@ declare module jasmine {
/** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */
returnValue(val: any): void;
/** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */
callFake(fn: () => any): void;
callFake(fn: Function): void;
/** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */
throwError(msg: string): void;
/** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */
+7
View File
@@ -10,6 +10,13 @@ interface JQueryAddressStatic {
change(callback: any): void;
value(url: any): void;
update(): void;
path(): string;
path(value: string): void;
internalChange(eventhandler: Function): void;
externalChange(eventhandler: Function): void;
parameter(name: string, value?: string): string;
value(): string;
history(value: boolean): void;
}
interface JQueryAddress {
@@ -0,0 +1,19 @@
/// <reference path='../jquery/jquery.d.ts'/>
/// <reference path='jquery.jsignature.d.ts'/>
/*
* Taken from the tests section on jSignature
*/
$(document).ready(function () {
var $sigdiv = $('#signature');
$sigdiv.jSignature();
$sigdiv.jSignature("reset");
var data = $sigdiv.jSignature("getData", "svgbase64");
$sigdiv.jSignature("setData", "data:" + data);
});
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for jQuery.jsignature v2
// Project: https://github.com/willowsystems/jSignature
// Definitions by: Patrick Magee <https://github.com/pjmagee>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Project by: Willow Systems Corp
/// <reference path='../jquery/jquery.d.ts'/>
interface JQuery {
/**
* inits the jSignature widget
*/
jSignature(): JQuery;
/**
* Arguments vary per command. When provided, command is expected to be a string with a command for jSignature. Commands supported at this time: init, reset, getData, setData, listPlugins
* @summary
* init is the default, assumed action. init takes one argument - a settings Object. You can omit the command and just pass the settings object in upon init. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* clear (also aliased as reset) clears the signature pad, data store (and puts back signature line and other decor). Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* getData takes an argument - the name of the data format. Returns a data object appropriate for the data format.
* setData (also aliased as importData) takes two arguments - data object, (optional) data format name. When data object is a string formatted in data-url pattern you don't need to specify the data dormat name. The data format name (mime) will be implied from the data-url prefix. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* listPlugins takes an argument - a string denoting the category (Only export, import supported at this time) of plugins to list. Returns an array of strings.
*
* @param command the command used to perform an action on the jSignature canvas
* @see http://willowsystems.github.io/jSignature/#/about/
*
*/
jSignature(command: string): any;
/**
* Arguments vary per command. When provided, command is expected to be a string with a command for jSignature. Commands supported at this time: init, reset, getData, setData, listPlugins
* @summary
* init is the default, assumed action. init takes one argument - a settings Object. You can omit the command and just pass the settings object in upon init. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* clear (also aliased as reset) clears the signature pad, data store (and puts back signature line and other decor). Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* getData takes an argument - the name of the data format. Returns a data object appropriate for the data format.
* setData (also aliased as importData) takes two arguments - data object, (optional) data format name. When data object is a string formatted in data-url pattern you don't need to specify the data dormat name. The data format name (mime) will be implied from the data-url prefix. Returns (in a traditional jQuery chainable way) jQuery object ref to the element onto which the plugin was applied.
* listPlugins takes an argument - a string denoting the category (Only export, import supported at this time) of plugins to list. Returns an array of strings.
*
* @param command the command used to perform an action on the jSignature canvas
* @param arg the argument used with the specified command
* @see http://willowsystems.github.io/jSignature/#/about/
*
*/
jSignature(command: string, ...arg: string[]): any;
}
@@ -0,0 +1,4 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="jquery.placeholder.d.ts"/>
$('input').placeholder();
+13
View File
@@ -0,0 +1,13 @@
// Type definitions for jquery.placeholder.js 2.0.7
// Project: https://github.com/mathiasbynens/jquery-placeholder
// Definitions by: Peter Gill <https://github.com/majorsilence>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface JQuery {
placeholder() : void;
}
@@ -0,0 +1,194 @@
/// <reference path="jquery.tooltipster.d.ts" />
// Type definition tests for jQuery Tooltipster 3.0.5
// Project: https://github.com/iamceege/tooltipster
// Definitions by: Patrick Magee <https://github.com/pjmagee/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Tests taken from the getting started section of the Tooltipster website
$(document).ready(function () {
$('.tooltip').tooltipster();
$('#my-tooltip').tooltipster({
content: $('<span><img src="my-image.png" /> <strong>This text is in bold case !</strong></span>')
});
});
$(document).ready(function () {
$('.tooltip').tooltipster({
contentAsHTML: true
});
});
$('.tooltip').tooltipster({
theme: 'tooltipster-noir'
});
$('.tooltip').tooltipster({
animation: 'fade',
delay: 200,
theme: 'tooltipster-default',
touchDevices: false,
trigger: 'hover'
});
$.fn.tooltipster('setDefaults', {
position: 'bottom'
});
var myNewContent = '';
function callback(): void {
}
// temporarily disable a tooltip from being able to open
$('.tooltip').tooltipster('disable');
// if a tooltip was disabled from opening, reenable its previous functionality
$('.tooltip').tooltipster('enable');
// hide and destroy tooltip functionality
$('.tooltip').tooltipster('destroy');
// return a tooltip's current content (if selector contains multiple origins, only the value of the first will be returned)
$('.tooltip').tooltipster('content');
// update tooltip content
$('.tooltip').tooltipster('content', myNewContent);
// reposition and resize the tooltip
$('.tooltip').tooltipster('reposition');
// return the HTML root element of the tooltip
$('.tooltip').tooltipster('elementTooltip');
// return the HTML root element of the icon if there is one, 'undefined' otherwise
$('.tooltip').tooltipster('elementIcon');
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function (origin, continueTooltip) {
// we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
// next, we want to check if our data has already been cached
if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'POST',
url: 'example.php',
success: function (data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('content', data).data('ajax', 'cached');
}
});
}
}
});
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: (origin, continueTooltip) => {
// we'll make this function asynchronous and allow the tooltip to go ahead and show the loading notification while fetching our data
continueTooltip();
// next, we want to check if our data has already been cached
if (origin.data('ajax') !== 'cached') {
$.ajax({
type: 'POST',
url: 'example.php',
success: function (data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('content', data).data('ajax', 'cached');
}
});
}
}
});
$('.tooltip').tooltipster({
functionInit: function (origin, content) {
if (content === 'This is bad content') {
// when the request has finished loading, we will change the tooltip's content
$.ajax({
type: 'POST',
url: 'example.php',
success: function (data) {
origin.tooltipster('content', 'New content has been loaded : ' + data);
}
});
// this returned string will overwrite the content of the tooltip for the time being
return 'Wait while we load new content...';
}
else {
// return nothing : the initialization continues normally with its content unchanged.
}
}
});
$('.tooltip').tooltipster({
functionInit: (origin, content) => {
if (content === 'This is bad content') {
// when the request has finished loading, we will change the tooltip's content
$.ajax({
type: 'POST',
url: 'example.php',
success: function (data) {
origin.tooltipster('content', 'New content has been loaded : ' + data);
}
});
// this returned string will overwrite the content of the tooltip for the time being
return 'Wait while we load new content...';
}
else {
// return nothing : the initialization continues normally with its content unchanged.
}
}
});
$(document).ready(function () {
// first on page load, initiate the Tooltipster plugin
$('.tooltip').tooltipster();
// then immediately show the tooltip
$('#example').tooltipster('show');
// as soon as a key is pressed on the keyboard, hide the tooltip.
$(window).keypress(function () {
$('#example').tooltipster('hide');
});
});
$(document).ready(function () {
$('.tooltip').tooltipster();
$('#example').tooltipster('show', function () {
alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content'));
});
$('#example').tooltipster('show', () => {
alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content'));
});
$(window).keypress(function () {
$('#example').tooltipster('hide', function () {
alert('The tooltip is now fully closed');
});
});
});
$('#my-special-tooltip').tooltipster('content', 'My new content');
+186
View File
@@ -0,0 +1,186 @@
// Type definitions for jQuery Tooltipster 3.0.5
// Project: https://github.com/iamceege/tooltipster
// Definitions by: Patrick Magee <https://github.com/pjmagee/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface JQueryTooltipsterOptions {
/**
* Determines how the tooltip will animate in and out. Feel free to modify or create custom transitions in the tooltipster.css file. In IE9 and 8, all animations default to a JavaScript generated, fade animation. Default: 'fade'
* fade, grow, swing, slide, fall
*/
animation?: string;
/**
* Adds the "speech bubble arrow" to the tooltip. Default: true
*/
arrow?: boolean;
/**
* Select a specific color for the "speech bubble arrow". Default: will inherit the tooltip's background color
* hex code / rgb
*/
arrowColor?: any;
/**
* If autoClose is set to false, the tooltip will never close unless you call the 'close' method yourself. Default: true
*/
autoClose?: boolean;
/**
* If set, this will override the content of the tooltip. Default: null
* @type string, jQuery object
*/
content?: any;
/**
* If the content of the tooltip is provided as a string, it is displayed as plain text by default. If this content should actually be interpreted as HTML, set this option to true. Default: false
*/
contentAsHTML?: boolean;
/**
* If you provide a jQuery object to the 'content' option, this sets if it is a clone of this object that should actually be used. Default: true
*/
contentCloning?: boolean;
/**
* Delay how long it takes (in milliseconds) for the tooltip to start animating in. Default: 200
*/
delay?: number;
/**
* Set a fixed width for the tooltip. The tooltip will always be a consistent width - no matter your content size. Default: 0 (auto width)
*/
fixedWidth?: number;
/**
* Set a max width for the tooltip. If the tooltip ends up being smaller than the set max width, the tooltip's width will be set automatically. Default: 0 (no max width)
*/
maxWidth?: number;
/**
* Create a custom function to be fired only once at instantiation. If the function returns a value, this value will become the content of the tooltip. See the advanced section to learn more. Default: function(origin, content) {}
*/
functionInit?: (origin, content) => any;
/**
* Create a custom function to be fired before the tooltip opens. This function may prevent or hold off the opening. See the advanced section to learn more. Default: function(origin, continueTooltip) { continueTooltip(); }
*/
functionBefore?: (origin, continueTooltip) => void;
/**
* Create a custom function to be fired when the tooltip and its contents have been added to the DOM. Default: function(origin, tooltip) {}
*/
functionReady?: (origin, tooltip) => void;
/**
* Create a custom function to be fired once the tooltip has been closed and removed from the DOM. Default: function(origin) {}
*/
functionAfter?: (origin) => void;
/**
* If using the iconDesktop or iconTouch options, this sets the content for your icon. Default: '(?)'
* @type string, jQuery object
*/
icon?: any;
/**
* If you provide a jQuery object to the 'icon' option, this sets if it is a clone of this object that should actually be used. Default: true
*/
iconCloning?: boolean;
/**
* Generate an icon next to your content that is responsible for activating the tooltip on non-touch devices. Default: false
*/
iconDesktop?: boolean;
/**
* If using the iconDesktop or iconTouch options, this sets the class on the icon (used to style the icon). Default: 'tooltipster-icon'
*/
iconTheme?: string;
/**
* Generate an icon next to your content that is responsible for activating the tooltip on touch devices (tablets, phones, etc). Default: false
*/
iconTouch?: boolean;
/**
* Give users the possibility to interact with the tooltip. Unless autoClose is set to false, the tooltip will still close if the user moves away from or clicks out of the tooltip. Default: false
*/
interactive?: boolean;
/**
* If the tooltip is interactive and activated by a hover event, set the amount of time (milliseconds) allowed for a user to hover off of the tooltip activator (origin) on to the tooltip itself - keeping the tooltip from closing. Default: 350
*/
interactiveTolerance?: number;
/**
* Offsets the tooltip (in pixels) farther left/right from the origin. Default: 0
*/
offsetX?: number;
/**
* Offsets the tooltip (in pixels) farther up/down from the origin. Default: 0
*/
offsetY?: number;
/**
* If true, only one tooltip will be allowed to be active at a time. Non-autoclosing tooltips will not be closed though. Default: false
*/
onlyOne?: boolean;
/**
* Set the position of the tooltip. Default: 'top'
* right, left, top, top-right, top-left, bottom, bottom-right, bottom-left
*/
position?: string;
/**
* Will reposition the tooltip if the origin moves. As this option may have an impact on performance, we suggest you enable it only if you need to. Default: false
*/
positionTracker?: boolean;
/**
* Set the speed of the animation. Default: 350
*/
speed?: number;
/**
* How long the tooltip should be allowed to live before closing. Default: 0 (disabled)
*/
timer?: number;
/**
* Set the theme used for your tooltip. Default: 'tooltipster-default'
*/
theme?: string;
/**
* If set to false, tooltips will not show on pure-touch devices, unless you open them yourself with the 'show' method. Touch gestures on devices which also have a mouse will still open the tooltips though. Default: true
*/
touchDevices?: boolean;
/**
* Set how tooltips should be activated and closed. See the advanced section to learn how to build custom triggers. Default: 'hover'
* hover, click, custom
*/
trigger?: string;
/**
* If a tooltip is open while its content is updated, play a subtle animation when the content changes. Default: true
*/
updateAnimation?: boolean;
}
interface JQuery {
/**
* Initiate the Tooltipster plugin
*/
tooltipster(): void;
/**
* Creates a new tooltip with the specified, or default, options.
* @param options The options
* @example
* $('.tooltip').tooltipster({
* animation: 'fade',
* delay: 200,
* theme: 'tooltipster-default',
* touchDevices: false,
* trigger: 'hover'
* });
*/
tooltipster(options?: JQueryTooltipsterOptions): JQuery;
/**
* Updates an existing tinyscrollbar with the specified, or default, options.
* @param options The options
* @param callback optional argument callback
* @example
* $(window).keypress(function() {
* $('#example').tooltipster('hide', function() {
* alert('The tooltip is now fully closed');
* });
* });
*/
tooltipster(method: string, callback?: Function): JQuery;
/**
* Call a method trigger with optional paramter
* @example $('#my-special-tooltip').tooltipster('content', 'My new content');
* @example
* $('#example').tooltipster('show', function() {
* alert('The tooltip is now fully open. The content is: ' + this.tooltipster('content'));
* });
*/
tooltipster(method: string, param?: string): any;
}
@@ -0,0 +1,22 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="jquery.ui.datetimepicker.d.ts" />
// basic no options
$('#datetimepicker').datetimepicker({
});
// basic with some options
$('#datetimepicker').datetimepicker({
dateFormat: "yy-mm-dd",
timeFormat: 'HH:mm',
nextText: "",
prevText: ""
});
// function within the plugin
$('#datetimepicker').datetimepicker('formatTime', {
format: "HH:mm",
time: { hours: 1, minutes: 1, seconds: 1 }
});
+132
View File
@@ -0,0 +1,132 @@
// Type definitions for jQuery UI DateTimePicker 0.3 Addon
//
// Project: http://trentrichardson.com/examples/timepicker/
// Definitions by: https://github.com/dougajmcdonald
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="../jqueryui/jqueryui.d.ts"/>
interface DateTimePickerOptions extends JQueryUI.DatepickerOptions {
// Control options
showButtonPanel?: boolean; //Default: true - Whether to show the button panel at the bottom.This is generally needed.
timeOnly?: boolean; //Default: false - Hide the datepicker and only provide a time interface.
onSelect?: () => any; //Default: null - Function to be called when a date is chosen or time has changed(parameters: datetimeText, datepickerInstance).
alwaysSetTime?: boolean; //Default: true - Always have a time set internally, even before user has chosen one.
separator?: string; //Default: " " - When formatting the time this string is placed between the formatted date and formatted time.
pickerTimeFormat?: string; //Default: (timeFormat option) - How to format the time displayed within the timepicker.
pickerTimeSuffix?: string; //Default: (timeSuffix option) - String to place after the formatted time within the timepicker.
showTimepicker?: boolean; //Default: true - Whether to show the timepicker within the datepicker.
addSliderAccess?: boolean; //Default: false - Adds the sliderAccess plugin to sliders within timepicker
sliderAccessArgs?: any; //Default: null - Object to pass to sliderAccess when used.
defaultValue?: string; //Default: null - String of the default time value placed in the input on focus when the input is empty.
minDateTime?: Date; //Default: null - Date object of the minimum datetime allowed.Also available as minDate.
maxDateTime?: Date; //Default: null - Date object of the maximum datetime allowed.Also Available as maxDate.
parse?: string; //Default: 'strict' - How to parse the time string. Two methods are provided: 'strict' which must match the timeFormat exactly, and 'loose' which uses javascript's new Date(timeString) to guess the time. You may also pass in a function(timeFormat, timeString, options) to handle the parsing yourself, returning a simple object:
// Alt field options
altFieldTimeOnly?: boolean; //Default: true - When altField is used from datepicker altField will only receive the formatted time and the original field only receives date.
altSeparator?: string; //Default: (separator option) - String placed between formatted date and formatted time in the altField.
altTimeSuffix?: string; //Default: (timeSuffix option) - String always placed after the formatted time in the altField.
altTimeFormat?: string; //Default: (timeFormat option) - The time format to use with the altField.
// Localization options
currentText?: string; //Default: "Now", A Localization Setting - Text for the Now button.
closeText?: string; //Default: "Done", A Localization Setting - Text for the Close button.
amNames?: string; //Default: ['AM', 'A'], A Localization Setting - Array of strings to try and parse against to determine AM.
pmNames?: string; //Default: ['PM', 'P'], A Localization Setting - Array of strings to try and parse against to determine PM.
timeFormat?: string; //Default: "HH:mm", A Localization Setting - String of format tokens to be replaced with the time.See Formatting.
timeSuffix?: string; //Default: "", A Localization Setting - String to place after the formatted time.
timeOnlyTitle?: string; //Default: "Choose Time", A Localization Setting - Title of the wigit when using only timepicker.
timeText?: string; //Default: "Time", A Localization Setting - Label used within timepicker for the formatted time.
hourText?: string; //Default: "Hour", A Localization Setting - Label used to identify the hour slider.
minuteText?: string; //Default: "Minute", A Localization Setting - Label used to identify the minute slider.
secondText?: string; //Default: "Second", A Localization Setting - Label used to identify the second slider.
millisecText?: string; //Default: "Millisecond", A Localization Setting - Label used to identify the millisecond slider.
microsecText?: string; //Default: "Microsecond", A Localization Setting - Label used to identify the microsecond slider.
timezoneText?: string; //Default: "Timezone", A Localization Setting - Label used to identify the timezone slider.
isRTL?: boolean; //Default: false, A Localization Setting - Right to Left support.
// Timefield options
controlType?: string; //Default: 'slider' - Whether to use 'slider' or 'select'.If 'slider' is unavailable through jQueryUI, 'select' will be used.For advanced usage you may pass an object which implements "create", "options", "value" methods to use controls other than sliders or selects.See the _controls property in the source code for more details.
showHour?: boolean; //Default: null - Whether to show the hour control. The default of null will use detection from timeFormat.
showMinute?: boolean; //Default: null - Whether to show the minute control. The default of null will use detection from timeFormat.
showSecond?: boolean; //Default: null - Whether to show the second control. The default of null will use detection from timeFormat.
showMillisec?: boolean; //Default: null - Whether to show the millisecond control. The default of null will use detection from timeFormat.
showMicrosec?: boolean; //Default: null - Whether to show the microsecond control. The default of null will use detection from timeFormat.
showTimezone?: boolean; //Default: null - Whether to show the timezone select.
showTime?: boolean; //Default: true - Whether to show the time selected within the datetimepicker.
stepHour?: number; //Default: 1 - Hours per step the slider makes.
stepMinute?: number; //Default: 1 - Minutes per step the slider makes.
stepSecond?: number; //Default: 1 - Seconds per step the slider makes.
stepMillisec?: number; //Default: 1 - Milliseconds per step the slider makes.
stepMicrosec?: number; //Default: 1 - Microseconds per step the slider makes.
hour?: number; //Default: 0 - Initial hour set.
minute?: number; //Default: 0 - Initial minute set.
second?: number; //Default: 0 - Initial second set.
millisec?: number; //Default: 0 - Initial millisecond set.
microsec?: number; //Default: 0 - Initial microsecond set. Note: Javascript's native Date object does not natively support microseconds. Timepicker adds ability to simply Date.setMicroseconds(m) and Date.getMicroseconds(). Date comparisons will not acknowledge microseconds. Use this only for display purposes.
timezone?: number; //Default: null - Initial timezone set.This is the offset in minutes.If null the browser's local timezone will be used. If you're timezone is "-0400" you would use - 240. For backwards compatibility you may pass "-0400", however the timezone is stored in minutes and more reliable.
hourMin?: number; //Default: 0 - The minimum hour allowed for all dates.
minuteMin?: number; //Default: 0 - The minimum minute allowed for all dates.
secondMin?: number; //Default: 0 - The minimum second allowed for all dates.
millisecMin?: number; //Default: 0 - The minimum millisecond allowed for all dates.
microsecMin?: number; //Default: 0 - The minimum microsecond allowed for all dates.
hourMax?: number; //Default: 23 - The maximum hour allowed for all dates.
minuteMax?: number; //Default: 59 - The maximum minute allowed for all dates.
secondMax?: number; //Default: 59 - The maximum second allowed for all dates.
millisecMax?: number; //Default: 999 - The maximum millisecond allowed for all dates.
microsecMax?: number; //Default: 999 - The maximum microsecond allowed for all dates.
hourGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in hours) between labels.
minuteGrid?: number; //Default: 0 - When greater than 0 a label grid will be generated under the slider.This number represents the units (in minutes) between labels.
secondGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in seconds) between labels.
millisecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in milliseconds) between labels.
microsecGrid?: number; //Default: 0 - When greater than 0 a label grid will be genereated under the slider.This number represents the units (in microseconds) between labels.
// Timezone options
timezoneList?: Array<TimezoneOptions> //Default: [generated timezones] - An array of timezones used to populate the timezone select.Can be an array of values or an array of objects: { label: "EDT", value: -240 }. The value should be the offset number in minutes.So "-0400" which is the format "-hhmm", would equate to - 240 minutes.
}
interface TimezoneOptions {
label: string;
value: number;
}
interface Time {
hour?: number;
minute?: number;
second?: number;
millisecond?: number;
timezone?: string;
}
interface formatTimeOptions {
format: string;
time: Time;
options?: DateTimePickerOptions;
}
interface parseTimeOptions {
format: string;
time: string;
options?: DateTimePickerOptions;
}
interface parseDateTimeOptions {
dateFormat: string;
timeFormat: string;
dateTimeString: string;
dateSettings: string;
timeSettings: string;
}
interface JQuery {
datetimepicker(): JQuery;
datetimepicker(options?: DateTimePickerOptions): JQuery;
datetimepicker(method: string, methodParameter: any): any;
datetimepicker(method: 'formatTime', methodParameter: formatTimeOptions): string;
datetimepicker(method: 'parseTime', methodParameter: parseTimeOptions): Time;
datetimepicker(method: 'parseDateTime', methodParameter: parseDateTimeOptions): Date;
}
+2 -2
View File
@@ -51,7 +51,7 @@ interface Validator
{
addClassRules(name: string, rules: any): void;
addClassRules(rules: any): void;
addMethod(name: string, method: (value: any, element: any, ...params: any[]) => any, message?: any): void;
addMethod(name: string, method: (value: any, element: any, params: any) => any, message?: any): void;
element(element: any): boolean;
form(): boolean;
format(template: string, ...arguments: string[]): string;
@@ -82,4 +82,4 @@ interface JQueryStatic
{
format(template: string, ...arguments: string[]): string;
validator: Validator;
}
}
+260 -89
View File
@@ -763,7 +763,7 @@ function test_children() {
var $kids = $(e.target).children();
var len = $kids.addClass("hilite").length;
$("#results span:first").text(len.toString());
$("#results span:first").text(len);
//$("#results span:last").text(e.target.tagName);
e.preventDefault();
@@ -887,6 +887,12 @@ function test_clone() {
.clone());
}
function test_prependTo() {
$("<p>Test</p>").prependTo(".inner");
$("h2").prependTo($(".container"));
$("span").prependTo("#foo");
}
function test_closest() {
$('li.item-a').closest('ul')
.css('background-color', 'red');
@@ -1091,90 +1097,6 @@ function test_dblclick() {
$('#target').dblclick();
}
function test_deferred() {
function returnPromise(): JQueryPromise<(data: { MyString: string; MyNumber: number; }, textStatus: string, jqXHR: JQueryXHR) => any> {
return $.ajax("test.php");
}
var x = returnPromise();
x.done((data, textStatus, jqXHR) => {
var myNumber: number = data.MyNumber;
var myString: string = data.MyString;
var theTextStatus: string = textStatus;
var thejqXHR: JQueryXHR = jqXHR;
});
$.get("test.php").always(function () {
alert("$.get completed with success or error callback arguments");
});
$.get("test.php").done(function () {
alert("$.get succeeded");
});
function fn1() {
$("p").append(" 1 ");
}
function fn2() {
$("p").append(" 2 ");
}
function fn3(n) {
$("p").append(n + " 3 " + n);
}
var dfd = $.Deferred();
dfd
.done([fn1, fn2], fn3, [fn2, fn1])
.done(function (n) {
$("p").append(n + " we're done.");
});
$("button").bind("click", function () {
dfd.resolve("and");
});
$.get("test.php")
.done(function () { alert("$.get succeeded"); })
.fail(function () { alert("$.get failed!"); });
dfd.state();
var defer = $.Deferred(),
filtered = defer.pipe(function (value) {
return value * 2;
});
defer.resolve(5);
filtered.done(function (value) {
alert("Value is ( 2*5 = ) 10: " + value);
});
filtered.fail(function (value) {
alert("Value is ( 3*6 = ) 18: " + value);
});
filtered.done(function (data) { });
function asyncEvent() {
var dfd: JQueryDeferred<string> = $.Deferred<string>();
setTimeout(function () {
dfd.resolve("hurray");
}, Math.floor(400 + Math.random() * 2000));
setTimeout(function () {
dfd.reject("sorry");
}, Math.floor(400 + Math.random() * 2000));
setTimeout(function working() {
if (dfd.state() === "pending") {
dfd.notify("working... ");
setTimeout(null, 500);
}
}, 1);
return dfd.promise();
}
var obj = {
hello: function (name) {
alert("Hello " + name);
}
},
defer = $.Deferred();
defer.promise(obj);
defer.resolve("John");
$.get("test.php").then(
function () { alert("$.get succeeded"); },
function () { alert("$.get failed!"); }
);
}
function test_delay() {
$('#foo').slideUp(300).delay(800).fadeIn(400);
$("button").click(function () {
@@ -1851,6 +1773,26 @@ function test_getScript() {
});
}
function test_jQueryget() {
console.log($("li").get(0));
console.log($("li")[0]);
console.log($("li").get(-1));
$("*", document.body).click(function (event) {
event.stopPropagation();
var domElement = $(this).get(0);
$("span:first").text("Clicked on - " + domElement.nodeName);
});
function display(divs) {
var a = [];
for (var i = 0; i < divs.length; i++) {
a.push(divs[i].innerHTML);
}
$("span").text(a.join(" "));
}
display($("div").get().reverse());
}
function test_globalEval() {
jQuery.globalEval("var newVar = true;");
}
@@ -2015,6 +1957,38 @@ function test_height() {
});
}
function test_wrap() {
$(".inner").wrap("<div class='new'></div>");
$(".inner").wrap(function () {
return "<div class='" + $(this).text() + "'></div>";
});
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
$("p").wrap(document.createElement("div"));
$("p").wrap($(".doublediv"));
}
function test_wrapAll() {
$(".inner").wrapAll("<div class='new' />");
$("p").wrapAll("<div></div>");
$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");
$("p").wrapAll(document.createElement("div"));
$("p").wrapAll($(".doublediv"));
}
function test_wrapInner() {
$(".inner").wrapInner("<div class='new'></div>");
$(".inner").wrapInner(function () {
return "<div class='" + this.nodeValue + "'></div>";
});
var elem: Element;
$(elem).wrapInner("<div class='test'></div>");
$(elem).wrapInner("<div class=\"test\"></div>");
$("p").wrapInner("<b></b>");
$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");
$("p").wrapInner(document.createElement("b"));
$("p").wrapInner($("<span class='red'></span>"));
}
function test_width() {
// Returns width of browser viewport
$(window).width();
@@ -2175,6 +2149,7 @@ function test_innerWidth() {
var p = $("p:first");
$("p:last").text("innerWidth:" + p.innerWidth());
p.innerWidth(123);
p.innerWidth('123px');
}
@@ -2213,6 +2188,37 @@ function test_scrollTop() {
$("div.demo").scrollTop(300);
}
function test_parent() {
$("*", document.body).each(function () {
var parentTag = $(this).parent().get(0).tagName;
$(this).prepend(document.createTextNode(parentTag + " > "));
});
$("p").parent(".selected").css("background", "yellow");
}
function test_parents() {
var parentEls = $("b").parents()
.map(function () {
return this.tagName;
})
.get()
.join(", ");
$("b").append("<strong>" + parentEls + "</strong>");
function showParents() {
$("div").css("border-color", "white");
var len = $("span.selected")
.parents("div")
.css("border", "2px red solid")
.length;
$("b").text("Unique div parents: " + len);
}
$("span").click(function () {
$(this).toggleClass("selected");
showParents();
});
}
function test_param() {
function test1() {
@@ -2876,6 +2882,36 @@ function test_makeArray() {
jQuery.isArray(arr) === true;
}
function test_replaceAll() {
$("<h2>New heading</h2>").replaceAll(".inner");
$(".first").replaceAll(".third");
$("<b>Paragraph. </b>").replaceAll("p");
}
function test_replaceWith() {
$("div.second").replaceWith("<h2>New heading</h2>");
$("div.inner").replaceWith("<h2>New heading</h2>");
$("div.third").replaceWith($(".first"));
$("button").click(function () {
$(this).replaceWith("<div>" + $(this).text() + "</div>");
});
$("p").replaceWith("<b>Paragraph. </b>");
$("p").click(function () {
$(this).replaceWith($("div"));
});
$("button").on("click", function () {
var $container = $("div.container").replaceWith(function () {
return $(this).contents();
});
$("p").append($container.attr("class"));
});
}
function test_map() {
$(':checkbox').map(function () {
return this.id;
@@ -2884,16 +2920,25 @@ function test_map() {
return $(this).val();
}).get().join(", "));
var mappedItems = $("li").map(function (index) {
var replacement = $("<li>").text($(this).text()).get(0);
if (index == 0) {
var replacement:any = $("<li>").text($(this).text()).get(0);
if (index === 0) {
// Make the first item all caps
$(replacement).text($(replacement).text().toUpperCase());
} else if (index == 1 || index == 3) {
} else if (index === 1 || index === 3) {
// Delete the second and fourth items
replacement = null;
} else if (index == 2) {
} else if (index === 2) {
// Make two of the third item and add some text
replacement = [replacement, $("<li>").get(0)];
$(replacement[0]).append("<b> - A</b>");
$(replacement[1]).append("Extra <b> - B</b>");
}
// Replacement will be a dom element, null,
// or an array of dom elements
return replacement;
});
$("#results").append(mappedItems);
@@ -3071,6 +3116,22 @@ function test_parseHTML() {
.appendTo( $log );
}
function test_not() {
$("li").not(":even").css("background-color", "red");
$("li").not(document.getElementById("notli"))
.css("background-color", "red");
$("div").not(".green, #blueone")
.css("border-color", "red");
$("p").not($("#selected")[0]);
$("p").not("#selected");
$("p").not($("div p.selected"));
}
function test_EventIsNewable() {
var ev = new jQuery.Event('click');
}
@@ -3100,3 +3161,113 @@ $.ajax({
alert(data);
}
});
function test_deferred() {
function returnPromise(): JQueryPromise<(data: { MyString: string; MyNumber: number; }, textStatus: string, jqXHR: JQueryXHR) => any> {
return $.ajax("test.php");
}
var x = returnPromise();
x.done((data, textStatus, jqXHR) => {
var myNumber: number = data.MyNumber;
var myString: string = data.MyString;
var theTextStatus: string = textStatus;
var thejqXHR: JQueryXHR = jqXHR;
});
$.get("test.php").always(function () {
alert("$.get completed with success or error callback arguments");
});
$.get("test.php").done(function () {
alert("$.get succeeded");
});
function fn1() {
$("p").append(" 1 ");
}
function fn2() {
$("p").append(" 2 ");
}
function fn3(n) {
$("p").append(n + " 3 " + n);
}
var dfd = $.Deferred();
dfd
.done([fn1, fn2], fn3, [fn2, fn1])
.done(function (n) {
$("p").append(n + " we're done.");
});
$("button").bind("click", function () {
dfd.resolve("and");
});
$.get("test.php")
.done(function () { alert("$.get succeeded"); })
.fail(function () { alert("$.get failed!"); });
dfd.state();
var defer = $.Deferred(),
filtered = defer.pipe(function (value) {
return value * 2;
});
defer.resolve(5);
filtered.done(function (value) {
alert("Value is ( 2*5 = ) 10: " + value);
});
filtered.fail(function (value) {
alert("Value is ( 3*6 = ) 18: " + value);
});
filtered.done(function (data) { });
var obj = {
hello: function (name) {
alert("Hello " + name);
}
},
defer = $.Deferred();
defer.promise(obj);
defer.resolve("John");
$.get("test.php").then(
function () { alert("$.get succeeded"); },
function () { alert("$.get failed!"); }
);
}
function test_deferred_promise() {
function asyncEvent() {
var dfd = $.Deferred<string>();
// Resolve after a random interval
setTimeout(function () {
dfd.resolve("hurray");
}, Math.floor(400 + Math.random() * 2000));
// Reject after a random interval
setTimeout(function () {
dfd.reject("sorry");
}, Math.floor(400 + Math.random() * 2000));
// Show a "working..." message every half-second
setTimeout(function working() {
if (dfd.state() === "pending") {
dfd.notify("working... ");
setTimeout(working, 500);
}
}, 1);
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
// Attach a done, fail, and progress handler for the asyncEvent
$.when(asyncEvent()).then(
function (status) {
alert(status + ", things are going well");
},
function (status) {
alert(status + ", you fail this time");
},
function (status) {
$("body").append(status);
}
);
}
+928 -90
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -976,6 +976,7 @@ interface JQuery {
sortable(methodName: 'disable'): void;
sortable(methodName: 'enable'): void;
sortable(methodName: 'widget'): JQuery;
sortable(methodName: 'toArray'): string[];
sortable(methodName: string): JQuery;
sortable(options: JQueryUI.SortableOptions): JQuery;
sortable(optionLiteral: string, optionName: string): any;
+1
View File
@@ -17,6 +17,7 @@ interface JWPlayer {
getFullscreen(): boolean;
getMute(): boolean;
getPlaylist(): any[];
getPlaylistIndex(): number;
getPlaylistItem(index: number): any;
getPosition(): number;
getQualityLevels(): any[];
+4
View File
@@ -46,3 +46,7 @@ interface KnockoutMapping {
interface KnockoutStatic {
mapping: KnockoutMapping;
}
declare module "knockout.mapping" {
export = KnockoutMapping;
}
+1 -1
View File
@@ -310,7 +310,7 @@ interface KnockoutUtils {
parseJson(jsonString: string): any;
stringifyJson(data: any, replacer: Function, space: string): string;
stringifyJson(data: any, replacer?: Function, space?: string): string;
postJson(urlOrForm: any, data: any, options: any): void;
+129 -104
View File
@@ -1,9 +1,33 @@
/// <reference path="lazy.js.d.ts" />
var sequence: LazyJS.Sequence;
var arraySeq: LazyJS.ArrayLikeSequence;
var objectSeq: LazyJS.ObjectLikeSequence;
var asyncSeq: LazyJS.AsyncSequence;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Foo {
foo(): string;
}
interface Bar {
bar(): string;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var foo: Foo;
var bar: Bar;
var fooArr: Foo[];
var barArr: Bar[];
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var fooSequence: LazyJS.Sequence<Foo>;
var barSequence: LazyJS.Sequence<Bar>;
var fooArraySeq: LazyJS.ArrayLikeSequence<Foo>;
var barArraySeq: LazyJS.ArrayLikeSequence<Bar>;
var fooObjectSeq: LazyJS.ObjectLikeSequence<Foo>;
var anyObjectSeq: LazyJS.ObjectLikeSequence<any>;
var fooAsyncSeq: LazyJS.AsyncSequence<Foo>;
var strSequence: LazyJS.Sequence<string>;
var stringSeq: LazyJS.StringLikeSequence;
var obj: Object;
@@ -23,141 +47,142 @@ function fnErrorCallback(error: any): void {
}
function fnValueCallback(value: any): void {
function fnValueCallback(value: Foo): void {
}
function fnGetKeyCallback(value: any): string {
return '';
function fnGetKeyCallback(value: Foo): string {
return str;
}
function fnTestCallback(value: any): boolean {
return false;
function fnTestCallback(value: Foo): boolean {
return bool;
}
function fnMapCallback(value: any): any {
return null;
function fnMapCallback(value: Foo): Bar {
return bar;
}
function fnMapStringCallback(value: string): string {
return '';
return str;
}
function fnNumberCallback(value: any): number {
return 0;
function fnNumberCallback(value: Foo): number {
return num;
}
function fnMemoCallback(memo: any, value: any): any {
return null;
function fnMemoCallback(memo: Bar, value: Foo): Bar {
return bar;
}
function fnGeneratorCallback(index: number): any {
return null;
function fnGeneratorCallback(index: number): Foo {
return foo;
}
// Lazy
arraySeq = Lazy([]);
objectSeq = Lazy({});
stringSeq = Lazy('');
fooArraySeq = Lazy(fooArr);
fooObjectSeq = Lazy<Foo>({a:foo, b:foo});
anyObjectSeq = Lazy<any>({a:num, b:str});
stringSeq = Lazy(str);
// Strict
var Strict = Lazy.strict();
arraySeq = Strict([1, 2, num]).pop();
fooArraySeq = Strict([foo, foo]).pop();
// Sequence
asyncSeq = sequence.async(num);
sequence = sequence.chunk(num);
sequence = sequence.compact();
sequence = sequence.concat(arr);
sequence = sequence.consecutive(num);
bool = sequence.contains(x);
sequence = sequence.countBy(str);
sequence = sequence.countBy(fnGetKeyCallback);
sequence = sequence.dropWhile(fnTestCallback);
sequence = sequence.each(fnValueCallback);
bool = sequence.every(fnTestCallback);
sequence = sequence.filter(fnTestCallback);
sequence = sequence.find(fnTestCallback);
sequence = sequence.findWhere(obj);
fooAsyncSeq = fooSequence.async(num);
fooSequence = fooSequence.chunk(num);
fooSequence = fooSequence.compact();
fooSequence = fooSequence.concat(arr);
fooSequence = fooSequence.consecutive(num);
bool = fooSequence.contains(foo);
fooSequence = fooSequence.countBy(str);
fooObjectSeq = fooSequence.countBy(fnGetKeyCallback);
fooSequence = fooSequence.dropWhile(fnTestCallback);
fooSequence = fooSequence.each(fnValueCallback);
bool = fooSequence.every(fnTestCallback);
fooSequence = fooSequence.filter(fnTestCallback);
fooSequence = fooSequence.find(fnTestCallback);
fooSequence = fooSequence.findWhere(obj);
x = sequence.first();
sequence = sequence.first(num);
x = fooSequence.first();
fooSequence = fooSequence.first(num);
sequence = sequence.flatten();
objectSeq = sequence.groupBy(fnGetKeyCallback);
sequence = sequence.indexOf(x);
sequence = sequence.initial();
sequence = sequence.initial(num);
sequence = sequence.intersection(arr);
sequence = sequence.invoke(str);
bool = sequence.isEmpty();
str = sequence.join();
str = sequence.join(str);
fooSequence = fooSequence.flatten();
fooObjectSeq = fooSequence.groupBy(fnGetKeyCallback);
fooSequence = fooSequence.indexOf(x);
fooSequence = fooSequence.initial();
fooSequence = fooSequence.initial(num);
fooSequence = fooSequence.intersection(arr);
fooSequence = fooSequence.invoke(str);
bool = fooSequence.isEmpty();
str = fooSequence.join();
str = fooSequence.join(str);
x = sequence.last();
sequence = sequence.last(num);
foo = fooSequence.last();
fooSequence = fooSequence.last(num);
sequence = sequence.lastIndexOf(x);
sequence = sequence.map(fnMapCallback);
x = sequence.max();
x = sequence.max(fnNumberCallback);
x = sequence.min();
x = sequence.min(fnNumberCallback);
sequence = sequence.pluck(str);
x = sequence.reduce(fnMemoCallback);
x = sequence.reduce(fnMemoCallback, x);
x = sequence.reduceRight(fnMemoCallback, x);
sequence = sequence.reject(fnTestCallback);
sequence = sequence.rest(num);
sequence = sequence.reverse();
sequence = sequence.shuffle();
bool = sequence.some();
bool = sequence.some(fnTestCallback);
sequence = sequence.sortBy(fnNumberCallback);
sequence = sequence.sortedIndex(x);
sequence = sequence.sum();
sequence = sequence.sum(fnNumberCallback);
sequence = sequence.takeWhile(fnTestCallback);
sequence = sequence.union(arr);
sequence = sequence.uniq();
sequence = sequence.where(obj);
sequence = sequence.without(arr);
sequence = sequence.zip(arr);
fooSequence = fooSequence.lastIndexOf(foo);
barSequence = fooSequence.map(fnMapCallback);
foo = fooSequence.max();
foo = fooSequence.max(fnNumberCallback);
foo = fooSequence.min();
foo = fooSequence.min(fnNumberCallback);
fooSequence = fooSequence.pluck(str);
bar = fooSequence.reduce(fnMemoCallback);
bar = fooSequence.reduce(fnMemoCallback, bar);
bar = fooSequence.reduceRight(fnMemoCallback, bar);
fooSequence = fooSequence.reject(fnTestCallback);
fooSequence = fooSequence.rest(num);
fooSequence = fooSequence.reverse();
fooSequence = fooSequence.shuffle();
bool = fooSequence.some();
bool = fooSequence.some(fnTestCallback);
fooSequence = fooSequence.sortBy(fnNumberCallback);
fooSequence = fooSequence.sortedIndex(foo);
fooSequence = fooSequence.sum();
fooSequence = fooSequence.sum(fnNumberCallback);
fooSequence = fooSequence.takeWhile(fnTestCallback);
fooSequence = fooSequence.union(fooArr);
fooSequence = fooSequence.uniq();
fooSequence = fooSequence.where(obj);
fooSequence = fooSequence.without(fooArr);
fooSequence = fooSequence.zip(arr);
arr = sequence.toArray();
obj = sequence.toObject();
fooArr = fooSequence.toArray();
obj = fooSequence.toObject();
// ArrayLikeSequence
arraySeq = arraySeq.concat();
arraySeq = arraySeq.first();
arraySeq = arraySeq.first(num);
x = arraySeq.get(num);
num = arraySeq.length();
arraySeq = arraySeq.map(fnMapCallback);
arraySeq = arraySeq.pop();
arraySeq = arraySeq.rest();
arraySeq = arraySeq.rest(num);
arraySeq = arraySeq.reverse();
arraySeq = arraySeq.shift();
arraySeq = arraySeq.slice(num);
arraySeq = arraySeq.slice(num, num);
fooArraySeq = fooArraySeq.concat();
fooArraySeq = fooArraySeq.first();
fooArraySeq = fooArraySeq.first(num);
foo = fooArraySeq.get(num);
num = fooArraySeq.length();
barArraySeq = fooArraySeq.map(fnMapCallback);
fooArraySeq = fooArraySeq.pop();
fooArraySeq = fooArraySeq.rest();
fooArraySeq = fooArraySeq.rest(num);
fooArraySeq = fooArraySeq.reverse();
fooArraySeq = fooArraySeq.shift();
fooArraySeq = fooArraySeq.slice(num);
fooArraySeq = fooArraySeq.slice(num, num);
// ObjectLikeSequence
objectSeq = objectSeq.defaults(obj);
sequence = objectSeq.functions();
objectSeq = objectSeq.get(str);
objectSeq = objectSeq.invert();
sequence = objectSeq.keys();
objectSeq = objectSeq.omit(strArr);
sequence = objectSeq.pairs();
objectSeq = objectSeq.pick(strArr);
arr = objectSeq.toArray();
obj = objectSeq.toObject();
sequence = objectSeq.values();
fooObjectSeq = fooObjectSeq.defaults(obj);
fooSequence = fooObjectSeq.functions();
fooObjectSeq = fooObjectSeq.get(str);
fooObjectSeq = fooObjectSeq.invert();
strSequence = fooObjectSeq.keys();
fooObjectSeq = fooObjectSeq.omit(strArr);
fooSequence = fooObjectSeq.pairs();
fooObjectSeq = fooObjectSeq.pick(strArr);
arr = fooObjectSeq.toArray();
obj = fooObjectSeq.toObject();
fooSequence = fooObjectSeq.values();
// StringLikeSequence
@@ -181,8 +206,8 @@ stringSeq = stringSeq.mapString(fnMapStringCallback);
stringSeq = stringSeq.match(exp);
stringSeq = stringSeq.reverse();
sequence = stringSeq.split(str);
sequence = stringSeq.split(exp);
stringSeq = stringSeq.split(str);
stringSeq = stringSeq.split(exp);
bool = stringSeq.startsWith(str);
stringSeq = stringSeq.substring(num);
+142 -138
View File
@@ -6,28 +6,31 @@
declare module LazyJS {
interface LazyStatic {
(value:string):StringLikeSequence;
(value:any[]):ArrayLikeSequence;
(value:Object):ObjectLikeSequence;
(value:ArrayLike):ArrayLikeSequence;
(value: string):StringLikeSequence;
<T>(value: T[]):ArrayLikeSequence<T>;
(value: any[]):ArrayLikeSequence<any>;
<T>(value: Object):ObjectLikeSequence<T>;
(value: Object):ObjectLikeSequence<any>;
strict():LazyStatic;
generate(generatorFn:GeneratorCallback, length?:number):GeneratedSequence;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number):GeneratedSequence<T>;
range(to:number):GeneratedSequence;
range(from:number, to:number, step?:number):GeneratedSequence;
range(to: number):GeneratedSequence<number>;
range(from: number, to: number, step?: number):GeneratedSequence<number>;
repeat(value:any, count?:number):GeneratedSequence;
repeat<T>(value: T, count?: number):GeneratedSequence<T>;
on(eventType:string):Sequence;
on<T>(eventType: string):Sequence<T>;
readFile(path:string):StringLikeSequence;
makeHttpRequest(path:string):StringLikeSequence;
readFile(path: string):StringLikeSequence;
makeHttpRequest(path: string):StringLikeSequence;
}
interface ArrayLike {
interface ArrayLike<T> {
length:number;
[index:number]:T;
}
interface Callback {
@@ -35,212 +38,213 @@ declare module LazyJS {
}
interface ErrorCallback {
(error:any):void;
(error: any):void;
}
interface ValueCallback {
(value:any):void;
interface ValueCallback<T> {
(value: T):void;
}
interface GetKeyCallback {
(value:any):string;
interface GetKeyCallback<T> {
(value: T):string;
}
interface TestCallback {
(value:any):boolean;
interface TestCallback<T> {
(value: T):boolean;
}
interface MapCallback {
(value:any):any;
interface MapCallback<T, U> {
(value: T):U;
}
interface MapStringCallback {
(value:string):string;
(value: string):string;
}
interface NumberCallback {
(value:any):number;
interface NumberCallback<T> {
(value: T):number;
}
interface MemoCallback {
(memo:any, value:any):any;
interface MemoCallback<T, U> {
(memo: U, value: T):U;
}
interface GeneratorCallback {
(index:number):any;
interface GeneratorCallback<T> {
(index: number):T;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator {
new(sequence:Sequence):Iterator;
current():any;
interface Iterator<T> {
new (sequence: Sequence<T>):Iterator<T>;
current():T;
moveNext():boolean;
}
interface GeneratedSequence extends Sequence {
new(generatorFn:GeneratorCallback, length:number):GeneratedSequence;
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number):GeneratedSequence<T>;
length():number;
}
interface AsyncSequence extends SequenceBase {
each(callback:ValueCallback):AsyncHandle;
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>):AsyncHandle<T>;
}
interface AsyncHandle {
interface AsyncHandle<T> {
cancel():void;
onComplete(callback:Callback):void;
onError(callback:ErrorCallback):void;
onComplete(callback: Callback):void;
onError(callback: ErrorCallback):void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName:string[], overrides:Object):Function;
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence extends SequenceBase {
each(eachFn:ValueCallback):Sequence;
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>):Sequence<T>;
}
interface SequenceBase extends SequenceBaser {
interface SequenceBase<T> extends SequenceBaser<T> {
first():any;
first(count:number):Sequence;
indexOf(value:any, startIndex?:number):Sequence;
first(count: number):Sequence<T>;
indexOf(value: any, startIndex?: number):Sequence<T>;
last():any;
last(count:number):Sequence;
lastIndexOf(value:any):Sequence;
last(count: number):Sequence<T>;
lastIndexOf(value: any):Sequence<T>;
reverse():Sequence;
reverse():Sequence<T>;
}
interface SequenceBaser {
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval:number):AsyncSequence;
chunk(size:number):Sequence;
compact():Sequence;
concat(var_args:any[]):Sequence;
consecutive(length:number):Sequence;
contains(value:any):boolean;
countBy(propertyName:string):Sequence;
countBy(keyFn:GetKeyCallback):Sequence;
dropWhile(predicateFn:TestCallback):Sequence;
every(predicateFn:TestCallback):boolean;
filter(predicateFn:TestCallback):Sequence;
find(predicateFn:TestCallback):Sequence;
findWhere(properties:Object):Sequence;
async(interval: number):AsyncSequence<T>;
chunk(size: number):Sequence<T>;
compact():Sequence<T>;
concat(var_args: T[]):Sequence<T>;
consecutive(length: number):Sequence<T>;
contains(value: T):boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
flatten():Sequence;
groupBy(keyFn:GetKeyCallback):ObjectLikeSequence;
initial(count?:number):Sequence;
intersection(var_args:any[]):Sequence;
invoke(methodName:string):Sequence;
isEmpty():boolean;
join(delimiter?:string):string;
map(mapFn:MapCallback):Sequence;
max(valueFn?:NumberCallback):any;
min(valueFn?:NumberCallback):any;
pluck(propertyName:string):Sequence;
reduce(aggregatorFn:MemoCallback, memo?:any):any;
reduceRight(aggregatorFn:MemoCallback, memo:any):any;
reject(predicateFn:TestCallback):Sequence;
rest(count?:number):Sequence;
shuffle():Sequence;
some(predicateFn?:TestCallback):boolean;
sortBy(sortFn:NumberCallback):Sequence;
sortedIndex(value:any):Sequence;
sum(valueFn?:NumberCallback):Sequence;
takeWhile(predicateFn:TestCallback):Sequence;
union(var_args:any[]):Sequence;
uniq():Sequence;
where(properties:Object):Sequence;
without(var_args:any[]):Sequence;
zip(var_args:any[]):Sequence;
flatten(): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
toArray():any[];
toObject():Object;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sortBy(sortFn: NumberCallback<T>): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): Sequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName:string[], overrides:Object):Function;
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence extends Sequence {
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat():ArrayLikeSequence;
first(count?:number):ArrayLikeSequence;
get(index:number):any;
length():number;
map(mapFn:MapCallback):ArrayLikeSequence;
pop():ArrayLikeSequence;
rest(count?:number):ArrayLikeSequence;
reverse():ArrayLikeSequence;
shift():ArrayLikeSequence;
slice(begin:number, end?:number):ArrayLikeSequence;
concat(): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName:string[], overrides:Object):Function;
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence extends Sequence {
assign(other:Object):ObjectLikeSequence;
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async():X;
defaults(defaults:Object):ObjectLikeSequence;
functions():Sequence;
get(property:string):ObjectLikeSequence;
invert():ObjectLikeSequence;
keys():Sequence;
omit(properties:string[]):ObjectLikeSequence;
pairs():Sequence;
pick(properties:string[]):ObjectLikeSequence;
toArray():any[];
toObject():Object;
values():Sequence;
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): Sequence<string>;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName:string[], overrides:Object):Function;
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser {
charAt(index:number):string;
charCodeAt(index:number):number;
contains(value:string):boolean;
endsWith(suffix:string):boolean;
interface StringLikeSequence extends SequenceBaser<string> {
charAt(index: number): string;
charCodeAt(index: number): number;
contains(value: string): boolean;
endsWith(suffix: string): boolean;
first():string;
first(count:number):StringLikeSequence;
first(): string;
first(count: number): StringLikeSequence;
indexOf(substring:string, startIndex?:number):number;
indexOf(substring: string, startIndex?: number): number;
last():string;
last(count:number):StringLikeSequence;
last(): string;
last(count: number): StringLikeSequence;
lastIndexOf(substring:string, startIndex?:number):number;
mapString(mapFn:MapStringCallback):StringLikeSequence;
match(pattern:RegExp):StringLikeSequence;
reverse():StringLikeSequence;
lastIndexOf(substring: string, startIndex?: number): number;
mapString(mapFn: MapStringCallback): StringLikeSequence;
match(pattern: RegExp): StringLikeSequence;
reverse(): StringLikeSequence;
split(delimiter:string):Sequence;
split(delimiter:RegExp):Sequence;
split(delimiter: string): StringLikeSequence;
split(delimiter: RegExp): StringLikeSequence;
startsWith(prefix:string):boolean;
substring(start:number, stop?:number):StringLikeSequence;
toLowerCase():StringLikeSequence;
toUpperCase():StringLikeSequence;
startsWith(prefix: string): boolean;
substring(start: number, stop?: number): StringLikeSequence;
toLowerCase(): StringLikeSequence;
toUpperCase(): StringLikeSequence;
}
}
declare var Lazy:LazyJS.LazyStatic;
declare var Lazy: LazyJS.LazyStatic;
declare module 'lazy.js' {
export = Lazy;
@@ -310,7 +310,7 @@ skyDriveProps = {
WL.ui(skyDriveProps);
function onDownloadFileCompleted(response: Microsoft.Live.IFilePickerResult) {
var msg = "", folder, file;
var msg = "", folder: number, file: number;
// For each folder selected...
if (response.data.folders.length > 0) {
for (folder = 0; folder < response.data.folders.length; folder++) {
@@ -536,7 +536,7 @@ var errorObj: Microsoft.Live.IError = {
}
};
var event: Microsoft.Live.IEvent = {
var eventI: Microsoft.Live.IEvent = {
"id": "event.611afb17fa9448f28cdb8277e8ffeb77.e9f015000d0249ce847c5306a25d7d75",
"name": "Global Project Risk Management Meeting",
"description": "Generate and assess risks for the project",
@@ -854,7 +854,7 @@ var videoCollection: Microsoft.Live.IObjectCollection<Microsoft.Live.IVideo> = {
* already exercised above.
*/
function log(message) {
function log(message: string) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
@@ -974,7 +974,7 @@ function showUserContactInfo() {
);
}
function enablePurchase(response) {
function enablePurchase() {
var date = new Date();
var year = date.getFullYear();
+6 -6
View File
@@ -1,27 +1,27 @@
/// <reference path="ng-grid.d.ts" />
var options1: ngGrid.GridOptions = {
var options1: ngGrid.IGridOptions = {
data: [{ 'Name': 'Bob' }, { 'Name': 'Jane' }]
};
var options2: ngGrid.GridOptions = {
var options2: ngGrid.IGridOptions = {
afterSelectionChange: () => { },
beforeSelectionChange: () => { },
beforeSelectionChange: () => {return true; },
dataUpdated: () => { }
};
var options3: ngGrid.GridOptions = {
var options3: ngGrid.IGridOptions = {
columnDefs: [
{ field: 'name', displayName: 'Name' },
{ field: 'age', displayName: 'Age' }
]
};
var options4: ngGrid.GridOptions = {
var options4: ngGrid.IGridOptions = {
pagingOptions: {
pageSizes: [1, 2, 3, 4],
pageSize: 2,
totalServerItems: 100,
currentPage: 1
}
};
};
+25 -17
View File
@@ -11,13 +11,13 @@ declare class ngGridReorderable {
declare module ngGrid {
export interface GridOptions {
export interface IGridOptions {
/** Define an aggregate template to customize the rows when grouped. See github wiki for more details. */
aggregateTemplate?: any;
aggregateTemplate?: string;
/** Callback for when you want to validate something after selection. */
afterSelectionChange?: Function;
afterSelectionChange?: (rowItem?: any, event?: any) => void ;
/** Callback if you want to inspect something before selection,
return false if you want to cancel the selection. return true otherwise.
@@ -25,19 +25,21 @@ declare module ngGrid {
use rowItem.changeSelection(event) method after returning false initially.
Note: when shift+ Selecting multiple items in the grid this will only get called
once and the rowItem will be an array of items that are queued to be selected. */
beforeSelectionChange?: Function;
beforeSelectionChange?: (rowItem?: any, event?: any) => boolean ;
/** checkbox templates. */
checkboxCellTemplate?: any;
checkboxCellTemplate?: string;
/** checkbox templates. */
checkboxHeaderTemplate?: any;
checkboxHeaderTemplate?: string;
/** definitions of columns as an array [], if not defined columns are auto-generated. See github wiki for more details. */
columnDefs?: ColumnDef[];
columnDefs?: IColumnDef[];
/** Data being displayed in the grid. Each item in the array is mapped to a row being displayed. */
data?: any[];
/** Data being displayed in the grid. This can be either a string of object ID or object reference.
Using string is preferred, as this turns on change tracking in ng-grid
*/
data?: any;
/** Data updated callback, fires every time the data is modified from outside the grid. */
dataUpdated?: Function;
@@ -79,7 +81,7 @@ declare module ngGrid {
filterText: The text bound to the built-in search box.
useExternalFilter: Bypass internal filtering if you want to roll your own filtering mechanism but want to use builtin search box.
*/
filterOptions?: FilterOptions;
filterOptions?: IFilterOptions;
/** Defining the height of the footer in pixels. */
footerRowHeight?: number;
@@ -91,7 +93,7 @@ declare module ngGrid {
headerRowHeight?: number;
/** Define a header row template for further customization. See github wiki for more details. */
headerRowTemplate?: any;
headerRowTemplate?: string;
/** Enables the use of jquery UI reaggable/droppable plugin. requires jqueryUI to work if enabled.
Useful if you want drag + drop but your users insist on crappy browsers. */
@@ -105,13 +107,13 @@ declare module ngGrid {
/** Maintains the column widths while resizing.
Defaults to true when using *'s or undefined widths. Can be ovverriden by setting to false. */
maintainColumnRatios?: any;
maintainColumnRatios?: boolean;
/** Set this to false if you only want one item selected at a time */
multiSelect?: boolean;
/** pagingOptions - */
pagingOptions?: PagingOptions;
pagingOptions?: IPagingOptions;
/** Array of plugin functions to register in ng-grid */
pinSelectionCheckbox?: boolean;
@@ -123,7 +125,7 @@ declare module ngGrid {
rowHeight?: number;
/** Define a row template to customize output. See github wiki for more details. */
rowTemplate?: any;
rowTemplate?: string;
/** all of the items selected in the grid. In single select mode there will only be one item in the array. */
selectedItems?: any[];
@@ -170,15 +172,21 @@ declare module ngGrid {
enableHighlighting?: boolean;
}
export interface ColumnDef {
export interface IColumnDef {
field?: string;
width?: any; //**this can be a string containing a relatively, absolute size units or a number: '30%','54px',45 /*
displayName?: string;
cellTemplate?: string;
enableCellEdit?: boolean;
pinned?: boolean;
}
export interface FilterOptions {
export interface IFilterOptions {
filterText?: string;
useExternalFilter?: boolean;
}
export interface PagingOptions {
export interface IPagingOptions {
/** pageSizes: list of available page sizes. */
pageSizes?: number[];
/** pageSize: currently selected page size. */
+4
View File
@@ -28,6 +28,10 @@ import TArray = require('ref-array');
func(-5);
func.async(-5, function(err: any, res: any) {});
}
{
var funcPtr = ffi.Callback('int', [ 'int' ], Math.abs);
var func = ffi.ForeignFunction(funcPtr, 'int', [ 'int' ]);
}
{
var printfPointer = ffi.DynamicLibrary().get('printf');
var printfGen = ffi.VariadicForeignFunction(printfPointer, 'void', [ 'string' ]);
+6 -6
View File
@@ -140,10 +140,10 @@ declare module "ffi" {
* accept C callback functions.
*/
export var Callback: {
new (retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer;
new (retType: any, argTypes: any[], fn: Function): NodeBuffer;
(retType: any, argTypes: any[], abi: number, fn: Function): NodeBuffer;
(retType: any, argTypes: any[], fn: Function): NodeBuffer;
new (retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer;
new (retType: any, argTypes: any[], fn: any): NodeBuffer;
(retType: any, argTypes: any[], abi: number, fn: any): NodeBuffer;
(retType: any, argTypes: any[], fn: any): NodeBuffer;
}
export var ffiType: {
@@ -154,8 +154,8 @@ declare module "ffi" {
FFI_TYPE: StructType;
}
export var CIF: Function;
export var CIF_var: Function;
export var CIF: (retType: any, types: any[], abi?: any) => NodeBuffer
export var CIF_var: (retType: any, types: any[], numFixedArgs: number, abi?: any) => NodeBuffer;
export var HAS_OBJC: boolean;
export var FFI_TYPES: {[key: string]: NodeBuffer};
export var FFI_OK: number;
+16 -2
View File
@@ -21,7 +21,9 @@ assert.doesNotThrow(() => {
if (false) { throw "a hammer at your face"; }
}, undefined, "What the...*crunch*");
////////////////////////////////////////////////////
/// File system tests : http://nodejs.org/api/fs.html
////////////////////////////////////////////////////
fs.writeFile("thebible.txt",
"Do unto others as you would have them do unto you.",
assert.ifError);
@@ -33,6 +35,18 @@ fs.writeFile("Harry Potter",
},
assert.ifError);
var content: string,
buffer: NodeBuffer;
content = fs.readFileSync('testfile', 'utf8');
content = fs.readFileSync('testfile', {encoding : 'utf8'});
buffer = fs.readFileSync('testfile');
buffer = fs.readFileSync('testfile', {flag : 'r'});
fs.readFile('testfile', 'utf8', (err, data) => content = data);
fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data);
fs.readFile('testfile', (err, data) => buffer = data);
fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data);
class Networker extends events.EventEmitter {
constructor() {
super();
@@ -65,4 +79,4 @@ function stream_readable_pipe_test() {
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
}
}
+5 -2
View File
@@ -848,10 +848,13 @@ declare module "fs" {
export function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: ErrnoException, bytesRead: number, buffer: NodeBuffer) => void): void;
export function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number;
export function readFile(filename: string, options: { encoding?: string; flag?: string; }, callback: (err: ErrnoException, data: any) => void): void;
export function readFile(filename: string, encoding: string, callback: (err: ErrnoException, data: string) => void): void;
export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: ErrnoException, data: string) => void): void;
export function readFile(filename: string, options: { flag?: string; }, callback: (err: ErrnoException, data: NodeBuffer) => void): void;
export function readFile(filename: string, callback: (err: ErrnoException, data: NodeBuffer) => void ): void;
export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer;
export function readFileSync(filename: string, encoding: string): string;
export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;
export function readFileSync(filename: string, options?: { flag?: string; }): NodeBuffer;
export function writeFile(filename: string, data: any, callback?: (err: ErrnoException) => void): void;
export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: ErrnoException) => void): void;
export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: ErrnoException) => void): void;
+152 -105
View File
@@ -1,8 +1,12 @@
// Type definitions for PlantomJS v1.8.0 API
// Type definitions for PhantomJS v1.9.0 API
// Project: https://github.com/ariya/phantomjs/wiki/API-Reference
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker>
// Definitions by: Jed Hunsaker <https://github.com/jedhunsaker> and Mike Keesey <https://github.com/keesey>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function require(module: string): any;
declare var phantom: Phantom;
interface Phantom {
// Properties
@@ -11,33 +15,35 @@ interface Phantom {
cookiesEnabled: boolean;
libraryPath: string;
scriptName: string; // DEPRECATED
version: any;
version: {
major: number;
minor: number;
patch: number;
};
// Functions
addCookie(cookie: Cookie): boolean;
clearCookies();
clearCookies(): void;
deleteCookie(cookieName: string): boolean;
exit(returnValue: any): boolean;
exit(returnValue?: any): boolean;
injectJs(filename: string): boolean;
// Callbacks
onError: Function;
onError: (msg: string, trace: string[]) => any;
}
interface System {
pid: number;
platform: string;
os: OS;
env: any;
os: {
architecture: string;
name: string;
version: string;
};
env: { [name: string]: string; };
args: string[];
}
interface OS {
architecture: string;
name: string;
version: string;
}
interface WebPage {
// Properties
@@ -46,8 +52,8 @@ interface WebPage {
clipRect: ClipRect;
content: string;
cookies: Cookie[];
customHeaders: any;
event;
customHeaders: { [name: string]: string; };
event: any; // :TODO: elaborate this when documentation improves
focusedFrameName: string;
frameContent: string;
frameName: string;
@@ -55,13 +61,13 @@ interface WebPage {
frameTitle: string;
frameUrl: string;
framesCount: number;
framesName;
framesName: any; // :TODO: elaborate this when documentation improves
libraryPath: string;
navigationLocked: boolean;
offlineStoragePath: string;
offlineStorageQuota: number;
ownsPages: boolean;
pages;
pages: WebPage[];
pagesWindowName: string;
paperSize: PaperSize;
plainText: string;
@@ -77,76 +83,113 @@ interface WebPage {
addCookie(cookie: Cookie): boolean;
childFramesCount(): number; // DEPRECATED
childFramesName(): string; // DEPRECATED
clearCookies();
close();
clearCookies(): void;
close(): void;
currentFrameName(): string; // DEPRECATED
deleteCookie(cookieName: string): boolean;
evaluate(fn: Function, ...args: any[]): any;
evaluateAsync(fn: Function);
evaluateJavascript(str: string);
getPage(windowName: string);
go(index: number);
goBack();
goForward();
includeJs(url: string, callback: Function);
evaluateAsync(fn: Function): void;
evaluateJavascript(str: string): any; // :TODO: elaborate this when documentation improves
getPage(windowName: string): WebPage;
go(index: number): void;
goBack(): void;
goForward(): void;
includeJs(url: string, callback: Function): void;
injectJs(filename: string): boolean;
open(url: string, callback: (status: string) => void);
openUrl(url: string, httpConf: any, settings: any);
release(); // DEPRECATED
reload();
render(filename: string);
renderBase64(format: any): string;
sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string);
sendEvent(keyboardEventType: string, keyOrKeys, aNull?, bNull?, modifier?);
setContent(content: string, url: string);
stop();
switchToFocusedFrame();
switchToFrame(frameName: string);
switchToFrame(framePosition);
switchToChildFrame(frameName: string);
switchToChildFrame(framePosition);
switchToMainFrame(); // DEPRECATED
switchToParentFrame(); // DEPRECATED
uploadFile(selector: string, filename: string);
open(url: string, callback: (status: string) => any): void;
open(url: string, method: string, callback: (status: string) => any): void;
open(url: string, method: string, data: any, callback: (status: string) => any): void;
openUrl(url: string, httpConf: any, settings: any): void; // :TODO: elaborate this when documentation improves
release(): void; // DEPRECATED
reload(): void;
render(filename: string): void;
renderBase64(format: string): string;
sendEvent(mouseEventType: string, mouseX?: number, mouseY?: number, button?: string): void;
sendEvent(keyboardEventType: string, keyOrKeys: any, aNull?: any, bNull?: any, modifier?: number): void;
setContent(content: string, url: string): void;
stop(): void;
switchToFocusedFrame(): void;
switchToFrame(frameName: string): void;
switchToFrame(framePosition: number): void;
switchToChildFrame(frameName: string): void;
switchToChildFrame(framePosition: number): void;
switchToMainFrame(): void; // DEPRECATED
switchToParentFrame(): void; // DEPRECATED
uploadFile(selector: string, filename: string): void;
// Callbacks
onAlert: Function;
onAlert: (msg: string) => any;
onCallback: Function; // EXPERIMENTAL
onClosing: Function;
onConfirm: Function;
onConsoleMessage: Function;
onError: Function;
onFilePicker: Function;
onInitialized: Function;
onLoadFinished: Function;
onLoadStarted: Function;
onNavigationRequested: Function;
onPageCreated: Function;
onPrompt: Function;
onResourceRequested: Function;
onResourceReceived: Function;
onUrlChanged: Function;
onClosing: (closingPage: WebPage) => any;
onConfirm: (msg: string) => boolean;
onConsoleMessage: (msg: string, lineNum?: number, sourceId?: string) => any;
onError: (msg: string, trace: string[]) => any;
onFilePicker: (oldFile: string) => string;
onInitialized: () => any;
onLoadFinished: (status: string) => any;
onLoadStarted: () => any;
onNavigationRequested: (url: string, type: string, willNavigate: boolean, main: boolean) => any;
onPageCreated: (newPage: WebPage) => any;
onPrompt: (msg: string, defaultVal: string) => string;
onResourceError: (resourceError: ResourceError) => any;
onResourceReceived: (response: ResourceResponse) => any;
onResourceRequested: (requestData: ResourceRequest, networkRequest: NetworkRequest) => any;
onUrlChanged: (targetUrl: string) => any;
// Callback triggers
closing(page);
initialized();
javaScriptAlertSent(message: string);
javaScriptConsoleMessageSent(message: string);
loadFinished(status);
loadStarted();
navigationRequested(url: string, navigationType, navigationLocked, isMainFrame: boolean);
rawPageCreated(page);
resourceReceived(request);
resourceRequested(resource);
urlChanged(url: string);
closing(closingPage: WebPage): void;
initialized(): void;
javaScriptAlertSent(msg: string): void;
javaScriptConsoleMessageSent(msg: string, lineNum?: number, sourceId?: string): void;
loadFinished(status: string): void;
loadStarted(): void;
navigationRequested(url: string, type: string, willNavigate: boolean, main: boolean): void;
rawPageCreated(newPage: WebPage): void;
resourceReceived(response: ResourceResponse): void;
resourceRequested(requestData: ResourceRequest, networkRequest: NetworkRequest): void;
urlChanged(targetUrl: string): void;
}
interface ResourceError {
id: number;
url: string;
errorCode: string;
errorString: string;
}
interface ResourceResponse {
id: number;
url: string;
time: Date;
headers: { [name: string]: string; };
bodySize: number;
contentType?: string;
redirectURL?: string;
stage: string;
status: number;
statusText: string;
}
interface ResourceRequest {
id: number;
method: string;
ur: string;
time: Date;
headers: { [name: string]: string; };
}
interface NetworkRequest {
abort(): void;
changeUrl(url: string): void;
setHeader(name: string, value: string): void;
}
interface PaperSize {
width: string;
height: string;
width?: string;
height?: string;
border: string;
format: string;
orientation: string;
format?: string;
orientation?: string;
}
interface WebPageSettings {
@@ -154,9 +197,11 @@ interface WebPageSettings {
loadImages: boolean;
localToRemoteUrlAccessEnabled: boolean;
userAgent: string;
userName: string;
password: string;
XSSAuditingEnabled: boolean;
webSecurityEnabled: boolean;
resourceTimeout: number;
}
interface FileSystem {
@@ -181,59 +226,62 @@ interface FileSystem {
readLink(path: string): string;
// Directory Functions
changeWorkingDirectory(path: string);
makeDirectory(path: string);
makeTree(path: string);
removeDirectory(path: string);
removeTree(path: string);
copyTree(source: string, destination: string);
changeWorkingDirectory(path: string): void;
makeDirectory(path: string): void;
makeTree(path: string): void;
removeDirectory(path: string): void;
removeTree(path: string): void;
copyTree(source: string, destination: string): void;
// File Functions
open(path: string, mode: string): Stream;
open(path: string, options: { mode: string; charset?: string; }): Stream;
read(path: string): string;
write(path: string, content: string, mode: string);
write(path: string, content: string, mode: string): void;
size(path: string): number;
remove(path: string);
copy(source: string, destination: string);
move(source: string, destination: string);
touch(path: string);
remove(path: string): void;
copy(source: string, destination: string): void;
move(source: string, destination: string): void;
touch(path: string): void;
}
interface Stream {
atEnd(): boolean;
close(): void;
flush(): void;
read(): string;
readLine(): string;
write(data: string);
writeLine(data: string);
flush();
close();
seek(position: number): void;
write(data: string): void;
writeLine(data: string): void;
}
interface WebServer {
port: number;
listen(port: number, cb?:(request, response) => void): boolean;
listen(ipAddressPort: string, cb?:(request, response) => void): boolean;
close();
listen(port: number, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean;
listen(ipAddressPort: string, cb?: (request: WebServerRequest, response: WebServerResponse) => void): boolean;
close(): void;
}
interface Request {
interface WebServerRequest {
method: string;
url: string;
httpVersion: number;
headers: any;
headers: { [name: string]: string; };
post: string;
postRaw: string;
}
interface Response {
headers: any;
setHeader(name: string, value: string);
interface WebServerResponse {
headers: { [name: string]: string; };
setHeader(name: string, value: string): void;
header(name: string): string;
statusCode: number;
setEncoding(encoding: string);
write(data: string);
writeHead(statusCode: number, headers?: any);
close();
closeGracefully();
setEncoding(encoding: string): void;
write(data: string): void;
writeHead(statusCode: number, headers?: { [name: string]: string; }): void;
close(): void;
closeGracefully(): void;
}
interface TopLeft {
@@ -247,11 +295,10 @@ interface Size {
}
interface ClipRect extends TopLeft, Size {
width: number;
height: number;
}
interface Cookie {
name: string;
value: string;
domain?: string;
}
+95 -41
View File
@@ -121,9 +121,9 @@ interface CaptureError {
}
interface Capture {
captureAudio(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureAudioOptions);
captureImage(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions);
captureVideo(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions);
captureAudio(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureAudioOptions): void;
captureImage(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void;
captureVideo(captureSuccess: (mediaFiles: MediaFile[]) => void , captureError: (error: CaptureError) =>void , options?: CaptureImageOptions): void;
}
interface Connection {
@@ -204,9 +204,9 @@ interface Contact {
categories: ContactField[];
urls: ContactField[];
save(onSuccess?: (contacts: Contacts) => any, onError?: (contactError: ContactError) => any);
remove(onSuccess?: (contacts: Contacts) => any, onError?: (contactError: ContactError) => any);
clone(): Contact;
save(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void;
remove(onSuccess?: (contacts: Contacts) => void, onError?: (contactError: ContactError) => void): void;
clone(): Contact;
}
interface ContactFindOptions {
@@ -289,10 +289,10 @@ interface FileWriter {
onerror: Function;
onwriteend: Function;
abort();
seek();
truncate();
write();
abort(): void;
seek(arg: number): void;
truncate(arg: number): void;
write(arg: any): void;
}
interface FileSystem {
@@ -310,29 +310,29 @@ interface FileSystemEntry {
fullPath: string;
filesystem: FileSystem;
getMetadata(onSuccess?: (arg) => any, onError?: (arg) => any);
setMetadata(onSuccess?: (arg) => any, onError?: (arg) => any, options?);
toURL();
remove(onSuccess?: (arg) => any, onError?: (arg) => any);
getParent(onSuccess?: (arg) => any, onError?: (arg) => any);
getMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void): void;
setMetadata(onSuccess?: (arg: Metadata) => void, onError?: (arg: FileError) => void, options?: any): void;
toURL(): string;
remove(onSuccess?: () => void, onError?: (arg: FileError) => void): void;
getParent(onSuccess?: (arg: DirectoryEntry) => void, onError?: (arg: FileError) => void): void;
}
interface FileEntry extends FileSystemEntry {
moveTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg) => any, onError: (arg) => any);
copyTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg) => any, onError: (arg) => any);
createWriter(onSuccess?: (arg) => any, onError?: (arg) => any);
file(onSuccess?: (arg) => any, onError?: (arg) => any);
moveTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void;
copyTo(parentEntry: DirectoryEntry, file: string, onSuccess: (arg: DirectoryEntry) => void, onError: (arg: FileError) => void): void;
createWriter(onSuccess?: (arg: FileWriter) => void, onError?: (arg: FileError) => void): void;
file(onSuccess?: (arg: File) => void, onError?: (arg: FileError) => void): void;
}
interface DirectoryEntry extends FileSystemEntry {
createReader();
getDirectory();
getFile();
removeRecursively();
createReader(): DirectoryReader;
getDirectory(path: string, options: Flags, successCallback: (result: DirectoryEntry) => void, errorCallback: (error: FileError) => void): void;
getFile(path: string, options: Flags, successCallback: (result: FileEntry) => void, errorCallback: (error: FileError) => void): void;
removeRecursively(successCallback: () => void, errorCallback: (error: FileError) => void): void;
}
interface DirectoryReader {
readEntries(successCallback: (entries: FileSystemEntry) => void , errorCallback: (error: FileError) => void );
readEntries(successCallback: (entries: FileSystemEntry) => void, errorCallback: (error: FileError) => void): void;
}
interface FileTransfer {
@@ -365,7 +365,10 @@ interface FileUploadResult {
response: string;
}
// TODO Flags
interface Flags {
create: boolean;
exclusive: boolean;
}
/*
interface LocalFileSystem {
@@ -432,19 +435,70 @@ declare var GlobalizationError: {
PATTERN_ERROR: number;
}
interface GlobalizationDate {
year: number;
month: number;
day: number;
hour: number;
minute: number;
second: number;
millisecond: number;
}
interface GlobalizationDateOptions {
formatLength?: string;
selector?: string;
}
interface GlobalizationDatePattern {
pattern: string;
timezone: string;
utc_offset: number;
dst_offset: number;
}
interface GlobalizationDateNameOptions {
type?: string;
item?: string;
}
interface GlobalizationNumberOptions {
type?: string;
}
interface GlobalizationNumberPattern {
pattern: string;
symbol: string;
fraction: number;
rounding: number;
positive: string;
negative: string;
decimal: string;
grouping: string;
}
interface GlobalizationCurrencyPattern {
pattern: string;
code: string;
fraction: number;
rounding: number;
decimal: string;
grouping: string;
}
interface Globalization {
getPreferredLanguage(successCB, errorCB): void;
getLocaleName(successCB, errorCB): void;
dateToString(date, successCB, errorCB, options): void;
stringToDate(dateString, successCB, errorCB, options): void;
getDatePattern(successCB, errorCB, options): void;
getDateNames(successCB, errorCB, options): void;
isDayLightSavingsTime(date, successCB, errorCB): void;
getFirstDayOfWeek(successCB, errorCB): void;
numberToString(number, successCB, errorCB, options): void;
stringToNumber(string, successCB, errorCB, options): void;
getNumberPattern(successCB, errorCB, options): void;
getCurrencyPattern(currencyCode, successCB, errorCB): void;
getPreferredLanguage(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void;
getLocaleName(successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void): void;
dateToString(date: Date, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
stringToDate(dateString: string, successCallback: (properties: GlobalizationDate) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
getDatePattern(successCallback: (properties: GlobalizationDatePattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateOptions): void;
getDateNames(successCallback: (properties: {value: string[]}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationDateNameOptions): void;
isDayLightSavingsTime(date: Date, successCallback: (properties: {dst: boolean}) => void, errorCallback: (error: GlobalizationError) => void): void;
getFirstDayOfWeek(successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void): void;
numberToString(number: number, successCallback: (properties: {value: string}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
stringToNumber(string: string, successCallback: (properties: {value: number}) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
getNumberPattern(successCallback: (parameters: GlobalizationNumberPattern) => void, errorCallback: (error: GlobalizationError) => void, options?: GlobalizationNumberOptions): void;
getCurrencyPattern(currencyCode: string, successCallback: (parameters: GlobalizationCurrencyPattern) => void, errorCallback: (error: GlobalizationError) => void): void;
}
/*
@@ -457,7 +511,7 @@ interface InAppBrowser {
*/
interface Media {
new (src: string, mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any, mediaStatus?: Function);
new (src: string, mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any, mediaStatus?: Function): Media;
getCurrentPosition(mediaSuccess: Function, mediaError?: (mediaError: MediaError) => any): void;
getDuration(): any;
play(): void;
@@ -469,7 +523,7 @@ interface Media {
stop(): void;
}
declare var Media: {
new(src: string, onSuccess: (arg) => any, onError: (arg) => any): Media;
new(src: string, onSuccess: (arg: any) => any, onError: (error: any) => any): Media;
}
interface Notification {
@@ -486,8 +540,8 @@ interface Splashscreen {
}
interface Database {
transaction(populateDB?: (tx: SQLTransaction) => any, errorCB?: (err) => any, successCB?: () => any);
changeVersion(var1: string, var2: string);
transaction(populateDB?: (tx: SQLTransaction) => any, errorCB?: (err: any) => any, successCB?: () => any): void;
changeVersion(var1: string, var2: string): void;
}
interface SQLResultSetRowList {
-1
View File
@@ -1 +0,0 @@
""
-1
View File
@@ -1 +0,0 @@
""
+3 -1
View File
@@ -28,6 +28,8 @@ server = restify.createServer({
responseTimeFormatter : (durationInMilliseconds: number) => {}
});
server.pre(restify.pre.sanitizePath());
server.on('someEvent', ()=>{});
@@ -98,7 +100,7 @@ server.get( /(.*)/, send);
server.head(/(.*)/, send);
new restify.ConflictError("test");
new restify.InvalidArguementError("message");
new restify.InvalidArgumentError("message");
new restify.RestError("message");
new restify.BadDigestError("message");
new restify.BadMethodError("message");
+127 -70
View File
@@ -3,13 +3,20 @@
// Definitions by: Bret Little <https://github.com/blittle>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface addressInterface {
/// <reference path="../node/node.d.ts" />
declare module "restify" {
import http = require('http');
interface addressInterface {
port: number;
family: string;
address: string;
}
}
interface Request {
interface Request extends http.ServerRequest {
header: (key: string, defaultValue?: string) => any;
accepts: (type: string) => boolean;
is: (type: string) => boolean;
@@ -20,13 +27,15 @@ interface Request {
log: Object;
id: string;
path: () => string;
query: string;
query: any;
secure: boolean;
time: number;
params: any;
}
interface Response {
body?: any; //available when bodyParser plugin is used
}
interface Response extends http.ServerResponse {
header: (key: string, value ?: any) => any;
cache: (type?: any, options?: Object) => any;
status: (code: number) => any;
@@ -39,30 +48,57 @@ interface Response {
headers: Object;
statusCode: number;
id: string;
}
}
interface Server extends http.Server {
use(handler: RequestHandler, ...handlers: RequestHandler[]): any;
use(handler: RequestHandler[], ...handlers: RequestHandler[]): any;
use(handler: RequestHandler, ...handlers: RequestHandler[][]): any;
use(handler: RequestHandler[], ...handlers: RequestHandler[][]): any;
post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
post(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
post(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
patch(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
patch(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
put(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
put(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
del(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
del(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
get(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
get(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[]): any;
head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[]): any;
head(route: any, routeCallBack: RequestHandler, ...routeCallBacks: RequestHandler[][]): any;
head(route: any, routeCallBack: RequestHandler[], ...routeCallBacks: RequestHandler[][]): any;
interface Server {
use: (... handler: any[]) => any;
post: (route: any, routeCallBack: RequestHadler) => any;
patch: (route: any, routeCallBack: RequestHadler) => any;
put: (route: any, routeCallBack: RequestHadler) => any;
del: (route: any, routeCallBack: RequestHadler) => any;
get: (route: any, routeCallBack: RequestHadler) => any;
head: (route: any, routeCallBack: RequestHadler) => any;
on: (event: string, callback: Function) => any;
name: string;
version: string;
log: Object;
acceptable: string[];
url: string;
address: () => addressInterface;
listen: (... args: any[]) => any;
close: (... args: any[]) => any;
pre: (routeCallBack: RequestHadler) => any;
listen(... args: any[]): any;
close(... args: any[]): any;
pre(routeCallBack: RequestHandler): any;
}
}
interface ServerOptions {
interface ServerOptions {
certificate ?: string;
key ?: string;
formatters ?: Object;
@@ -72,9 +108,9 @@ interface ServerOptions {
version ?: string;
responseTimeHeader ?: string;
responseTimeFormatter ?: (durationInMilliseconds: number) => any;
}
}
interface ClientOptions {
interface ClientOptions {
accept?: string;
connectTimeout?: number;
dtrace?: Object;
@@ -86,26 +122,26 @@ interface ClientOptions {
url?: string;
userAgent?: string;
version?: string;
}
}
interface Client {
interface Client {
get: (path: string, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
head: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any;
post: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
put: (path: string, object: any, callback?: (err: any, req: Request, res: Response, obj: any) => any) => any;
del: (path: string, callback?: (err: any, req: Request, res: Response) => any) => any;
basicAuth: (username: string, password: string) => any;
}
}
interface HttpClient extends Client {
interface HttpClient extends Client {
get: (path?: any, callback?: Function) => any;
head: (path?:any, callback?: Function) => any;
post: (opts?: any, callback?: Function) => any;
put: (opts?: any, callback?: Function) => any;
del: (opts?: any, callback?: Function) => any;
}
}
interface ThrottleOptions {
interface ThrottleOptions {
burst?: number;
rate?: number;
ip?: boolean;
@@ -114,50 +150,71 @@ interface ThrottleOptions {
tokensTable?: Object;
maxKeys?: number;
overrides?: Object;
}
}
interface RequestHadler {
(req: Request, res: Response, next: Function): any;
}
interface Next {
(err?: any): any;
}
declare module "restify" {
export function createServer(options?: ServerOptions): Server;
interface RequestHandler {
(req: Request, res: Response, next: Next): any;
}
export function createJsonClient(options?: ClientOptions): Client;
export function createStringClient(options?: ClientOptions): Client;
export function createClient(options?: ClientOptions): HttpClient;
interface CORS {
(cors?: {
origins?: string[];
credentials?: boolean;
headers?: string[];
}): RequestHandler;
origins: string[];
ALLOW_HEADERS: string[];
credentials: boolean;
}
export class ConflictError { constructor(message?: any); }
export class InvalidArguementError { constructor(message?: any); }
export class RestError { constructor(message?: any); }
export class BadDigestError { constructor(message: any); }
export class BadMethodError { constructor(message: any); }
export class BadRequestError { constructor(message: any); }
export class InternalError { constructor(message: any); }
export class InvalidContentError { constructor(message: any); }
export class InvalidCredentialsError { constructor(message: any); }
export class InvalidHeaderError { constructor(message: any); }
export class InvalidVersionError { constructor(message: any); }
export class MissingParameterError { constructor(message: any); }
export class NotAuthorizedError { constructor(message: any); }
export class RequestExpiredError { constructor(message: any); }
export class RequestThrottledError { constructor(message: any); }
export class ResourceNotFoundError { constructor(message: any); }
export class WrongAcceptError { constructor(message: any); }
export function createServer(options?: ServerOptions): Server;
export function acceptParser(parser: any): RequestHadler;
export function authorizationParser(): RequestHadler;
export function dateParser(skew?: number): RequestHadler;
export function queryParser(options?: Object): RequestHadler;
export function urlEncodedBodyParser(options?: Object): RequestHadler[];
export function jsonp(): RequestHadler;
export function gzipResponse(options?: Object): RequestHadler;
export function bodyParser(options?: Object): RequestHadler[];
export function requestLogger(options?: Object): RequestHadler;
export function serveStatic(options?: Object): RequestHadler;
export function throttle(options?: ThrottleOptions): RequestHadler;
export function conditionalRequest(): RequestHadler[];
export function auditLogger(options?: Object): Function;
export function fullResponse(): RequestHadler;
export var defaultResponseHeaders : any;
export function createJsonClient(options?: ClientOptions): Client;
export function createStringClient(options?: ClientOptions): Client;
export function createClient(options?: ClientOptions): HttpClient;
export class ConflictError { constructor(message?: any); }
export class InvalidArgumentError { constructor(message?: any); }
export class RestError { constructor(message?: any); }
export class BadDigestError { constructor(message: any); }
export class BadMethodError { constructor(message: any); }
export class BadRequestError { constructor(message: any); }
export class InternalError { constructor(message: any); }
export class InvalidContentError { constructor(message: any); }
export class InvalidCredentialsError { constructor(message: any); }
export class InvalidHeaderError { constructor(message: any); }
export class InvalidVersionError { constructor(message: any); }
export class MissingParameterError { constructor(message: any); }
export class NotAuthorizedError { constructor(message: any); }
export class RequestExpiredError { constructor(message: any); }
export class RequestThrottledError { constructor(message: any); }
export class ResourceNotFoundError { constructor(message: any); }
export class WrongAcceptError { constructor(message: any); }
export function acceptParser(parser: any): RequestHandler;
export function authorizationParser(): RequestHandler;
export function dateParser(skew?: number): RequestHandler;
export function queryParser(options?: Object): RequestHandler;
export function urlEncodedBodyParser(options?: Object): RequestHandler[];
export function jsonp(): RequestHandler;
export function gzipResponse(options?: Object): RequestHandler;
export function bodyParser(options?: Object): RequestHandler[];
export function requestLogger(options?: Object): RequestHandler;
export function serveStatic(options?: Object): RequestHandler;
export function throttle(options?: ThrottleOptions): RequestHandler;
export function conditionalRequest(): RequestHandler[];
export function auditLogger(options?: Object): Function;
export function fullResponse(): RequestHandler;
export var defaultResponseHeaders : any;
export var CORS: CORS;
export module pre {
export function pause(): RequestHandler;
export function sanitizePath(options?: any): RequestHandler;
export function userAgentConnection(options?: any): RequestHandler;
}
}
+4
View File
@@ -436,3 +436,7 @@ declare module Rx {
export var AsyncSubject: AsyncSubjectStatic;
}
declare module "rx" {
export = Rx
}
+3 -3
View File
@@ -1,14 +1,14 @@
/// <reference path="smoothie.d.ts" />
// Smoothie supports browserify
import Smoothie = require('smoothie');
import smoothie = require('smoothie');
var canvas: HTMLCanvasElement = document.createElement('canvas');
document.body.appendChild(canvas);
var series: Smoothie.TimeSeries = new Smoothie.TimeSeries(),
chart: Smoothie.SmoothieChart = new Smoothie.SmoothieChart({
var series: smoothie.TimeSeries = new smoothie.TimeSeries(),
chart: smoothie.SmoothieChart = new smoothie.SmoothieChart({
grid : {
strokeStyle : '#404040'
},
+171 -53
View File
@@ -1,66 +1,184 @@
// Type definitions for smoothie
// Type definitions for Smoothie Charts 1.21
// Project: https://github.com/joewalnes/smoothie
// Definitions by: Mike H. Hawley <https://github.com/mikehhawley>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions by: Drew Noakes <https://drewnoakes.com>
// Mike H. Hawley <https://github.com/mikehhawley>
// Definitions: https://github.com/borisyankov/DefinitelyTyped/smoothie
// NOTE this reference is here to make the DefinitelyTyped `npm test` suite pass and
// may be removed if you are using this module declaration in isolation from the
// rest of DefinitelyTyped.
/// <reference path="../node/node.d.ts" />
declare module "smoothie" {
export class TimeSeries {
constructor(options?: {
resetBoundsInterval?: number;
resetBounds?: boolean
});
public resetBounds(): void;
public append(timestamp: number, value: number, sumRepeatedTimeStampValues?: boolean): void;
public dropOldData(oldestValidTime: number, maxDataSetLength: number): void;
declare module "smoothie"
{
export interface ITimeSeriesOptions
{
resetBounds?: boolean;
resetBoundsInterval?: number;
}
export class SmoothieChart {
constructor(options?: {
millisPerPixel?: number;
maxValueScale?: number;
interpolation?: string;
scaleSmoothing?: number;
maxDataSetLength?: number;
grid?: {
fillStyle?: string;
strokeStyle?: string;
lineWidth?: number;
sharpLines?: boolean;
millisPerLine?: number;
verticalSections?: number;
borderVisible?: boolean
};
labels?: {
fillStyle?: string;
disabled?: boolean;
fontSize?: number;
fontFamily?: string;
precision?: number
};
horizontalLines?: number[]
});
export interface ITimeSeriesPresentationOptions
{
stokeStyle?: string;
fillStyle?: string;
lineWidth?: number;
}
public addTimeSeries(timeSeries: TimeSeries, options?: {
lineWidth?: number;
strokeStyle?: string
}): void;
export class TimeSeries
{
/**
* Initialises a new <code>TimeSeries</code> with optional data options.
*
* Options are of the form (defaults shown):
*
* <pre>
* {
* resetBounds: true, // enables/disables automatic scaling of the y-axis
* resetBoundsInterval: 3000 // the period between scaling calculations, in millis
* }
* </pre>
*
* Presentation options for TimeSeries are specified as an argument to <code>SmoothieChart.addTimeSeries</code>.
*/
constructor(options?: ITimeSeriesOptions);
public removeTimeSeries(timeSeries: TimeSeries): void;
/**
* Recalculate the min/max values for this <code>TimeSeries</code> object.
*
* This causes the graph to scale itself in the y-axis.
*/
resetBounds(): void;
public streamTo(canvas: HTMLCanvasElement, delayMillis: number): void;
/**
* Adds a new data point to the <code>TimeSeries</code>, preserving chronological order.
*
* @param timestamp the position, in time, of this data point
* @param value the value of this data point
* @param sumRepeatedTimeStampValues if <code>timestamp</code> has an exact match in the series, this flag controls
* whether it is replaced, or the values summed (defaults to false.)
*/
append(timestamp: number, value: number, sumRepeatedTimeStampValues?: boolean): void;
public start(): void;
public stop(): void;
dropOldData(oldestValidTime: number, maxDataSetLength: number): void;
}
public updateValueRange(): void;
public render(canvas?: HTMLCanvasElement, time?: number): void;
export interface IGridOptions
{
/** The background colour of the chart. */
fillStyle?: string;
/** The pixel width of grid lines. */
lineWidth?: number;
/** Colour of grid lines. */
stokeStyle?: string;
/** Distance between vertical grid lines. */
millisPerLine?: number;
/** Controls whether grid lines are 1px sharp, or softened. */
sharpLines?: boolean;
/** Number of vertical sections marked out by horizontal grid lines. */
verticalSections?: number;
/** Whether the grid lines trace the border of the chart or not. */
borderVisible?: boolean;
}
export interface ILabelOptions
{
/** Enables/disables labels showing the min/max values. */
disabled?: boolean;
/** Colour for text of labels. */
fillStyle?: string;
fontSize?: number;
fontFamily?: string;
precision?: number;
}
export interface IRange { min: number; max: number }
export interface IHorizontalLine
{
value?: number;
color?: string;
lineWidth?: number;
}
export interface IChartOptions
{
/** Specify to clamp the lower y-axis to a given value. */
minValue?: number;
/** Specify to clamp the upper y-axis to a given value. */
maxValue?: number;
/** Allows proportional padding to be added above the chart. for 10% padding, specify 1.1. */
maxValueScale?: number;
yRangeFunction?: (range:IRange)=>IRange;
/** Controls the rate at which y-value zoom animation occurs. */
scaleSmoothing?: number;
/** Sets the speed at which the chart pans by. */
millisPerPixel?: number;
maxDataSetLength?: number;
/** One of: 'bezier', 'linear', 'step' */
interpolation?: string;
/** Optional function to format time stamps for bottom of chart. You may use <code>SmoothieChart.timeFormatter</code>, or your own/ */
timestampFormatter?: (date:Date)=>string;
horizontalLines?: IHorizontalLine[];
grid?: IGridOptions;
labels?: ILabelOptions;
}
/**
* Initialises a new <code>SmoothieChart</code>.
*
* Options are optional and may be sparsely populated. Just specify the values you
* need and the rest will be given sensible defaults.
*/
export class SmoothieChart
{
constructor(chartOptions?: IChartOptions);
/**
* Adds a <code>TimeSeries</code> to this chart, with optional presentation options.
*/
addTimeSeries(series: TimeSeries, seriesOptions?: ITimeSeriesPresentationOptions): void;
/**
* Removes the specified <code>TimeSeries</code> from the chart.
*/
removeTimeSeries(series: TimeSeries): void;
/**
* Gets render options for the specified <code>TimeSeries</code>.
*
* As you may use a single <code>TimeSeries</code> in multiple charts with different formatting in each usage,
* these settings are stored in the chart.
*/
getTimeSeriesOptions(timeSeries: TimeSeries): ITimeSeriesPresentationOptions;
/**
* Brings the specified <code>TimeSeries</code> to the top of the chart. It will be rendered last.
*/
bringToFront(timeSeries: TimeSeries): void;
/**
* Instructs the <code>SmoothieChart</code> to start rendering to the provided canvas, with specified delay.
*
* @param canvas the target canvas element
* @param delayMillis an amount of time to wait before a data point is shown. This can prevent the end of the series
* from appearing on screen, with new values flashing into view, at the expense of some latency.
*/
streamTo(canvas: HTMLCanvasElement, delayMillis?: number): void;
/**
* Starts the animation of this chart. Called by <code>streamTo</code>.
*/
start(): void;
/**
* Stops the animation of this chart.
*/
stop(): void;
updateValueRange(): void;
render(canvas?: HTMLCanvasElement, time?: number): void;
}
}
+50 -47
View File
@@ -12,55 +12,58 @@ declare module "socket.io" {
export function listen(server: http.Server, options: any, fn: Function): SocketManager;
export function listen(server: http.Server, fn?: Function): SocketManager;
export function listen(port: Number): SocketManager;
}
interface Socket {
id: string;
json:any;
log: any;
volatile: any;
broadcast: any;
in(room: string): Socket;
to(room: string): Socket;
join(name: string, fn: Function): Socket;
leave(name: string, fn: Function): Socket;
set(key: string, value: any, fn: Function): Socket;
get(key: string, fn: Function): Socket;
has(key: string, fn: Function): Socket;
del(key: string, fn: Function): Socket;
disconnect(): Socket;
send(data: any, fn: Function): Socket;
emit(ev: any, ...data:any[]): Socket;
on(ns: string, fn: Function): Socket;
}
interface SocketNamespace {
clients(room: string): Socket[];
log: any;
store: any;
json: any;
volatile: any;
in(room: string): SocketNamespace;
on(evt: string, fn: (socket: Socket) => void): SocketNamespace;
to(room: string): SocketNamespace;
except(id: any): SocketNamespace;
send(data: any): any;
emit(ev: any, ...data:any[]): Socket;
socket(sid: any, readable: boolean): Socket;
authorization(fn: Function);
}
interface Socket {
id: string;
json:any;
log: any;
volatile: any;
broadcast: any;
in(room: string): Socket;
to(room: string): Socket;
join(name: string, fn: Function): Socket;
leave(name: string, fn: Function): Socket;
set(key: string, value: any, fn: Function): Socket;
get(key: string, fn: Function): Socket;
has(key: string, fn: Function): Socket;
del(key: string, fn: Function): Socket;
disconnect(): Socket;
send(data: any, fn: Function): Socket;
emit(ev: any, ...data:any[]): Socket;
on(ns: string, fn: Function): Socket;
}
interface SocketNamespace {
clients(room: string): Socket[];
log: any;
store: any;
json: any;
volatile: any;
in(room: string): SocketNamespace;
on(evt: string, fn: (socket: Socket) => void): SocketNamespace;
to(room: string): SocketNamespace;
except(id: any): SocketNamespace;
send(data: any): any;
emit(ev: any, ...data:any[]): Socket;
socket(sid: any, readable: boolean): Socket;
authorization(fn: Function): SocketNamespace;
}
interface SocketManager {
get(key: any): any;
set(key: any, value: any): SocketManager;
enable(key: any): SocketManager;
disable(key: any): SocketManager;
enabled(key: any): boolean;
disabled(key: any): boolean;
configure(env: string, fn: Function): SocketManager;
configure(fn: Function): SocketManager;
of(nsp: string): SocketNamespace;
on(ns: string, fn: Function): SocketManager;
sockets: SocketNamespace;
}
interface SocketManager {
get(key: any): any;
set(key: any, value: any): SocketManager;
enable(key: any): SocketManager;
disable(key: any): SocketManager;
enabled(key: any): boolean;
disabled(key: any): boolean;
configure(env: string, fn: Function): SocketManager;
configure(fn: Function): SocketManager;
of(nsp: string): SocketNamespace;
on(ns: string, fn: Function): SocketManager;
sockets: SocketNamespace;
}
-1
View File
@@ -1 +0,0 @@
""
+4
View File
@@ -79,3 +79,7 @@ interface StateMachine {
}
declare var StateMachine: StateMachineStatic;
declare module "state-machine" {
export = StateMachineStatic;
}
+4 -4
View File
@@ -1,5 +1,5 @@
/// <reference path='svgjs.d.ts' />
/// <reference path='../jquery/jquery.d.ts' />
/// <reference path='svgjs.d.ts' />
// create svg drawing paper
@@ -46,7 +46,7 @@ function renderSVG(data:string) {
var container = SVG(div) // this creates an SVG tag inside
container.svg(data) // this creates an SVG inside the SVG
var $inner = $(div).find("svg svg")
var inner:svgjs.Element = $inner.get(0).instance
var inner:svgjs.Element = (<svgjs.LinkedHTMLElement>$inner.get(0)).instance
// Copy in the important attributes
root.attr('x', inner.attr('x'))
@@ -61,8 +61,8 @@ function renderSVG(data:string) {
// Activate and Label all child paths
var index = 0
el.find("rect, path, circle, ellipse").each(function() {
var $path = $(this)
var path = $path.get(0).instance
var $path: JQuery = $(this)
var path = (<svgjs.LinkedHTMLElement>$path.get(0)).instance
var uniqueId = "path"+index++
path.attr({"path-id": uniqueId})
})
+3 -1
View File
@@ -88,6 +88,8 @@ declare module svgjs {
move(x:number, y:number, anchor?:boolean):Element;
x(x:number, anchor?:boolean):Element;
y(y:number, anchor?:boolean):Element;
x(): number;
y(): number;
center(x:number, y:number, anchor?:boolean):Element;
cx(x:number, anchor?:boolean):Element;
@@ -267,4 +269,4 @@ declare module svgjs {
e?: number;
f?: number;
}
}
}
-45
View File
@@ -13896,51 +13896,6 @@ declare var ballPosition: THREE.Vector3;
new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true, transparent: true, opacity: 0.1 } )
];
// tetrahedron
var points = [
new THREE.Vector3( 100, 0, 0 ),
new THREE.Vector3( 0, 100, 0 ),
new THREE.Vector3( 0, 0, 100 ),
new THREE.Vector3( 0, 0, 0 )
];
object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );
object.position.set( 0, 0, 0 );
scene.add( object );
// cube
var points = [
new THREE.Vector3( 50, 50, 50 ),
new THREE.Vector3( 50, 50, -50 ),
new THREE.Vector3( -50, 50, -50 ),
new THREE.Vector3( -50, 50, 50 ),
new THREE.Vector3( 50, -50, 50 ),
new THREE.Vector3( 50, -50, -50 ),
new THREE.Vector3( -50, -50, -50 ),
new THREE.Vector3( -50, -50, 50 ),
];
object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );
object.position.set( -200, 0, -200 );
scene.add( object );
// random convex
points = [];
for ( var i = 0; i < 30; i ++ ) {
points.push( randomPointInSphere( 50 ) );
}
object = THREE.SceneUtils.createMultiMaterialObject( new THREE.ConvexGeometry( points ), materials );
object.position.set( -200, 0, 200 );
scene.add( object );
object = new THREE.AxisHelper( 50 );
object.position.set( 200, 0, -200 );
scene.add( object );
+194 -59
View File
@@ -171,6 +171,7 @@ declare module THREE {
* @param vector point to look at
*/
lookAt(vector: Vector3): void;
clone(camera?: Camera): Camera;
}
/**
@@ -227,6 +228,8 @@ declare module THREE {
* Updates the camera projection matrix. Must be called after change of parameters.
*/
updateProjectionMatrix(): void;
clone(): OrthographicCamera;
}
/**
@@ -318,6 +321,7 @@ declare module THREE {
* Updates the camera projection matrix. Must be called after change of parameters.
*/
updateProjectionMatrix(): void;
clone(): PerspectiveCamera;
}
// Core ///////////////////////////////////////////////////////////////////////////////////////////////
@@ -383,6 +387,8 @@ declare module THREE {
morphTargets: any[];
hasTangents: boolean;
addAttribute(name: string, type: Function, numItems: number, itemSize: number): any;
/**
* Bakes matrix transform directly into vertex coordinates.
*/
@@ -419,6 +425,8 @@ declare module THREE {
dispose(): void;
normalizeNormals(): void;
clone(): BufferGeometry;
}
/**
@@ -450,8 +458,8 @@ declare module THREE {
oldTime: number;
/**
* When the clock is running, It holds the time elapsed btween the start of the clock to the previous update.
* This counted from the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
* When the clock is running, It holds the time elapsed between the start of the clock to the previous update.
* This parameter is in seconds of three decimal places.
*/
elapsedTime: number;
@@ -471,12 +479,12 @@ declare module THREE {
stop(): void;
/**
* Get milliseconds passed since the clock started.
* Get the seconds passed since the clock started.
*/
getElapsedTime(): number;
/**
* Get the milliseconds passed since the last call to this method.
* Get the seconds passed since the last call to this method.
*/
getDelta(): number;
}
@@ -914,6 +922,13 @@ declare module THREE {
computeLineDistances(): void;
}
export class Geometry2 extends BufferGeometry {
vertices: Float32Array;
normals: Float32Array;
uvs: Float32Array;
}
/**
* Base class for scene graph objects
*/
@@ -1108,11 +1123,6 @@ declare module THREE {
clone(object?: Object3D, recursive?: boolean): Object3D;
/**
* Creates a new clone of this object and all descendants.
*/
clone(object?: Object3D): Object3D;
/**
* Searches through the object's children and returns the first with a matching name, optionally recursive.
* @param name String to match to the children's Object3d.name property.
@@ -1198,6 +1208,8 @@ declare module THREE {
export class Light extends Object3D {
constructor(hex?: number);
color: Color;
clone(light?: Light): Light;
}
/**
@@ -1215,6 +1227,8 @@ declare module THREE {
* @param hex Numeric value of the RGB component of the color.
*/
constructor(hex?: number);
clone(): AmbientLight;
}
export class AreaLight extends Light{
@@ -1405,6 +1419,8 @@ declare module THREE {
* Default null.
*/
shadowMatrix: Matrix4;
clone(): DirectionalLight;
}
export class HemisphereLight extends Light {
@@ -1413,6 +1429,8 @@ declare module THREE {
position: Vector3;
groundColor: Color;
intensity: number;
clone(): HemisphereLight;
}
/**
@@ -1443,6 +1461,8 @@ declare module THREE {
* Default 0.0.
*/
distance: number;
clone(): PointLight;
}
/**
@@ -1563,6 +1583,8 @@ declare module THREE {
shadowMapSize: Vector2;
shadowCamera: Camera;
shadowMap: RenderTarget;
clone(): SpotLight;
}
// Loaders //////////////////////////////////////////////////////////////////////////////////
@@ -1630,19 +1652,36 @@ declare module THREE {
addStatusElement(): HTMLElement;
}
export class BufferGeometryLoader {
constructor(manager?: LoadingManager);
load(url: string, onLoad: (bufferGeometry: BufferGeometry) => void): void;
setCrossOrigin(crossOrigin: string): void;
parse(json: any): BufferGeometry;
}
export class Geometry2Loader {
constructor(manager?: LoadingManager);
load(url: string, onLoad: (geometry2: Geometry2) => void): void;
setCrossOrigin(crossOrigin: string): void;
parse(json: any): Geometry2;
}
/**
* A loader for loading an image.
* Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object.
*/
export class ImageLoader extends EventDispatcher {
constructor();
export class ImageLoader {
constructor(manager?: LoadingManager);
crossOrigin: string;
/**
* Begin loading from url
* @param url
*/
load(url: string, onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement;
load(url: string, onLoad?: (image: HTMLImageElement) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): HTMLImageElement;
setCrossOrigin(crossOrigin: string): void;
}
@@ -1669,7 +1708,7 @@ declare module THREE {
* Handles and keeps track of loaded and pending data.
*/
export class LoadingManager {
constructor(onLoad?: (event: any) => void, onProgress?: (event: any) => void, onError?: (event: any) => void);
constructor(onLoad?: () => void, onProgress?: (url: string, loaded: number, total: number) => void, onError?: () => void);
/**
* Will be called when load starts.
@@ -1687,13 +1726,32 @@ declare module THREE {
* Will be called when each element in the scene completes loading.
* The default is a function with empty body.
*/
onError: (event: () => void) => void;
onError: () => void;
itemStart(url: string): void;
itemEnd(url: string): void;
}
export class MaterialLoader extends EventDispatcher {
constructor(manager?: LoadingManager);
load(url: string, onLoad: (material: Material) => void): void;
setCrossOrigin(crossOrigin: string): void;
parse(json: any): Material;
}
export class ObjectLoader extends EventDispatcher {
constructor(manager?: LoadingManager);
load(url: string, onLoad: (object: Object3D) => void): void;
setCrossOrigin(crossOrigin: string): void;
parse<T extends Object3D>(json: any): T;
parseGeometries(json: any): any[]; // Array of BufferGeometry or Geometry or Geometry2.
parseMaterials(json: any): Material[]; // Array of Classes that inherits from Matrial.
parseObject<T extends Object3D>(data: any, geometries: any[], materials: Material[]): T;
}
interface SceneLoaderResult{
scene: Scene;
geometries: {[id:string]:Geometry;};
@@ -1739,7 +1797,6 @@ declare module THREE {
*/
onLoadComplete: () => void;
/**
* Will be called when load completes.
* The default is a function with empty body.
@@ -1751,17 +1808,18 @@ declare module THREE {
* The default is a function with empty body.
*/
callbackProgress: (progress: SceneLoaderProgress, result: SceneLoaderResult) => void;
hierarchyHandlerMap: any;
geometryHandlerMap: any;
hierarchyHandlers: any;
geometryHandlers: any;
/**
* @param url
* @param callbackFinished This function will be called with the loaded model as an instance of scene when the load is completed.
*/
load(url: string, callbackFinished: (scene: Scene) => void ): void;
addHierarchyHandler(typeID: string, loaderClass: Object): void;
load(url: string, onLoad: (result: SceneLoaderResult) => void): void;
setCrossOrigin(crossOrigin: string): void;
addHierarchyHandler(typeID: string, loaderClass: any): void;
parse(json: any, callbackFinished: (result: SceneLoaderResult) => void, url: string): void;
addGeometryHandler(typeID: string, loaderClass: Object): void;
addGeometryHandler(typeID: string, loaderClass: any): void;
}
/**
@@ -1769,14 +1827,28 @@ declare module THREE {
* Unlike other loaders, this one emits events instead of using predefined callbacks. So if you're interested in getting notified when things happen, you need to add listeners to the object.
*/
export class TextureLoader extends EventDispatcher {
constructor();
constructor(manager?: LoadingManager);
crossOrigin: string;
/**
* Begin loading from url
*
* @param url
*/
load(url: string): void;
load(url: string, onLoad: (texture: Texture) => void): void;
setCrossOrigin(crossOrigin: string): void;
}
export class XHRLoader extends EventDispatcher {
constructor(manager?: LoadingManager);
crossOrigin: string;
/**
* Begin loading from url
*
* @param url
*/
constructor(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void);
load(onLoad?: (responseText: string) => void, onProgress?: (event: any) => void, onError?: (event: any) => void): void;
setCrossOrigin(crossOrigin: string): void;
}
// Materials //////////////////////////////////////////////////////////////////////////////////
@@ -1881,7 +1953,7 @@ declare module THREE {
*/
needsUpdate: boolean;
clone(): Material;
clone(material?:Material): Material;
dispose(): void;
setValues(values: Object): void;
@@ -2325,12 +2397,10 @@ declare module THREE {
* @see <a href="https://github.com/mrdoob/three.js/blob/master/src/math/Color.js">src/math/Color.js</a>
*/
export class Color {
constructor(hex?: string);
/**
* @param hex initial color in hexadecimal
*/
constructor(hex?: number);
constructor(color?: Color);
constructor(color?: string);
constructor(color?: number);
constructor(r: number, g: number, b: number);
/**
* Red channel value between 0 and 1. Default is 1.
@@ -2347,6 +2417,10 @@ declare module THREE {
*/
b: number;
set(color: Color): Color;
set(color: number): Color;
set(color: string): Color;
/**
* Copies given color.
* @param color Color to copy.
@@ -2433,9 +2507,6 @@ declare module THREE {
* Clones this color.
*/
clone(): Color;
set(value: number): void;
set(value: string): void;
}
export class Euler {
@@ -3851,6 +3922,8 @@ declare module THREE {
render(scene: Scene, camera: Camera): void;
clear(): void;
setClearColor(color: Color, opacity?: number): void;
setClearColor(color: string, opacity?: number): void;
setClearColor(color: number, opacity?: number): void;
setFaceCulling(): void;
supportsVertexTextures(): void;
setSize(width: number, height: number, updateStyle?: boolean): void;
@@ -4068,7 +4141,7 @@ declare module THREE {
/**
* Resizes the output canvas to (width, height), and also sets the viewport to fit that size, starting in (0, 0).
*/
setSize(width: number, height: number): void;
setSize(width: number, height: number, updateStyle?: boolean): void;
/**
* Sets the viewport to render from (x, y) to (x + width, y + height).
@@ -4088,7 +4161,9 @@ declare module THREE {
/**
* Sets the clear color, using color for the color and alpha for the opacity.
*/
setClearColor(color: Color, alpha: number): void;
setClearColor(color: Color, alpha?: number): void;
setClearColor(color: string, alpha?: number): void;
setClearColor(color: number, alpha?: number): void;
/**
* Returns a THREE.Color instance with the current clear color.
@@ -4249,7 +4324,7 @@ declare module THREE {
id: number;
}
export class RenderableParticle {
export class RenderableSprite {
constructor();
scale: Vector2;
@@ -4663,22 +4738,18 @@ declare module THREE {
addToUpdate(animation: Animation): void;
};
export class AnimationMorphTarget {
constructor(root: Bone, data: any);
root: Bone;
data: Object;
hierarchy: KeyFrames[];
currentTime: number;
timeScale: number;
isPlaying: boolean;
isPaused: boolean;
loop: boolean;
influence: number;
export class MorphAnimation {
constructor(mesh: Mesh);
play(loop?: boolean, startTimeMS?: number): void;
mesh: Mesh;
frames: number;
currentTime: number;
duration: number;
loop: boolean;
isPlaying: boolean;
play(): void;
pause(): void;
stop(): void;
update(deltaTimeMS: number): void;
}
@@ -4963,15 +5034,6 @@ declare module THREE {
// Extras / Geomerties /////////////////////////////////////////////////////////////////////
export class CircleGeometry extends Geometry {
constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number);
}
export class ConvexGeometry extends Geometry {
constructor(vertices: Vector3[]);
}
/**
* CubeGeometry is the quadrilateral primitive geometry class. It is typically used for creating a cube or irregular quadrilateral of the dimensions provided within the (optional) 'width', 'height', & 'depth' constructor arguments.
*/
@@ -4987,6 +5049,22 @@ declare module THREE {
constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number);
}
export class BoxGeometry2 extends Geometry2 {
/**
* @param width Width of the sides on the X axis.
* @param height Height of the sides on the Y axis.
* @param depth Depth of the sides on the Z axis.
* @param widthSegments Number of segmented faces along the width of the sides.
* @param heightSegments Number of segmented faces along the height of the sides.
* @param depthSegments Number of segmented faces along the depth of the sides.
*/
constructor(width: number, height: number, depth: number, widthSegments?: number, heightSegments?: number, depthSegments?: number);
}
export class CircleGeometry extends Geometry {
constructor(radius?: number, segments?: number, thetaStart?: number, thetaLength?: number);
}
export class CubeGeometry extends BoxGeometry {
}
@@ -5030,6 +5108,10 @@ declare module THREE {
constructor(width: number, height: number, widthSegments?: number, heightSegments?: number);
}
export class PlaneGeometry2 extends Geometry2 {
constructor(width: number, height: number, widthSegments?: number, heightSegments?: number);
}
export class PolyhedronGeometry extends Geometry {
constructor(vertices: Vector3[], faces: Face[], radius?: number, detail?: number);
}
@@ -5128,10 +5210,20 @@ declare module THREE {
constructor(object: Object3D, hex: number);
object: Object3D;
box: Box3;
vertices: Vector3[];
update(): void;
}
export class BoxHelper extends Line {
constructor(object: Object3D);
object: Object3D;
box: Box3;
update(object?: Object3D): void;
}
export class CameraHelper extends Line {
constructor(camera: Camera);
@@ -5151,6 +5243,23 @@ declare module THREE {
update(): void;
}
export class EdgesHelper extends Line {
constructor(object: Object3D, hex?: number);
matrixAutoUpdate: boolean;
matrixWorld: Matrix4;
}
export class FaceNormalsHelper extends Line {
constructor(object: Object3D, size?: number, hex?: number, linewidth?: number);
size: number;
matrixAutoUpdate: boolean;
normalMatrix: Matrix3;
update(object?: Object3D): void;
}
export class GridHelper extends Line {
constructor(size: number, step: number);
@@ -5184,6 +5293,32 @@ declare module THREE {
update(): void;
}
export class VertexNormalsHelper extends Line {
constructor(object: Object3D, size?: number, hex?: number, linewidth?: number);
size: number;
matrixAutoUpdate: boolean;
normalMatrix: Matrix3;
update(object?: Object3D): void;
}
export class VertexTangentsHelper extends Line {
constructor(object: Object3D, size?: number, hex?: number, linewidth?: number);
size: number;
matrixAutoUpdate: boolean;
update(object?: Object3D): void;
}
export class WireframeHelper extends Line {
constructor(object: Object3D, hex?: number);
matrixAutoUpdate: boolean;
matrixWorld: Matrix4;
}
// Extras / Objects /////////////////////////////////////////////////////////////////////
export class ImmediateRenderObject extends Object3D {
+19
View File
@@ -0,0 +1,19 @@
/// <reference path="urlrouter.d.ts" />
import http = require("http");
import urlrouter = require("urlrouter");
var result = urlrouter((app) => {
app.get('/', (req, res, next) => {
res.end('hello urlrouter');
});
app.get('/user/:id([0-9]+)', (req, res, next) => {
res.end('hello user ' + req.params.id);
});
});
var req: urlrouter.ServerRequest;
var res: urlrouter.ServerResponse;
function next() { }
result(req, res, next);
+69
View File
@@ -0,0 +1,69 @@
// Type definitions for urlrouter
// Project: https://github.com/fengmk2/urlrouter
// Definitions by: soywiz <https://github.com/soywiz>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "_UrlRouterInternal" {
import http = require("http");
export interface ServerRequest extends http.ServerRequest {
params: any;
}
export interface ServerResponse extends http.ServerResponse {
}
export interface App {
// https://github.com/visionmedia/node-methods/blob/master/index.js
get(urlpattern: string, handler: HttpHandler): void;
post(urlpattern: string, handler: HttpHandler): void;
put(urlpattern: string, handler: HttpHandler): void;
head(urlpattern: string, handler: HttpHandler): void;
delete(urlpattern: string, handler: HttpHandler): void;
options(urlpattern: string, handler: HttpHandler): void;
trace(urlpattern: string, handler: HttpHandler): void;
copy(urlpattern: string, handler: HttpHandler): void;
lock(urlpattern: string, handler: HttpHandler): void;
mkcol(urlpattern: string, handler: HttpHandler): void;
move(urlpattern: string, handler: HttpHandler): void;
propfind(urlpattern: string, handler: HttpHandler): void;
proppatch(urlpattern: string, handler: HttpHandler): void;
unlock(urlpattern: string, handler: HttpHandler): void;
report(urlpattern: string, handler: HttpHandler): void;
mkactivity(urlpattern: string, handler: HttpHandler): void;
checkout(urlpattern: string, handler: HttpHandler): void;
merge(urlpattern: string, handler: HttpHandler): void;
"m-search"(urlpattern: string, handler: HttpHandler): void;
notify(urlpattern: string, handler: HttpHandler): void;
subscribe(urlpattern: string, handler: HttpHandler): void;
unsubscribe(urlpattern: string, handler: HttpHandler): void;
patch(urlpattern: string, handler: HttpHandler): void;
search(urlpattern: string, handler: HttpHandler): void;
all(urlpattern: string, handler: HttpHandler): void;
redirect(urlpattern: string, to: string): void;
}
export interface Options {
paramsName?: string;
pageNotFound?: (req: ServerRequest, res: ServerResponse) => void;
errorHandler?: (err:Error, req: ServerRequest, res: ServerResponse) => void;
}
export function _UrlRouterfunc(handler: (app: App) => void, options?: any): void;
export interface HttpHandler {
(req: ServerRequest, res: ServerResponse, next?: () => void): void;
}
}
declare module "urlrouter" {
import _UrlRouterInternal = require("_UrlRouterInternal");
function _UrlRouterInternal(handler: (app: _UrlRouterInternal.App) => void): _UrlRouterInternal.HttpHandler;
export = _UrlRouterInternal;
}
+225 -78
View File
@@ -4,14 +4,11 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Vega {
export interface VG {
parse: Parse;
}
export interface Parse {
spec(url: string, callback: (chart: (args: ViewArgs) => View) => void): void;
spec(spec: Spec, callback: (chart: (args: ViewArgs) => View) => void): void;
data(dataSet: Vega.Data[], callback: () => void): void;
data(dataSet: Data[], callback: () => void): void;
// TODO all the other stuff
}
@@ -39,14 +36,20 @@ declare module Vega {
renderer(r: string): View;
data(): any;
data(d: any): View;
data(): Runtime.DataSets;
data(d: any/*TODO*/): View;
initialize(i: any): View;
initialize(selector: string): View;
initialize(node: Element): View;
render(r?: any[]): View;
update(options?: UpdateOptions): View;
model(): Vega.Model;
defs(): Defs;
defs(defs: Defs): View;
}
export interface Padding {
@@ -65,6 +68,123 @@ declare module Vega {
ease?: string;
}
export interface Bounds {
x1: number;
y1: number;
x2: number;
y2: number;
clear(): Bounds;
set(x1: number, y1: number, x2: number, y2: number): Bounds;
add(x: number, y: number): Bounds;
expand(d: number): Bounds;
round(): Bounds;
translate(dx: number, dy: number): Bounds;
rotate(angle: number, x: number, y: number): Bounds;
union(b: Bounds): Bounds;
encloses(b: Bounds): boolean;
intersects(b: Bounds): boolean;
contains(x: number, y: number): boolean;
width(): number;
height(): number;
}
export interface Model {
defs(): Defs;
defs(defs: Defs): Model;
data(): Runtime.DataSets;
data(data: Runtime.DataSets): Model;
ingest(name: string, tx: any/*TODO*/, input: any/*TODO*/): void;
dependencies(name: string, tx: any/*TODO*/): void;
width(w: number): Model;
height(h: number): Model;
scene(): Node;
scene(node: Node): Model;
build(): Model;
encode(trans?: any/*TODO*/, request?: string, item?: any): Model;
reset(): Model;
}
export module Runtime {
export interface DataSets {
[name: string]: Datum[];
}
export interface Datum {
[key: string]: any
}
export interface Marks {
type: string;
width: number;
height: number;
scales: Scale[];
axes: Axis[];
legends: Legend[];
marks: Mark[];
}
export interface Mark {
// Stuff from Spec.Mark
type: string;
name?: string;
description?: string;
from?: Mark.From;
key?: string;
delay?: Properties;
// Runtime PropertySets
properties?: PropertySets;
}
export interface PropertySets {
enter?: Properties;
exit?: Properties;
update?: Properties;
hover?: Properties;
}
export interface Properties {
(item: Node, group: Node, trans: any/*TODO*/): void;
}
}
export interface Node {
def: Runtime.Mark;
marktype: string;
interactive: boolean;
items: Node[];
bounds: Bounds;
// mark item members
hasPropertySet(name: string): boolean;
cousin(offset: number, index: number): Node;
sibling(offset: number): Node;
remove(): Node;
touch(): void;
// group members
scales?: {[name: string]: any};
axisItems?: Node[];
}
export interface Defs {
width: number;
height: number;
viewport?: number[];
padding: any;
marks: Runtime.Marks;
data: Data[];
}
export interface Spec {
/**
* A unique name for the visualization specification.
@@ -227,12 +347,12 @@ declare module Vega {
export module Axis {
export interface Properties {
majorTicks?: Mark.PropertySet;
minorTicks?: Mark.PropertySet;
grid?: Mark.PropertySet;
labels?: Mark.PropertySet;
title?: Mark.PropertySet;
axis?: Mark.PropertySet;
majorTicks?: PropertySet;
minorTicks?: PropertySet;
grid?: PropertySet;
labels?: PropertySet;
title?: PropertySet;
axis?: PropertySet;
}
}
@@ -246,9 +366,9 @@ declare module Vega {
name?: string;
description?: string;
from?: Mark.From;
properties?: Mark.PropertySets;
properties?: PropertySets;
key?: string;
delay?: Mark.ValueRef;
delay?: ValueRef;
}
export module Mark {
@@ -257,80 +377,107 @@ declare module Vega {
data?: string;
transform?: Data.Transform[];
}
}
export interface PropertySets {
// TODO docs
enter?: PropertySet;
exit?: PropertySet;
update?: PropertySet;
hover?: PropertySet;
}
export interface PropertySets {
// TODO docs
enter?: PropertySet;
exit?: PropertySet;
update?: PropertySet;
hover?: PropertySet;
}
export interface PropertySet {
// TODO docs
export interface PropertySet {
// TODO docs
// -- Shared visual properties
x?: ValueRef;
x2?: ValueRef;
width?: ValueRef;
y?: ValueRef;
y2?: ValueRef;
height?: ValueRef;
opacity?: ValueRef;
fill?: ValueRef;
fillOpacity?: ValueRef;
stroke?: ValueRef;
strokeWidth?: ValueRef;
strokeOpacity?: ValueRef;
strokeDash?: ValueRef;
strokeDashOffset?: ValueRef;
// -- Shared visual properties
x?: ValueRef;
x2?: ValueRef;
width?: ValueRef;
y?: ValueRef;
y2?: ValueRef;
height?: ValueRef;
opacity?: ValueRef;
fill?: ValueRef;
fillOpacity?: ValueRef;
stroke?: ValueRef;
strokeWidth?: ValueRef;
strokeOpacity?: ValueRef;
strokeDash?: ValueRef;
strokeDashOffset?: ValueRef;
// -- symbol
size?: ValueRef;
shape?: ValueRef;
// -- symbol
size?: ValueRef;
shape?: ValueRef;
// -- path
path?: ValueRef;
// -- path
path?: ValueRef;
// -- arc
innerRadius?: ValueRef;
outerRadius?: ValueRef;
startAngle?: ValueRef;
endAngle?: ValueRef;
// -- arc
innerRadius?: ValueRef;
outerRadius?: ValueRef;
startAngle?: ValueRef;
endAngle?: ValueRef;
// -- area / line
interpolate?: ValueRef;
tension?: ValueRef;
// -- area / line
interpolate?: ValueRef;
tension?: ValueRef;
// -- image / text
align?: ValueRef;
baseline?: ValueRef;
// -- image / text
align?: ValueRef;
baseline?: ValueRef;
// -- image
url?: ValueRef;
// -- image
url?: ValueRef;
// -- text
text?: ValueRef;
dx?: ValueRef;
dy?: ValueRef;
angle?: ValueRef;
font?: ValueRef;
fontSize?: ValueRef;
fontWeight?: ValueRef;
fontStyle?: ValueRef;
}
// -- text
text?: ValueRef;
dx?: ValueRef;
dy?: ValueRef;
angle?: ValueRef;
font?: ValueRef;
fontSize?: ValueRef;
fontWeight?: ValueRef;
fontStyle?: ValueRef;
}
export interface ValueRef {
// TODO docs
value?: any;
field?: any;
group?: any;
scale?: any;
mult?: number;
offset?: number;
band?: boolean;
}
export interface ValueRef {
// TODO docs
value?: any;
field?: any;
group?: any;
scale?: any;
mult?: number;
offset?: number;
band?: boolean;
}
}
declare var vg: Vega.VG;
declare module vg {
export var parse: Vega.Parse;
export module scene {
export function item(mark: Vega.Node): Vega.Node;
}
export class Bounds implements Vega.Bounds {
x1: number;
y1: number;
x2: number;
y2: number;
clear(): Bounds;
set(x1: number, y1: number, x2: number, y2: number): Bounds;
add(x: number, y: number): Bounds;
expand(d: number): Bounds;
round(): Bounds;
translate(dx: number, dy: number): Bounds;
rotate(angle: number, x: number, y: number): Bounds;
union(b: Bounds): Bounds;
encloses(b: Bounds): boolean;
intersects(b: Bounds): boolean;
contains(x: number, y: number): boolean;
width(): number;
height(): number;
}
// TODO: classes for View, Model, etc.
}
+50 -13
View File
@@ -2,40 +2,77 @@
// Project: https://github.com/jonrohan/ZeroClipboard
// Definitions by: Eric J. Smith <https://github.com/ejsmith>
// Definitions by: Blake Niemyjski <https://github.com/niemyjski>
// Definitions by: György Balássy <https://github.com/balassy>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class ZeroClipboard {
constructor(elements?: any, options?: ZeroClipboardOptions);
setCurrent(element: any): void;
activate(element: any): void;
setText(newText: string): void;
setTitle(newTitle: string): void;
title(newTitle: string): void;
setSize(width: number, height: number): void;
setHandCursor(enabled: boolean): void;
forceHandCursor(enabled: boolean): void;
version: string;
moviePath: string;
trustedDomains: any;
text: string;
hoverClass: string;
activeClass: string;
resetBridge(): void;
deactivate(): void;
ready: boolean;
reposition(): void; // returns false in some scenarios, but never returns true
on(eventName: string, func: Function): void;
addEventListener(eventName: string, func: Function): void;
off(eventName: string, func: Function): void;
removeEventListener(eventName: string, func: Function): void;
receiveEvent(eventName: string, args: any): void;
glue(elements: any): void;
unglue(elements: any): void;
static setDefaults(options: ZeroClipboardOptions): void;
clip(elements: any): void;
unclip(elements: any): void;
static config(options: ZeroClipboardOptions): void;
static destroy(): void;
static detectFlashSupport(): boolean;
static dispatch(eventName: string, args: any): void;
static emit(eventName: string, args: any): void;
}
interface ZeroClipboardOptions {
/** Setting this to false would allow users to handle calling ZeroClipboard.activate(...); themselves instead of relying on our per-element mouseover handler */
autoActivate?: boolean;
/** Include a "nocache" query parameter on requests for the SWF. */
cacheBust?: boolean;
/** Debug enabled: send console messages with deprecation warnings, etc. */
debug?: boolean;
/** Forcibly set the hand cursor ("pointer") for all clipped elements. */
forceHandCursor?: boolean;
/** URL to the movie. NOTE: For versions >= v1.3.x and < v2.x, you must use swfPath by setting moviePath! */
moviePath?: string;
/** URL to the movie, relative to the page. NOTE: For versions >= v1.3.x and < v2.x, you must use swfPath by setting moviePath! */
swfPath?: string;
/** Forcibly set the hand cursor ("pointer") for all clipped elements. */
trustedDomains?: any;
hoverClass?: string;
/** Sets the title of the div encapsulating the Flash object. */
title?: string;
/** The z-index used by the Flash object. */
zIndex?: number;
/** DEPRECATED. The class used to indicate that a clipped element is active (is being clicked). */
activeClass?: string;
/** DEPRECATED. The class used to indicate that a clipped element is being hovered over. */
hoverClass?: string;
/** DEPRECATED. SWF outbound scripting policy. Possible values: "never", "sameDomain", "always". */
allowScriptAccess?: string;
/** DEPRECATED, use trustedDomains instead! SWF inbound scripting policy: page origins that the SWF should trust. (single string or array of strings. */
trustedOrigins?: any;
/** DEPRECATED, use cacheBust instead! Include a "nocache" query parameter on requests for the SWF. */
useNoCache?: boolean;
}
// Support AMD.
declare module "zeroclipboard" { export = ZeroClipboard; }