Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Dave Allen
2015-01-22 15:30:07 -08:00
124 changed files with 7525 additions and 1969 deletions
+9 -1
View File
@@ -87,6 +87,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](chai-as-promised/chai-as-promised.d.ts) [chai-as-promised](https://github.com/domenic/chai-as-promised) by [jt000](https://github.com/jt000)
* [:link:](chai-datetime/chai-datetime.d.ts) [chai-datetime](https://github.com/gaslight/chai-datetime.git) by [Cliff Burger](https://github.com/cliffburger)
* [:link:](chai-fuzzy/chai-fuzzy.d.ts) [chai-fuzzy](http://chaijs.com/plugins/chai-fuzzy) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](chai-http/chai-http.d.ts) [chai-http](https://github.com/chaijs/chai-http) by [Wim Looman](https://github.com/Nemo157)
* [:link:](chai-jquery/chai-jquery.d.ts) [chai-jquery](https://github.com/chaijs/chai-jquery) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid)
* [:link:](chalk/chalk.d.ts) [chalk](https://github.com/sindresorhus/chalk) by [Diullei Gomes](https://github.com/Diullei), [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](change-case/change-case.d.ts) [change-case](https://github.com/blakeembrey/change-case) by [Asana](https://asana.com)
@@ -134,6 +135,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](devextreme/dx.devextreme.d.ts) [DevExtreme](http://js.devexpress.com) by [DevExpress Inc.](http://devexpress.com)
* [:link:](dhtmlxgantt/dhtmlxgantt.d.ts) [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) by [Maksim Kozhukh](http://github.com/mkozhukh)
* [:link:](dhtmlxscheduler/dhtmlxscheduler.d.ts) [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) by [Maksim Kozhukh](http://github.com/mkozhukh)
* [:link:](di-lite/di-lite.d.ts) [di-lite](https://github.com/NickQiZhu/di.js) by [Timothy Morris](https://github.com/dcrusader)
* [:link:](diff/diff.d.ts) [diff](https://github.com/kpdecker/jsdiff) by [vvakame](https://github.com/vvakame)
* [:link:](docCookies/docCookies.d.ts) [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) by [Jon Egerton](https://github.com/jonegerton)
* [:link:](dock-spawn/dock-spawn.d.ts) [Dock Spawn](http://dockspawn.com) by [Drew Noakes](https://drewnoakes.com)
@@ -151,6 +153,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](easystarjs/easystarjs.d.ts) [EasyStar.js](http://easystarjs.com) by [Magnus Gustafsson](https://github.com/borundin)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](element-resize-event/element-resize-event.d.ts) [element-resize-event](https://github.com/KyleAMathews/element-resize-event) by [Rogier Schouten](https://github.com/rogierschouten)
* [:link:](elm/elm.d.ts) [Elm](http://elm-lang.org) by [Dénes Harmath](https://github.com/thSoft)
* [:link:](ember/ember.d.ts) [Ember.js](http://emberjs.com) by [Jed Mao](https://github.com/jedmao)
* [:link:](emissary/emissary.d.ts) [emissary](https://github.com/atom/emissary) by [vvakame](https://github.com/vvakame)
@@ -193,6 +196,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](flux/flux.d.ts) [Flux](http://facebook.github.io/flux) by [Steve Baker](https://github.com/stkb)
* [:link:](ion.rangeSlider/ion.rangeSlider.d.ts) [for Ion.RangeSlider](https://github.com/IonDen/ion.rangeSlider) by [Sixin Li](https://github.com/sixinli)
* [:link:](form-data/form-data.d.ts) [form-data](https://github.com/felixge/node-form-data) by [Carlos Ballesteros Velasco](https://github.com/soywiz)
* [:link:](formidable/formidable.d.ts) [Formidable](https://github.com/felixge/node-formidable) by [Wim Looman](https://github.com/Nemo157)
* [:link:](foundation/foundation.d.ts) [Foundation](http://foundation.zurb.com) by [Boris Yankov](https://github.com/borisyankov)
* [:link:](fpsmeter/FPSMeter.d.ts) [FPSmeter](http://darsa.in/fpsmeter) by [Aaron Lampros](http://github.com/alampros)
* [:link:](from/from.d.ts) [from](https://github.com/dominictarr/from) by [Bart van der Schoor](https://github.com/Bartvds)
@@ -333,6 +337,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](jquery.superLink/jquery.superLink.d.ts) [jquery.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) by [Blake Niemyjski](https://github.com/niemyjski)
* [:link:](jquery.tile/jquery.tile.d.ts) [jquery.tile.js](https://github.com/urin/jquery.tile.js) by [Shunsuke Ohtani](https://github.com/zaneli)
* [:link:](jquery.timeago/jquery.timeago.d.ts) [jQuery.timeago.js](http://timeago.yarp.com) by [François Guillot](http://fguillot.developpez.com)
* [:link:](jquery.tipsy/jquery.tipsy.d.ts) [jQuery.tipsy](http://onehackoranother.com/projects/jquery/tipsy) by [Brian Dukes](https://github.com/bdukes)
* [:link:](jquery.transit/jquery.transit.d.ts) [jQuery.transit.js](http://ricostacruz.com/jquery.transit) by [MrBigDog2U](https://github.com/MrBigDog2U)
* [:link:](jquery.validation/jquery.validation.d.ts) [jquery.validation](http://jqueryvalidation.org) by [François de Campredon](https://github.com/fdecampredon), [Johj Reilly](https://github.com/johnnyreilly)
* [:link:](jquery.timer/jquery.timer.d.ts) [jQueryTimer](https://github.com/jchavannes/jquery-timer) by [Joshua Strobl](https://github.com/JoshStrobl)
@@ -345,6 +350,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](jsbn/jsbn.d.ts) [jsbn](http://www-cs-students.stanford.edu/%7Etjw/jsbn) by [Eugene Chernyshov](https://github.com/Evgenus)
* [:link:](jscrollpane/jscrollpane.d.ts) [jScrollPane](http://jscrollpane.kelvinluck.com) by [Dániel Tar](https://github.com/qcz)
* [:link:](jsdeferred/jsdeferred.d.ts) [JSDeferred](https://github.com/cho45/jsdeferred) by [Daisuke Mino](https://github.com/minodisk)
* [:link:](jsdom/jsdom.d.ts) [jsdom](https://github.com/tmpvar/jsdom) by [Asana](https://asana.com)
* [:link:](jsesc/jsesc.d.ts) [jsesc](https://github.com/mathiasbynens/jsesc) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](jsfl/jsfl.d.ts) [JSFL](https://adobe.com) by [soywiz](https://github.com/soywiz)
* [:link:](jshamcrest/jshamcrest.d.ts) [JsHamcrest](https://github.com/danielfm/jshamcrest) by [David Harkness](https://github.com/dharkness)
@@ -493,7 +499,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](notifyjs/notifyjs.d.ts) [notify.js](https://github.com/alexgibson/notify.js) by [soundTricker](https://github.com/soundTricker)
* [:link:](noVNC/noVNC.d.ts) [noVNC](https://github.com/kanaka/noVNC) by [Ken Smith](https://github.com/smithkl42)
* [:link:](npm/npm.d.ts) [npm](https://github.com/npm/npm) by [Maxime LUCE](https://github.com/SomaticIT)
* [:link:](nprogress/nprogress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com)
* [:link:](nprogress/NProgress.d.ts) [NProgress](https://github.com/rstacruz/nprogress) by [Judah Gabriel Himango](http://debuggerdotbreak.wordpress.com)
* [:link:](numeraljs/numeraljs.d.ts) [Numeral.js](https://github.com/adamwdraper/Numeral-js) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](object-path/object-path.d.ts) [objectPath](https://github.com/mariocasciaro/object-path) by [Paulo Cesar](https://github.com/pocesar)
* [:link:](oboe/oboe.d.ts) [oboe](https://github.com/jimhigson/oboe.js) by [Jared Klopper](https://github.com/optical)
@@ -581,6 +587,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](rx/rx.time.d.ts) [RxJS-Time](http://rx.codeplex.com) by [Carl de Billy](http://carl.debilly.net), [Igor Oleinikov](https://github.com/Igorbek)
* [:link:](rx/rx.virtualtime.d.ts) [RxJS-VirtualTime](http://rx.codeplex.com) by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek)
* [:link:](sammyjs/sammyjs.d.ts) [Sammy.js](http://sammyjs.org) by [Boris Yankov](https://github.com/borisyankov), [Oisin Grehan](https://github.com/oising)
* [:link:](sanitize-filename/sanitize-filename.d.ts) [sanitize-filename](https://github.com/parshap/node-sanitize-filename) by [Wim Looman](https://github.com/Nemo157)
* [:link:](screenfull/screenfull.d.ts) [screenfull.js](https://github.com/sindresorhus/screenfull.js) by [Ilia Choly](http://github.com/icholy)
* [:link:](select2/select2.d.ts) [Select2](http://ivaynberg.github.com/select2) by [Boris Yankov](https://github.com/borisyankov)
* [:link:](selectize/selectize.d.ts) [Selectize](https://github.com/brianreavis/selectize.js) by [Adi Dahiya](https://github.com/adidahiya)
@@ -705,6 +712,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](webrtc/MediaStream.d.ts) [WebRTC](http://dev.w3.org/2011/webrtc) by [Ken Smith](https://github.com/smithkl42)
* [:link:](websocket/websocket.d.ts) [websocket](https://github.com/Worlize/WebSocket-Node) by [Paul Loyd](https://github.com/loyd)
* [:link:](when/when.d.ts) [When](https://github.com/cujojs/when) by [Derek Cicerone](https://github.com/derekcicerone), [Wim Looman](https://github.com/Nemo157)
* [:link:](which/which.d.ts) [which](https://github.com/isaacs/node-which) by [vvakame](https://github.com/vvakame)
* [:link:](winjs/winjs.d.ts) [WinJS](http://try.buildwinjs.com) by [TypeScript samples](https://www.typescriptlang.org), [Adam Hewitt](https://github.com/adamhewitt627), [Craig Treasure](https://github.com/craigktreasure), [Jeff Fisher](https://github.com/xirzec)
* [:link:](winrt/winrt.d.ts) [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) by [TypeScript samples](https://www.typescriptlang.org)
* [:link:](winston/winston.d.ts) [winston](https://github.com/flatiron/winston) by [bonnici](https://github.com/bonnici), [Peter Harris](https://github.com/codeanimal)
+11
View File
@@ -0,0 +1,11 @@
/// <reference path="FileSaver.d.ts" />
/**
* @summary Test for "saveAs" function.
*/
function testSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
saveAs(data, filename);
}
+1
View File
@@ -0,0 +1 @@
--noImplicitAny
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for FileSaver.js
// Project: https://github.com/eligrey/FileSaver.js/
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Interface for "saveAs" function.
* @author Cyril Schumacher
* @version 1.0
*/
interface FileSaver {
(
/**
* @summary Data.
* @type {Blob}
*/
data: Blob,
/**
* @summary File name.
* @type {DOMString}
*/
filename: string
): void
}
declare var saveAs: FileSaver;
+1
View File
@@ -918,6 +918,7 @@ declare module protractor {
* @return {!webdriver.promise.Promise} A promise that resolves to the final
* value of the accumulator.
*/
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise<T>, initialValue: T): webdriver.promise.Promise<T>;
reduce<T>(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise<T>;
/**
+26 -7
View File
@@ -8,10 +8,29 @@
declare var $routeProvider: ng.route.IRouteProvider;
$routeProvider
.when('/projects/:projectId/dashboard',{
controller: '',
templateUrl: '',
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.otherwise({redirectTo: '/'});
.when('/projects/:projectId/dashboard', {
controller: 'I am a string',
templateUrl: "So am I",
caseInsensitiveMatch: true,
reloadOnSearch: false
})
.when('/projects/:projectId/dashboard2', {
controller: function () {
//Look at me - I'm a function!
},
template: function ($routeParams?: ng.route.IRouteParamsService) {
return "I return a string"
}
})
.when('/projects/:projectId/dashboard3', {
controllerAs: 'I am a string',
template: "Yup. String"
})
.when('/projects/:projectId/dashboard4', {
controller: 'I am a string',
templateUrl: function ($routeParams?: ng.route.IRouteParamsService) {
return "I return a string"
}
})
.otherwise({ redirectTo: '/' })
.otherwise({ redirectTo: ($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) => "" });
+5 -5
View File
@@ -42,7 +42,7 @@ declare module ng.route {
* {(string|function()=}
* Controller fn that should be associated with newly created scope or the name of a registered controller if passed as a string.
*/
controller?: any;
controller?: string|Function;
/**
* A controller alias name. If present the controller will be published to scope under the controllerAs name.
*/
@@ -59,7 +59,7 @@ declare module ng.route {
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
template?: string;
template?: string|{($routeParams?: ng.route.IRouteParamsService) : string;}
/**
* {string=|function()=}
* Path or function that returns a path to an html template that should be used by ngView.
@@ -68,14 +68,14 @@ declare module ng.route {
*
* {Array.<Object>} - route parameters extracted from the current $location.path() by applying the current route
*/
templateUrl?: any;
templateUrl?: string|{ ($routeParams?: ng.route.IRouteParamsService): string; }
/**
* {Object.<string, function>=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:
*
* - key - {string}: a name of a dependency to be injected into the controller.
* - factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.
*/
resolve?: {[key: string]: any};
resolve?: {[key: string]: any};
/**
* {(string|function())=}
* Value to update $location path with and trigger route redirection.
@@ -87,7 +87,7 @@ declare module ng.route {
* - {Object} - current $location.search()
* - The custom redirectTo function is expected to return a string which will be used to update $location.path() and $location.search().
*/
redirectTo?: any;
redirectTo?: string|{($routeParams?: ng.route.IRouteParamsService, $locationPath?: string, $locationSearch?: any) : string};
/**
* Reload route when only $location.search() or $location.hash() changes.
*
+35 -82
View File
@@ -392,32 +392,44 @@ declare module ng {
// see http://docs.angularjs.org/api/ng.$compile.directive.Attributes
///////////////////////////////////////////////////////////////////////////
interface IAttributes {
// this is necessary to be able to access the scoped attributes. it's not very elegant
// because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way
// this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656
/**
* this is necessary to be able to access the scoped attributes. it's not very elegant
* because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way
* this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656
*/
[name: string]: any;
// Adds the CSS class value specified by the classVal parameter to the
// element. If animations are enabled then an animation will be triggered
// for the class addition.
/**
* Adds the CSS class value specified by the classVal parameter to the
* element. If animations are enabled then an animation will be triggered
* for the class addition.
*/
$addClass(classVal: string): void;
// Removes the CSS class value specified by the classVal parameter from the
// element. If animations are enabled then an animation will be triggered for
// the class removal.
/**
* Removes the CSS class value specified by the classVal parameter from the
* element. If animations are enabled then an animation will be triggered for
* the class removal.
*/
$removeClass(classVal: string): void;
// Set DOM element attribute value.
/**
* Set DOM element attribute value.
*/
$set(key: string, value: any): void;
// Observes an interpolated attribute.
// The observer function will be invoked once during the next $digest
// following compilation. The observer is then invoked whenever the
// interpolated value changes.
/**
* Observes an interpolated attribute.
* The observer function will be invoked once during the next $digest
* following compilation. The observer is then invoked whenever the
* interpolated value changes.
*/
$observe(name: string, fn: (value?: any) => any): Function;
// A map of DOM element attribute names to the normalized name. This is needed
// to do reverse lookup from normalized name back to actual name.
/**
* A map of DOM element attribute names to the normalized name. This is needed
* to do reverse lookup from normalized name back to actual name.
*/
$attr: Object;
}
@@ -820,33 +832,9 @@ declare module ng {
* Change search part when called with parameter and return $location.
*
* @param search New search params
* @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted.
* @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign.
*/
search(search: string, paramValue: string): ILocationService;
/**
* Change search part when called with parameter and return $location.
*
* @param search New search params
* @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted.
*/
search(search: string, paramValue: number): ILocationService;
/**
* Change search part when called with parameter and return $location.
*
* @param search New search params
* @param paramValue If paramValue is an array, it will override the property of the search component of $location specified via the first argument.
*/
search(search: string, paramValue: string[]): ILocationService;
/**
* Change search part when called with parameter and return $location.
*
* @param search New search params
* @param paramValue If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign.
*/
search(search: string, paramValue: boolean): ILocationService;
search(search: string, paramValue: string|number|string[]|boolean): ILocationService;
state(): any;
state(state: any): ILocationService;
@@ -906,15 +894,7 @@ declare module ng {
*
* @param promises An array or hash of promises.
*/
all(promises: IPromise<any>[]): IPromise<any[]>;
/**
* Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
*
* Returns a single promise that will be resolved with an array/hash of values, each value corresponding to the promise at the same index/key in the promises array/hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.
*
* @param promises An array or hash of promises.
*/
all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any }>;
all(promises: IPromise<any>[]|{ [id: string]: IPromise<any>; }): IPromise<any[]>;
/**
* Creates a Deferred object which represents a task which will finish in the future.
*/
@@ -932,13 +912,7 @@ declare module ng {
*
* @param value Value or a promise
*/
when<T>(value: IPromise<T>): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
* @param value Value or a promise
*/
when<T>(value: T): IPromise<T>;
when<T>(value: IPromise<T>|T): IPromise<T>;
/**
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.
*
@@ -953,32 +927,12 @@ declare module ng {
*
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
*
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.
*
* This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.
*/
then<TResult>(successCallback: (promiseValue: T) => TResult, errorCallback?: (reason: any) => TResult, notifyCallback?: (state: any) => any): IPromise<TResult>;
then<TResult>(successCallback: (promiseValue: T) => IHttpPromise<TResult>|IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => IHttpPromise<TResult>): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => IPromise<TResult>): IPromise<TResult>;
/**
* Shorthand for promise.then(null, errorCallback)
*/
catch<TResult>(onRejected: (reason: any) => TResult): IPromise<TResult>;
catch<TResult>(onRejected: (reason: any) => IHttpPromise<TResult>|IPromise<TResult>|TResult): IPromise<TResult>;
/**
* Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.
@@ -1273,8 +1227,7 @@ declare module ng {
interface IHttpPromise<T> extends IPromise<T> {
success(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;
error(callback: IHttpPromiseCallback<any>): IHttpPromise<T>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => IPromise<TResult>, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => TResult, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
then<TResult>(successCallback: (response: IHttpPromiseCallbackArg<T>) => IPromise<TResult>|TResult, errorCallback?: (response: IHttpPromiseCallbackArg<any>) => any): IPromise<TResult>;
}
/**
+8 -8
View File
@@ -311,14 +311,14 @@ declare module Backbone {
private _updateHash(location: Location, fragment: string, replace: boolean): void;
}
interface ViewOptions<TModel extends Model> {
model?: TModel;
collection?: Backbone.Collection<TModel>;
el?: any;
id?: string;
className?: string;
tagName?: string;
attributes?: any[];
interface ViewOptions<TModel extends Model> {
model?: TModel;
collection?: Backbone.Collection<TModel>;
el?: any;
id?: string;
className?: string;
tagName?: string;
attributes?: {[id: string]: any};
}
class View<TModel extends Model> extends Events {
+3 -3
View File
@@ -26,8 +26,8 @@ interface BootboxButton {
}
interface BootboxDialogOptions {
message: any; // String | Element
title?: any; // String | Element
message: string | Element;
title?: string | Element;
callback?: (result: boolean) => any;
show?: boolean;
onEscape?: () => any;
@@ -60,4 +60,4 @@ interface BootboxStatic {
hideAll(): void;
}
declare var bootbox: BootboxStatic;
declare var bootbox: BootboxStatic;
+5 -5
View File
@@ -18,8 +18,8 @@ declare module "bunyan" {
child(obj:Object, simple?:boolean):Logger;
reopenFileStreams():void;
level(value:any /* number | string */):void;
levels(name:any /* number | string */, value:any /* number | string */):void;
level(value: number | string):void;
levels(name: number | string, value: number | string):void;
trace(error:Error, format?:any, ...params:any[]):void;
trace(buffer:Buffer, format?:any, ...params:any[]):void;
@@ -62,9 +62,9 @@ declare module "bunyan" {
interface Stream {
type?: string;
level?: any; // number | string
level?: number | string;
path?: string;
stream?: WritableStream;
stream?: WritableStream | Stream;
closeOnExit?: boolean;
}
@@ -77,7 +77,7 @@ declare module "bunyan" {
export var ERROR:number;
export var FATAL:number;
export function resolveLevel(value:any /* number | string */):number;
export function resolveLevel(value: number | string):number;
export function createLogger(options:LoggerOptions):Logger;
+103
View File
@@ -0,0 +1,103 @@
/// <reference path="../when/when.d.ts" />
/// <reference path="./chai-http.d.ts" />
import fs = require('fs');
import http = require('http');
import chai = require('chai');
import chaiHttp = require('chai-http');
import when = require('when');
chai.use(chaiHttp);
// Add promise support if this does not exist natively.
if (!global.Promise) {
chai.request.addPromises(when.promise);
}
var app: http.Server;
chai.request(app).get('/');
chai.request('http://localhost:8080').get('/');
chai.request(app)
.put('/user/me')
.set('X-API-Key', 'foobar')
.send({ password: '123', confirmPassword: '123' });
chai.request(app)
.post('/user/me')
.field('_method', 'put')
.field('password', '123')
.field('confirmPassword', '123');
chai.request(app)
.post('/user/avatar')
.attach('imageField', fs.readFileSync('avatar.png'), 'avatar.png');
chai.request(app)
.get('/protected')
.auth('user', 'pass');
chai.request(app)
.get('/search')
.query('name', 'foo')
.query('limit', '10');
chai.request(app)
.put('/user/me')
.send({ passsword: '123', confirmPassword: '123' })
.end((err: any, res: chaiHttp.Response) => {
chai.expect(err).to.be.null;
chai.expect(res).to.have.status(200);
});
chai.request(app)
.put('/user/me')
.send({ passsword: '123', confirmPassword: '123' })
.then((res: chaiHttp.Response) => chai.expect(res).to.have.status(200))
.catch((err: any) => { throw err; });
var agent = chai.request.agent(app);
agent
.post('/session')
.send({ username: 'me', password: '123' })
.then((res: chaiHttp.Response) => {
chai.expect(res).to.have.cookie('sessionid');
// The `agent` now has the sessionid cookie saved, and will send it
// back to the server in the next request:
return agent.get('/user/me')
.then((res: chaiHttp.Response) => chai.expect(res).to.have.status(200));
});
function test1() {
var req = chai.request(app).get('/');
req.then((res: chaiHttp.Response) => {
chai.expect(res).to.have.status(200);
chai.expect(res).to.have.header('content-type', 'text/plain');
chai.expect(res).to.have.header('content-type', /^text/);
chai.expect(res).to.have.headers;
chai.expect('127.0.0.1').to.be.an.ip;
chai.expect(res).to.be.json;
chai.expect(res).to.be.html;
chai.expect(res).to.be.text;
chai.expect(res).to.redirect;
chai.expect(res).to.redirectTo('http://example.com');
chai.expect(res).to.have.param('orderby');
chai.expect(res).to.have.param('orderby', 'date');
chai.expect(res).to.not.have.param('limit');
chai.expect(req).to.have.cookie('session_id');
chai.expect(req).to.have.cookie('session_id', '1234');
chai.expect(req).to.not.have.cookie('PHPSESSID');
chai.expect(res).to.have.cookie('session_id');
chai.expect(res).to.have.cookie('session_id', '1234');
chai.expect(res).to.not.have.cookie('PHPSESSID');
chai.expect(res.body).to.have.property('version', '4.0.0');
}, (err: any) => {
throw err;
});
}
when(chai.request(app).get('/')).done(() => console.log('success'), () => console.log('failure'));
+87
View File
@@ -0,0 +1,87 @@
// Type definitions for chai-http
// Project: https://github.com/chaijs/chai-http
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../chai/chai.d.ts" />
declare module chai {
export function request(server: any): chaiHttp.Agent;
export module request {
export function agent(server: any): chaiHttp.Agent;
export function addPromises(promiseConstructor: chaiHttp.PromiseConstructor): void;
}
interface Assertions extends chaiHttp.Assertions {
}
interface TypeComparison extends chaiHttp.TypeComparison {
}
}
declare function chaiHttp(chai: any, utils: any): void;
declare module chaiHttp {
interface PromiseConstructor {
<T>(resolver: (resolve: (value: T) => void, reject: (reason: any) => void) => void): Promise<T>;
}
interface Promise<T> {
then<U>(onFulfilled: (value: T) => U, onRejected?: (reason: any) => U): Promise<U>;
}
interface Response {
body: any;
type: string;
status: number;
}
interface Request extends FinishedRequest {
attach(field: string, file: string, filename: string): Request;
attach(field: string, file: Buffer, filename: string): Request;
set(field: string, val: string): Request;
query(key: string, value: string): Request;
send(data: Object): Request;
auth(user: string, name: string): Request;
field(name: string, val: string): Request;
end(callback?: (err: any, res: Response) => void): FinishedRequest;
}
interface FinishedRequest {
then(success?: (res: Response) => void, failure?: (err: any) => void): FinishedRequest;
catch(failure?: (err: any) => void): FinishedRequest;
}
interface Agent {
get(url: string, callback?: (err: any, res: Response) => void): Request;
post(url: string, callback?: (err: any, res: Response) => void): Request;
put(url: string, callback?: (err: any, res: Response) => void): Request;
head(url: string, callback?: (err: any, res: Response) => void): Request;
del(url: string, callback?: (err: any, res: Response) => void): Request;
options(url: string, callback?: (err: any, res: Response) => void): Request;
patch(url: string, callback?: (err: any, res: Response) => void): Request;
}
interface Assertions {
status(code: number): any;
header(key: string, value?: string): any;
header(key: string, value?: RegExp): any;
headers: any;
json: any;
// text: any;
// html: any;
redirect: any;
redirectTo(location: string): any;
param(key: string, value?: string): any;
cookie(key: string, value?: string): any;
}
interface TypeComparison {
ip: any;
}
}
declare module "chai-http" {
export = chaiHttp;
}
+2 -2
View File
@@ -18,7 +18,7 @@ declare module chrome.app.runtime {
}
interface LaunchDataItem {
entry: File;
entry: FileEntry;
type: string;
}
@@ -367,4 +367,4 @@ declare module chrome.sockets.tcpServer {
var onAccept: Event<AcceptEventArgs>;
var onAcceptError: Event<AcceptErrorEventArgs>;
}
}
+12 -8
View File
@@ -2173,20 +2173,24 @@ declare module chrome.webNavigation {
error: string;
}
interface WebNavigationEventFilters {
url: chrome.events.UrlFilter[];
}
interface WebNavigationReferenceFragmentUpdatedEvent extends chrome.events.Event {
addListener(callback: (details: ReferenceFragmentUpdatedDetails) => void): void;
addListener(callback: (details: ReferenceFragmentUpdatedDetails) => void, filters? : WebNavigationEventFilters): void;
}
interface WebNavigationCompletedEvent extends chrome.events.Event {
addListener(callback: (details: CompletedDetails) => void): void;
addListener(callback: (details: CompletedDetails) => void, filters? : WebNavigationEventFilters): void;
}
interface WebNavigationHistoryStateUpdatedEvent extends chrome.events.Event {
addListener(callback: (details: HistoryStateUpdatedDetails) => void): void;
addListener(callback: (details: HistoryStateUpdatedDetails) => void, filters?: WebNavigationEventFilters): void;
}
interface WebNavigationCreatedNavigationTargetEvent extends chrome.events.Event {
addListener(callback: (details: CreatedNavigationTargetDetails) => void): void;
addListener(callback: (details: CreatedNavigationTargetDetails) => void, filters?: WebNavigationEventFilters): void;
}
interface WebNavigationTabReplacedEvent extends chrome.events.Event {
@@ -2194,19 +2198,19 @@ declare module chrome.webNavigation {
}
interface WebNavigationBeforeNavigateEvent extends chrome.events.Event {
addListener(callback: (details: BeforeNavigateDetails) => void): void;
addListener(callback: (details: BeforeNavigateDetails) => void, filters?: WebNavigationEventFilters): void;
}
interface WebNavigationCommittedEvent extends chrome.events.Event {
addListener(callback: (details: CommittedDetails) => void): void;
addListener(callback: (details: CommittedDetails) => void, filters?: WebNavigationEventFilters): void;
}
interface WebNavigationDomContentLoadedEvent extends chrome.events.Event {
addListener(callback: (details: DomContentLoadedDetails) => void): void;
addListener(callback: (details: DomContentLoadedDetails) => void, filters?: WebNavigationEventFilters): void;
}
interface WebNavigationErrorOccurredEvent extends chrome.events.Event {
addListener(callback: (details: ErrorOccurredDetails) => void): void;
addListener(callback: (details: ErrorOccurredDetails) => void, filters?: WebNavigationEventFilters): void;
}
export function getFrame(details: GetFrameDetails, callback: (details?: GetFrameResultDetails) => void): void;
+17
View File
@@ -32,12 +32,29 @@ var conf = convict({
format: (val: string) => validator.isUUID(val),
default: '01527E56-8431-11E4-AF91-47B661C210CA'
},
db: {
ip: {
doc: 'The IP address to bind.',
format: 'ipaddress',
default: '127.0.0.1',
env: 'IP_ADDRESS',
},
port: {
doc: 'The port to bind.',
format: 'port',
default: 0,
env: 'PORT',
arg: 'port',
}
}
});
// load environment dependent configuration
var env = conf.get('env');
var dbip = conf.get('db.ip');
conf.loadFile('./config/' + env + '.json');
conf.loadFile(['./configs/always.json', './configs/sometimes.json']);
+1 -1
View File
@@ -8,7 +8,7 @@ declare module "convict" {
module convict {
interface Schema {
[name: string]: {
[name: string]: convict.Schema | {
default: any;
doc?: string;
format?: any;
+43
View File
@@ -0,0 +1,43 @@
/// <reference path="../d3/d3.d.ts" />
/// <reference path="d3.cloud.layout.d.ts" />
interface ICompTextSize{
text:string;
size:number;
x?:number;
y?:number;
rotate?:number;
}
var fill = d3.scale.category20();
d3.layout.cloud().size([300, 300])
.words([
"Hello", "world", "normally", "you", "want", "more", "words",
"than", "this"].map(function(d:string) {
return {text: d, size: 10 + Math.random() * 90};
}))
.padding(5)
.rotate(function() { return ~~(Math.random() * 2) * 90; })
.font("Impact")
.fontSize(function(d:ICompTextSize) { return d.size; })
.on("end", draw)
.start();
function draw(words:ICompTextSize[]) {
d3.select("body").append("svg")
.attr("width", 300)
.attr("height", 300)
.append("g")
.attr("transform", "translate(150,150)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d:ICompTextSize) { return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d:ICompTextSize, i:number) { return fill(i); })
.attr("text-anchor", "middle")
.attr("transform", function(d:ICompTextSize) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d:ICompTextSize) { return d.text; });
}
+45
View File
@@ -0,0 +1,45 @@
// Type definitions for d3JS cloud layout plugin by Jason Davies
// Project: https://github.com/jasondavies/d3-cloud
// Definitions by: hans windhoff <https://github.com/hansrwindhoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../d3/d3.d.ts" />
declare module D3 {
export module Layout {
export interface IRotate {
(number:number) : CloudLayout;
(number:()=>number) : CloudLayout;
}
export interface CloudLayout {
(layers: any[], index?: number): any[];
values(accessor?: (d: any) => any): CloudLayout;
offset(offset: string): CloudLayout;
size: {
/**
* Gets the available layout size
*/
(): Array<number>;
/**
* Sets the available layout size
*/
(size: Array<number>): CloudLayout;
};
words: (inputArray: Array<any>) => CloudLayout;
rotate:IRotate;
padding: (number:number) => CloudLayout;
font: (string:string) => CloudLayout;
fontSize(fctn: (d: any) => number): CloudLayout;
on: (eventname: string, callee: (words: any[]) => void) => CloudLayout;
start: () => CloudLayout;
}
export interface Layout {
cloud(): CloudLayout;
}
}
}
+13
View File
@@ -0,0 +1,13 @@
/// <reference path="dagre.d.ts"/>
module DagreTests {
var gDagre = new dagre.graphlib.Graph();
gDagre.setGraph({});
gDagre.setDefaultEdgeLabel(function(){
return ;
});
gDagre.setNode("a", {});
gDagre.setEdge("b", "c");
dagre.layout(gDagre);
}
+29
View File
@@ -0,0 +1,29 @@
// Type definitions for dagre 0.7.0
// Project: https://github.com/cpettitt/dagre
// Definitions by: Qinfeng Chen <https://github.com/qinfchen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Dagre{
interface DagreFactory {
graphlib: GraphLib;
layout(graph: Graph): void;
}
interface Graph {
new (): Graph;
edges(): string[];
edge(id: string): any;
nodes(): string[];
node(id: string): any;
setDefaultEdgeLabel(callback: () => void): void;
setEdge(sourceId: string, targetId: string): void;
setGraph(options: { [key: string]: any }): void;
setNode(id: string, node: { [key: string]: any }): void;
}
interface GraphLib {
Graph: Graph
}
}
declare var dagre: Dagre.DagreFactory;
+280
View File
@@ -0,0 +1,280 @@
/// <reference path="deployJava.d.ts" />
/**
* @summary Test for the method: "allowPlugin".
*/
function testAllowPlugin() {
var result: boolean = deployJava.allowPlugin();
}
/**
* @summary Test for the method: "compareVersions".
*/
function testCompareVersions() {
var installed = '1.8';
var required = '1.7';
var result = deployJava.compareVersions(installed, required);
}
/**
* @summary Test for the method: "compareVersionToPattern".
*/
function testCompareVersionToPattern() {
var version: string = '1.8';
var patternArray: Array<string> = ['1.6', '1.7', '1.8'];
var familyMatch: boolean = false;
var minMatch: boolean = true;
var result = deployJava.compareVersionToPattern(version, patternArray, familyMatch, minMatch);
}
/**
* @summary Test for the method: "enableAlerts".
*/
function testEnableAlerts() {
deployJava.enableAlerts();
}
/**
* @summary Test for the method: "FFInstall".
*/
function testFFInstall() {
var result: boolean = deployJava.FFInstall();
}
/**
* @summary Test for the method: "getBrowser".
*/
function testGetBrowser() {
var result: string = deployJava.getBrowser();
}
/**
* @summary Test for the method: "getJPIVersionUsingMimeType".
*/
function testGetJPIVersionUsingMimeType() {
deployJava.getJPIVersionUsingMimeType();
}
/**
* @summary Test for the method: "getJREs".
*/
function testGetJREs() {
var versions: Array<String> = deployJava.getJREs();
}
/**
* @summary Test for the method: "getPlugin".
*/
function testGetPlugin() {
var versions: HTMLElement = deployJava.getPlugin();
}
/**
* @summary Test for the method: "IEInstall".
*/
function testIEInstall() {
var result: boolean = deployJava.IEInstall();
}
/**
* @summary Test for the method: "installJRE".
*/
function testInstallJRE() {
var requestVersion: string = '1.8';
var result: boolean = deployJava.installJRE(requestVersion);
}
/**
* @summary Test for the method: "installLatestJRE".
*/
function testInstallLatestJRE() {
var installCallback: Function = () => {};
var result: boolean = deployJava.installLatestJRE(installCallback);
}
/**
* @summary Test for the method: "isAutoInstallEnabled".
*/
function testIsAutoInstallEnabled() {
var requestedJREVersion: string = '1.8';
var result: boolean = deployJava.isAutoInstallEnabled();
var result: boolean = deployJava.isAutoInstallEnabled(requestedJREVersion);
}
/**
* @summary Test for the method: "isAutoUpdateEnabled".
*/
function testIsAutoUpdateEnabled() {
var result: boolean = deployJava.isAutoUpdateEnabled();
}
/**
* @summary Test for the method: "isCallbackSupported".
*/
function testIsCallbackSupported() {
var result: boolean = deployJava.isCallbackSupported();
}
/**
* @summary Test for the method: "isPlugin2".
*/
function testIsPlugin2() {
var result: boolean = deployJava.isPlugin2();
}
/**
* @summary Test for the method: "isPluginInstalled".
*/
function testIsPluginInstalled() {
var result: boolean = deployJava.isPluginInstalled();
}
/**
* @summary Test for the method: "isWebStartInstalled".
*/
function testIsWebStartInstalled() {
var minimumVersion: string = '1.7';
var result: boolean = deployJava.isWebStartInstalled();
var result: boolean = deployJava.isWebStartInstalled(minimumVersion);
}
/**
* @summary Test for the method: "launch".
*/
function testLaunch() {
var jnlp: string = 'http://www.example.com/';
var result: boolean = deployJava.launch(jnlp);
}
/**
* @summary Test for the method: "launchWebStartApplication".
*/
function testLaunchWebStartApplication() {
var jnlp: string = 'http://www.example.com/';
deployJava.launchWebStartApplication(jnlp);
}
/**
* @summary Test for the method: "poll".
*/
function testPool() {
deployJava.poll();
}
/**
* @summary Test for the method: "refresh".
*/
function testRefresh() {
deployJava.refresh();
}
/**
* @summary Test for the method: "runApplet".
*/
function testRunApplet() {
var attributes: Object = {
code:'java2d.Java2DemoApplet.class',
archive:'Java2Demo.jar',
width:710,
height:540
};
var parameters: Object = { fontSize:16, permissions:'sandbox' };
var version: string = '1.8';
deployJava.runApplet(attributes, parameters);
deployJava.runApplet(attributes, parameters, version);
}
/**
* @summary Test for the method: "setAdditionalPackages".
*/
function testSetAdditionalPackages() {
var packageList: string = 'javax.swing';
var result: boolean = deployJava.setAdditionalPackages(packageList);
}
/**
* @summary Test for the method: "setAutoUpdateEnabled".
*/
function testSetAutoUpdateEnabled() {
deployJava.setAutoUpdateEnabled();
}
/**
* @summary Test for the method: "setEarlyAccess".
*/
function testSetEarlyAccess() {
var enabled: string = 'true';
deployJava.setEarlyAccess(enabled);
}
/**
* @summary Test for the method: "setInstallerType".
*/
function testSetInstallerType() {
var type: string = 'kernel';
deployJava.setInstallerType(type);
}
/**
* @summary Test for the method: "testForMSVM".
*/
function testTestForMSVM() {
var result: boolean = deployJava.testForMSVM();
}
/**
* @summary Test for the method: "testUsingActiveX".
*/
function testTestUsingActiveX() {
var version: string = '1.7.0';
var result: boolean = deployJava.testUsingActiveX(version);
}
/**
* @summary Test for the method: "testUsingMimeTypes".
*/
function testTestUsingMimeTypes() {
var version: string = '1.7.0';
var result: boolean = deployJava.testUsingMimeTypes(version);
}
/**
* @summary Test for the method: "testUsingPluginsArray".
*/
function testTestUsingPluginsArray() {
var version: string = '1.7.0';
var result: boolean = deployJava.testUsingPluginsArray(version);
}
/**
* @summary Test for the method: "versionCheck".
*/
function testVersionCheck() {
deployJava.versionCheck('1.x');
}
/**
* @summary Test for the method: "writeAppletTag".
*/
function testWriteAppletTag() {
var attributes: Object = {
code:'java2d.Java2DemoApplet.class',
archive:'Java2Demo.jar',
width:710,
height:540
};
var parameters: Object = { fontSize:16, permissions:'sandbox' };
deployJava.writeAppletTag(attributes, parameters);
}
/**
* @summary Test for the method: "writeEmbedTag".
*/
function testWriteEmbedTag() {
deployJava.writeEmbedTag();
}
+1
View File
@@ -0,0 +1 @@
--noImplicitAny
+315
View File
@@ -0,0 +1,315 @@
// Type definitions for deployJava.js
// Project: https://www.java.com/js/deployJava.txt
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module DeployJava {
/**
* @summary Interface for {@link deployJava} object.
* @author Cyril Schumacher
* @version 1.0
*/
interface DeployJavaStatic {
/**
* @summary Brand name.
* @member {string}
*/
brand: string;
/**
* @summary Debug mode.
* @member {boolean}
*/
debug: boolean;
/**
* @summary Early Access state.
* @member {string}
*/
EAInstallEnabled: boolean;
/**
* @summary URL to early access.
* @member {string}
*/
EarlyAccessURL: string;
/**
* @summary Preferred install type (null, online, kernel).
* @member {string}
*/
installType: string;
/**
* @summary Locale.
* @member {string}
*/
locale: string;
/**
* @summary Interval for check versions of JRE available.
* @member {number}
*/
myInterval: number;
/**
* @summary JRE versions installed.
* @member {Array<string>}
*/
preInstallJREList: Array<string>;
/**
* @summary URL of current document.
* @member {string}
*/
returnPage: string;
/**
* @summary Determines if the browser has allowed the Java plugin.
* @return {boolean} True if the Java plugin is allowed, otherwise, False.
*/
allowPlugin(): boolean;
/**
* @summary Compares a installed version and required version.
* @param {string} installed JRE installed version.
* @param {string} required JRE required version.
* @return {boolean} True if installed version is greater than or equal to required version.
*/
compareVersions(installed: string, required: string): boolean;
/**
* @summary Compares a version with a pattern.
* @param {string} version Version to compare.
* @param {Array<string>} patternArray Patterns to compare.
* @param {boolean} familyMatch Family match.
* @param {boolean} minMatch Minimum version match.
* @return {boolean} True if a or many patterns are identical to version, otherwise, False.
*/
compareVersionToPattern(version: string, patternArray: Array<string>, familyMatch: boolean, minMatch: boolean): boolean;
/**
* @summary Enable alerts.
*/
enableAlerts(): void;
/**
* @summary Redirect to Java plugin website for Mozilla Firefox.
* @return {boolean} True if the redirection to Java plugin website was performed, otherwise, False.
*/
FFInstall(): boolean;
/**
* @summary Gets browser name.
* @return {string} Browser name.
*/
getBrowser(): string;
/**
* @summary Obtains JPI version using {@link navigator.mimeTypes} array if found,
* set the version to {@link firefoxJavaVersion}.
*/
getJPIVersionUsingMimeType(): void;
/**
* @summary Get JRE versions (in format : "#.#[.#[_#]]") installed.
* @return {Array<string>} JRE Version list.
*/
getJREs(): Array<string>;
/**
* Gets a Java plugin.
* @return {HTMLElement} Java plugin.
*/
getPlugin(): HTMLElement;
/**
* Redirect to Java plugin website for Internet Explorer.
* @return {boolean} True if the redirection to Java plugin website was performed, otherwise, False.
*/
IEInstall(): boolean;
/**
* @summary Triggers a JRE installation.
* @param {string} requestVersion JRE request version.
* @return {boolean} True if the install is succeeded, otherwise, False.
*/
installJRE(requestVersion: string): boolean;
/**
* @summary Triggers a installation of the latest version of JRE.
* @param {Function} installCallback A reference to a javascript callback function for reporting install status.
* @return {boolean} True if the install is succeeded, otherwise, False.
*/
installLatestJRE(installCallback?: Function): boolean;
/**
* @summary Determines if JRE auto install for the version is enabled for the local system.
*
* DT plugin for 6uX only knows about JRE installer signed by SUN cert.
* If it encounter Oracle signed JRE installer, it will have chance of
* deadlock when running with IE. This function is to guard against this.
*
* @param {string} requestedJREVersion JRE version. If not specified, it will be treated as installing any JRE version.
* @return {boolean} True if JRE auto install for the version is enabled for the local system, otherwise, False.
*/
isAutoInstallEnabled(requestedJREVersion?: string): boolean;
/**
* @summary Determines if the plugin is installed and AutoUpdate is enabled.
* @return {boolean} True if the plugin is installed and AutoUpdate is enabled, otherwise, False.
*/
isAutoUpdateEnabled(): boolean;
/**
* @summary Determines if JRE install callback is supported.
* @return {boolean} True if JRE install callback is supported, otherwise, False.
*/
isCallbackSupported(): boolean;
/**
* @summary Determines if the next generation plugin (Plugin II) is default.
* @return {boolean} True if next generation plugin is default, otherwise, False.
*/
isPlugin2(): boolean;
/**
* @summary Determines if the ActiveX or XPI plugin is installed.
* @return {boolean} True if the ActiveX or XPI plugin is installed, otherwise, False.
*/
isPluginInstalled(): boolean;
/**
* @summary Checks if an installation of Java Web Start of the specified minimum version can be detected.
* @param {string} minimumVersion Minimum version.
* @return {boolean} True if an installation of Java Web Start of the specified minimum version can be detected
*/
isWebStartInstalled(minimumVersion?: string): boolean;
/**
* @summary Launch a JNLP application (using the plugin if available).
* @param {string} jnlp JNLP file.
* @return {boolean} True if a JNLP application is launched, otherwise, False.
*/
launch(jnlp: string): boolean;
/**
* @summary Launch the specified JNLP application using the passed in jnlp file.
* @param {string} jnlp JNLP file.
*/
launchWebStartApplication(jnlp: string): void;
/**
* @summary Checks versions of JRE available.
*/
poll(): void;
/**
* @summary Writes embed tags if JRE plugin is available.
*/
refresh(): void;
/**
* @summary Ensures that an appropriate JRE is installed and then runs an applet.
*
* After installJRE() is called, the script will attempt to detect that the
* JRE installation has completed and begin running the applet, but there
* are circumstances (such as when the JRE installation requires a browser
* restart) when this cannot be fulfilled.
* As with writeAppletTag(), this function should only be called prior to
* the web page being completely rendered. Note that version wildcards
* (star (*) and plus (+)) are not supported, and including them in the
* minimumVersion will result in an error message.
*
* @param {Object} attributes Names and values of the attributes of the generated <applet> tag.
* @param {Object} parameters Names and values of the <param> tags in the generated <applet> tag.
* @param {string} minimumVersion A minimum version of the JRE software that is required to run this applet. Default value is : "1.1".
*/
runApplet(attributes: Object, parameters: Object, minimumVersion?: string): void;
/**
* @summary Sets additional package list.
*
* Note: To be used by kernel installer.
*
* @param {string} packageList Package list.
* @return {boolean} True if the value was set, otherwise, False if the plugin is already installed.
*/
setAdditionalPackages(packageList: string): boolean;
/**
* @summary Sets AutoUpdate on if plugin is installed.
*/
setAutoUpdateEnabled(): void;
/**
* @summary Sets preference to install Early Access versions if available.
* @param {string} enabled Preference to install Early Access versions.
*/
setEarlyAccess(enabled: string): void;
/**
* @summary Sets the preferred install type.
* @param {string} type Preferred install (null, online or kernel).
* @return {boolean} True if the value was set, otherwise, False if the plugin is already installed.
*/
setInstallerType(type: string): boolean;
/**
* @summary Detects the Microsoft virtual machine.
* @return {boolean} True if the Microsoft virtual machine exists, otherwise, False.
*/
testForMSVM(): boolean;
/**
* @summary Checks if ActiveX can be used with Java plugin.
* @param {string} Java version.
* @return {boolean} True if ActiveX can be used, otherwise, False.
*/
testUsingActiveX(version: string): boolean;
/**
* @summary Checks if MIME types can be used with Java plugin.
* @param {string} Java version.
* @return {boolean} True if MIME types can be used, otherwise, False.
*/
testUsingMimeTypes(version: string): boolean;
/**
* @summary Checks if plugins can be used with Java plugin.
* @param {string} Java version.
* @return {boolean} True if plugins can be used, otherwise, False.
*/
testUsingPluginsArray(version: string): boolean;
/**
* @summary Check if there is a matching JRE version currently installed.
* @param {string} versionPattern Java version pattern (in format : #[.#[.#[_#]]][+|*]).
* @return {boolean} True if there is a matching JRE version currently installed, otherwise, False.
*/
versionCheck(versionPattern: string): boolean;
/**
* @summary Write in outputs an applet tag for applet with the specified attributes and parameters.
*
* Each key/value pair in attributes becomes an attribute of the applet tag
* itself, while key/value pairs in parameters become <PARAM> tags.
* No version checking or other special behaviors are performed; the tag is
* simply written to the page using document.writeln().
* As document.writeln() is generally only safe to use while the page is
* being rendered, you should never call this function after the page
* has been completed.
*
* @param {Object} attributes Names and values of the attributes of the generated <applet> tag.
* @param {Object} parameters Names and values of the <param> tags in the generated <applet> tag.
*/
writeAppletTag(attributes: Object, parameters: Object): void;
/**
* @summary Write in outputs an embed tag for applet.
*/
writeEmbedTag(): void;
}
}
declare var deployJava: DeployJava.DeployJavaStatic;
+139
View File
@@ -0,0 +1,139 @@
/// <reference path="di-lite.d.ts" />
interface Dependency {
dependencies?: string;
}
function doTest(test: (ctx: any, ...obj: Dependency[]) => void) {
// create di context
var ctx = di.createContext(),
A: Dependency = () => {
this.dependencies = "b, c";
},
B: Dependency = () => {
this.dependencies = "c";
},
C: Dependency = () => {};
// register a class with an unique name
ctx.register("a", A);
ctx.register("b", B);
ctx.register("c", C);
test(ctx, A, B, C);
}
module BasicWiring {
doTest(ctx => {
// initialize di container so all singleton(default) objects will be wired at this stage
ctx.initialize();
var instanceOfA = ctx.get("a");
instanceOfA.b === ctx.get("b"); // true
instanceOfA.c === ctx.get("c"); // true
var instanceOfB = ctx.get("b");
instanceOfB.c === ctx.get("c"); // true
});
}
module WiringWithAssignment {
doTest((ctx, A) => {
A.dependencies = "bee=b, c"; // mix explicit and implicit assignment
ctx.initialize();
var instanceOfA = ctx.get("a");
instanceOfA.bee === ctx.get("b"); // true - explicit assignment
instanceOfA.c === ctx.get("c"); // true - implicit assignment
});
}
module PassiveDependencyResolution {
doTest((ctx, A) => {
ctx.register("a", A);
ctx.get("a"); // this triggers the dependency resolution for "a" alone
ctx.initialize();
});
}
module PrototypeStrategy {
doTest((ctx, A) => {
ctx.register("prototype", A).strategy(di.strategy.proto);
ctx.get("prototype") === ctx.get("prototype"); // false
ctx.create("prototype", 100); // create can be used if you want to explicitly pass in a new parameter
});
}
module PassingConstructorArguments {
class ProfileView { }
doTest(ctx => {
ctx.register("str", String, "hello world"); // signle simple argument
ctx.register("profileView", ProfileView, { el: "#profile_div" }); // signle object literal argument
ctx.register("array", Array, ["Saab", "Volvo", "BMW"]); // multiple argument is passed in using an array
});
}
module CyclicalDependency {
doTest((ctx, A, B) => {
A.dependencies = "b";
B.dependencies = "a";
ctx.register("a", A);
ctx.register("b", B);
ctx.initialize();
ctx.get("a").b === ctx.get("b"); // true
ctx.get("b").a === ctx.get("a"); // true
ctx.get("a").b.a === ctx.get("a"); // true
ctx.get("b").a.b === ctx.get("b"); // true
});
}
module FunctionalObject {
doTest(ctx => {
var FuncObject = (spec: any) => {
var that = {};
return that;
},
spec: any = [];
ctx.register("funcObjSingleton", FuncObject, spec).factory(di.factory.func);
// function chaining can be used to customize your object registration
ctx.register("funcObjProto", FuncObject, spec)
.strategy(di.strategy.proto)
.factory(di.factory.func);
ctx.initialize();
ctx.get("funcObjSingleton"); // will return you a signleton instance of FuncObject
ctx.get("funcObjProto"); // will return you a new instance of FuncObject each time
});
}
module RuntimeDependenciesOverride {
doTest((ctx, A) => {
ctx.register("a", A)
.dependencies("bee=b"); // dependencies specified here will take precedence
ctx.get("a").bee === ctx.get("b"); // true
});
}
module CreateYourOwn {
class Backbone {
history: History = new History();
}
class History {
start() {}
}
doTest(ctx => {
ctx.register("history").object(new Backbone().history);
ctx.get("history").start(); // you can use it since it is already created and initialized
ctx.initialize(); // initialize the rest of the objects
});
}
+69
View File
@@ -0,0 +1,69 @@
// Type definitions for di-lite 0.3.3
// Project: https://github.com/NickQiZhu/di.js
// Definitions by: Timothy Morris <https://github.com/dcrusader>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module DiLite {
interface DiLiteStatic {
version: string;
createContext(): CreateContext;
dependencyExpression(depExp: string): string;
entry(name: string, ctx: CreateContext): any;
strategy: StrategyEnum;
factory: FactoryEnum;
utils: Utils;
}
interface Dictionary<T> {
[index: string]: T;
}
interface CreateContext {
map: Dictionary<any>;
entry<T>(name: string): T;
register<T>(name: string, service: T): Entry;
has(name: string): boolean;
get(name: string): any;
create<T>(name: string, args: any): T;
initialize(): void;
clear(): void;
inject<T>(name: string, o: T, dependencies: string): T;
ready<T>(o: Function): T;
ready<T>(o: any): T;
}
interface Entry {
create(newArgs: any): Entry;
object<T>(o: T): Entry;
object<T>(): T;
strategy<T>(s: Function): Entry;
strategy<T>(): T;
type<T>(t: T): Entry;
type<T>(): T;
dependencies<T>(d: T): Entry;
dependencies<T>(): T;
args<T>(a: T): Entry;
args<T>(): T;
factory(f: Function): Entry;
factory<T>(): T;
}
interface StrategyEnum {
proto<TObject, TType>(name: string, object: TObject, type: TType, args: any, ctx: CreateContext, dependencies: any): TObject;
singleton<TObject, TType>(name: string, object: TObject, type: TType, args: any, ctx?: CreateContext, dependencies?: any): TObject;
}
interface FactoryEnum {
constructor<T>(type: T, args: any): T;
func<T>(type: T, args: any): T;
}
interface Utils {
invokeStmt(args: any, op: string): string;
}
}
declare module "di-lite" {
export = di;
}
declare var di: DiLite.DiLiteStatic;
@@ -0,0 +1,8 @@
/// <reference path="element-resize-event.d.ts" />
import ere = require("element-resize-event");
var domNode: Element = null;
ere(domNode, (): void => {
});
+9
View File
@@ -0,0 +1,9 @@
// Type definitions for element-resize-event 1.0.1
// Project: https://github.com/KyleAMathews/element-resize-event
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "element-resize-event" {
function elementResizeEvent(domNode: Element, callback: () => void): void;
export = elementResizeEvent;
}
+45 -7
View File
@@ -253,6 +253,20 @@ declare module Ember {
**/
function A(arr?: any[]): NativeArray;
/**
The Ember.ActionHandler mixin implements support for moving an actions property to an _actions
property at extend time, and adding _actions to the object's mergedProperties list.
**/
class ActionHandlerMixin {
/**
Triggers a named action on the ActionHandler
**/
send(name: string, ...args: any[]): void;
/**
The collection of functions, keyed by name, available on this ActionHandler as action targets.
**/
actions: ActionsHash;
}
/**
An instance of Ember.Application is the starting point for every Ember application. It helps to
instantiate, initialize and coordinate the many objects that make up your app.
**/
@@ -446,6 +460,11 @@ declare module Ember {
controllers: {};
needs: string[];
target: any;
model: any;
queryParams: any;
send(name: string, ...args: any[]): void;
actions: {};
}
/**
Array polyfills to support ES5 features in older browsers.
@@ -719,15 +738,27 @@ declare module Ember {
static isClass: boolean;
static isMethod: boolean;
}
class Controller extends Object { }
/**
Additional methods for the ControllerMixin.
**/
class ControllerMixin {
class Controller extends Object implements ControllerMixin {
replaceRoute(name: string, ...args: any[]): void;
transitionToRoute(name: string, ...args: any[]): void;
controllers: {};
model: any;
needs: string[];
queryParams: any;
target: any;
send(name: string, ...args: any[]): void;
actions: ActionsHash;
}
/**
Additional methods for the ControllerMixin.
**/
class ControllerMixin extends ActionHandlerMixin {
replaceRoute(name: string, ...args: any[]): void;
transitionToRoute(name: string, ...args: any[]): void;
controllers: {};
model : any;
needs: string[];
queryParams: any;
target: any;
}
/**
@@ -790,7 +821,7 @@ declare module Ember {
and other classes like Ember._SimpleMetamorphView that don't need the fully functionaltiy of Ember.View.
Unless you have specific needs for CoreView, you will use Ember.View in your applications.
**/
class CoreView extends Object {
class CoreView extends Object implements ActionHandlerMixin {
static detect(obj: any): boolean;
static detectInstance(obj: any): boolean;
/**
@@ -805,6 +836,8 @@ declare module Ember {
static metaForProperty(key: string): {};
static isClass: boolean;
static isMethod: boolean;
send(name: string, ...args: any[]): void;
actions: ActionsHash;
parentView: CoreView;
}
class DAG {
@@ -1449,6 +1482,10 @@ declare module Ember {
controllers: Object;
needs: string[];
target: any;
model: any;
queryParams: any;
send(name: string, ...args: any[]): void;
actions: {};
}
class ObjectProxy extends Object {
static detect(obj: any): boolean;
@@ -1527,7 +1564,7 @@ declare module Ember {
elementTag: string;
parentBuffer: RenderBuffer;
}
class Route extends Object {
class Route extends Object implements ActionHandlerMixin {
static detect(obj: any): boolean;
static detectInstance(obj: any): boolean;
/**
@@ -2181,6 +2218,7 @@ declare module Em {
**/
var $: typeof Ember.$;
var A: typeof Ember.A;
class ActionHandlerMixin extends Ember.ActionHandlerMixin { }
class Application extends Ember.Application { }
class Array extends Ember.Array { }
class ArrayController extends Ember.ArrayController { }
+81
View File
@@ -0,0 +1,81 @@
/// <reference path="./formidable.d.ts" />
import formidable = require('formidable');
import http = require('http');
import util = require('util');
http.createServer((req, res) => {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, (err, fields, files) => {
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
});
var form = new formidable.IncomingForm();
form.encoding = 'utf-8';
form.uploadDir = '/my/dir';
form.keepExtensions = false;
form.maxFieldsSize = 2 * 1024 * 1024;
form.maxFields = 1000;
form.hash = false;
form.hash = 'sha1';
form.multiples = false;
if (form.type === 'multipart') {
}
if (form.bytesReceived > 100) {
}
if (form.bytesExpected > 100) {
}
var req: http.ServerRequest;
form.parse(req);
form.parse(req, (err: any, fields: formidable.Fields, files: formidable.Files) => {
var key: string;
for (key in fields) {
console.log(key, '=', fields[key]);
}
for (key in files) {
console.log('file', key, 'is', files[key].type);
}
});
form.onPart = function (part: formidable.Part) {
if (!part.filename) {
form.handlePart(part);
}
};
var file: formidable.File;
file.size = 0;
file.path = '/tmp/whatever';
file.name = 'a_file';
file.type = 'application/json';
file.lastModifiedDate = new Date();
file.hash = '12345';
JSON.stringify(file.toJSON());
form.on('progess', (bytesReceived: number, bytesExpected: number) => {});
+56
View File
@@ -0,0 +1,56 @@
// Type definitions for Formidable 1.0.16
// Project: https://github.com/felixge/node-formidable/
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "formidable" {
import http = require("http");
import stream = require("stream");
import events = require("events");
export class IncomingForm extends events.EventEmitter {
encoding: string;
uploadDir: string;
keepExtensions: boolean;
maxFieldsSize: number;
maxFields: number;
hash: string | boolean;
multiples: boolean;
type: string;
bytesReceived: number;
bytesExpected: number;
onPart: (part: Part) => void;
handlePart(part: Part): void;
parse(req: http.ServerRequest, callback?: (err: any, fields: Fields, files: Files) => any): void;
}
export interface Fields {
[key: string]: string;
}
export interface Files {
[key: string]: File; // | File[];
}
export interface Part extends stream.Stream {
headers: { [key: string]: string };
name: string;
filename?: string;
mime?: string;
}
export interface File {
size: number;
path: string;
name: string;
type: string;
lastModifiedDate?: Date;
hash?: string;
toJSON(): Object;
}
}
+17 -19
View File
@@ -19,24 +19,22 @@
};
(()=>{
window.addEventListener('GamepadConnected', (e: Gamepad.GamepadEvent)=>{
var gamepadconnected = (e: Gamepad.GamepadEvent) => {
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('GamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
if(e.gamepad.mapping == 'standard'){
console.log("The Gamepad's controls have been mapped to the Standard Gamepad layout.");
}
};
var gamepaddisconnected = (e: Gamepad.GamepadEvent) => {
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('webkitGamepadConnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('webkitGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
window.addEventListener('mozGamepadConnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' connected!');
}, false);
window.addEventListener('mozGamepadDisconnected', (e: Gamepad.GamepadEvent)=>{
console.log('Gamepad ' + e.gamepad.index + ' disconnected!');
}, false);
};
window.addEventListener('GamepadConnected', gamepadconnected, false);
window.addEventListener('GamepadDisconnected', gamepaddisconnected, false);
window.addEventListener('webkitGamepadConnected', gamepadconnected, false);
window.addEventListener('webkitGamepadDisconnected', gamepaddisconnected, false);
window.addEventListener('mozGamepadConnected', gamepadconnected, false);
window.addEventListener('mozGamepadDisconnected', gamepaddisconnected, false);
var requestAnimationFrame = window.requestAnimationFrame || (<any>window).mozRequestAnimationFrame;
var getGamepads = navigator.getGamepads || navigator.webkitGetGamepads;
@@ -45,13 +43,13 @@
{
requestAnimationFrame.call(window, runAnimation);
var gamepads: Gamepad.GamepadList = getGamepads.call(navigator);
var gamepads: Gamepad.Gamepad[] = getGamepads.call(navigator);
for(var i = 0; i < gamepads.length; i++){
var pad: Gamepad.Gamepad = gamepads[i];
if(pad){
if(pad && pad.connected){
for (var k = 0; k < pad.buttons.length; k++)
{
var button = pad.buttons[k];
var button: Gamepad.GamepadButton = pad.buttons[k];
if(button.pressed){
console.log('pad[' + pad.index + ']: ' + 'time=' + pad.timestamp + ' id="' + pad.id + '" button[' + k + '] = ' + button.value);
}
+12
View File
@@ -37,6 +37,18 @@ declare module Gamepad{
* @readonly
*/
buttons:GamepadButton[];
/**
* Indicates whether the physical device represented by this object is still connected to the system. When a gamepad becomes unavailable, whether by being physically disconnected, powered off or otherwise unusable, the connected attribute must be set to false.
* @readonly
*/
connected:boolean;
/**
* The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it should indicate that a mapping is in use by setting this property to a known mapping name. Currently the only known mapping is "standard", which corresponds to the Standard Gamepad layout. If the user agent does not have knowledge of the device layout and is simply providing the controls as represented by the driver in use, then it must set the mapping property to an empty string.
* @readonly
*/
mapping:string;
}
/**
+2
View File
@@ -40,6 +40,8 @@ declare module UniversalAnalytics {
// https://developers.google.com/analytics/devguides/collection/analyticsjs/method-reference
interface ga {
l: number;
q: any[];
(command: string, poly: string, opt_poly?: {}): UniversalAnalytics.Tracker;
(command: string, trackingId: string, auto: string, opt_configObject?: {}): UniversalAnalytics.Tracker;
(command: string, hitDetails: {}): void;
+1 -1
View File
@@ -112,7 +112,7 @@ var params_obj = { a:['4','5','6'], b:{x:['7'], y:'8', z:['9','0','true','false'
params_obj_bang_coerce = { "!a":[4], a:[5,6] };//, b:{x:[7], y:8, z:[9,0,true,false,undefined,'']}, c:1 };
test( 'jQuery.param.sorted', function() {
var tests = [
var tests: any[] = [
{
obj: {z:1,b:2,ab:3,bc:4,ba:5,aa:6,a1:7,x:8},
traditional: false,
+2 -1
View File
@@ -19,6 +19,7 @@ interface JQueryCookieStatic {
(): {[key:string]:string};
(name: string): any;
(name: string, converter: (value: string) => any): any;
(name: string, value: string): void;
(name: string, value: string, options: JQueryCookieOptions): void;
(name: string, value: any): void;
@@ -30,4 +31,4 @@ interface JQueryStatic {
removeCookie(name: string): boolean;
removeCookie(name: string, options: JQueryCookieOptions): boolean;
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ interface JQueryStatic {
interface JQuery {
livestamp(date: Date): JQuery;
livestamp(moment: Moment): JQuery;
livestamp(moment: moment.Moment): JQuery;
livestamp(timestamp: number): JQuery;
livestamp(timestamp: string): JQuery;
}
+32
View File
@@ -0,0 +1,32 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="jquery.tipsy.d.ts"/>
// basic
$('#example-1').tipsy();
// code snippets from http://onehackoranother.com/projects/jquery/tipsy/
$('#foo').tipsy({gravity: 'n'}); // nw | n | ne | w | e | sw | s | se
$('#foo').tipsy({gravity: $.fn.tipsy.autoNS});
$('#example-fade').tipsy({fade: true});
$('#example-custom-attribute').tipsy({title: 'id'});
$('#example-callback').tipsy({title: function() { return this.getAttribute('original-title').toUpperCase(); } });
$('#example-fallback').tipsy({fallback: "Where's my tooltip yo'?" });
$('#example-html').tipsy({html: true });
$('#example-delay').tipsy({delayIn: 500, delayOut: 1000});
$(function() {
$('#focus-example [title]').tipsy({trigger: 'focus', gravity: 'w'});
});
function onclickExample1() { $("#manual-example a[rel=tipsy]").tipsy("show"); return false; }
function onclickExample2() { $("#manual-example a[rel=tipsy]").tipsy("hide"); return false; }
$('#manual-example a[rel=tipsy]').tipsy({trigger: 'manual'});
$('a.live-tipsy').tipsy({live: true});
+107
View File
@@ -0,0 +1,107 @@
// Type definitions for jQuery.tipsy
// Project: http://onehackoranother.com/projects/jquery/tipsy/
// Definitions by: Brian Dukes <https://github.com/bdukes/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface JQuery {
/**
* initialize tipsy plugin
*/
tipsy: JQueryTipsy.Tipsy;
}
declare module JQueryTipsy {
interface Options {
/**
* delay before showing tooltip (ms)
*
* default: 0
*/
delayIn?: number;
/**
* delay before hiding tooltip (ms)
*
* default: 0
*/
delayOut?: number;
/**
* fade tooltips in/out?
*
* default: false
*/
fade?: boolean;
/**
* fallback text to use when no tooltip text
*
* default: ''
*/
fallback?: string;
/**
* gravity
*
* default: 'n'
*/
gravity?: any; // string or () => string
/**
* is tooltip content HTML?
*
* default: false
*/
html?: boolean;
/**
* use live event support?
*
* default: false
*/
live?: boolean;
/**
* pixel offset of tooltip from element
*
* default: 0
*/
offset?: number;
/**
* opacity of tooltip
*
* default: 0.8
*/
opacity?: number;
/**
* attribute/callback containing tooltip text
*
* default: 'title'
*/
title?: any; // string or () => string
/**
* how tooltip is triggered - hover | focus | manual
*
* default: 'hover'
*/
trigger?: string;
}
interface Tipsy {
/**
* initialize tipsy plugin
*/
(options?: Options): JQuery;
/**
* determine gravity either to North or South automatically based on the element's location in the viewport
*/
autoNS: () => string;
/**
* determine gravity either to West or East automatically based on the element's location in the viewport
*/
autoWE: () => string;
/**
* determine gravity either to Southwest or Southeast automatically based on the element's location in the viewport
*/
autoSWSE: () => string;
/**
* determine gravity either to Northwest or Northeast automatically based on the element's location in the viewport
*/
autoNWNE: () => string;
}
}
+8
View File
@@ -25,4 +25,12 @@ interface JQuery {
transition(options: JQueryTransitOptions, duration: number, easing: string): JQuery;
transition(options: JQueryTransitOptions, complete: () => void): JQuery;
transition(options: JQueryTransitOptions, duration: number, easing: string, complete: () => void): JQuery;
/**
* Set one or more CSS properties for the set of matched elements.
*
* @param propertyName A CSS property name.
* @param value A value to set for the property.
*/
css(propertyName: string, value: number[]): JQuery;
}
+7 -7
View File
@@ -1,6 +1,6 @@
// Type definitions for jquery.validation 1.11.1
// Project: http://jqueryvalidation.org/
// Definitions by: François de Campredon <https://github.com/fdecampredon>, Johj Reilly <https://github.com/johnnyreilly>
// Definitions by: François de Campredon <https://github.com/fdecampredon>, John Reilly <https://github.com/johnnyreilly>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -89,21 +89,21 @@ interface ValidationOptions
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onclick?: any;
onclick?: boolean|Function;
/**
* Boolean or Function. Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onfocusout?: any;
onfocusout?: boolean|Function;
/**
* Boolean or Function. Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable.
*
* Set to a Function to decide for yourself when to run validation.
* A boolean true is not a valid value.
*/
onkeyup?: any;
onkeyup?: boolean|Function;
/**
* Validate the form on submit. Set to false to use only other events for validation.
* Set to a Function to decide for yourself when to run validation.
@@ -127,7 +127,7 @@ interface ValidationOptions
/**
* String or Function. If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like "ok!".
*/
success?: any;
success?: string|{($label: JQuery, validatedInput: HTMLElement):void};
/**
* Called to revert changes made by option highlight, same arguments as highlight.
*
@@ -180,13 +180,13 @@ interface Validator
* @param name The name of the method used to identify it and referencing it; this must be a valid JavaScript identifier
* @param method The actual method implementation, returning true if an element is valid. First argument: Current value. Second argument: Validated element. Third argument: Parameters.
*/
addMethod(name: string, method: (value: any, element: any, params: any) => any, message?: any): void;
addMethod(name: string, method: (value: any, element: HTMLElement, params: any) => any, message?: any): void;
/**
* Validates a single element, returns true if it is valid, false otherwise.
*
* @param element An element to validate, must be inside the validated form. eg "#myselect"
*/
element(element: any): boolean;
element(element: string): boolean;
/**
* Validates the form, returns true if it is valid, false otherwise.
*/
+1 -1
View File
@@ -3043,7 +3043,7 @@ function test_merge() {
var first = ['a', 'b', 'c'];
var second = ['d', 'e', 'f'];
$.merge($.merge([], first), second);
var z = $.merge([0, 1, 2], ['a', 'b', 'c']);
var z = $.merge<any>([0, 1, 2], ['a', 'b', 'c']);
}
function test_prop() {
+62 -813
View File
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
import jsdom = require("jsdom");
jsdom.defaultDocumentFeatures.FetchExternalResources = ["img"];
jsdom.env(
"http://nodejs.org/dist/",
["http://code.jquery.com/jquery.js"],
function (errors: Error[], window: Window) {
}
);
jsdom.env(
"http://nodejs.org/dist/",
function (errors: Error[], window: Window) {
}
);
jsdom.env(
"http://nodejs.org/dist/",
{
scripts: ["http://code.jquery.com/jquery.js"],
},
function (errors: Error[], window: Window) {
}
);
jsdom.env(
'<p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom!</a></p>',
["http://code.jquery.com/jquery.js"],
function (errors: Error[], window: Window) {
}
);
jsdom.env({
url: "http://news.ycombinator.com/",
scripts: ["http://code.jquery.com/jquery.js"],
done: function (errors: Error[], window: Window) {
}
});
var jquery: string;
jsdom.env({
url: "http://news.ycombinator.com/",
src: [jquery],
done: function (errors: Error[], window: Window) {
}
});
var window: Window = jsdom.jsdom("<div>foobar</div>").parentWindow;
var document: Document = jsdom.jsdom("<html></html>");
+143
View File
@@ -0,0 +1,143 @@
// Type definitions for jsdom 2.0.0
// Project: https://github.com/tmpvar/jsdom
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "jsdom" {
/**
* The do-what-I-mean API.
*
* Example:
* jsdom.env(html, function (errors, window) {
* // free memory associated with the window
* window.close();
* });
*
* @param urlOrSource may be a URL, file name, or HTML fragment
* @param scriptUrlsOrSources a string or array of strings, containing file names or URLs that will be inserted as
* @param config Configuration object
* @param callback
*/
export function env(urlOrHtml: string, scripts: string, config: Config, callback?: Callback): void;
export function env(urlOrHtml: string, scripts: string, callback: Callback): void;
export function env(urlOrHtml: string, scripts: string[], config: Config, callback?: Callback): void;
export function env(urlOrHtml: string, scripts: string[], callback: Callback): void;
export function env(urlOrHtml: string, callback: Callback): void;
export function env(urlOrHtml: string, config: Config, callback?: Callback): void;
export function env(config: Config, callback?: Callback): void;
/**
* The jsdom.jsdom method does less things automatically; it takes in only HTML source, and does not let you to
* separately supply script that it will inject and execute. It just gives you back a document object,
* with usable document.parentWindow, and starts asynchronously executing any <script>s included in the HTML source.
* You can listen for the 'load' event to wait until scripts are done loading and executing, just like you would in a
* normal HTML page.
*
* @param markup is a HTML document to be parsed. You can also pass undefined to get the basic document,
* equivalent to what a browser will give if you open up an empty .html file.
* @param options see the explanation of the config object above.
*/
export function jsdom(markup: string, config?: Config): Document;
/**
* Before creating any documents, you can modify the defaults for all future documents:
*/
export var defaultDocumentFeatures: FeatureOptions;
export interface Callback {
(errors: Error[], window: Window): any;
}
export interface FeatureOptions {
/**
* Enables/disables fetching files over the file system/HTTP
* Allowed: ["script", "img", "css", "frame", "iframe", "link"] or false
* Default for jsdom.env: false
*/
FetchExternalResources?: any;
/**
* Enables/disables JavaScript execution
* Default: ["script"]
* Allowed: ["script"] or false,
* Default for jsdom.env: false
*/
ProcessExternalResources?: any;
/**
* Filters resource downloading and processing to disallow those matching the given regular expression
* Default: false (allow all)
* Allowed: /url to be skipped/ or false
* Example: /http:\/\/example.org/js/bad\.js/
*/
SkipExternalResources?: any;
}
export interface EnvDocument {
/**
* the new document will have this referrer.
*/
referrer?: string;
/**
* manually set a cookie value, e.g. 'key=value; expires=Wed, Sep 21 2011 12:00:00 GMT; path=/'.
*/
cookie?: string;
/**
* a cookie domain for the manually set cookie; defaults to 127.0.0.1.
*/
cookieDomain?: string;
}
export interface Config {
/**
* a HTML fragment
*/
html?: string;
/**
* a file which jsdom will load HTML from; the resulting window's location.href will be a file:// URL.
*/
file?: string;
/**
* sets the resulting window's location.href; if config.html and config.file are not provided, jsdom will load HTML from this URL
*/
url?: string;
/**
* a string or array of strings, containing file names or URLs that will be inserted as <script> tags
*/
scripts?: string[];
/**
* an array of JavaScript strings that will be evaluated against the resulting document. Similar to scripts, but it accepts JavaScript instead of paths/URLs.
*/
src?: string[];
/**
* a custom cookie jar, if desired; see mikeal/request documentation.
*/
jar?: any;
/**
* either "auto", "html", or "xml". The default is "auto", which uses HTML behavior unless config.url responds with an XML Content-Type, or config.file contains a filename ending in .xml or .xhtml. Setting to "xml" will attempt to parse the document as an XHTML document. (jsdom is currently only OK at doing that.)
*/
parsingMode?: string;
document?: EnvDocument;
/**
* Note: the default feature set for jsdom.env does not include fetching remote JavaScript and executing it. This is something that you will need to carefully enable yourself.
*/
features?: FeatureOptions;
/**
* Now that you know about created and loaded, you can see that done is essentially both of them smashed together:
* If window creation succeeds and no <script>s cause errors, then errors will be null, and window will be usable.
* If window creation succeeds but there are script errors, then errors will be an array containing those errors, but window will still be usable.
* If window creation fails, then errors will be an array containing the creation error, and window will not be passed.
*/
done?: Callback;
/**
* The loaded callback is called along with the window's 'load' event. This means it will only be called if creation succeeds without error. Note that by the time it has called, any external resources will have been downloaded, and any <script>s will have finished executing. If errors is non-null, it will contain an array of all JavaScript errors that occured during script execution. window will still be passed, however.
*/
loaded?: Callback;
/**
* The created callback is called as soon as the window is created, or if that process fails. You may access all window properties here; however, window.document is not ready for use yet, as the HTML has not been parsed. The primary use-case for created is to modify the window object (e.g. add new functions on built-in prototypes) before any scripts execute. You can also set an event handler for 'load' or other events on the window if you wish. But the loaded callback, below, can be more useful, since it includes script errors. If the error argument is non-null, it will contain whatever loading error caused the window creation to fail; in that case window will not be passed.
*/
created?: (error: Error, window: Window) => void;
}
}
+2
View File
@@ -163,6 +163,8 @@ declare module Knockback {
}
interface Static extends Utils {
ViewModel;
CollectionObservable;
collectionObservable(model?: Backbone.Collection<Backbone.Model>, options?: CollectionOptions): CollectionObservable;
/** Base class for observing model attributes. */
observable(
+2 -1
View File
@@ -9,6 +9,7 @@ interface KnockoutPostBox {
subscribe<T>(topic: string, handler: (value: T) => void , target?: any): KnockoutSubscription;
publish<T>(topic: string, value?: T): void;
defaultComparer<T>(newValue: T, oldValue: T): boolean;
serializer: (object: any) => string;
}
interface KnockoutObservable<T> {
@@ -29,4 +30,4 @@ interface KnockoutObservableArray<T> {
interface KnockoutStatic {
postbox: KnockoutPostBox;
}
}
+2 -2
View File
@@ -306,7 +306,7 @@ interface KnockoutUtils {
triggerEvent(element: any, eventType: any): void;
unwrapObservable<T>(value: KnockoutObservable<T>): T;
unwrapObservable<T>(value: KnockoutObservable<T> | T): T;
peekObservable<T>(value: KnockoutObservable<T>): T;
@@ -442,7 +442,7 @@ interface KnockoutStatic {
cleanNode(node: Element): Element;
renderTemplate(template: Function, viewModel: any, options?: any, target?: any, renderMode?: any): any;
renderTemplate(template: string, viewModel: any, options?: any, target?: any, renderMode?: any): any;
unwrap(value: any): any;
unwrap<T>(value: KnockoutObservable<T> | T): T;
computedContext: KnockoutComputedContext;
+7
View File
@@ -648,4 +648,11 @@ function test_Components() {
// Empty config for registering custom elements that are handled by name convention
ko.components.register('name', { /* No config needed */ });
}
}
function testUnwrapUnion() {
var possibleObs: KnockoutObservable<number> | number;
var num = ko.unwrap(possibleObs);
}
+27
View File
@@ -48,3 +48,30 @@ laddaBtn.start().stop().toggle().setProgress(42).enable().disable().start();
// Test isLoading
console.assert(laddaBtn.isLoading() === true);
//Test jQuery plugin Support
// Automatically trigger the loading animation on click
$('input[type=submit]').ladda('bind');
// Same as the above but automatically stops after two seconds
$('input[type=submit]').ladda('bind', { timeout: 2000 });
// Create a new instance of ladda for the specified button
var ljq = $('.my-button').ladda();
// Start loading
ljq.ladda('start');
// Will display a progress bar for 50% of the button width
ljq.ladda('setProgress', 0.5);
// Stop loading
ljq.ladda('stop');
// Toggle between loading/not loading states
ljq.ladda('toggle');
// Check the current state
ljq.ladda('isLoading');
$.ladda('stopAll');
+32 -1
View File
@@ -1,8 +1,10 @@
// Type definitions for Ladda 0.9.4
// Project: https://github.com/hakimel/Ladda
// Definitions by: Danil Flores <https://github.com/dflor003/>
// Definitions by: Danil Flores <https://github.com/dflor003/>, Michael Lee <https://github.com/leemicw>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface ILaddaButton {
start(): ILaddaButton;
startAfter(delay: number): ILaddaButton
@@ -34,3 +36,32 @@ declare var Ladda: ILadda;
declare module "ladda" {
export = Ladda;
}
interface JQuery {
/**
* Creates a new instance of ladda for the selected button
*/
ladda(): JQuery;
/**
* The action controls or checks the state of the ladda button.
* Possible actions are 'start', 'stop', 'toggle', 'stopAll'
* Possible check 'isLoading'
*/
ladda(action: string): JQuery;
/**
* When the action is 'setProgress' you can pass a number between
* 0 and 1 for the options to represent the progress. For example .5 would be 50%
* When the action is 'bind' you can pass an object with a property
* called timeout with the timeout value in milliseconds.
* For example { timeout: 2000 }
*/
ladda(action: string, options: any): JQuery;
}
interface JQueryStatic {
ladda(action: string): JQuery;
}
+4
View File
@@ -2335,6 +2335,10 @@ declare module L {
*/
attributionControl: Control.Attribution;
/**
* Map state options
*/
options: MapOptions;
////////////////
////////////////
+15 -13
View File
@@ -5,8 +5,14 @@
/// <reference path="../moment/moment.d.ts" />
interface Moment {
tz(timezone: string): Moment;
declare module moment {
interface Moment {
tz(timezone: string): Moment;
}
interface MomentStatic {
tz: MomentTimezone;
}
}
interface MomentZone {
@@ -21,12 +27,12 @@ interface MomentZone {
}
interface MomentTimezone {
(date: number, timezone: string): Moment;
(date: number[], timezone: string): Moment;
(date: string, format: string, timezone: string): Moment;
(date: Date, timezone: string): Moment;
(date: Moment, timezone: string): Moment;
(date: Object, timezone: string): Moment;
(date: number, timezone: string): moment.Moment;
(date: number[], timezone: string): moment.Moment;
(date: string, format: string, timezone: string): moment.Moment;
(date: Date, timezone: string): moment.Moment;
(date: moment.Moment, timezone: string): moment.Moment;
(date: Object, timezone: string): moment.Moment;
zone(timezone: string): MomentZone;
@@ -45,12 +51,8 @@ interface MomentTimezone {
names(): string[];
}
interface MomentStatic {
tz: MomentTimezone;
}
declare module 'moment-timezone' {
var _tmp: MomentStatic;
var _tmp: moment.MomentStatic;
export = _tmp;
}
+5 -5
View File
@@ -302,7 +302,7 @@ moment.locale('en', {
});
moment.locale('en', {
months : function (momentToFormat: Moment, format: string) {
months : function (momentToFormat: moment.Moment, format: string) {
// momentToFormat is the moment currently being formatted
// format is the formatting string
if (/^MMMM/.test(format)) { // if the format starts with 'MMMM'
@@ -321,7 +321,7 @@ moment.locale('en', {
});
moment.locale('en', {
monthsShort : function (momentToFormat: Moment, format: string) {
monthsShort : function (momentToFormat: moment.Moment, format: string) {
if (/^MMMM/.test(format)) {
return this.nominative[momentToFormat.month()];
} else {
@@ -337,7 +337,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdays : function (momentToFormat: Moment) {
weekdays : function (momentToFormat: moment.Moment) {
return this.weekdays[momentToFormat.day()];
}
});
@@ -347,7 +347,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdaysShort : function (momentToFormat: Moment) {
weekdaysShort : function (momentToFormat: moment.Moment) {
return this.weekdaysShort[momentToFormat.day()];
}
});
@@ -357,7 +357,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdaysMin : function (momentToFormat: Moment) {
weekdaysMin : function (momentToFormat: moment.Moment) {
return this.weekdaysMin[momentToFormat.day()];
}
});
+5 -5
View File
@@ -302,7 +302,7 @@ moment.locale('en', {
});
moment.locale('en', {
months : function (momentToFormat: Moment, format: string) {
months : function (momentToFormat: moment.Moment, format: string) {
// momentToFormat is the moment currently being formatted
// format is the formatting string
if (/^MMMM/.test(format)) { // if the format starts with 'MMMM'
@@ -321,7 +321,7 @@ moment.locale('en', {
});
moment.locale('en', {
monthsShort : function (momentToFormat: Moment, format: string) {
monthsShort : function (momentToFormat: moment.Moment, format: string) {
if (/^MMMM/.test(format)) {
return this.nominative[momentToFormat.month()];
} else {
@@ -337,7 +337,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdays : function (momentToFormat: Moment) {
weekdays : function (momentToFormat: moment.Moment) {
return this.weekdays[momentToFormat.day()];
}
});
@@ -347,7 +347,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdaysShort : function (momentToFormat: Moment) {
weekdaysShort : function (momentToFormat: moment.Moment) {
return this.weekdaysShort[momentToFormat.day()];
}
});
@@ -357,7 +357,7 @@ moment.locale('en', {
});
moment.locale('en', {
weekdaysMin : function (momentToFormat: Moment) {
weekdaysMin : function (momentToFormat: moment.Moment) {
return this.weekdaysMin[momentToFormat.day()];
}
});
+468 -464
View File
@@ -1,464 +1,468 @@
// Type definitions for Moment.js 2.8.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface MomentInput {
years?: number;
y?: number;
months?: number;
M?: number;
weeks?: number;
w?: number;
days?: number;
d?: number;
hours?: number;
h?: number;
minutes?: number;
m?: number;
seconds?: number;
s?: number;
milliseconds?: number;
ms?: number;
}
interface Duration {
humanize(withSuffix?: boolean): string;
as(units: string): number;
milliseconds(): number;
asMilliseconds(): number;
seconds(): number;
asSeconds(): number;
minutes(): number;
asMinutes(): number;
hours(): number;
asHours(): number;
days(): number;
asDays(): number;
months(): number;
asMonths(): number;
years(): number;
asYears(): number;
add(n: number, p: string): Duration;
add(n: number): Duration;
add(d: Duration): Duration;
subtract(n: number, p: string): Duration;
subtract(n: number): Duration;
subtract(d: Duration): Duration;
toISOString(): string;
}
interface Moment {
format(format: string): string;
format(): string;
fromNow(withoutSuffix?: boolean): string;
startOf(unitOfTime: string): Moment;
endOf(unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
* @param amount the amount you want to add
*/
add(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by adding time.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
add(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by adding time.
*
* @param duration a length of time
*/
add(duration: Duration): Moment;
/**
* Mutates the original moment by subtracting time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
*/
subtract(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
subtract(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param duration a length of time
*/
subtract(duration: Duration): Moment;
calendar(): string;
calendar(start: Moment): string;
clone(): Moment;
/**
* @return Unix timestamp, or milliseconds since the epoch.
*/
valueOf(): number;
local(): Moment; // current date/time in local mode
utc(): Moment; // current date/time in UTC mode
isValid(): boolean;
year(y: number): Moment;
year(): number;
quarter(): number;
quarter(q: number): Moment;
month(M: number): Moment;
month(M: string): Moment;
month(): number;
day(d: number): Moment;
day(d: string): Moment;
day(): number;
date(d: number): Moment;
date(): number;
hour(h: number): Moment;
hour(): number;
hours(h: number): Moment;
hours(): number;
minute(m: number): Moment;
minute(): number;
minutes(m: number): Moment;
minutes(): number;
second(s: number): Moment;
second(): number;
seconds(s: number): Moment;
seconds(): number;
millisecond(ms: number): Moment;
millisecond(): number;
milliseconds(ms: number): Moment;
milliseconds(): number;
weekday(): number;
weekday(d: number): Moment;
isoWeekday(): number;
isoWeekday(d: number): Moment;
weekYear(): number;
weekYear(d: number): Moment;
isoWeekYear(): number;
isoWeekYear(d: number): Moment;
week(): number;
week(d: number): Moment;
weeks(): number;
weeks(d: number): Moment;
isoWeek(): number;
isoWeek(d: number): Moment;
isoWeeks(): number;
isoWeeks(d: number): Moment;
weeksInYear(): number;
isoWeeksInYear(): number;
dayOfYear(): number;
dayOfYear(d: number): Moment;
from(f: Moment): string;
from(f: Moment, suffix: boolean): string;
from(d: Date): string;
from(s: string): string;
from(date: number[]): string;
diff(b: Moment): number;
diff(b: Moment, unitOfTime: string): number;
diff(b: Moment, unitOfTime: string, round: boolean): number;
toDate(): Date;
toISOString(): string;
unix(): number;
isLeapYear(): boolean;
zone(): number;
zone(b: number): Moment;
zone(b: string): Moment;
daysInMonth(): number;
isDST(): boolean;
isBefore(): boolean;
isBefore(b: Moment): boolean;
isBefore(b: string): boolean;
isBefore(b: Number): boolean;
isBefore(b: Date): boolean;
isBefore(b: number[]): boolean;
isBefore(b: Moment, granularity: string): boolean;
isBefore(b: String, granularity: string): boolean;
isBefore(b: Number, granularity: string): boolean;
isBefore(b: Date, granularity: string): boolean;
isBefore(b: number[], granularity: string): boolean;
isAfter(): boolean;
isAfter(b: Moment): boolean;
isAfter(b: string): boolean;
isAfter(b: Number): boolean;
isAfter(b: Date): boolean;
isAfter(b: number[]): boolean;
isAfter(b: Moment, granularity: string): boolean;
isAfter(b: String, granularity: string): boolean;
isAfter(b: Number, granularity: string): boolean;
isAfter(b: Date, granularity: string): boolean;
isAfter(b: number[], granularity: string): boolean;
isSame(b: Moment): boolean;
isSame(b: string): boolean;
isSame(b: Number): boolean;
isSame(b: Date): boolean;
isSame(b: number[]): boolean;
isSame(b: Moment, granularity: string): boolean;
isSame(b: String, granularity: string): boolean;
isSame(b: Number, granularity: string): boolean;
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
// Deprecated as of 2.8.0.
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
locale(language: string): Moment;
locale(reset: boolean): Moment;
locale(): string;
localeData(language: string): Moment;
localeData(reset: boolean): Moment;
localeData(): MomentLanguage;
// Deprecated as of 2.7.0.
max(date: Date): Moment;
max(date: number): Moment;
max(date: any[]): Moment;
max(date: string): Moment;
max(date: string, format: string): Moment;
max(clone: Moment): Moment;
// Deprecated as of 2.7.0.
min(date: Date): Moment;
min(date: number): Moment;
min(date: any[]): Moment;
min(date: string): Moment;
min(date: string, format: string): Moment;
min(clone: Moment): Moment;
get(unit: string): number;
set(unit: string, value: number): Moment;
}
interface MomentCalendar {
lastDay: any;
sameDay: any;
nextDay: any;
lastWeek: any;
nextWeek: any;
sameElse: any;
}
interface MomentLanguage {
months?: any;
monthsShort?: any;
weekdays?: any;
weekdaysShort?: any;
weekdaysMin?: any;
longDateFormat?: MomentLongDateFormat;
relativeTime?: MomentRelativeTime;
meridiem?: (hour: number, minute: number, isLowercase: boolean) => string;
calendar?: MomentCalendar;
ordinal?: (num: number) => string;
}
interface MomentLongDateFormat {
L: string;
LL: string;
LLL: string;
LLLL: string;
LT: string;
l?: string;
ll?: string;
lll?: string;
llll?: string;
lt?: string;
}
interface MomentRelativeTime {
future: any;
past: any;
s: any;
m: any;
mm: any;
h: any;
hh: any;
d: any;
dd: any;
M: any;
MM: any;
y: any;
yy: any;
}
interface MomentStatic {
version: string;
(): Moment;
(date: number): Moment;
(date: number[]): Moment;
(date: string, format?: string, strict?: boolean): Moment;
(date: string, format?: string, language?: string, strict?: boolean): Moment;
(date: string, formats: string[], strict?: boolean): Moment;
(date: string, formats: string[], language?: string, strict?: boolean): Moment;
(date: string, specialFormat: () => void, strict?: boolean): Moment;
(date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment;
(date: Date): Moment;
(date: Moment): Moment;
(date: Object): Moment;
utc(): Moment;
utc(date: number): Moment;
utc(date: number[]): Moment;
utc(date: string, format?: string, strict?: boolean): Moment;
utc(date: string, format?: string, language?: string, strict?: boolean): Moment;
utc(date: string, formats: string[], strict?: boolean): Moment;
utc(date: string, formats: string[], language?: string, strict?: boolean): Moment;
utc(date: Date): Moment;
utc(date: Moment): Moment;
utc(date: Object): Moment;
unix(timestamp: number): Moment;
invalid(parsingFlags?: Object): Moment;
isMoment(): boolean;
isMoment(m: any): boolean;
// Deprecated in 2.8.0.
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
locale(language?: string): string;
locale(language?: string[]): string;
locale(language?: string, definition?: MomentLanguage): string;
localeData(language?: string): MomentLanguage;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
calendar: any;
ordinal: (num: number) => string;
duration(milliseconds: Number): Duration;
duration(num: Number, unitOfTime: string): Duration;
duration(input: MomentInput): Duration;
duration(object: any): Duration;
duration(): Duration;
parseZone(date: string): Moment;
months(): string[];
months(index: number): string;
months(format: string): string[];
months(format: string, index: number): string;
monthsShort(): string[];
monthsShort(index: number): string;
monthsShort(format: string): string[];
monthsShort(format: string, index: number): string;
weekdays(): string[];
weekdays(index: number): string;
weekdays(format: string): string[];
weekdays(format: string, index: number): string;
weekdaysShort(): string[];
weekdaysShort(index: number): string;
weekdaysShort(format: string): string[];
weekdaysShort(format: string, index: number): string;
weekdaysMin(): string[];
weekdaysMin(index: number): string;
weekdaysMin(format: string): string[];
weekdaysMin(format: string, index: number): string;
min(moments: Moment[]): Moment;
max(moments: Moment[]): Moment;
normalizeUnits(unit: string): string;
relativeTimeThreshold(threshold: string, limit: number): void;
/**
* Constant used to enable explicit ISO_8601 format parsing.
*/
ISO_8601(): void;
}
declare var moment: MomentStatic;
declare module 'moment' {
export = moment;
}
// Type definitions for Moment.js 2.8.0
// Project: https://github.com/timrwood/moment
// Definitions by: Michael Lakerveld <https://github.com/Lakerfield>, Aaron King <https://github.com/kingdango>, Hiroki Horiuchi <https://github.com/horiuchi>, Dick van den Brink <https://github.com/DickvdBrink>, Adi Dahiya <https://github.com/adidahiya>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module moment {
interface MomentInput {
years?: number;
y?: number;
months?: number;
M?: number;
weeks?: number;
w?: number;
days?: number;
d?: number;
hours?: number;
h?: number;
minutes?: number;
m?: number;
seconds?: number;
s?: number;
milliseconds?: number;
ms?: number;
}
interface Duration {
humanize(withSuffix?: boolean): string;
as(units: string): number;
milliseconds(): number;
asMilliseconds(): number;
seconds(): number;
asSeconds(): number;
minutes(): number;
asMinutes(): number;
hours(): number;
asHours(): number;
days(): number;
asDays(): number;
months(): number;
asMonths(): number;
years(): number;
asYears(): number;
add(n: number, p: string): Duration;
add(n: number): Duration;
add(d: Duration): Duration;
subtract(n: number, p: string): Duration;
subtract(n: number): Duration;
subtract(d: Duration): Duration;
toISOString(): string;
}
interface Moment {
format(format: string): string;
format(): string;
fromNow(withoutSuffix?: boolean): string;
startOf(unitOfTime: string): Moment;
endOf(unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
* @param amount the amount you want to add
*/
add(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by adding time.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to add (eg "years" / "hours" etc)
*/
add(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by adding time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
add(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by adding time.
*
* @param duration a length of time
*/
add(duration: Duration): Moment;
/**
* Mutates the original moment by subtracting time. (deprecated in 2.8.0)
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(unitOfTime: string, amount: number): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
* @param amount the amount you want to subtract
*/
subtract(amount: number, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time. Note that the order of arguments can be flipped.
*
* @param amount the amount you want to add
* @param unitOfTime the unit of time you want to subtract (eg "years" / "hours" etc)
*/
subtract(amount: string, unitOfTime: string): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param objectLiteral an object literal that describes multiple time units {days:7,months:1}
*/
subtract(objectLiteral: MomentInput): Moment;
/**
* Mutates the original moment by subtracting time.
*
* @param duration a length of time
*/
subtract(duration: Duration): Moment;
calendar(): string;
calendar(start: Moment): string;
clone(): Moment;
/**
* @return Unix timestamp, or milliseconds since the epoch.
*/
valueOf(): number;
local(): Moment; // current date/time in local mode
utc(): Moment; // current date/time in UTC mode
isValid(): boolean;
year(y: number): Moment;
year(): number;
quarter(): number;
quarter(q: number): Moment;
month(M: number): Moment;
month(M: string): Moment;
month(): number;
day(d: number): Moment;
day(d: string): Moment;
day(): number;
date(d: number): Moment;
date(): number;
hour(h: number): Moment;
hour(): number;
hours(h: number): Moment;
hours(): number;
minute(m: number): Moment;
minute(): number;
minutes(m: number): Moment;
minutes(): number;
second(s: number): Moment;
second(): number;
seconds(s: number): Moment;
seconds(): number;
millisecond(ms: number): Moment;
millisecond(): number;
milliseconds(ms: number): Moment;
milliseconds(): number;
weekday(): number;
weekday(d: number): Moment;
isoWeekday(): number;
isoWeekday(d: number): Moment;
weekYear(): number;
weekYear(d: number): Moment;
isoWeekYear(): number;
isoWeekYear(d: number): Moment;
week(): number;
week(d: number): Moment;
weeks(): number;
weeks(d: number): Moment;
isoWeek(): number;
isoWeek(d: number): Moment;
isoWeeks(): number;
isoWeeks(d: number): Moment;
weeksInYear(): number;
isoWeeksInYear(): number;
dayOfYear(): number;
dayOfYear(d: number): Moment;
from(f: Moment): string;
from(f: Moment, suffix: boolean): string;
from(d: Date): string;
from(s: string): string;
from(date: number[]): string;
diff(b: Moment): number;
diff(b: Moment, unitOfTime: string): number;
diff(b: Moment, unitOfTime: string, round: boolean): number;
toDate(): Date;
toISOString(): string;
unix(): number;
isLeapYear(): boolean;
zone(): number;
zone(b: number): Moment;
zone(b: string): Moment;
daysInMonth(): number;
isDST(): boolean;
isBefore(): boolean;
isBefore(b: Moment): boolean;
isBefore(b: string): boolean;
isBefore(b: Number): boolean;
isBefore(b: Date): boolean;
isBefore(b: number[]): boolean;
isBefore(b: Moment, granularity: string): boolean;
isBefore(b: String, granularity: string): boolean;
isBefore(b: Number, granularity: string): boolean;
isBefore(b: Date, granularity: string): boolean;
isBefore(b: number[], granularity: string): boolean;
isAfter(): boolean;
isAfter(b: Moment): boolean;
isAfter(b: string): boolean;
isAfter(b: Number): boolean;
isAfter(b: Date): boolean;
isAfter(b: number[]): boolean;
isAfter(b: Moment, granularity: string): boolean;
isAfter(b: String, granularity: string): boolean;
isAfter(b: Number, granularity: string): boolean;
isAfter(b: Date, granularity: string): boolean;
isAfter(b: number[], granularity: string): boolean;
isSame(b: Moment): boolean;
isSame(b: string): boolean;
isSame(b: Number): boolean;
isSame(b: Date): boolean;
isSame(b: number[]): boolean;
isSame(b: Moment, granularity: string): boolean;
isSame(b: String, granularity: string): boolean;
isSame(b: Number, granularity: string): boolean;
isSame(b: Date, granularity: string): boolean;
isSame(b: number[], granularity: string): boolean;
// Deprecated as of 2.8.0.
lang(language: string): Moment;
lang(reset: boolean): Moment;
lang(): MomentLanguage;
locale(language: string): Moment;
locale(reset: boolean): Moment;
locale(): string;
localeData(language: string): Moment;
localeData(reset: boolean): Moment;
localeData(): MomentLanguage;
// Deprecated as of 2.7.0.
max(date: Date): Moment;
max(date: number): Moment;
max(date: any[]): Moment;
max(date: string): Moment;
max(date: string, format: string): Moment;
max(clone: Moment): Moment;
// Deprecated as of 2.7.0.
min(date: Date): Moment;
min(date: number): Moment;
min(date: any[]): Moment;
min(date: string): Moment;
min(date: string, format: string): Moment;
min(clone: Moment): Moment;
get(unit: string): number;
set(unit: string, value: number): Moment;
}
interface MomentCalendar {
lastDay: any;
sameDay: any;
nextDay: any;
lastWeek: any;
nextWeek: any;
sameElse: any;
}
interface MomentLanguage {
months?: any;
monthsShort?: any;
weekdays?: any;
weekdaysShort?: any;
weekdaysMin?: any;
longDateFormat?: MomentLongDateFormat;
relativeTime?: MomentRelativeTime;
meridiem?: (hour: number, minute: number, isLowercase: boolean) => string;
calendar?: MomentCalendar;
ordinal?: (num: number) => string;
}
interface MomentLongDateFormat {
L: string;
LL: string;
LLL: string;
LLLL: string;
LT: string;
l?: string;
ll?: string;
lll?: string;
llll?: string;
lt?: string;
}
interface MomentRelativeTime {
future: any;
past: any;
s: any;
m: any;
mm: any;
h: any;
hh: any;
d: any;
dd: any;
M: any;
MM: any;
y: any;
yy: any;
}
interface MomentStatic {
version: string;
(): Moment;
(date: number): Moment;
(date: number[]): Moment;
(date: string, format?: string, strict?: boolean): Moment;
(date: string, format?: string, language?: string, strict?: boolean): Moment;
(date: string, formats: string[], strict?: boolean): Moment;
(date: string, formats: string[], language?: string, strict?: boolean): Moment;
(date: string, specialFormat: () => void, strict?: boolean): Moment;
(date: string, specialFormat: () => void, language?: string, strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], strict?: boolean): Moment;
(date: string, formatsIncludingSpecial: any[], language?: string, strict?: boolean): Moment;
(date: Date): Moment;
(date: Moment): Moment;
(date: Object): Moment;
utc(): Moment;
utc(date: number): Moment;
utc(date: number[]): Moment;
utc(date: string, format?: string, strict?: boolean): Moment;
utc(date: string, format?: string, language?: string, strict?: boolean): Moment;
utc(date: string, formats: string[], strict?: boolean): Moment;
utc(date: string, formats: string[], language?: string, strict?: boolean): Moment;
utc(date: Date): Moment;
utc(date: Moment): Moment;
utc(date: Object): Moment;
unix(timestamp: number): Moment;
invalid(parsingFlags?: Object): Moment;
isMoment(): boolean;
isMoment(m: any): boolean;
// Deprecated in 2.8.0.
lang(language?: string): string;
lang(language?: string, definition?: MomentLanguage): string;
locale(language?: string): string;
locale(language?: string[]): string;
locale(language?: string, definition?: MomentLanguage): string;
localeData(language?: string): MomentLanguage;
longDateFormat: any;
relativeTime: any;
meridiem: (hour: number, minute: number, isLowercase: boolean) => string;
calendar: any;
ordinal: (num: number) => string;
duration(milliseconds: Number): Duration;
duration(num: Number, unitOfTime: string): Duration;
duration(input: MomentInput): Duration;
duration(object: any): Duration;
duration(): Duration;
parseZone(date: string): Moment;
months(): string[];
months(index: number): string;
months(format: string): string[];
months(format: string, index: number): string;
monthsShort(): string[];
monthsShort(index: number): string;
monthsShort(format: string): string[];
monthsShort(format: string, index: number): string;
weekdays(): string[];
weekdays(index: number): string;
weekdays(format: string): string[];
weekdays(format: string, index: number): string;
weekdaysShort(): string[];
weekdaysShort(index: number): string;
weekdaysShort(format: string): string[];
weekdaysShort(format: string, index: number): string;
weekdaysMin(): string[];
weekdaysMin(index: number): string;
weekdaysMin(format: string): string[];
weekdaysMin(format: string, index: number): string;
min(moments: Moment[]): Moment;
max(moments: Moment[]): Moment;
normalizeUnits(unit: string): string;
relativeTimeThreshold(threshold: string, limit: number): void;
/**
* Constant used to enable explicit ISO_8601 format parsing.
*/
ISO_8601(): void;
}
}
declare var moment: moment.MomentStatic;
declare module 'moment' {
export = moment;
}
+3 -3
View File
@@ -12,7 +12,7 @@ declare module "mongoose" {
function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection;
function disconnect(callback?: (err?: any) => void): Mongoose;
function model<T extends Document>(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model<T>;
function model<T extends Document>(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model<T>;
function modelNames(): string[];
function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose;
@@ -31,7 +31,7 @@ declare module "mongoose" {
createConnection(host: string, database_name: string, port?: number, options?: ConnectionOption): Connection;
disconnect(callback?: (err?: any) => void): Mongoose;
get(key: string): any;
model<T extends Document>(name: string, schema: Schema, collection?: string, skipInit?: boolean): Model<T>;
model<T extends Document>(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model<T>;
modelNames(): string[];
plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose;
set(key: string, value: any): void;
@@ -47,7 +47,7 @@ declare module "mongoose" {
close(callback?: (err: any) => void): Connection;
collection(name: string, options?: Object): Collection;
model<T extends Document>(name: string, schema: Schema, collection?: string): Model<T>;
model<T extends Document>(name: string, schema?: Schema, collection?: string): Model<T>;
modelNames(): string[];
open(host: string, database?: string, port?: number, options?: ConnectionOption, callback?: (err: any) => void): Connection;
openSet(uris: string, database?: string, options?: ConnectionSetOption, callback?: (err: any) => void): Connection;
@@ -59,7 +59,7 @@ declare module spiderMonkeyParserAPI {
params: Pattern[];
defaults: Expression[];
rest?: Identifier;
body?: any; // BlockStatement | Expression;
body?: BlockStatement | Expression;
generator: boolean;
expression: boolean;
}
@@ -74,7 +74,7 @@ declare module spiderMonkeyParserAPI {
* An empty statement, i.e., a solitary semicolon.
*/
interface EmptyStatement extends Statement {
type: string; //"EmptyStatement";
type: string; // "EmptyStatement";
}
/**
@@ -190,7 +190,7 @@ declare module spiderMonkeyParserAPI {
*/
interface ForStatement extends Statement {
type: string; // "ForStatement";
init?: any; // VariableDeclaration | Expression;
init?: VariableDeclaration | Expression;
test?: Expression;
update?: Expression;
body: Statement;
@@ -201,7 +201,7 @@ declare module spiderMonkeyParserAPI {
*/
interface ForInStatement extends Statement {
type: string; // "ForInStatement";
left: any; // VariableDeclaration | Expression;
left: VariableDeclaration | Expression;
right: Expression;
body: Statement;
each: boolean;
@@ -212,7 +212,7 @@ declare module spiderMonkeyParserAPI {
*/
interface ForOfStatement extends Statement {
type: string; // "ForOfStatement";
left: any; // VariableDeclaration | Expression;
left: VariableDeclaration | Expression;
right: Expression;
body: Statement;
}
@@ -248,7 +248,7 @@ declare module spiderMonkeyParserAPI {
params: Pattern[];
defaults: Expression[];
rest?: Identifier;
body: any; // BlockStatement | Expression;
body: BlockStatement | Expression;
generator: boolean;
expression: boolean;
}
@@ -307,7 +307,7 @@ declare module spiderMonkeyParserAPI {
*/
interface Property extends Node {
type: string; // "Property";
key: any; // Literal | Identifier;
key: Literal | Identifier;
value: Expression;
kind: string; // "init" | "get" | "set";
}
@@ -321,7 +321,7 @@ declare module spiderMonkeyParserAPI {
params: Pattern[];
defaults: Expression[];
rest?: Identifier;
body: any; // BlockStatement | Expression;
body: BlockStatement | Expression;
generator: boolean;
expression: boolean;
}
@@ -334,7 +334,7 @@ declare module spiderMonkeyParserAPI {
params: Pattern[];
defaults: Expression[];
rest?: Identifier;
body: any; // BlockStatement | Expression;
body: BlockStatement | Expression;
generator: boolean;
expression: boolean;
}
@@ -433,7 +433,7 @@ declare module spiderMonkeyParserAPI {
interface MemberExpression extends Expression {
type: string; // "MemberExpression";
object: Expression;
property: any; // Identifier | Expression;
property: Identifier | Expression;
computed: boolean;
}
@@ -510,7 +510,7 @@ declare module spiderMonkeyParserAPI {
*/
interface ObjectPattern extends Pattern {
type: string; // "ObjectPattern";
properties: {key: any /* Literal | Identifier */; value: Pattern;}[]; // [ { key: Literal | Identifier, value: Pattern } ];
properties: {key: Literal | Identifier; value: Pattern;}[]; // [ { key: Literal | Identifier, value: Pattern } ];
}
/**
@@ -565,8 +565,7 @@ declare module spiderMonkeyParserAPI {
*/
interface Literal extends Node, Expression {
type: string; // "Literal";
// TODO union types
value: any; // string | boolean | null | number | RegExp;
value?: string | boolean | number | RegExp;
}
/**
+1 -1
View File
@@ -21,7 +21,7 @@ declare module "nexpect" {
wait(expectation:RegExp):IChain;
sendline(line:string):IChain;
sendEof():IChain;
run(callback:(err:Error, output:string[], exit:any /* string | number */)=>void):child_process.ChildProcess;
run(callback:(err:Error, output:string[], exit: string | number)=>void):child_process.ChildProcess;
}
interface ISpawnOptions {
+12 -12
View File
@@ -8,9 +8,9 @@
"resolved": "https://registry.npmjs.org/definition-tester/-/definition-tester-0.2.0.tgz",
"dependencies": {
"bluebird": {
"version": "2.5.3",
"version": "2.7.1",
"from": "bluebird@^2.5.3",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.5.3.tgz"
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-2.7.1.tgz"
},
"definition-header": {
"version": "0.1.0",
@@ -23,9 +23,9 @@
"resolved": "https://registry.npmjs.org/joi/-/joi-4.9.0.tgz",
"dependencies": {
"hoek": {
"version": "2.10.0",
"version": "2.11.0",
"from": "hoek@^2.2.x",
"resolved": "https://registry.npmjs.org/hoek/-/hoek-2.10.0.tgz"
"resolved": "https://registry.npmjs.org/hoek/-/hoek-2.11.0.tgz"
},
"topo": {
"version": "1.0.2",
@@ -38,9 +38,9 @@
"resolved": "https://registry.npmjs.org/isemail/-/isemail-1.1.1.tgz"
},
"moment": {
"version": "2.8.4",
"version": "2.9.0",
"from": "moment@2.x.x",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.8.4.tgz"
"resolved": "https://registry.npmjs.org/moment/-/moment-2.9.0.tgz"
}
}
},
@@ -86,9 +86,9 @@
"resolved": "https://registry.npmjs.org/git-wrapper/-/git-wrapper-0.1.1.tgz"
},
"glob": {
"version": "4.3.2",
"version": "4.3.5",
"from": "glob@^4.3.2",
"resolved": "https://registry.npmjs.org/glob/-/glob-4.3.2.tgz",
"resolved": "https://registry.npmjs.org/glob/-/glob-4.3.5.tgz",
"dependencies": {
"inflight": {
"version": "1.0.4",
@@ -204,7 +204,7 @@
},
"inherits": {
"version": "2.0.1",
"from": "inherits@2",
"from": "inherits@~2.0.1",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz"
}
}
@@ -243,9 +243,9 @@
}
},
"typescript": {
"version": "1.3.0",
"from": "typescript@1.3.0",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-1.3.0.tgz"
"version": "1.4.1",
"from": "typescript@1.4.1",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-1.4.1.tgz"
}
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ declare module "optimist" {
wrap(columns: number): Optimist;
help(): void;
showHelp(fn: Function): void;
showHelp(fn?: Function): void;
usage(message: string): Optimist;
+1 -1
View File
@@ -37,6 +37,6 @@
},
"devDependencies": {
"definition-tester": "0.2.0",
"typescript": "1.3.0"
"typescript": "1.4.1"
}
}
+85
View File
@@ -0,0 +1,85 @@
/// <reference path="page.d.ts" />
import page = require("page");
//***********************************************************************
// Basic Example
// https://github.com/visionmedia/page.js/tree/master/examples/basic
//************************************************************************
page.base('/basic');
page('/', index);
page('/about', about);
page('/contact', contact);
page('/contact/:contactName', contact);
page('/contact/inline/:contactName', ctx => { });
page();
var index: PageJS.Callback = function() {
document.querySelector('p')
.textContent = 'viewing index';
}
var about: PageJS.Callback = function() {
document.querySelector('p')
.textContent = 'viewing about';
}
var contact: PageJS.Callback = function(ctx) {
document.querySelector('p')
.textContent = 'viewing contact ' + (ctx.params.contactName || '');
}
//***********************************************************************
// State Example
// https://github.com/visionmedia/page.js/tree/master/examples/state/app.js
//************************************************************************
interface Avatars {
[idx: string]: string;
}
var avatars: Avatars = {
glottis: 'http://homepage.ntlworld.com/stureek/images/glottis03.jpg',
manny: 'http://kprojekt.net/wp-content/uploads/manny.jpg',
sal: 'http://homepage.ntlworld.com/stureek/images/sal01.jpg'
};
page.base('/state');
page('/', index2);
page('/user/:name', load, show);
page('*', notfound);
page();
// everything below is not part of page.js
// just callbacks etc..
function text(str: string) {
document.querySelector('p').textContent = str;
}
function index2() {
text('Click a user below to load their avatar');
(<HTMLElement>document.querySelector('img'))
.style.display = 'none';
}
var load: PageJS.Callback = function (ctx, next) {
// check if we have .state.avatar already available
// this could for example be a cached html fragment.
if (ctx.state.avatar) {
ctx['avatar'] = ctx.state.avatar;
next();
return;
}
// pretend we're querying some database etc
setTimeout(function () {
// you can assign properties to the context
// for use between these functions. The .state
// property is what's saved in history.
ctx.state.avatar = ctx['avatar'] = avatars[ctx.params.name];
ctx.save();
next();
}, 600);
}
var show: PageJS.Callback = function (ctx) {
var img: any = document.querySelector('img');
img.src = ctx['avatar'];
img.style.display = 'block';
text('Showing ' + ctx.params.name);
}
function notfound() {
document.querySelector('p')
.textContent = 'not found';
}
+1
View File
@@ -0,0 +1 @@
--noImplicitAny --module commonjs
+214
View File
@@ -0,0 +1,214 @@
// Type definitions for page v1.5.0
// Project: http://visionmedia.github.io/page.js/
// Definitions by: Alan Norbauer <http://alan.norbauer.com/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module PageJS {
interface Static {
/**
* Defines a route mapping path to the given callback(s).
*
* page('/', user.list)
* page('/user/:id', user.load, user.show)
* page('/user/:id/edit', user.load, user.edit)
* page('*', notfound)
*
* Links that are not of the same origin are disregarded and will not be dispatched.
*/
(path: string, ...callbacks: Callback[]): void;
/**
* This is equivalent to page('*', callback) for generic "middleware".
*/
(callback: Callback): void;
/**
* Navigate to the given path.
*
* $('.view').click(function(e){
* page('/user/12')
* e.preventDefault()
* })
*/
(path: string): void;
/**
* Setup redirect form one path to other.
*/
(fromPath: string, toPath: string): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
* - click bind to click events [true]
* - popstate bind to popstate[true]
* - dispatch perform initial dispatch[true]
* - hashbang add #!before urls[false]
*
* If you wish to load serve initial content from the server you likely will want to set dispatch to false.
*/
(options: Options): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
* - click bind to click events [true]
* - popstate bind to popstate[true]
* - dispatch perform initial dispatch[true]
* - hashbang add #!before urls[false]
*
* If you wish to load serve initial content from the server you likely will want to set dispatch to false.
*/
(): void;
/**
* Identical to page(fromPath, toPath)
*/
redirect(fromPath: string, toPath: string): void;
/**
* Calling page.redirect with only a string as the first parameter redirects to another route. Waits for the current route to push state and after replaces it with the new one leaving the browser history clean.
*
* page('/default', function(){
* // some logic to decide which route to redirect to
* if(admin) {
* page.redirect('/admin');
* } else {
* page.redirect('/guest');
* }
* });
*
* page('/default');
*
*/
redirect(page: string): void;
/**
* Navigate to the given path.
*
* $('.view').click(function(e){
* page('/user/12')
* e.preventDefault()
* })
*
* Identical to page(path).
*/
show(path: string): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
* - click bind to click events [true]
* - popstate bind to popstate[true]
* - dispatch perform initial dispatch[true]
* - hashbang add #!before urls[false]
*
* If you wish to load serve initial content from the server you likely will want to set dispatch to false.
*
* Identical to page([options]).
*/
start(options: Options): void;
/**
* Register page's popstate / click bindings. If you're doing selective binding you'll like want to pass { click: false } to specify this yourself. The following options are available:
*
* - click bind to click events [true]
* - popstate bind to popstate[true]
* - dispatch perform initial dispatch[true]
* - hashbang add #!before urls[false]
*
* If you wish to load serve initial content from the server you likely will want to set dispatch to false.
*/
start(): void;
/**
* Unbind both the popstate and click handlers.
*/
stop(): void;
/**
* Get or set the base path. For example if page.js is operating within /blog/* set the base path to "/blog".
*/
base(path?: string): void;
/**
* Defines an exit route mapping path to the given callback(s).
*
* Exit routes are called when a page changes, using the context from the previous change. For example:
*
* page('/sidebar', function(ctx, next) {
* sidebar.open = true
* next()
* })
*
* page.exit('/sidebar', function(next) {
* sidebar.open = false
* next()
* })
*/
exit(path: string, callback: Callback, moreCallbacks?: Callback[]): void;
/**
* Equivalent to page.exit('*', callback).
*/
exit(callback: Callback): void;
}
interface Options {
/**
* bind to click events (default = true)
*/
click?: boolean;
/**
* bind to popstate (default = true)
*/
popstate?: boolean;
/**
* perform initial dispatch (default = true)
*/
dispatch?: boolean;
/**
* add #!before urls (default = false)
*/
hashbang?: boolean;
}
interface Callback {
(ctx: Context, next: () => any): any;
}
/**
* Routes are passed Context objects, these may be used to share state, for example ctx.user =, as well as the history "state" ctx.state that the pushState API provides.
*/
interface Context {
[idx: string]: any;
/**
* Saves the context using replaceState(). For example this is useful for caching HTML or other resources that were loaded for when a user presses "back".
*/
save: () => void;
/**
* If true, marks the context as handled to prevent default 404 behaviour. For example this is useful for the routes with interminate quantity of the callbacks.
*/
handled: boolean;
/**
* Pathname including the "base" (if any) and query string "/admin/login?foo=bar".
*/
canonicalPath: string;
/**
* Pathname and query string "/login?foo=bar".
*/
path: string;
/**
* Query string void of leading ? such as "foo=bar", defaults to "".
*/
queryString: string;
/**
* The pathname void of query string "/login".
*/
pathname: string;
/**
* The pushState state object.
*/
state: any;
/**
* The pushState title.
*/
title: string;
/**
* The parameters from the url, e.g. /user/:id => Context.params.id
*/
params: any;
}
}
declare module "page" {
var page: PageJS.Static;
export = page;
}
+2 -5
View File
@@ -12,10 +12,7 @@ declare module PromisesAPlus {
new <T>(resolver: (resolvePromise: (value: T) => void, rejectPromise: (reason: any) => void) => void): Thenable<T>;
}
interface Thenable<R> {
then<U>(onFulfill: (value: R) => Thenable<U>, onReject: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfill: (value: R) => Thenable<U>, onReject?: (error: any) => U): Thenable<U>;
then<U>(onFulfill: (value: R) => U, onReject: (error: any) => Thenable<U>): Thenable<U>;
then<U>(onFulfill?: (value: R) => U, onReject?: (error: any) => U): Thenable<U>;
interface Thenable<T> {
then<R>(onFulfill?: (value: T) => Thenable<R>|R, onReject?: (error: any) => Thenable<R>|R): Thenable<R>;
}
}
+2 -4
View File
@@ -32,7 +32,7 @@ var INPUT_REF: string = "input";
// Top-Level API
// --------------------------------------------------------------------------
var reactClass: React.ComponentClass<Props> = React.createClass<Props>({
var reactClass = React.createClass<Props>({
getDefaultProps: () => {
return <Props>{
hello: undefined,
@@ -193,9 +193,7 @@ var childMap: { [key: string]: number } =
React.Children.map<number>(children, (child) => { return 42; });
React.Children.forEach(children, (child) => {});
var nChildren: number = React.Children.count(children);
var onlyChild = React.Children.only([null, [[["Hallo"], true]], false, {
test: null
}]);
var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]);
//
// Example from http://facebook.github.io/react/
+62 -62
View File
@@ -8,12 +8,12 @@ declare module React {
// React Elements
// ----------------------------------------------------------------------
// type ReactType = ComponentClass<any> | string;
type ReactType = ComponentClass<any> | string;
interface ReactElement<P> {
type: any; // ReactType
type: ComponentClass<P> | string;
props: P;
key: any; // number | string
key: number | string;
ref: string;
}
@@ -22,14 +22,15 @@ declare module React {
//
// React Nodes
// http://facebook.github.io/react/docs/glossary.html
// ----------------------------------------------------------------------
// type ReactText = string | number;
// type Fragment = ReactNode[];
// type ReactNode = ReactElement<any> | Fragment | ReactText | KeyMap;
// interface KeyMap {
// [key: string]: ReactNode;
// }
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;
// Should be Array<ReactNode> but type aliases cannot be recursive
type ReactFragment = Array<ReactChild | any[] | boolean>;
type ReactNode = ReactChild | ReactFragment | boolean;
//
// React Components
@@ -41,7 +42,11 @@ declare module React {
propTypes?: ValidationMap<P>;
}
interface ComponentClass<P> extends ComponentStatics<P> {
interface ComponentClassType<P> extends ComponentStatics<P> {
new (): ComponentClass<P>;
}
interface ComponentClass<P> {
// Deprecated in 0.12. See http://fb.me/react-legacyfactory
// new(props: P): ReactElement<P>;
// (props: P): ReactElement<P>;
@@ -52,7 +57,7 @@ declare module React {
// ----------------------------------------------------------------------
interface ComponentFactory<P> {
(props?: P, ...children: any/*ReactNode*/[]): ReactElement<P>;
(props?: P, ...children: ReactNode[]): ReactElement<P>;
}
interface HTMLFactory extends ComponentFactory<HTMLAttributes> {}
@@ -63,9 +68,9 @@ declare module React {
// ----------------------------------------------------------------------
interface TopLevelAPI {
createClass<P>(spec: ComponentSpec<P, any>): ComponentClass<P>;
createElement<P>(type: any/*ReactType*/, props: P, ...children: any/*ReactNode*/[]): ReactElement<P>;
createFactory<P>(componentClass: ComponentClass<P>): ComponentFactory<P>;
createClass<P>(spec: ComponentSpec<P, any>): ComponentClassType<P>;
createElement<P>(type: ComponentClass<P> | string, props: P, ...children: ReactNode[]): ReactElement<P>;
createFactory<P>(componentClass: ComponentClassType<P>): ComponentFactory<P>;
render<P>(element: ReactElement<P>, container: Element, callback?: () => any): Component<P>;
unmountComponentAtNode(container: Element): boolean;
renderToString(element: ReactElement<any>): string;
@@ -241,8 +246,8 @@ declare module React {
// ----------------------------------------------------------------------
export interface ReactAttributes {
children?: any; // ReactNode
key?: any; // number | string
children?: ReactNode;
key?: number | string;
ref?: string;
// Event Attributes
@@ -282,13 +287,13 @@ declare module React {
onWheel?: WheelEventHandler;
dangerouslySetInnerHTML?: {
__html: string
__html: string;
};
}
interface CSSProperties {
columnCount?: number;
flex?: any; // number | string
flex?: number | string;
flexGrow?: number;
flexShrink?: number;
fontWeight?: number;
@@ -318,8 +323,8 @@ declare module React {
autoComplete?: boolean;
autoFocus?: boolean;
autoPlay?: boolean;
cellPadding?: any; // number | string
cellSpacing?: any; // number | string
cellPadding?: number | string;
cellSpacing?: number | string;
charSet?: string;
checked?: boolean;
classID?: string;
@@ -342,8 +347,8 @@ declare module React {
encType?: string;
form?: string;
formNoValidate?: boolean;
frameBorder?: any; // number | string
height?: any; // number | string
frameBorder?: number | string;
height?: number | string;
hidden?: boolean;
href?: string;
hrefLang?: string;
@@ -356,12 +361,12 @@ declare module React {
list?: string;
loop?: boolean;
manifest?: string;
max?: any; // number | string
max?: number | string;
maxLength?: number;
media?: string;
mediaGroup?: string;
method?: string;
min?: any; // number | string
min?: number | string;
multiple?: boolean;
muted?: boolean;
name?: string;
@@ -394,7 +399,7 @@ declare module React {
srcDoc?: string;
srcSet?: string;
start?: number;
step?: any; // number | string
step?: number | string;
style?: CSSProperties;
tabIndex?: number;
target?: string;
@@ -402,7 +407,7 @@ declare module React {
type?: string;
useMap?: string;
value?: string;
width?: any; // number | string
width?: number | string;
wmode?: string;
// Non-standard Attributes
@@ -415,49 +420,49 @@ declare module React {
}
interface SVGAttributes extends ReactAttributes {
cx?: any; // SVGLength | SVGAnimatedLength
cx?: SVGLength | SVGAnimatedLength;
cy?: any;
d?: string;
dx?: any; // SVGLength | SVGAnimatedLength
dy?: any; // SVGLength | SVGAnimatedLength
dx?: SVGLength | SVGAnimatedLength;
dy?: SVGLength | SVGAnimatedLength;
fill?: any; // SVGPaint | string
fillOpacity?: any; // number | string
fillOpacity?: number | string;
fontFamily?: string;
fontSize?: any; // number | string
fx?: any; // SVGLength | SVGAnimatedLength
fy?: any; // SVGLength | SVGAnimatedLength
gradientTransform?: any; // SVGTransformList | SVGAnimatedTransformList
fontSize?: number | string;
fx?: SVGLength | SVGAnimatedLength;
fy?: SVGLength | SVGAnimatedLength;
gradientTransform?: SVGTransformList | SVGAnimatedTransformList;
gradientUnits?: string;
markerEnd?: string;
markerMid?: string;
markerStart?: string;
offset?: any; // number | string
opacity?: any; // number | string
offset?: number | string;
opacity?: number | string;
patternContentUnits?: string;
patternUnits?: string;
points?: string;
preserveAspectRatio?: string;
r?: any; // SVGLength | SVGAnimatedLength
rx?: any; // SVGLength | SVGAnimatedLength
ry?: any; // SVGLength | SVGAnimatedLength
r?: SVGLength | SVGAnimatedLength;
rx?: SVGLength | SVGAnimatedLength;
ry?: SVGLength | SVGAnimatedLength;
spreadMethod?: string;
stopColor?: any; // SVGColor | string
stopOpacity?: any; // number | string
stopOpacity?: number | string;
stroke?: any; // SVGPaint
strokeDasharray?: string;
strokeLinecap?: string;
strokeOpacity?: any; // number | string
strokeWidth?: any; // SVGLength | SVGAnimatedLength
strokeOpacity?: number | string;
strokeWidth?: SVGLength | SVGAnimatedLength;
textAnchor?: string;
transform?: any; // SVGTransformList | SVGAnimatedTransformList
transform?: SVGTransformList | SVGAnimatedTransformList;
version?: string;
viewBox?: string;
x1?: any; // SVGLength | SVGAnimatedLength
x2?: any; // SVGLength | SVGAnimatedLength
x?: any; // SVGLength | SVGAnimatedLength
y1?: any; // SVGLength | SVGAnimatedLength
y2?: any; // SVGLength | SVGAnimatedLength
y?: any; // SVGLength | SVGAnimatedLength
x1?: SVGLength | SVGAnimatedLength;
x2?: SVGLength | SVGAnimatedLength;
x?: SVGLength | SVGAnimatedLength;
y1?: SVGLength | SVGAnimatedLength;
y2?: SVGLength | SVGAnimatedLength
y?: SVGLength | SVGAnimatedLength;
}
//
@@ -637,13 +642,11 @@ declare module React {
// React.Children
// ----------------------------------------------------------------------
// type Child = ReactElement<any> | ReactText;
interface ReactChildren {
map<T>(children: any/*ReactNode*/, fn: (child: any/*Child*/) => T): { [key:string]: T };
forEach(children: any/*ReactNode*/, fn: (child: any/*Child*/) => any): void;
count(children: any/*ReactNode*/): number;
only(children: any/*ReactNode*/): any/*Child*/;
map<T>(children: ReactNode, fn: (child: ReactChild) => T): { [key:string]: T };
forEach(children: ReactNode, fn: (child: ReactChild) => any): void;
count(children: ReactNode): number;
only(children: ReactNode): ReactChild;
}
//
@@ -659,7 +662,7 @@ declare module React {
// ----------------------------------------------------------------------
interface TransitionGroupProps {
component?: any; // ReactType
component?: ReactType;
childFactory?: (child: ReactElement<any>) => ReactElement<any>;
}
@@ -670,9 +673,6 @@ declare module React {
transitionLeave?: boolean;
}
interface CSSTransitionGroup extends ComponentClass<CSSTransitionGroupProps> {}
interface TransitionGroup extends ComponentClass<TransitionGroupProps> {}
//
// React.addons (Mixins)
// ----------------------------------------------------------------------
@@ -757,7 +757,7 @@ declare module React {
mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils;
isElementOfType(element: ReactElement<any>, type: any/*ReactType*/): boolean;
isElementOfType(element: ReactElement<any>, type: ReactType): boolean;
isDOMComponent(instance: Component<any>): boolean;
isCompositeComponent(instance: Component<any>): boolean;
isCompositeComponentWithType(instance: Component<any>, type: ComponentClass<any>): boolean;
@@ -873,10 +873,10 @@ declare module React {
interface AddonsExports extends Exports {
addons: {
CSSTransitionGroup: CSSTransitionGroup;
CSSTransitionGroup: ComponentClassType<CSSTransitionGroupProps>;
LinkedStateMixin: LinkedStateMixin;
PureRenderMixin: PureRenderMixin;
TransitionGroup: TransitionGroup;
TransitionGroup: ComponentClassType<TransitionGroupProps>;
batchedUpdates<A, B>(callback: (a: A, b: B) => any, a: A, b: B): void;
batchedUpdates<A>(callback: (a: A) => any, a: A): void;
+98 -1
View File
@@ -1,8 +1,24 @@
/// <reference path="./rest.d.ts" />
import when = require('when');
import rest = require('rest');
import defaultRequest = require('rest/interceptor/defaultRequest');
import hateoas = require('rest/interceptor/hateoas');
import location = require('rest/interceptor/location');
import mime = require('rest/interceptor/mime');
import pathPrefix = require('rest/interceptor/pathPrefix');
import basicAuth = require('rest/interceptor/basicAuth');
import oAuth = require('rest/interceptor/oAuth');
import csrf = require('rest/interceptor/csrf');
import errorCode = require('rest/interceptor/errorCode');
import retry = require('rest/interceptor/retry');
import timeout = require('rest/interceptor/timeout');
import jsonp = require('rest/interceptor/jsonp');
import xdomain = require('rest/interceptor/ie/xdomain');
import xhr = require('rest/interceptor/ie/xhr');
import interceptor = require('rest/interceptor');
import registry = require('rest/mime/registry');
rest('/').then(function(response) {
@@ -15,7 +31,7 @@ client({ path: '/data.json' }).then(function(response) {
console.log('response: ', response);
});
client = rest.wrap(mime, { mime: 'application/json' }).wrap(errorCode, { code: 500 });
client = rest.wrap<mime.Config>(mime, { mime: 'application/json' }).wrap(errorCode, { code: 500 });
client({ path: '/data.json' }).then(
function(response) {
console.log('response: ', response);
@@ -38,3 +54,84 @@ registry.register('application/vnd.com.example', {
}
});
var noop = interceptor({
init: (config: any) => {
return config;
},
request: (request: rest.Request, config: any, meta: rest.Meta) => {
return request;
},
response: (response: rest.Response, config: any, meta: rest.Meta) => {
return response;
},
success: (response: rest.Response, config: any, meta: rest.Meta) => {
return response;
},
error: (response: rest.Response, config: any, meta: rest.Meta) => {
return response;
}
});
var fail = interceptor({
success: (response: rest.Response) => when.reject<rest.Response>(response),
});
var succeed = interceptor({
error: (response: rest.Response) => when(response),
});
var defaulted = interceptor({
init: (config: any) => {
config.prop = config.prop || 'default-value';
return config;
},
});
interface KnownConfig {
prop: string;
}
var knownConfig = interceptor({
success: (response: rest.Response, config: KnownConfig) => {
console.log(config);
return response;
},
});
var transformedConfig = interceptor({
init: (config: KnownConfig) => {
return config.prop;
},
success: (response: rest.Response, config: string) => {
console.log(config);
return response;
},
});
var promiseOrResponse = interceptor({
success: (response: rest.Response) => {
return response;
},
error: (response: rest.Response) => {
return when(response);
},
});
client = rest
.wrap(defaultRequest)
.wrap(hateoas)
.wrap(location)
.wrap(mime)
.wrap(pathPrefix)
.wrap(basicAuth)
.wrap(oAuth)
.wrap(csrf)
.wrap(errorCode)
.wrap(retry)
.wrap(timeout)
.wrap(jsonp)
.wrap(xdomain)
.wrap(xhr)
.wrap(noop)
.wrap(fail)
.wrap(knownConfig, { prop: 'value' })
.wrap(transformedConfig, { prop: 'value' });
+243 -14
View File
@@ -14,7 +14,7 @@ declare module "rest" {
function rest(request: rest.Request): rest.ResponsePromise;
module rest {
export function wrap(interceptor: Interceptor, config?: any): Client;
export function wrap<T>(interceptor: Interceptor<T>, config?: T): Client;
export interface Request {
method?: string;
@@ -48,8 +48,8 @@ declare module "rest" {
header(headerName: string): when.Promise<any>; // string or string[]
}
export interface Interceptor {
(parent?: Client, config?: any): Client;
export interface Interceptor<T> {
(parent?: Client, config?: T): Client;
}
export interface Client {
@@ -57,36 +57,265 @@ declare module "rest" {
(request: Request): ResponsePromise;
skip(): Client;
wrap(interceptor: Interceptor, config?: any): Client;
wrap<T>(interceptor: Interceptor<T>, config?: T): Client;
}
export interface Meta {
client: Client;
arguments: any;
}
}
}
declare module "rest/interceptor" {
import when = require("when");
import rest = require("rest");
function interceptor<T, U>(config: interceptor.Config<T, U>): rest.Interceptor<T>;
module interceptor {
interface Config<T, U> {
init?: (config: T) => U;
request?: (request: rest.Request, config: U, meta: rest.Meta) => rest.Request | when.Promise<rest.Request>;
response?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;
success?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;
error?: (response: rest.Response, config: U, meta: rest.Meta) => rest.Response | when.Promise<rest.Response>;
}
}
export = interceptor;
}
declare module "rest/interceptor/defaultRequest" {
import rest = require("rest");
var defaultRequest: rest.Interceptor<defaultRequest.Config>;
module defaultRequest {
interface Config {
method?: string;
path?: string;
params?: any;
headers?: any;
entity?: any;
mixin?: any;
}
}
export = defaultRequest;
}
declare module "rest/interceptor/hateoas" {
import rest = require("rest");
var hateoas: rest.Interceptor<hateoas.Config>;
module hateoas {
interface Config {
target?: string;
client?: rest.Client;
}
}
export = hateoas;
}
declare module "rest/interceptor/location" {
import rest = require("rest");
var location: rest.Interceptor<location.Config>;
module location {
interface Config {
client?: rest.Client;
code?: number;
}
}
export = location;
}
declare module "rest/interceptor/mime" {
import rest = require("rest");
import registry = require("rest/mime/registry");
var mime: rest.Interceptor<mime.Config>;
module mime {
interface Config {
mime?: string;
accept?: string;
registry?: registry.Registry;
permissive?: boolean;
}
}
export = mime;
}
declare module "rest/interceptor/pathPrefix" {
import rest = require("rest");
var pathPrefix: rest.Interceptor<pathPrefix.Config>;
module pathPrefix {
interface Config {
prefix?: string;
}
}
export = pathPrefix;
}
declare module "rest/interceptor/basicAuth" {
import rest = require("rest");
var basicAuth: rest.Interceptor<basicAuth.Config>;
module basicAuth {
interface Config {
username?: string;
password?: string;
}
}
export = basicAuth;
}
declare module "rest/interceptor/oAuth" {
import rest = require("rest");
var oAuth: rest.Interceptor<oAuth.Config>;
module oAuth {
interface DismissWindow {
(): void;
}
interface Config {
token?: string;
clientId?: string;
scope?: string;
authorizationUrl?: string;
redirectUrl?: string;
windowStrategy?: (url: string) => DismissWindow;
oAuthCallback?: (hash: string) => void;
oAuthCallbackName?: string;
}
}
export = oAuth;
}
declare module "rest/interceptor/csrf" {
import rest = require("rest");
var csrf: rest.Interceptor<csrf.Config>;
module csrf {
interface Config {
name?: string;
token?: string;
}
}
export = csrf;
}
declare module "rest/interceptor/errorCode" {
import rest = require("rest");
var errorCode: rest.Interceptor;
var errorCode: rest.Interceptor<errorCode.Config>;
module errorCode {
interface Config {
code?: number;
}
}
export = errorCode;
}
declare module "rest/interceptor/mime" {
declare module "rest/interceptor/retry" {
import rest = require("rest");
var mime: rest.Interceptor;
var retry: rest.Interceptor<retry.Config>;
export = mime;
module retry {
interface Config {
initial?: number;
multiplier?: number;
max?: number;
}
}
export = retry;
}
declare module "rest/interceptor/timeout" {
import rest = require("rest");
var timeout: rest.Interceptor<timeout.Config>;
module timeout {
interface Config {
timeout?: number;
transient?: boolean;
}
}
export = timeout;
}
declare module "rest/interceptor/jsonp" {
import rest = require("rest");
var jsonp: rest.Interceptor<jsonp.Config>;
module jsonp {
interface Config {
callback?: {
param?: string;
prefix?: string;
name?: string;
}
}
}
export = jsonp;
}
declare module "rest/interceptor/ie/xdomain" {
import rest = require("rest");
var xdomain: rest.Interceptor<{}>;
export = xdomain;
}
declare module "rest/interceptor/ie/xhr" {
import rest = require("rest");
var xhr: rest.Interceptor<{}>;
export = xhr;
}
declare module "rest/mime/registry" {
import when = require("when");
export interface MIMEConverter {
read(value: string): any; // any or when.Promise<any>;
write(value: any): any; // string or when.Promise<string>;
var registry: registry.Registry;
module registry {
interface MIMEConverter {
read(value: string): any | when.Promise<any>;
write(value: any): string | when.Promise<string>;
}
interface Registry {
lookup(mimeType: string): when.Promise<MIMEConverter>;
register(mimeType: string, converter: MIMEConverter): void;
}
}
export function lookup(mimeType: string): when.Promise<MIMEConverter>;
export function register(mimeType: string, converter: MIMEConverter): void;
export = registry;
}
+4 -3
View File
@@ -4,10 +4,11 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../bunyan/bunyan.d.ts" />
declare module "restify" {
import http = require('http');
import bunyan = require('bunyan');
interface addressInterface {
@@ -24,7 +25,7 @@ declare module "restify" {
contentLength: number;
contentType: string;
href: () => string;
log: Object;
log: bunyan.Logger;
id: string;
path: () => string;
query: any;
@@ -210,7 +211,7 @@ declare module "restify" {
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;
@@ -0,0 +1,12 @@
/// <reference path="./sanitize-filename.d.ts" />
import sanitize = require('sanitize-filename');
// Some string that may be unsafe as a filesystem filename
var UNSAFE_FILENAME = "h*ello:/world?\u0000";
// Sanitize the unsafe filename to be safe for use as a filename
var filename: string;
filename = sanitize(UNSAFE_FILENAME);
filename = sanitize(UNSAFE_FILENAME, { replacement: '--' });
+16
View File
@@ -0,0 +1,16 @@
// Type definitions for sanitize-filename v1.1.1
// Project: https://github.com/parshap/node-sanitize-filename
// Definitions by: Wim Looman <https://github.com/Nemo157>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "sanitize-filename" {
function sanitize(filename: string, options?: sanitize.Options): string;
module sanitize {
interface Options {
replacement: string;
}
}
export = sanitize;
}
+6
View File
@@ -8,6 +8,12 @@ module SigmaJsTests {
}
});
s.settings({
maxNodeSize: 10
});
s.settings("maxNodeSize");
s.addRenderer({
type: 'canvas',
container: container
+1 -1
View File
@@ -3,7 +3,6 @@
// Definitions by: Qinfeng Chen <https://github.com/qinfchen>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module SigmaJs{
interface Animation {
camera(camera: Camera, target: { [index: string]: any }, options: { [index: string]: any }): number;
@@ -129,6 +128,7 @@ declare module SigmaJs{
refresh(): void;
renderers: Renderer[];
settings(key: string): any;
settings(settings: { [index: string]: any }): void;
// forceAtlas2 layout
configForceAtlas2(configs: { [key: string]: any }): void;
+2 -2
View File
@@ -216,8 +216,8 @@ declare module Snap {
clear():void;
el(name:string, attr:Object):Snap.Element;
gradient(gradient:string):any;
g(varargs:any):Object;
group(el:any,...els:any[]):any;
g(varargs?:any):any;
group(el?:any,...els:any[]):any;
mask(varargs:any):Object;
ptrn(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
svg(x:number,y:number,width:number,height:number,vbx:number,vby:number,vbw:number,vbh:number):Object;
+7 -7
View File
@@ -8,12 +8,6 @@
interface JQuery {
/**
* Initializes the input element that it is called on
* as a spectrum colorpicker instance.
*/
spectrum(options?: Spectrum.Options): JQuery;
/**
* Shows the colorpicker.
*/
@@ -97,6 +91,12 @@ interface JQuery {
*/
spectrum(methodName: string): any; // in most cases this is JQuery except for the get method which returns a tinycolorInstance
/**
* Initializes the input element that it is called on
* as a spectrum colorpicker instance.
*/
spectrum(options?: Spectrum.Options): JQuery;
/**
* Called at the beginning of a drag event on either hue slider, alpha slider, or main color picker areas.
*/
@@ -289,4 +289,4 @@ declare module Spectrum {
*/
beforeShow?: (color: tinycolorInstance) => void;
}
}
}
@@ -0,0 +1,56 @@
// Type definitions for tedious-connection-pool
// Project: https://github.com/pekim/tedious-connection-pool
// Definitions by: Cyprien Autexier <https://github.com/sandorfr>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="./tedious-connection-pool.d.ts" />
"use strict";
import ConnectionPool = require("tedious-connection-pool");
import tedious = require("tedious");
var config: tedious.ConnectionConfig = {
userName: "rogier",
password: "rogiers password",
server: "127.0.0.1",
options: {
database: "somedb",
instance: "someinstance"
}
};
var poolConfig : ConnectionPool.PoolConfig = {
min: 1,
max: 4
};
var pool: ConnectionPool = new ConnectionPool(poolConfig, config);
pool.on('error', (err: Error) => {
console.error(err);
});
pool.acquire((err: Error, connection: ConnectionPool.PooledConnection) =>{
console.log("hurray");
connection.beginTransaction((error: Error): void => {}, "some name");
connection.rollbackTransaction((error: Error): void => {});
connection.commitTransaction((error: Error): void => {});
var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => {
});
request.on("row", (row: tedious.ColumnValue[]): void => {
});
connection.execSql(request);
connection.release();
pool.drain();
});
+109
View File
@@ -0,0 +1,109 @@
// Type definitions for tedious-connection-pool
// Project: https://github.com/pekim/tedious-connection-pool
// Definitions by: Cyprien Autexier <https://github.com/sandorfr>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../tedious/tedious.d.ts" />
declare module "tedious-connection-pool" {
import tedious = require('tedious');
module tcp {
/**
* Extends Tedious Connection with release function
*/
export class PooledConnection extends tedious.Connection {
/**
* If the connection is issued from a connection pool returns the connection to the pool.
*/
release():void;
}
/**
* Acquire function callback signature
*/
export interface ConnectionCallback {
/**
* Provides a connection or an error
* @param err error if any
* @param connection issued from the pool
*/
(err:Error, connection:PooledConnection): void;
}
/**
* Pool Configuration interface
*/
export interface PoolConfig {
/**
* Minimum concurrent connections
*/
min?: number;
/**
* Maximum concurrent connections
*/
max?: number;
/**
* Defines if logging is activated
*/
log?: boolean;
/**
* Idle timeout
*/
idleTimeout?: number;
/**
* Retry delay
*/
retryDelay?: number;
/**
* Acquire timeout
*/
acquireTimeout?: number;
}
}
/**
* Tedious Connection Pool Class
*/
class tcp {
/**
* Connection Pool constructor
* @param poolConfig the pool configuration
* @param connectionConfig the connection configuration
*/
constructor(poolConfig:tcp.PoolConfig, connectionConfig:tedious.ConnectionConfig);
/**
* acquires a connection from the pool
* @param callback invoked when the connection is retrieved and ready
*/
acquire(callback:tcp.ConnectionCallback):void;
/**
* listens for a specific connection pool event
* @param event the event name
* @param callback invoked when the event is raised
*/
on(event:string, callback:Function):void;
/**
* closes opened connections
*/
drain():void;
}
export = tcp;
}
@@ -4,7 +4,6 @@
// https://github.com/mrdoob/three.js/blob/master/examples/canvas_camera_orthographic.html
() => {
var container, stats;
var camera, scene, renderer;
@@ -47,10 +46,9 @@
}
var material1 = new THREE.LineBasicMaterial({ color: 0x000000, opacity: 0.2 });
var material = new THREE.LineBasicMaterial({ color: 0x000000, opacity: 0.2 });
var line = new THREE.Line(geometry, material1);
line.mode = THREE.LinePieces;
var line = new THREE.Line(geometry, material, THREE.LinePieces);
scene.add(line);
// Cubes
@@ -93,8 +91,8 @@
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
stats = new Stats();
+2 -2
View File
@@ -61,7 +61,7 @@
// Plane
var geometry2 = new THREE.PlaneGeometry(200, 200);
var geometry2 = new THREE.PlaneBufferGeometry(200, 200);
geometry2.applyMatrix(new THREE.Matrix4().makeRotationX(- Math.PI / 2));
var material = new THREE.MeshBasicMaterial({ color: 0xe0e0e0, overdraw: 0.5 });
@@ -71,8 +71,8 @@
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
stats = new Stats();
@@ -6,7 +6,10 @@
() => {
var container, stats;
var camera, scene, projector, renderer;
var camera, scene, renderer;
var raycaster;
var mouse;
init();
animate();
@@ -48,12 +51,15 @@
}
projector = new THREE.Projector();
//
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2();
renderer = new THREE.CanvasRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
stats = new Stats();
@@ -62,6 +68,7 @@
container.appendChild(stats.domElement);
document.addEventListener('mousedown', onDocumentMouseDown, false);
document.addEventListener('touchstart', onDocumentTouchStart, false);
//
@@ -78,14 +85,24 @@
}
function onDocumentTouchStart(event) {
event.preventDefault();
event.clientX = event.touches[0].clientX;
event.clientY = event.touches[0].clientY;
onDocumentMouseDown(event);
}
function onDocumentMouseDown(event) {
event.preventDefault();
var vector = new THREE.Vector3((event.clientX / window.innerWidth) * 2 - 1, - (event.clientY / window.innerHeight) * 2 + 1, 0.5);
projector.unprojectVector(vector, camera);
mouse.x = (event.clientX / renderer.domElement.width) * 2 - 1;
mouse.y = - (event.clientY / renderer.domElement.height) * 2 + 1;
var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize());
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
@@ -42,14 +42,14 @@
}
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xff0040, program: program } ) );
light1.add( sprite );
var sprite = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xff0040, program: program }));
light1.add(sprite);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x0040ff, program: program } ) );
light2.add( sprite );
var sprite = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x0040ff, program: program }));
light2.add(sprite);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0x80ff80, program: program } ) );
light3.add( sprite );
var sprite = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0x80ff80, program: program }));
light3.add(sprite);
loader = new THREE.JSONLoader();
loader.load('obj/WaltHeadLo.js', function (geometry) {
@@ -60,6 +60,7 @@
});
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
@@ -93,17 +94,17 @@
if (mesh) mesh.rotation.y -= 0.01;
light1.position.x = Math.sin( time * 0.7 ) * 30;
light1.position.y = Math.cos( time * 0.5 ) * 40;
light1.position.z = Math.cos( time * 0.3 ) * 30;
light1.position.x = Math.sin(time * 0.7) * 30;
light1.position.y = Math.cos(time * 0.5) * 40;
light1.position.z = Math.cos(time * 0.3) * 30;
light2.position.x = Math.cos( time * 0.3 ) * 30;
light2.position.y = Math.sin( time * 0.5 ) * 40;
light2.position.z = Math.sin( time * 0.7 ) * 30;
light2.position.x = Math.cos(time * 0.3) * 30;
light2.position.y = Math.sin(time * 0.5) * 40;
light2.position.z = Math.sin(time * 0.7) * 30;
light3.position.x = Math.sin( time * 0.7 ) * 30;
light3.position.y = Math.cos( time * 0.3 ) * 40;
light3.position.z = Math.sin( time * 0.5 ) * 30;
light3.position.x = Math.sin(time * 0.7) * 30;
light3.position.y = Math.cos(time * 0.3) * 40;
light3.position.z = Math.sin(time * 0.5) * 30;
renderer.render(scene, camera);
+14 -19
View File
@@ -5,9 +5,6 @@
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var materials: THREE.Material[];
var debugContext: any;
// -------
var container, stats;
var camera, scene, renderer, objects;
@@ -44,15 +41,14 @@
var material = new THREE.LineBasicMaterial({ color: 0xffffff, opacity: 0.2 });
var line = new THREE.Line(geometry, material);
line.mode = THREE.LinePieces;
var line = new THREE.Line(geometry, material, THREE.LinePieces);
scene.add(line);
// Spheres
var geometry2 = new THREE.SphereGeometry(100, 14, 7);
materials = [
var materials: THREE.Material[] = [
new THREE.MeshBasicMaterial({ color: 0x00ffff, wireframe: true, side: THREE.DoubleSide }),
new THREE.MeshBasicMaterial({ color: 0xff0000, blending: THREE.AdditiveBlending }),
@@ -61,8 +57,7 @@
new THREE.MeshDepthMaterial({ overdraw: 0.5 }),
new THREE.MeshNormalMaterial({ overdraw: 0.5 }),
new THREE.MeshBasicMaterial({ map: THREE.ImageUtils.loadTexture('textures/land_ocean_ice_cloud_2048.jpg') }),
new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', new THREE.SphericalReflectionMapping()), overdraw: 0.5 }),
new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', new THREE.SphericalRefractionMapping()), overdraw: 0.5 })
new THREE.MeshBasicMaterial({ envMap: THREE.ImageUtils.loadTexture('textures/envmap.png', THREE.SphericalReflectionMapping), overdraw: 0.5 })
];
@@ -79,7 +74,7 @@
for (var i = 0, l = materials.length; i < l; i++) {
var sphere = new THREE.Mesh(geometry2, materials[i]);
var sphere = new THREE.Mesh(geometry, materials[i]);
sphere.position.x = (i % 5) * 200 - 400;
sphere.position.z = Math.floor(i / 5) * 200 - 200;
@@ -103,9 +98,9 @@
}
// Lights
// Lights
scene.add(new THREE.AmbientLight(Math.random() * 0x202020));
scene.add(new THREE.AmbientLight(Math.random() * 0x202020));
var directionalLight = new THREE.DirectionalLight(Math.random() * 0xffffff);
directionalLight.position.x = Math.random() - 0.5;
@@ -117,11 +112,12 @@
pointLight = new THREE.PointLight(0xffffff, 1);
scene.add(pointLight);
var sprite = new THREE.Sprite( new THREE.SpriteCanvasMaterial( { color: 0xffffff, program: program } ) );
sprite.scale.set( 8, 8, 8 );
pointLight.add( sprite );
var sprite = new THREE.Sprite(new THREE.SpriteCanvasMaterial({ color: 0xffffff, program: program }));
sprite.scale.set(8, 8, 8);
pointLight.add(sprite);
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
@@ -134,7 +130,7 @@
container.appendChild(debugCanvas);
debugContext = debugCanvas.getContext('2d');
var debugContext = debugCanvas.getContext('2d');
debugContext.setTransform(1, 0, 0, 1, 256, 256);
debugContext.strokeStyle = '#000000';
@@ -198,10 +194,9 @@
}
pointLight.position.x = Math.sin( timer * 7 ) * 300;
pointLight.position.y = Math.cos( timer * 5 ) * 400;
pointLight.position.z = Math.cos( timer * 3 ) * 300;
pointLight.position.x = Math.sin(timer * 7) * 300;
pointLight.position.y = Math.cos(timer * 5) * 400;
pointLight.position.z = Math.cos(timer * 3) * 300;
renderer.render(scene, camera);
@@ -47,6 +47,7 @@
}
renderer = new THREE.CanvasRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
+12 -10
View File
@@ -6,7 +6,6 @@
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var object: any;
// -------
var table = [
"H", "Hydrogen", "1.00794", 1, 1,
@@ -160,7 +159,7 @@
var symbol = document.createElement('div');
symbol.className = 'symbol';
symbol.textContent = (table[i]).toString();
symbol.textContent = table[i].toString();
element.appendChild(symbol);
var details = document.createElement('div');
@@ -168,16 +167,17 @@
details.innerHTML = table[i + 1] + '<br>' + table[i + 2];
element.appendChild(details);
object = new THREE.CSS3DObject(element);
object.position.x = Math.random() * 4000 - 2000;
object.position.y = Math.random() * 4000 - 2000;
object.position.z = Math.random() * 4000 - 2000;
scene.add(object);
var cssobject = new THREE.CSS3DObject(element);
cssobject.position.x = Math.random() * 4000 - 2000;
cssobject.position.y = Math.random() * 4000 - 2000;
cssobject.position.z = Math.random() * 4000 - 2000;
scene.add(cssobject);
objects.push(object);
objects.push(cssobject);
//
object = new THREE.Object3D();
var object = new THREE.Object3D();
object.position.x = (<number>table[i + 3] * 140) - 1330;
object.position.y = - (<number>table[i + 4] * 180) + 990;
@@ -247,6 +247,7 @@
}
//
renderer = new THREE.CSS3DRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.domElement.style.position = 'absolute';
@@ -288,7 +289,7 @@
}, false);
transform(targets.table, 5000);
transform(targets.table, 2000);
//
@@ -316,6 +317,7 @@
.start();
}
new TWEEN.Tween(this)
.to({}, duration * 2)
.onUpdate(render)
+5 -5
View File
@@ -27,16 +27,16 @@
scene = new THREE.Scene();
var image = document.createElement( 'img' );
image.addEventListener( 'load', function ( event ) {
var image = document.createElement('img');
image.addEventListener('load', function (event) {
for ( var i = 0; i < particlesTotal; i ++ ) {
for (var i = 0; i < particlesTotal; i++) {
var object = new THREE.CSS3DSprite( image.cloneNode() );
var object = new THREE.CSS3DSprite(image.cloneNode());
object.position.x = Math.random() * 4000 - 2000,
object.position.y = Math.random() * 4000 - 2000,
object.position.z = Math.random() * 4000 - 2000
scene.add(object);
scene.add(object);
objects.push(object);
+78 -5
View File
@@ -779,6 +779,20 @@
return true;
};
var eulerEquals = function (a, b, tolerance?: any) {
tolerance = tolerance || 0.0001;
var diff = Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + Math.abs(a.z - b.z);
return (diff < tolerance);
};
var quatEquals = function (a, b, tolerance?: any) {
tolerance = tolerance || 0.0001;
var diff = Math.abs(a.x - b.x) + Math.abs(a.y - b.y) + Math.abs(a.z - b.z) + Math.abs(a.w - b.w);
return (diff < tolerance);
};
test( "constructor/equals", function() {
var a = new THREE.Euler();
ok( a.equals( eulerZero ), "Passed!" );
@@ -799,13 +813,23 @@
});
test( "set", function() {
test("set/setFromVector3/toVector3", function () {
var a = new THREE.Euler();
a.set( 0, 1, 0, "ZYX" );
ok( a.equals( eulerAzyx ), "Passed!" );
ok( ! a.equals( eulerAxyz ), "Passed!" );
ok( ! a.equals( eulerZero ), "Passed!" );
ok(!a.equals(eulerZero), "Passed!");
var vec = new THREE.Vector3(0, 1, 0);
var b = new THREE.Euler().setFromVector3(vec, "ZYX");
console.log(a, b);
ok(a.equals(b), "Passed!");
var c = b.toVector3();
console.log(c, vec);
ok(c.equals(vec), "Passed!");
});
test( "Quaternion.setFromEuler/Euler.fromQuaternion", function() {
@@ -816,7 +840,7 @@
var v2 = new THREE.Euler().setFromQuaternion( q, v.order );
var q2 = new THREE.Quaternion().setFromEuler( v2 );
ok( q.equals( q2 ), "Passed!" );
ok(eulerEquals(q, q2), "Passed!");
}
});
@@ -841,14 +865,33 @@
v.reorder( 'YZX' );
var q2 = new THREE.Quaternion().setFromEuler( v );
ok( q.equals( q2 ), "Passed!" );
ok(quatEquals(q, q2), "Passed!");
v.reorder( 'ZXY' );
var q3 = new THREE.Quaternion().setFromEuler( v );
ok( q.equals( q3 ), "Passed!" );
ok(quatEquals(q, q3), "Passed!");
}
});
test("gimbalLocalQuat", function () {
// known problematic quaternions
var q1 = new THREE.Quaternion(0.5207769385244341, -0.4783214164122354, 0.520776938524434, 0.47832141641223547);
var q2 = new THREE.Quaternion(0.11284905712620674, 0.6980437630368944, -0.11284905712620674, 0.6980437630368944);
var eulerOrder = "ZYX";
// create Euler directly from a Quaternion
var eViaQ1 = new THREE.Euler().setFromQuaternion(q1, eulerOrder); // there is likely a bug here
// create Euler from Quaternion via an intermediate Matrix4
var mViaQ1 = new THREE.Matrix4().makeRotationFromQuaternion(q1);
var eViaMViaQ1 = new THREE.Euler().setFromRotationMatrix(mViaQ1, eulerOrder);
// the results here are different
ok(eulerEquals(eViaQ1, eViaMViaQ1), "Passed!"); // this result is correct
});
// -------------------------------------------- Frustum
var unit3 = new THREE.Vector3( 1, 0, 0 );
@@ -1483,6 +1526,36 @@
}
});
test("makeBasis/extractBasis", function () {
var identityBasis = [new THREE.Vector3(1, 0, 0), new THREE.Vector3(0, 1, 0), new THREE.Vector3(0, 0, 1)];
var a = new THREE.Matrix4().makeBasis(identityBasis[0], identityBasis[1], identityBasis[2]);
var identity = new THREE.Matrix4();
ok(matrixEquals4(a, identity), "Passed!");
var testBases = [[new THREE.Vector3(0, 1, 0), new THREE.Vector3(-1, 0, 0), new THREE.Vector3(0, 0, 1)]];
for (var i = 0; i < testBases.length; i++) {
var testBasis = testBases[i];
var b = new THREE.Matrix4().makeBasis(testBasis[0], testBasis[1], testBasis[2]);
var outBasis = [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()];
b.extractBasis(outBasis[0], outBasis[1], outBasis[2]);
// check what goes in, is what comes out.
for (var j = 0; j < outBasis.length; j++) {
console.log(outBasis[j], testBasis[j]);
ok(outBasis[j].equals(testBasis[j]), "Passed!");
}
// get the basis out the hard war
for (var j = 0; j < identityBasis.length; j++) {
outBasis[j].copy(identityBasis[j]);
outBasis[j].applyMatrix4(b);
}
// did the multiply method of basis extraction work?
for (var j = 0; j < outBasis.length; j++) {
ok(outBasis[j].equals(testBasis[j]), "Passed!");
}
}
});
test( "transpose", function() {
var a = new THREE.Matrix4();
var b = a.clone().transpose();
+1
View File
@@ -3,6 +3,7 @@
//////////////////////////////////////////////////////////////
/// <reference path="../../stats/stats.d.ts" />
/// <reference path="../../dat-gui/dat-gui.d.ts" />
/// <reference path="../detector.d.ts" />
/// <reference path="../three-canvasrenderer.d.ts" />
/// <reference path="../three-css3drenderer.d.ts" />
+7 -14
View File
@@ -86,8 +86,8 @@
light.castShadow = true;
//light.shadowCameraVisible = true;
light.shadowMapWidth = 2048;
light.shadowMapHeight = 2048;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 1024;
var d = 300;
@@ -101,11 +101,6 @@
scene.add(light);
light = new THREE.DirectionalLight(0x3dff0c, 0.35);
light.position.set(0, -1, 0);
scene.add(light);
// cloth material
var clothTexture = THREE.ImageUtils.loadTexture('textures/patterns/circuit_pattern.png');
@@ -151,17 +146,14 @@
// ground
var initColor = new THREE.Color(0x497f13);
var initTexture = THREE.ImageUtils.generateDataTexture(1, 1, initColor);
var groundMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x111111, map: initTexture });
var groundTexture = THREE.ImageUtils.loadTexture("textures/terrain/grasslight-big.jpg", undefined, function () { groundMaterial.map = groundTexture });
var groundTexture = THREE.ImageUtils.loadTexture("textures/terrain/grasslight-big.jpg");
groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
groundTexture.repeat.set(25, 25);
groundTexture.anisotropy = 16;
var mesh = new THREE.Mesh(new THREE.PlaneGeometry(20000, 20000), groundMaterial);
var groundMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff, specular: 0x111111, map: groundTexture });
var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(20000, 20000), groundMaterial);
mesh.position.y = -250;
mesh.rotation.x = - Math.PI / 2;
mesh.receiveShadow = true;
@@ -211,6 +203,7 @@
//
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(scene.fog.color);
@@ -5,16 +5,13 @@
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var material: THREE.SpriteMaterial;
var geometry: THREE.Geometry;
var dat:any;
// -------
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var FLOOR = -250;
var container,stats;
var container, stats;
var camera, scene;
var renderer;
@@ -28,56 +25,56 @@
var clock = new THREE.Clock();
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
document.addEventListener('mousemove', onDocumentMouseMove, false);
init();
animate();
function init() {
container = document.getElementById( 'container' );
container = document.getElementById('container');
camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 );
camera = new THREE.PerspectiveCamera(30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000);
camera.position.z = 2200;
scene = new THREE.Scene();
scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 );
scene.fog = new THREE.Fog(0xffffff, 2000, 10000);
scene.add( camera );
scene.add(camera);
// GROUND
var groundMaterial = new THREE.MeshPhongMaterial( { emissive: 0xbbbbbb } );
var planeGeometry = new THREE.PlaneGeometry( 16000, 16000 );
var geometry = new THREE.PlaneBufferGeometry(16000, 16000);
var material = new THREE.MeshPhongMaterial({ emissive: 0xbbbbbb });
var ground = new THREE.Mesh( planeGeometry, groundMaterial );
ground.position.set( 0, FLOOR, 0 );
ground.rotation.x = -Math.PI/2;
scene.add( ground );
var ground = new THREE.Mesh(geometry, material);
ground.position.set(0, FLOOR, 0);
ground.rotation.x = -Math.PI / 2;
scene.add(ground);
ground.receiveShadow = true;
// LIGHTS
var ambient = new THREE.AmbientLight( 0x222222 );
scene.add( ambient );
var ambient = new THREE.AmbientLight(0x222222);
scene.add(ambient);
var light = new THREE.DirectionalLight( 0xebf3ff, 1.6 );
light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 );
scene.add( light );
var light = new THREE.DirectionalLight(0xebf3ff, 1.6);
light.position.set(0, 140, 500).multiplyScalar(1.1);
scene.add(light);
light.castShadow = true;
light.shadowMapWidth = 2048;
light.shadowMapWidth = 1024;
light.shadowMapHeight = 2048;
var d = 390;
light.shadowCameraLeft = -d * 2;
light.shadowCameraRight = d * 2;
light.shadowCameraLeft = -d;
light.shadowCameraRight = d;
light.shadowCameraTop = d * 1.5;
light.shadowCameraBottom = -d;
@@ -86,19 +83,19 @@
//
var light = new THREE.DirectionalLight( 0x497f13, 1 );
light.position.set( 0, -1, 0 );
scene.add( light );
var light = new THREE.DirectionalLight(0x497f13, 1);
light.position.set(0, -1, 0);
scene.add(light);
// RENDERER
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.domElement.style.position = "relative";
renderer.setClearColor( scene.fog.color, 1 );
container.appendChild( renderer.domElement );
container.appendChild(renderer.domElement);
renderer.gammaInput = true;
renderer.gammaOutput = true;
@@ -109,16 +106,16 @@
// STATS
stats = new Stats();
container.appendChild( stats.domElement );
container.appendChild(stats.domElement);
//
var loader = new THREE.JSONLoader();
loader.load( "models/skinned/knight.js", function ( geometry, materials ) {
loader.load("models/skinned/knight.js", function (geometry, materials) {
createScene( geometry, materials, 0, FLOOR, -300, 60 )
createScene(geometry, materials, 0, FLOOR, -300, 60)
} );
});
// GUI
@@ -126,7 +123,7 @@
//
window.addEventListener( 'resize', onWindowResize, false );
window.addEventListener('resize', onWindowResize, false);
}
@@ -138,18 +135,18 @@
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setSize(window.innerWidth, window.innerHeight);
}
function ensureLoop( animation ) {
function ensureLoop(animation) {
for ( var i = 0; i < animation.hierarchy.length; i ++ ) {
for (var i = 0; i < animation.hierarchy.length; i++) {
var bone = animation.hierarchy[ i ];
var bone = animation.hierarchy[i];
var first = bone.keys[ 0 ];
var last = bone.keys[ bone.keys.length - 1 ];
var first = bone.keys[0];
var last = bone.keys[bone.keys.length - 1];
last.pos = first.pos;
last.rot = first.rot;
@@ -159,9 +156,9 @@
}
function createScene( geometry, materials, x, y, z, s ) {
function createScene(geometry, materials, x, y, z, s) {
ensureLoop( geometry.animation );
ensureLoop(geometry.animation);
geometry.computeBoundingBox();
var bb = geometry.boundingBox;
@@ -182,16 +179,16 @@
//var bumpMap = THREE.ImageUtils.generateDataTexture( 1, 1, new THREE.Color() );
//var bumpMap = THREE.ImageUtils.loadTexture( "textures/water.jpg" );
for ( var i = 0; i < materials.length; i ++ ) {
for (var i = 0; i < materials.length; i++) {
var m = materials[ i ];
var m = materials[i];
m.skinning = true;
m.morphTargets = true;
m.specular.setHSL( 0, 0, 0.1 );
m.specular.setHSL(0, 0, 0.1);
m.color.setHSL( 0.6, 0, 0.6 );
m.ambient.copy( m.color );
m.color.setHSL(0.6, 0, 0.6);
m.ambient.copy(m.color);
//m.map = map;
//m.envMap = envMap;
@@ -205,20 +202,20 @@
}
mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) );
mesh.position.set( x, y - bb.min.y * s, z );
mesh.scale.set( s, s, s );
scene.add( mesh );
mesh = new THREE.SkinnedMesh(geometry, new THREE.MeshFaceMaterial(materials));
mesh.position.set(x, y - bb.min.y * s, z);
mesh.scale.set(s, s, s);
scene.add(mesh);
mesh.castShadow = true;
mesh.receiveShadow = true;
helper = new THREE.SkeletonHelper( mesh );
helper = new THREE.SkeletonHelper(mesh);
helper.material.linewidth = 3;
helper.visible = false;
scene.add( helper );
scene.add(helper);
var animation = new THREE.Animation( mesh, geometry.animation );
var animation = new THREE.Animation(mesh, geometry.animation);
animation.play();
}
@@ -226,22 +223,22 @@
function initGUI() {
var API = {
'show model' : true,
'show skeleton' : false
'show model': true,
'show skeleton': false
};
var gui = new dat.GUI();
gui.add( API, 'show model' ).onChange( function() { mesh.visible = API[ 'show model' ]; } );
gui.add(API, 'show model').onChange(function () { mesh.visible = API['show model']; });
gui.add( API, 'show skeleton' ).onChange( function() { helper.visible = API[ 'show skeleton' ]; } );
gui.add(API, 'show skeleton').onChange(function () { helper.visible = API['show skeleton']; });
}
function onDocumentMouseMove( event ) {
function onDocumentMouseMove(event) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY );
mouseX = (event.clientX - windowHalfX);
mouseY = (event.clientY - windowHalfY);
}
@@ -249,7 +246,7 @@
function animate() {
requestAnimationFrame( animate );
requestAnimationFrame(animate);
render();
stats.update();
@@ -260,38 +257,38 @@
var delta = 0.75 * clock.getDelta();
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 );
camera.position.x += (mouseX - camera.position.x) * .05;
camera.position.y = THREE.Math.clamp(camera.position.y + (- mouseY - camera.position.y) * .05, 0, 1000);
camera.lookAt( scene.position );
camera.lookAt(scene.position);
// update skinning
THREE.AnimationHandler.update( delta );
THREE.AnimationHandler.update(delta);
if ( helper !== undefined ) helper.update();
if (helper !== undefined) helper.update();
// update morphs
if ( mesh ) {
if (mesh) {
var time = Date.now() * 0.001;
// mouth
mesh.morphTargetInfluences[ 1 ] = ( 1 + Math.sin( 4 * time ) ) / 2;
mesh.morphTargetInfluences[1] = (1 + Math.sin(4 * time)) / 2;
// frown ?
mesh.morphTargetInfluences[ 2 ] = ( 1 + Math.sin( 2 * time ) ) / 2;
mesh.morphTargetInfluences[2] = (1 + Math.sin(2 * time)) / 2;
// eyes
mesh.morphTargetInfluences[ 3 ] = ( 1 + Math.cos( 4 * time ) ) / 2;
mesh.morphTargetInfluences[3] = (1 + Math.cos(4 * time)) / 2;
}
renderer.render( scene, camera );
renderer.render(scene, camera);
}
}
+10 -9
View File
@@ -56,7 +56,7 @@
var chunkSize = 21845;
var indices = new Uint16Array( triangles * 3 );
var indices = new Uint16Array(triangles * 3);
for (var i = 0; i < indices.length; i++) {
@@ -64,9 +64,9 @@
}
var positions = new Float32Array( triangles * 3 * 3 );
var normals = new Float32Array( triangles * 3 * 3 );
var colors = new Float32Array( triangles * 3 * 3 );
var positions = new Float32Array(triangles * 3 * 3);
var normals = new Float32Array(triangles * 3 * 3);
var colors = new Float32Array(triangles * 3 * 3);
var color = new THREE.Color();
@@ -162,10 +162,10 @@
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.addAttribute('index', new THREE.BufferAttribute(indices, 1));
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('normal', new THREE.BufferAttribute(normals, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
var offsets = triangles / chunkSize;
@@ -194,7 +194,8 @@
//
renderer = new THREE.WebGLRenderer({ antialias: false });
renderer.setClearColor(scene.fog.color, 1);
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.gammaInput = true;
+6 -1
View File
@@ -17,6 +17,7 @@
animate();
function init() {
container = document.createElement('div');
document.body.appendChild(container);
@@ -85,13 +86,14 @@
}
var particles = new THREE.PointCloud( geometry, new THREE.PointCloudMaterial( { color: 0x888888 } ) );
var particles = new THREE.PointCloud(geometry, new THREE.PointCloudMaterial({ color: 0x888888 }));
scene.add(particles);
//
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
renderer.domElement.style.position = "relative";
container.appendChild(renderer.domElement);
@@ -168,6 +170,7 @@
}
function render() {
var r = Date.now() * 0.0005;
@@ -191,6 +194,7 @@
cameraOrthoHelper.visible = false;
} else {
cameraOrtho.far = mesh.position.length();
cameraOrtho.updateProjectionMatrix();
@@ -214,5 +218,6 @@
renderer.setViewport(SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2, SCREEN_HEIGHT);
renderer.render(scene, camera);
}
}
@@ -35,7 +35,7 @@
amplitude: { type: "f", value: 1.0 },
color: { type: "c", value: new THREE.Color(0xff2200) },
texture: { type: "t", value: THREE.ImageUtils.loadTexture("textures/water.jpg") }
texture: { type: "t", value: THREE.ImageUtils.loadTexture("textures/water.jpg") },
};
@@ -70,7 +70,8 @@
scene.add(sphere);
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0x050505, 1);
renderer.setClearColor(0x050505);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(WIDTH, HEIGHT);
var container = document.getElementById('container');
+1
View File
@@ -110,6 +110,7 @@
//
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
+1
View File
@@ -13,6 +13,7 @@
function init() {
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
+6 -11
View File
@@ -5,7 +5,7 @@
() => {
var container, stats;
var camera, scene, projector, raycaster, renderer;
var camera, scene, raycaster, renderer;
var mouse = new THREE.Vector2(), INTERSECTED;
var radius = 100, theta = 0;
@@ -30,14 +30,10 @@
scene = new THREE.Scene();
var light = new THREE.DirectionalLight(0xffffff, 2);
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 1, 1).normalize();
scene.add(light);
var light = new THREE.DirectionalLight(0xffffff);
light.position.set(-1, -1, -1).normalize();
scene.add(light);
var geometry = new THREE.BoxGeometry(20, 20, 20);
for (var i = 0; i < 2000; i++) {
@@ -60,11 +56,11 @@
}
projector = new THREE.Projector();
raycaster = new THREE.Raycaster();
renderer = new THREE.WebGLRenderer();
renderer.setClearColor(0xf0f0f0);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.sortObjects = false;
container.appendChild(renderer.domElement);
@@ -120,12 +116,11 @@
camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta));
camera.lookAt(scene.position);
camera.updateMatrixWorld();
// find intersections
var vector = new THREE.Vector3(mouse.x, mouse.y, 1);
projector.unprojectVector(vector, camera);
raycaster.set(camera.position, vector.sub(camera.position).normalize());
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(scene.children);
@@ -6,61 +6,59 @@
() => {
// ------- variable definitions that does not exist in the original code. These are for typescript.
var material: THREE.SpriteMaterial;
var intersection: THREE.Intersection;
var container: HTMLElement;
var pcBuffer: THREE.PointCloud;
var v: any;
// -------
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
if (!Detector.webgl) Detector.addGetWebGLMessage();
var renderer, scene, camera, stats;
var pointclouds;
var projector, raycaster, intersects;
var mouse = { x: 1, y: 1 };
var vector = new THREE.Vector3();
intersection = null;
var raycaster, intersects;
var mouse = new THREE.Vector2();
var intersection = null;
var spheres = [];
var spheresIndex = 0;
var clock;
var threshold = 0.1;
var pointSize = 0.01;
var pointSize = 0.05;
var width = 150;
var length = 150;
var rotateY = new THREE.Matrix4().makeRotationY( 0.005 );
var rotateY = new THREE.Matrix4().makeRotationY(0.005);
init();
animate();
function generatePointCloudGeometry( color, width, length ){
function generatePointCloudGeometry(color, width, length) {
var geometry = new THREE.BufferGeometry();
var numPoints = width*length;
var numPoints = width * length;
var positions = new Float32Array( numPoints*3 );
var colors = new Float32Array( numPoints*3 );
var positions = new Float32Array(numPoints * 3);
var colors = new Float32Array(numPoints * 3);
var k = 0;
for( var i = 0; i < width; i++ ) {
for (var i = 0; i < width; i++) {
for( var j = 0; j < length; j++ ) {
for (var j = 0; j < length; j++) {
var u = i / width;
var v = j / length;
var x = u - 0.5;
var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8 ) ) / 20;
var y = (Math.cos(u * Math.PI * 8) + Math.sin(v * Math.PI * 8)) / 20;
var z = v - 0.5;
positions[ 3 * k ] = x;
positions[ 3 * k + 1 ] = y;
positions[ 3 * k + 2 ] = z;
positions[3 * k] = x;
positions[3 * k + 1] = y;
positions[3 * k + 2] = z;
var intensity = ( y + 0.1 ) * 5;
colors[ 3 * k ] = color.r * intensity;
colors[ 3 * k + 1 ] = color.g * intensity;
colors[ 3 * k + 2 ] = color.b * intensity;
var intensity = (y + 0.1) * 5;
colors[3 * k] = color.r * intensity;
colors[3 * k + 1] = color.g * intensity;
colors[3 * k + 2] = color.b * intensity;
k++;
@@ -68,85 +66,85 @@
}
geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.addAttribute('color', new THREE.BufferAttribute(colors, 3));
geometry.computeBoundingBox();
return geometry;
}
function generatePointcloud( color, width, length ) {
function generatePointcloud(color, width, length) {
var geometry = generatePointCloudGeometry( color, width, length );
var geometry = generatePointCloudGeometry(color, width, length);
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
var material = new THREE.PointCloudMaterial({ size: pointSize, vertexColors: THREE.VertexColors });
var pointcloud = new THREE.PointCloud(geometry, material);
return pointcloud;
}
function generateIndexedPointcloud( color, width, length ) {
function generateIndexedPointcloud(color, width, length) {
var geometry = generatePointCloudGeometry( color, width, length );
var geometry = generatePointCloudGeometry(color, width, length);
var numPoints = width * length;
var indices = new Uint16Array( numPoints );
var indices = new Uint16Array(numPoints);
var k = 0;
for( var i = 0; i < width; i++ ) {
for (var i = 0; i < width; i++) {
for( var j = 0; j < length; j++ ) {
for (var j = 0; j < length; j++) {
indices[ k ] = k;
indices[k] = k;
k++;
}
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
geometry.addAttribute('index', new THREE.BufferAttribute(indices, 1));
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
var material = new THREE.PointCloudMaterial({ size: pointSize, vertexColors: THREE.VertexColors });
var pointcloud = new THREE.PointCloud(geometry, material);
return pointcloud;
}
function generateIndexedWithOffsetPointcloud( color, width, length ){
function generateIndexedWithOffsetPointcloud(color, width, length) {
var geometry = generatePointCloudGeometry( color, width, length );
var geometry = generatePointCloudGeometry(color, width, length);
var numPoints = width * length;
var indices = new Uint16Array( numPoints );
var indices = new Uint16Array(numPoints);
var k = 0;
for( var i = 0; i < width; i++ ){
for (var i = 0; i < width; i++) {
for( var j = 0; j < length; j++ ) {
for (var j = 0; j < length; j++) {
indices[ k ] = k;
indices[k] = k;
k++;
}
}
geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
geometry.addAttribute('index', new THREE.BufferAttribute(indices, 1));
var offset = { start: 0, count: indices.length, index: 0 };
geometry.offsets.push( offset );
geometry.offsets.push(offset);
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
var material = new THREE.PointCloudMaterial({ size: pointSize, vertexColors: THREE.VertexColors });
var pointcloud = new THREE.PointCloud(geometry, material);
return pointcloud;
}
function generateRegularPointcloud( color, width, length ) {
function generateRegularPointcloud(color, width, length) {
var geometry = new THREE.Geometry();
var numPoints = width * length;
@@ -155,24 +153,24 @@
var k = 0;
for( var i = 0; i < width; i++ ) {
for (var i = 0; i < width; i++) {
for( var j = 0; j < length; j++ ) {
for (var j = 0; j < length; j++) {
var u = i / width;
v = j / length;
var v = j / length;
var x = u - 0.5;
var y = ( Math.cos( u * Math.PI * 8 ) + Math.sin( v * Math.PI * 8) ) / 20;
var y = (Math.cos(u * Math.PI * 8) + Math.sin(v * Math.PI * 8)) / 20;
var z = v - 0.5;
v = new THREE.Vector3( x,y,z );
var vec = new THREE.Vector3(x, y, z);
var intensity = ( y + 0.1 ) * 7;
colors[ 3 * k ] = color.r * intensity;
colors[ 3 * k + 1 ] = color.g * intensity;
colors[ 3 * k + 2 ] = color.b * intensity;
var intensity = (y + 0.1) * 7;
colors[3 * k] = color.r * intensity;
colors[3 * k + 1] = color.g * intensity;
colors[3 * k + 2] = color.b * intensity;
geometry.vertices.push( v );
colors[ k ] = ( color.clone().multiplyScalar( intensity ) );
geometry.vertices.push(vec);
colors[k] = (color.clone().multiplyScalar(intensity));
k++;
@@ -183,8 +181,8 @@
geometry.colors = colors;
geometry.computeBoundingBox();
var material = new THREE.PointCloudMaterial( { size: pointSize, vertexColors: THREE.VertexColors } );
var pointcloud = new THREE.PointCloud( geometry, material );
var material = new THREE.PointCloudMaterial({ size: pointSize, vertexColors: THREE.VertexColors });
var pointcloud = new THREE.PointCloud(geometry, material);
return pointcloud;
@@ -192,63 +190,62 @@
function init() {
container = document.getElementById( 'container' );
container = document.getElementById('container');
scene = new THREE.Scene();
clock = new THREE.Clock();
camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.applyMatrix( new THREE.Matrix4().makeTranslation( 0,0,20 ) );
camera.applyMatrix( new THREE.Matrix4().makeRotationX( -0.5 ) );
camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
camera.applyMatrix(new THREE.Matrix4().makeTranslation(0, 0, 20));
camera.applyMatrix(new THREE.Matrix4().makeRotationX(-0.5));
//
pcBuffer = generatePointcloud( new THREE.Color( 1,0,0 ), width, length );
pcBuffer.scale.set( 10,10,10 );
pcBuffer.position.set( -5,0,5 );
scene.add( pcBuffer );
pcBuffer = generatePointcloud(new THREE.Color(1, 0, 0), width, length);
pcBuffer.scale.set(10, 10, 10);
pcBuffer.position.set(-5, 0, 5);
scene.add(pcBuffer);
var pcIndexed = generateIndexedPointcloud( new THREE.Color( 0,1,0 ), width, length );
pcIndexed.scale.set( 10,10,10 );
pcIndexed.position.set( 5,0,5 );
scene.add( pcIndexed );
var pcIndexed = generateIndexedPointcloud(new THREE.Color(0, 1, 0), width, length);
pcIndexed.scale.set(10, 10, 10);
pcIndexed.position.set(5, 0, 5);
scene.add(pcIndexed);
var pcIndexedOffset = generateIndexedWithOffsetPointcloud( new THREE.Color( 0,1,1 ), width, length );
pcIndexedOffset.scale.set( 10,10,10 );
pcIndexedOffset.position.set( 5,0,-5 );
scene.add( pcIndexedOffset );
var pcIndexedOffset = generateIndexedWithOffsetPointcloud(new THREE.Color(0, 1, 1), width, length);
pcIndexedOffset.scale.set(10, 10, 10);
pcIndexedOffset.position.set(5, 0, -5);
scene.add(pcIndexedOffset);
var pcRegular = generateRegularPointcloud( new THREE.Color( 1,0,1 ), width, length );
pcRegular.scale.set( 10,10,10 );
pcRegular.position.set( -5,0,-5 );
scene.add( pcRegular );
var pcRegular = generateRegularPointcloud(new THREE.Color(1, 0, 1), width, length);
pcRegular.scale.set(10, 10, 10);
pcRegular.position.set(-5, 0, -5);
scene.add(pcRegular);
pointclouds = [ pcBuffer, pcIndexed, pcIndexedOffset, pcRegular ];
pointclouds = [pcBuffer, pcIndexed, pcIndexedOffset, pcRegular];
//
var sphereGeometry = new THREE.SphereGeometry( 0.1, 32, 32 );
var sphereMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, shading: THREE.FlatShading } );
var sphereGeometry = new THREE.SphereGeometry(0.1, 32, 32);
var sphereMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000, shading: THREE.FlatShading });
for ( var i = 0; i < 40; i++ ) {
for (var i = 0; i < 40; i++) {
var sphere = new THREE.Mesh( sphereGeometry, sphereMaterial );
scene.add( sphere );
spheres.push( sphere );
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
scene.add(sphere);
spheres.push(sphere);
}
//
renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
//
projector = new THREE.Projector();
raycaster = new THREE.Raycaster();
raycaster.params.PointCloud.threshold = threshold;
@@ -257,21 +254,21 @@
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild( stats.domElement );
container.appendChild(stats.domElement);
//
window.addEventListener( 'resize', onWindowResize, false );
document.addEventListener( 'mousemove', onDocumentMouseMove, false );
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousemove', onDocumentMouseMove, false);
}
function onDocumentMouseMove( event ) {
function onDocumentMouseMove(event) {
event.preventDefault();
mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = - (event.clientY / window.innerHeight) * 2 + 1;
}
@@ -280,13 +277,13 @@
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame( animate );
requestAnimationFrame(animate);
render();
stats.update();
@@ -297,39 +294,35 @@
function render() {
camera.applyMatrix( rotateY );
camera.updateMatrixWorld( true );
camera.applyMatrix(rotateY);
camera.updateMatrixWorld();
vector.set( mouse.x, mouse.y, 0.1 );
raycaster.setFromCamera(mouse, camera);
projector.unprojectVector( vector, camera );
var intersections = raycaster.intersectObjects(pointclouds);
intersection = (intersections.length) > 0 ? intersections[0] : null;
raycaster.ray.set( camera.position, vector.sub( camera.position ).normalize() );
if (toggle > 0.02 && intersection !== null) {
var intersections = raycaster.intersectObjects( pointclouds );
intersection = ( intersections.length ) > 0 ? intersections[ 0 ] : null;
if ( toggle > 0.02 && intersection !== null) {
spheres[ spheresIndex ].position.copy( intersection.point );
spheres[ spheresIndex ].scale.set( 1, 1, 1 );
spheresIndex = ( spheresIndex + 1 ) % spheres.length;
spheres[spheresIndex].position.copy(intersection.point);
spheres[spheresIndex].scale.set(1, 1, 1);
spheresIndex = (spheresIndex + 1) % spheres.length;
toggle = 0;
}
for ( var i = 0; i < spheres.length; i++ ) {
for (var i = 0; i < spheres.length; i++) {
var sphere = spheres[ i ];
sphere.scale.multiplyScalar( 0.98 );
sphere.scale.clampScalar( 0.01, 1 );
var sphere = spheres[i];
sphere.scale.multiplyScalar(0.98);
sphere.scale.clampScalar(0.01, 1);
}
toggle += clock.getDelta();
renderer.render( scene, camera );
renderer.render(scene, camera);
}
}
+3 -3
View File
@@ -116,7 +116,7 @@
lensFlare.add(textureFlare3, 70, 1.0, THREE.AdditiveBlending);
lensFlare.customUpdateCallback = lensFlareUpdateCallback;
lensFlare.position.copy( light.position );
lensFlare.position.copy(light.position);
scene.add(lensFlare);
@@ -125,9 +125,9 @@
// renderer
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(scene.fog.color, 1);
container.appendChild(renderer.domElement);
//
@@ -79,7 +79,7 @@
// GROUND
var groundGeo = new THREE.PlaneGeometry(10000, 10000);
var groundGeo = new THREE.PlaneBufferGeometry(10000, 10000);
var groundMat = new THREE.MeshPhongMaterial({ ambient: 0xffffff, color: 0xffffff, specular: 0x050505 });
groundMat.color.setHSL(0.095, 1, 0.75);
@@ -140,11 +140,11 @@
// RENDERER
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setClearColor(scene.fog.color);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
renderer.setClearColor(scene.fog.color, 1);
renderer.gammaInput = true;
renderer.gammaOutput = true;

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