Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Kiarash Ghiaseddin
2015-02-18 02:02:57 +01:00
46 changed files with 8373 additions and 407 deletions
+16 -6
View File
@@ -63,7 +63,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](bgiframe/typescript.bgiframe.d.ts) [bgiframe](https://github.com/sumegizoltan/BgiFrame) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](big.js/big.js.d.ts) [big.js](https://github.com/MikeMcl/big.js) by [Steve Ognibene](https://github.com/nycdotnet)
* [:link:](bigint/bigint.d.ts) [BigInt](https://github.com/Evgenus/BigInt) by [Eugene Chernyshov](https://github.com/Evgenus)
* [:link:](big-integer/big-integer.d.ts) [BigInteger.js](https://github.com/peterolson/BigInteger.js) by [Ingo Bürk](https://github.com/Airblader)
* [:link:](big-integer/big-integer.d.ts) [BigInteger.js](https://github.com/peterolson/BigInteger.js) by [Ingo Bürk](https://github.com/Airblader), [Roel van Uden](https://github.com/Deathspike)
* [:link:](bigscreen/bigscreen.d.ts) [BigScreen](http://brad.is/coding/BigScreen) by [Douglas Eichelberger](https://github.com/dduugg)
* [:link:](bluebird/bluebird.d.ts) [bluebird](https://github.com/petkaantonov/bluebird) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](body-parser/body-parser.d.ts) [body-parser](http://expressjs.com) by [Santi Albo](https://github.com/santialbo), [VILIC VANE](https://vilic.info), [Jonathan Häberle](https://github.com/dreampulse)
@@ -149,6 +149,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [: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)
* [:link:](documentdb/documentdb.d.ts) [DocumentDB](https://github.com/Azure/azure-documentdb-node) by [Noel Abrahams](https://github.com/NoelAbrahams)
* [:link:](dojo/dojo.d.ts) [Dojo](http://dojotoolkit.org) by [Michael Van Sickle](https://github.com/vansimke)
* [:link:](domo/domo.d.ts) [Domo](http://domo-js.com) by [Steve Fenton](https://github.com/Steve-Fenton)
* [:link:](domready/domready.d.ts) [domready](https://github.com/ded/domready) by [Christian Holm Nielsen](https://github.com/dotnetnerd)
@@ -174,8 +175,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](errorhandler/errorhandler.d.ts) [errorhandler](https://github.com/expressjs/errorhandler) by [Santi Albo](https://github.com/santialbo)
* [:link:](es6-promise/es6-promise.d.ts) [es6-promise](https://github.com/jakearchibald/ES6-Promise) by [François de Campredon](https://github.com/fdecampredon), [vvakame](https://github.com/vvakame)
* [:link:](esprima/esprima.d.ts) [Esprima](http://esprima.org) by [teppeis](https://github.com/teppeis)
* [:link:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [Rogier Schouten](https://github.com/rogierschouten)
* [:link:](eventemitter2/eventemitter2.d.ts) [EventEmitter2](https://github.com/asyncly/EventEmitter2) by [ryiwamoto](https://github.com/ryiwamoto)
* [:link:](event-loop-lag/event-loop-lag.d.ts) [event-loop-lag](https://github.com/pebble/event-loop-lag) by [rogierschouten](https://github.com/rogierschouten)
* [:link:](exit/exit.d.ts) [exit](https://github.com/cowboy/node-exit) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](expect.js/expect.js.d.ts) [expect.js](https://github.com/LearnBoost/expect.js) by [Teppei Sato](https://github.com/teppeis)
* [:link:](expectations/expectations.d.ts) [expectations.js](https://github.com/spmason/expectations) by [vvakame](https://github.com/vvakame)
@@ -232,8 +233,8 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](google.analytics/ga.d.ts) [Google Analytics (Classic and Universal)](https://developers.google.com/analytics/devguides/collection/gajs) by [Ronnie Haakon Hegelund](http://ronniehegelund.blogspot.dk), [Pat Kujawa](http://patkujawa.com)
* [:link:](gapi/gapi.d.ts) [Google API Client](https://code.google.com/p/google-api-javascript-client) by [Frank M](https://github.com/sgtfrankieboy)
* [:link:](google.feeds/google.feed.api.d.ts) [Google Feed Apis](https://developers.google.com/feed) by [RodneyJT](https://github.com/RodneyJT)
* [:link:](googlemaps/google.maps.d.ts) [Google Geolocation](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk)
* [:link:](google.geolocation/google.geolocation.d.ts) [Google Geolocation](https://code.google.com/p/geo-location-javascript) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](googlemaps/google.maps.d.ts) [Google Geolocation](https://developers.google.com/maps) by [Folia A/S](http://www.folia.dk)
* [:link:](gapi.pagespeedonline/gapi.pagespeedonline.d.ts) [Google Page Speed Online Api](https://developers.google.com/speed/pagespeed) by [Frank M](https://github.com/sgtfrankieboy)
* [:link:](recaptcha/recaptcha.d.ts) [Google Recaptcha](https://www.google.com/recaptcha) by [Brent Jenkins](https://github.com/brentj73)
* [:link:](gapi.translate/gapi.translate.d.ts) [Google Translate API](https://developers.google.com/translate) by [Frank M](https://github.com/sgtfrankieboy)
@@ -300,6 +301,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](jasmine-fixture/jasmine-fixture.d.ts) [Jasmine-fixture](https://github.com/searls/jasmine-fixture) by [Craig Brett](https://github.com/craigbrett17)
* [:link:](jasmine-jquery/jasmine-jquery.d.ts) [Jasmine-JQuery](https://github.com/velesin/jasmine-jquery) by [Gregor Stamac](https://github.com/gstamac)
* [:link:](jasmine-matchers/jasmine-matchers.d.ts) [jasmine-matchers](https://github.com/uxebu/jasmine-matchers) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](java-applet/java-applet.d.ts) [Java Applet](https://www.java.com) by [Cyril Schumacher](https://github.com/cyrilschumacher)
* [:link:](jdataview/jdataview.d.ts) [jDataView](https://github.com/jDataView/jDataView) by [Ingvar Stepanyan](https://github.com/RReverser)
* [:link:](jest/jest.d.ts) [Jest](http://facebook.github.io/jest) by [Asana](https://asana.com)
* [:link:](jjv/jjv.d.ts) [JJV](https://github.com/acornejo/jjv) by [Wim Looman](https://github.com/Nemo157)
@@ -418,6 +420,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](kolite/kolite.d.ts) [KoLite](https://github.com/CodeSeven/kolite) by [Boris Yankov](https://github.com/borisyankov)
* [:link:](kuromoji/kuromoji.d.ts) [kuromoji.js](https://github.com/takuyaa/kuromoji.js) by [MIZUSHIMA Junki](https://github.com/mzsm)
* [:link:](ladda/ladda.d.ts) [Ladda](https://github.com/hakimel/Ladda) by [Danil Flores](https://github.com/dflor003), [Michael Lee](https://github.com/leemicw)
* [:link:](later/later.d.ts) [LaterJS](http://bunkat.github.io/later) by [Jason D Dryhurst-Smith](http://jasonds.co.uk)
* [:link:](lazy.js/lazy.js.d.ts) [Lazy.js](https://github.com/dtao/lazy.js) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](leaflet/leaflet.d.ts) [Leaflet.js](https://github.com/Leaflet/Leaflet) by [Vladimir Zotov](https://github.com/rgripper)
* [:link:](jquery.leanModal/jquery.leanModal.d.ts) [leanModal.js](http://leanmodal.finelysliced.com.au) by [FinelySliced](https://github.com/FinelySliced)
@@ -468,6 +471,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](mixpanel/mixpanel.d.ts) [Mixpanel](https://mixpanel.com) by [Knut Eirik Leira Hjelle](https://github.com/hjellek)
* [:link:](mixto/mixto.d.ts) [mixto](https://github.com/atom/mixto) by [vvakame](https://github.com/vvakame)
* [:link:](mkdirp/mkdirp.d.ts) [mkdirp](http://github.com/substack/node-mkdirp) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](mkpath/mkpath.d.ts) [mkpath](https://www.npmjs.com/package/mkpath) by [Jared Klopper](https://github.com/optical)
* [:link:](mocha/mocha.d.ts) [mocha](http://mochajs.org) by [Kazi Manzur Rashid](https://github.com/kazimanzurrashid), [otiai10](https://github.com/otiai10), [jt000](https://github.com/jt000)
* [:link:](mocha-phantomjs/mocha-phantomjs.d.ts) [mocha-phantomjs](http://metaskills.net/mocha-phantomjs) by [Erik Schierboom](https://github.com/ErikSchierboom)
* [:link:](mockery/mockery.d.ts) [mockery](https://github.com/mfncooper/mockery) by [jt000](https://github.com/jt000)
@@ -511,6 +515,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](ip/ip.d.ts) [node-ip](https://github.com/indutny/node-ip) by [Peter Harris](https://github.com/codeanimal)
* [:link:](multiparty/multiparty.d.ts) [node-multiparty](https://github.com/andrewrk/node-multiparty) by [Ken Fukuyama](https://github.com/kenfdev)
* [:link:](mysql/mysql.d.ts) [node-mysql](https://github.com/felixge/node-mysql) by [William Johnston](https://github.com/wjohnsto)
* [:link:](node-persist/node-persist.d.ts) [node-persist](https://github.com/simonlast/node-persist) by [Spencer Williams](http://spencerwi.com)
* [:link:](promptly/promptly.d.ts) [node-promptly](https://github.com/IndigoUnited/node-promptly) by [Dan Spencer](https://github.com/danrspencer)
* [:link:](radius/radius.d.ts) [node-radius](https://github.com/retailnext/node-radius) by [Peter Harris](https://github.com/codeanimal)
* [:link:](node-uuid/node-uuid.d.ts) [node-uuid.js](https://github.com/broofa/node-uuid) by [Jeff May](https://github.com/jeffmay)
@@ -524,8 +529,9 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](nodemailer/nodemailer.d.ts) [Nodemailer](https://github.com/andris9/Nodemailer) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](nodeunit/nodeunit.d.ts) [nodeunit](https://github.com/caolan/nodeunit) by [Jeff Goddard](https://github.com/jedigo)
* [:link:](nomnom/nomnom.d.ts) [nomnom](https://github.com/harthur/nomnom) by [Paul Vick](https://github.com/panopticoncentral)
* [:link:](notify/notify.d.ts) [Notify.js](https://github.com/jpillora/notifyjs) by [Xiaohan Zhang](https://github.com/hellochar)
* [:link:](nopt/nopt.d.ts) [nopt](https://github.com/npm/nopt) by [jbondc](https://github.com/jbondc)
* [:link:](notifyjs/notifyjs.d.ts) [notify.js](https://github.com/alexgibson/notify.js) by [soundTricker](https://github.com/soundTricker)
* [:link:](notify/notify.d.ts) [Notify.js](https://github.com/jpillora/notifyjs) by [Xiaohan Zhang](https://github.com/hellochar)
* [: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)
@@ -586,6 +592,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](raphael/raphael.d.ts) [Raphael](http://raphaeljs.com) by [CheCoxshall](https://github.com/CheCoxshall)
* [:link:](ravenjs/ravenjs.d.ts) [Raven.js](https://github.com/getsentry/raven-js) by [Santi Albo](https://github.com/santialbo)
* [:link:](react/react.d.ts) [React](http://facebook.github.io/react) by [Asana](https://asana.com)
* [:link:](react-router/react-router.d.ts) [React Router](https://github.com/rackt/react-router) by [Yuichi Murata](https://github.com/mrk21)
* [:link:](readdir-stream/readdir-stream.d.ts) [readdir-stream](https://github.com/logicalparadox/readdir-stream) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](redis/redis.d.ts) [redis](https://github.com/mranney/node_redis) by [Carlos Ballesteros Velasco](https://github.com/soywiz), [Peter Harris](https://github.com/CodeAnimal)
* [:link:](ref/ref.d.ts) [ref](https://github.com/TooTallNate/ref) by [Paul Loyd](https://github.com/loyd)
@@ -619,12 +626,15 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [: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:](sanitize-html/sanitize-html.d.ts) [sanitize-html](https://github.com/punkave/sanitize-html) by [Rogier Schouten](https://github.com/rogierschouten)
* [:link:](sax/sax.d.ts) [sax js](https://github.com/isaacs/sax-js) by [Asana](https://asana.com)
* [: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)
* [:link:](selenium-webdriver/selenium-webdriver.d.ts) [Selenium WebDriverJS](https://code.google.com/p/selenium) by [Bill Armstrong](https://github.com/BillArmstrong)
* [:link:](semver/semver.d.ts) [semver](https://github.com/isaacs/node-semver) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](sendgrid/sendgrid.d.ts) [sendgrid](https://github.com/sendgrid/sendgrid-nodejs) by [Maxime LUCE](https://github.com/SomaticIT)
* [:link:](sequelize/sequelize.d.ts) [Sequelize 2.0.0 dev13](http://sequelizejs.com) by [samuelneff](https://github.com/samuelneff), [Peter Harris](https://github.com/codeanimal)
* [:link:](sharedworker/SharedWorker.d.ts) [SharedWorker](http://www.w3.org/TR/workers) by [Toshiya Nakakura](https://github.com/nakakura)
* [:link:](shelljs/shelljs.d.ts) [ShellJS](http://shelljs.org) by [Niklas Mollenhauer](https://github.com/nikeee)
* [:link:](should/should.d.ts) [should.js](https://github.com/visionmedia/should.js) by [Alex Varju](https://github.com/varju), [Maxime LUCE](https://github.com/SomaticIT)
@@ -658,7 +668,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](sharepoint/SharePoint.d.ts) [sptypescript](http://sptypescript.codeplex.com) by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru), [Andrey Markeev](http://markeev.com)
* [:link:](sqlite3/sqlite3.d.ts) [sqlite3](https://github.com/mapbox/node-sqlite3) by [Nick Malaguti](https://github.com/nmalaguti)
* [:link:](stampit/stampit.d.ts) [stampit](https://github.com/ericelliott/stampit) by [Vasyl Boroviak](https://github.com/koresar)
* [:link:](stats/stats.d.ts) [Stats.js r11](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai)
* [:link:](stats/stats.d.ts) [Stats.js r12](http://github.com/mrdoob/stats.js) by [Gregory Dalton](https://github.com/gregolai)
* [:link:](status-bar/status-bar.d.ts) [status-bar](https://github.com/atom/status-bar) by [vvakame](https://github.com/vvakame)
* [:link:](storejs/storejs.d.ts) [store.js](https://github.com/marcuswestin/store.js) by [Vincent Bortone](https://github.com/vbortone)
* [:link:](stream-to-array/stream-to-array.d.ts) [stream-to-array](https://github.com/stream-utils/stream-to-array) by [Bart van der Schoor](https://github.com/Bartvds)
@@ -679,7 +689,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](swiz/swiz.d.ts) [swiz](https://github.com/racker/node-swiz) by [Jeff Goddard](https://github.com/jedigo)
* [:link:](tape/tape.d.ts) [tape](https://github.com/substack/tape) by [Bart van der Schoor](https://github.com/Bartvds)
* [:link:](tar/tar.d.ts) [tar](https://github.com/npm/node-tar) by [Maxime LUCE](https://github.com/SomaticIT)
* [:link:](tcomb/tcomb.d.ts) [tcomb](https://github.com/npm/tcomb) by [Jed Mao](https://github.com/jedmao)
* [:link:](tcomb/tcomb.d.ts) [tcomb](http://gcanti.github.io/tcomb/guide/index.html) by [Jed Mao](https://github.com/jedmao)
* [:link:](tedious/tedious.d.ts) [tedious](https://pekim.github.io/tedious) by [Rogier Schouten](https://github.com/rogierschouten)
* [:link:](tedious-connection-pool/tedious-connection-pool.d.ts) [tedious-connection-pool](https://github.com/pekim/tedious-connection-pool) by [Cyprien Autexier](https://github.com/sandorfr)
* [:link:](teechart/teechart.d.ts) [TeeChart](http://www.steema.com) by [Steema Software](https://steema.com)
+66
View File
@@ -0,0 +1,66 @@
/// <reference path="documentdb.d.ts" />
import docDB = require('documentdb');
var docDBClient = new docDB.DocumentClient('host', { masterKey: 'masterKey' });
docDBClient.createDatabase({ id: 'foo' }, undefined, (error, result) => {
if (error) {
throw new Error(error.body);
}
else {
console.log('Created database: ' + result.id);
}
});
docDBClient.createCollection('database', { id: 'foo' }, undefined, (error, result) => {
if (error) {
throw new Error(error.body);
}
else {
console.log('Created collection: ' + result.id);
}
});
var procedure: docDB.Procedure = {
id: 'procedure-one',
body: function () {
console.log('foo');
}
};
docDBClient.createStoredProcedure('collection', procedure, undefined, (error, result) => {
if (error) {
throw new Error(error.body);
}
else {
console.log('Created procedure: ' + result.id);
}
});
var document: docDB.NewDocument<{ val: string }> = {
id: '10'
};
docDBClient.createDocument('collection', document, undefined, (error, result) => {
if (error) {
throw new Error(error.body);
}
else {
console.log('Created document: ' + result.id);
}
});
docDBClient.executeStoredProcedure('procedure', [10, 'foo'], (error, result) => {
if (error) {
throw new Error(error.body);
}
else {
console.log('Procedure result: ' + result);
}
});
+350
View File
@@ -0,0 +1,350 @@
// Type definitions for DocumentDB
// Project: https://github.com/Azure/azure-documentdb-node
// Definitions by: Noel Abrahams <https://github.com/NoelAbrahams>
// Definitions: https://github.com/borisyankov/DefinitelyTyped/documentdb
declare module 'documentdb' {
/** The feed options and query methods.*/
interface FeedOptions {
/** Max number of items to be returned in the enumeration operation. */
maxItemCount?: number;
/** Opaque token for continuing the enumeration. */
continuation?: string;
/** Token for use with Session consistency. */
sessionToken?: string;
}
/** Options that can be specified for a request issued to the DocumentDB servers. */
interface RequestOptions {
/** Indicates what is the pre trigger to be invoked before the operation. */
preTriggerInclude?: string;
/** Indicates what is the post trigger to be invoked after the operation. */
postTriggerInclude?: string;
/** Conditions Associated with the request. */
accessCondition?: {
/** Conditional HTTP method header type.*/
type: string;
/** Conditional HTTP method header value.*/
condition: string
};
/** Specifies indexing directives (index, do not index ..etc).*/
indexingDirective?: string;
/** Consistency level required by the client. */
consistencyLevel?: string;
/** Token for use with Session consistency.*/
sessionToken?: string;
/** Expiry time (in seconds) for resource token associated with permission (applicable only for requests on permissions).*/
resourceTokenExpirySeconds?: number;
/** Disables the automatic id generation. If id is missing in the body and this option is true, an error will be returned. */
disableAutomaticIdGeneration?: boolean;
}
/** Represents the error object returned from a failed query. */
interface QueryError {
/** The response code corresponding to the error. */
code: number;
/** A string representing the error information. */
body: string; //{ code: string; message: string; };
}
/**
* The callback to execute after the request execution.
* @param error - Will contain error information if an error occurs, undefined otherwise.
* @param resource - An object that represents the requested resource (Db, collection, document ... etc) if no error happens.
* @param responseHeaders - An object that contain the response headers.
*/
interface RequestCallback<TResult> {
(error: QueryError, resource: TResult, responseHeaders: any): void;
}
/** Represents the result returned from a query. */
interface QueryIterator<TResultRow> {
toArray(callback: (error: QueryError, result: TResultRow[]) => void): void;
}
/** Reprents an object with a unique identifier. */
interface UniqueId {
/** The user-defined unique identifier for a document or other DocumentDB object (database, collection, procedure...) */
id: string;
}
/** Represents the common meta data for all DocumentDB objects. */
interface AbstractMeta extends UniqueId {
/** The self link.*/
_self: string;
/** The time the object was created.*/
_ts: string;
_rid?: string;
_etag?: string;
_attachments?: string;
}
/** Represents a custom document for storing in DocumentDB */
interface NewDocument<TContent> extends UniqueId {
/** A custom property for containing the actual JSON object representing the document.
* Define a custom property in order to disambiguate the JSON document from the metadata added by Azure.
* This property is optional and the name is application-specific.
*/
//doc: TContent;
}
/** Represents a document retrieved from storage.
* This differs from a new document by the properties in AbstractMeta, which are added by the system.
*/
interface RetrievedDocument<TContent> extends NewDocument<TContent>, AbstractMeta {
}
/** Represents the meta data for a database. */
interface DatabaseMeta extends AbstractMeta {
}
/** Represents the meta data for a collection. */
interface CollectionMeta extends AbstractMeta {
}
/** Represents the meta data for a stored procedure. */
interface ProcedureMeta extends AbstractMeta {
body: string;
}
/** An object that is used for authenticating requests and must contains one of the options. */
export interface AuthOptions {
/** The authorization master key to use to create the client. */
masterKey?: string;
/** An object that contains resources tokens. Keys for the object are resource Ids and values are the resource tokens.*/
resourceTokens?: any;
/** An array of {@link Permission} objects. */
permissionFeed?: any[];
}
/** Represents a DocumentDB stored procecedure. */
export interface Procedure extends UniqueId {
/** The function representing the stored procedure. */
body(...params: any[]): void;
}
/** Represents DocumentDB collection. */
export interface Collection extends UniqueId {
indexingPolicy?: IndexingPolicy;
}
/** The Indexing Path
* <p> Indexing paths hints to optimize indexing. <br>
* Indexing paths allow tradeoff between indexing storage and query performance
* </p>
*/
interface IndexingPath {
/** The indexing type(range or hash) {@link IndexType}.*/
IndexType: string;
/** Path to be indexed.*/
Path: string;
/** Precision for this particular Index type for numeric data. */
NumericPrecision: number;
/** Precision for this particular Index type for string data. */
StringPrecision: number;
}
/** The Indexing Policy represents the indexing policy configuration for a collection. */
interface IndexingPolicy {
/** Specifies whether automatic indexing is enabled for a collection.
<p>In automatic indexing, documents can be explicitly excluded from indexing using {@link RequestOptions}.
In manual indexing, documents can be explicitly included. </p> */
automatic: boolean;
/** The indexing mode (consistent or lazy) {@link IndexingMode}. */
indexingMode: string;
/** An array of {@link IndexingPath} represents The paths to be incuded for indexing. */
IncludedPath: IndexingPath[];
/** An array of strings representing the paths to be excluded from indexing. */
ExcludedPaths: string[];
}
/** Provides a client-side logical representation of the Azure DocumentDB database account. This client is used to configure and execute requests against the service.
*/
export class DocumentClient {
/**
* Constructs a DocumentClient.
* @param urlConnection - The service endpoint to use to create the client.
* @param auth - An object that is used for authenticating requests and must contains one of the options.
* @param [connectionPolicy] - An instance of {@link ConnectionPolicy} class. This parameter is optional and the default connectionPolicy will be used if omitted.
* @param [consistencyLevel] - An optional parameter that represents the consistency level. It can take any value from {@link ConsistencyLevel}.
*/
constructor(urlConnection: string, auth: AuthOptions, connectionPolicy?: any, consistencyLevel?: string);
/** Send a request for creating a database.
* <p>
* A database manages users, permissions and a set of collections. <br>
* Each Azure DocumentDB Database Account is able to support multiple independent named databases, with the database being the logical container for data. <br>
* Each Database consists of one or more collections, each of which in turn contain one or more documents. Since databases are an an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs. <br>
* </p>
* @param body - A json object that represents The database to be created.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public createDatabase(body: UniqueId, options: RequestOptions, callback: RequestCallback<DatabaseMeta>): void;
/**
* Creates a collection.
* <p>
* A collection is a named logical container for documents. <br>
* A database may contain zero or more named collections and each collection consists of zero or more JSON documents. <br>
* Being schema-free, the documents in a collection do not need to share the same structure or fields. <br>
* Since collections are application resources, they can be authorized using either the master key or resource keys. <br>
* </p>
* @param databaseLink - The self-link of the database.
* @param body - Represents the body of the collection.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public createCollection(databaseLink: string, body: Collection, options: RequestOptions, callback: RequestCallback<CollectionMeta>): void;
/**
* Create a StoredProcedure.
* <p>
* DocumentDB allows stored procedures to be executed in the storage tier, directly against a document collection. The script <br>
* gets executed under ACID transactions on the primary storage partition of the specified collection. For additional details, <br>
* refer to the server-side JavaScript API documentation.
* </p>
* @param collectionLink - The self-link of the collection.
* @param procedure - Represents the body of the stored procedure.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public createStoredProcedure(collectionLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback<ProcedureMeta>): void;
/**
* Create a document.
* <p>
* There is no set schema for JSON documents. They may contain any number of custom properties as well as an optional list of attachments. <br>
* A Document is an application resource and can be authorized using the master key or resource keys
* </p>
* @param collectionLink - The self-link of the collection.
* @param document - Represents the body of the document. Can contain any number of user defined properties.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public createDocument<TDocument>(collectionSelfLink: string, document: NewDocument<TDocument>, options: RequestOptions, callback: RequestCallback<RetrievedDocument<TDocument>>): void;
/**
* Execute the StoredProcedure represented by the object.
* @param procedureLink - The self-link of the stored procedure.
* @param [params] - Represents the parameters of the stored procedure.
* @param callback - The callback for the request.
*/
public executeStoredProcedure<TDocument>(procedureLink: string, params: any[], callback: RequestCallback<TDocument>): void;
/** Lists all databases that satisfy a query.
* @param query - A SQL query string.
* @param [options] - The feed options.
* @returns - An instance of QueryIterator to handle reading feed.
*/
public queryDatabases(query: string): QueryIterator<DatabaseMeta>;
/**
* Query the collections for the database.
* @param databaseLink - The self-link of the database.
* @param query - A SQL query string.
* @param [options] - Represents the feed options.
* @returns - An instance of queryIterator to handle reading feed.
*/
public queryCollections(databaseLink: string, query: string): QueryIterator<CollectionMeta>;
/**
* Query the storedProcedures for the collection.
* @param collectionLink - The self-link of the collection.
* @param query - A SQL query string.
* @param [options] - Represents the feed options.
* @returns - An instance of queryIterator to handle reading feed.
*/
public queryStoredProcedures(collectionLink: string, query: string): QueryIterator<ProcedureMeta>;
/**
* Query the documents for the collection.
* @param collectionLink - The self-link of the collection.
* @param query - A SQL query string.
* @param [options] - Represents the feed options.
* @returns - An instance of queryIterator to handle reading feed.
*/
public queryDocuments<TDocument>(collectionLink: string, query: string, options?: FeedOptions): QueryIterator<RetrievedDocument<TDocument>>;
/**
* Delete the document object.
* @param documentLink - The self-link of the document.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public deleteDocument(documentLink: string, options: RequestOptions, callback: RequestCallback<void>): void;
/**
* Delete the database object.
* @param databaseLink - The self-link of the database.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public deleteDatabase(databaseLink: string, options: RequestOptions, callback: RequestCallback<void>): void;
/**
* Delete the collection object.
* @param collectionLink - The self-link of the collection.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public deleteCollection(collectionLink: string, options: RequestOptions, callback: RequestCallback<void>): void;
/**
* Delete the StoredProcedure object.
* @param procedureLink - The self-link of the stored procedure.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public deleteStoredProcedure(procedureLink: string, options: RequestOptions, callback: RequestCallback<void>): void;
/**
* Replace the StoredProcedure object.
* @param procedureLink - The self-link of the stored procedure.
* @param procedure - Represent the new procedure body.
* @param [options] - The request options.
* @param callback - The callback for the request.
*/
public replaceStoredProcedure(procedureLink: string, procedure: Procedure, options: RequestOptions, callback: RequestCallback<ProcedureMeta>): void;
}
}
+17 -10
View File
@@ -1,22 +1,29 @@
/// <reference path="java-applet.d.ts" />
/**
* @summary Test for the applet status.
* @summary Test for the typage.
*/
function testTypage() {
var applet: HTMLAppletElement = <HTMLAppletElement>document.getElementById('applet');
var javaApplet: JavaApplet = applet;
}
/**
* @summary Test for the java applet status.
*/
function testStatus() {
var java: Java = {
status: AppletStatus.Loading
};
var applet: JavaApplet = <JavaApplet>document.getElementById('applet');
var status: number = applet.status;
}
/**
* @summary Test for the handlers.
*/
function testHandlers() {
var applet: JavaApplet = <JavaApplet>document.getElementById('applet');
var handler: Function = () => {};
var java: Java = {
onError: handler,
onLoad: handler,
onStop: handler
};
}
applet.onError = handler;
applet.onLoad = handler;
applet.onStop = handler;
}
+15 -10
View File
@@ -4,10 +4,11 @@
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Applet Status.
* {@link http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/applet_dev_guide.html#JSDPG719|Applet Status And Event Handlers}
* @summary Java applet Status. More details: {@link http://docs.oracle.com/javase/8/docs/technotes/guides/deploy/applet_dev_guide.html#JSDPG719|Applet Status And Event Handlers}
* @enum {number}
* @readonly
*/
declare enum AppletStatus {
declare enum JavaAppletStatus {
/**
* @summary Applet is loading.
*/
@@ -25,28 +26,32 @@ declare enum AppletStatus {
}
/**
* @summary Interface for Java object.
* @summary Interface for Java applet object.
* @author Cyril Schumacher
* @version 1.0
*/
interface Java {
interface JavaApplet extends HTMLAppletElement {
/**
* Handler if the applet status is ERROR. An error has occurred while loading the applet.
* @summary Handler if the applet status is {@link JavaAppletStatus#Error}. An error has occurred while loading the applet.
* @type {Function}
*/
onError?: Function;
/**
* Handler if the applet status is READY. Applet has finished loading and is ready to receive JavaScript calls.
* @summary Handler if the applet status is {@link JavaAppletStatus#Ready}. Applet has finished loading and is ready to receive JavaScript calls.
* @type {Function}
*/
onLoad?: Function;
/**
* Handler if the applet has stopped.
* @summary Handler if the applet has stopped.
* @type {Function}
*/
onStop?: Function;
/**
* @summary Applet Status.
* @summary Java applet Status.
* @type {JavaAppletStatus}
*/
status?: AppletStatus;
status?: JavaAppletStatus;
}
+16
View File
@@ -0,0 +1,16 @@
/// <reference path="jbinary.d.ts" />
var originalData = [0x05, 0x03, 0x7F, 0x1E];
var b1 = new jBinary(originalData);
console.log(b1.readAll());
console.log(b1.read('int8'));
b1.seek(4);
console.log(b1.read('int8'));
console.log(b1.tell());
b1.write('int8', 0x9A, 2);
b1.writeAll(originalData);
console.log(b1.slice(0, 2));
+32
View File
@@ -0,0 +1,32 @@
// Type definitions for jBinary
// Project: https://github.com/jDataView/jBinary
// Definitions by: Tim Bureck <https://github.com/tbureck>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Additional notes:
// Method stubs and types are taken from the official jBinary documentation, which can be found here:
// https://github.com/jDataView/jBinary/wiki/jBinary-Constructor
// https://github.com/jDataView/jBinary/wiki/jBinary-Methods
/// <reference path="../jdataview/jdataview.d.ts" />
declare class jBinary
{
constructor(data:Array<number>);
constructor(data:jDataView, typeSet:Object);
constructor(bufferSize:number, typeSet:Object);
read(type:string, offset?:number):any;
readAll():any;
write(type:string, data:any, offset?:number):number;
writeAll(data:any):number;
tell():number;
seek(position:number, callback?: (prop:jBinary, data:any) => any):number;
skip(count:number, callback?: (prop:jBinary, data:any) => any):number;
slice(start:number, end:number, forceCopy?:boolean):jBinary;
as(typeSet:Object, modifyOriginal?:boolean):jBinary;
}
+1 -1
View File
@@ -616,7 +616,7 @@ interface KnockoutComponentTemplate {
}
interface KnockoutComponentInfo {
element: any;
element: Node;
}
/* end register overloads */
interface KnockoutComponentDefinition {
+631
View File
@@ -0,0 +1,631 @@
/// <reference path="./later.d.ts"/>
module LaterTest_DefineSchedule {
// define a new schedule
var textSched = later.parse.text('at 10:15am every weekday');
var cronSched = later.parse.cron('0 0/5 14,18 * * ?');
var recurSched = later.parse.recur().last().dayOfMonth();
var manualSched = <Later.IScheduleData>{ schedules: [ <Later.IRecurrence>{ M: [ 3 ], D: [ 21 ] } ] };
// this schedule will fire on the closest weekday to the 15th
// every month at 2:00 am except in March
var complexSched = later.parse.recur()
.on(15).dayOfMonth().onWeekday().on(2).hour()
.and()
.on(14).dayOfMonth().on(6).dayOfWeek().on(2).hour()
.and()
.on(16).dayOfMonth().on(2).dayOfWeek().on(2).hour()
.except()
.on(3).month();
}
module LaterTest_ConfigureTimezone {
// set later to use UTC (the default)
later.date.UTC();
// set later to use local time
later.date.localTime();
}
module LaterTest_TimePeriods {
export function second() {
var d = new Date('2013-03-22T10:02:05Z');
later.second.name;
// 'second'
later.second.range;
// 1
later.second.val(d);
// 5
later.second.isValid(d, 10);
// false
later.second.extent();
// [0, 59]
later.second.start(d);
// 'Fri, 22 Mar 2013 10:02:05 GMT'
later.second.end(d);
// 'Fri, 22 Mar 2013 10:02:05 GMT'
later.second.next(d, 27);
// 'Fri, 22 Mar 2013 10:02:27 GMT'
later.second.prev(d, 27);
// 'Fri, 22 Mar 2013 10:01:27 GMT'
}
export function minute() {
var d = new Date('2013-03-22T10:02:05Z');
later.minute.name;
// 'minute'
later.minute.range;
// 60
later.minute.val(d);
// 2
later.minute.isValid(d, 2);
// true
later.minute.extent();
// [0, 59]
later.minute.start(d);
// 'Fri, 22 Mar 2013 10:02:00 GMT'
later.minute.end(d);
// 'Fri, 22 Mar 2013 10:02:59 GMT'
later.minute.next(d, 27);
// 'Fri, 22 Mar 2013 10:27:00 GMT'
later.minute.prev(d, 27);
// 'Fri, 22 Mar 2013 09:27:59 GMT'
}
export function hour() {
var d = new Date('2013-03-22T10:02:05Z');
later.hour.name;
// 'hour'
later.hour.range;
// 3600
later.hour.val(d);
// 10
later.hour.isValid(d, 2);
// false
later.hour.extent();
// [0, 23]
later.hour.start(d);
// 'Fri, 22 Mar 2013 10:00:00 GMT'
later.hour.end(d);
// 'Fri, 22 Mar 2013 10:59:59 GMT'
later.hour.next(d, 5);
// 'Sat, 23 Mar 2013 05:00:00 GMT'
later.hour.prev(d, 21);
// 'Thu, 21 Mar 2013 21:59:59 GMT'
}
export function time() {
var d = new Date('2013-03-22T10:02:05Z');
later.time.name;
// 'time'
later.time.range;
// 1
later.time.val(d);
// 36125
later.time.isValid(d, 36125);
// true
later.time.extent();
// [0, 86399]
later.time.start(d);
// 'Fri, 22 Mar 2013 00:00:00 GMT'
later.time.end(d);
// 'Fri, 22 Mar 2013 23:59:59 GMT'
later.time.next(d, 60);
// 'Sat, 23 Mar 2013 00:01:00 GMT'
later.time.prev(d, 60);
// 'Fri, 22 Mar 2013 00:01:00 GMT'
}
export function day() {
var d = new Date('2013-03-22T10:02:05Z');
later.day.name;
// 'day'
later.day.range;
// 86400
later.day.val(d);
// 22
later.day.isValid(d, 3);
// false
later.day.extent(d);
// [1, 31]
later.day.start(d);
// 'Fri, 22 Mar 2013 00:00:00 GMT'
later.day.end(d);
// 'Fri, 22 Mar 2013 23:59:59 GMT'
later.day.next(d, 11);
// 'Thu, 11 Apr 2013 00:00:00 GMT'
later.day.prev(d, 2);
// 'Sat, 02 Mar 2013 23:59:59 GMT'
}
export function day_of_week() {
var d = new Date('2013-03-22T10:02:05Z');
later.dayOfWeek.name;
// 'day of week'
later.dayOfWeek.range;
// 86400
later.dayOfWeek.val(d);
// 6
later.dayOfWeek.isValid(d, 3);
// false
later.dayOfWeek.extent();
// [1, 7]
later.dayOfWeek.start(d);
// 'Fri, 22 Mar 2013 00:00:00 GMT'
later.dayOfWeek.end(d);
// 'Fri, 22 Mar 2013 23:59:59 GMT'
later.dayOfWeek.next(d, 1);
// 'Sun, 24 Mar 2013 00:00:00 GMT'
later.dayOfWeek.prev(d, 5);
// 'Thu, 21 Mar 2013 23:59:59 GMT'
}
export function day_of_week_count() {
var d = new Date('2013-03-22T10:02:05Z');
later.dayOfWeekCount.name;
// 'day of week count'
later.dayOfWeekCount.range;
// 604800
later.dayOfWeekCount.val(d);
// 4
later.dayOfWeekCount.isValid(d, 4);
// true
later.dayOfWeekCount.extent(d);
// [1, 5]
later.dayOfWeekCount.start(d);
// 'Fri, 22 Mar 2013 00:00:00 GMT'
later.dayOfWeekCount.end(d);
// 'Thu, 28 Mar 2013 23:59:59 GMT'
// zero is special cased and means the last instance of
// a day of the week in the month, instead of meaning the
// first day of the week with the highest instance count
// which would have been Mar 29 with value 5.
later.dayOfWeekCount.next(d, 0);
// 'Mon, 25 Mar 2013 00:00:00 GMT'
later.dayOfWeekCount.prev(d, 2);
// 'Thu, 14 Mar 2013 23:59:59 GMT'
}
export function day_of_year() {
var d = new Date('2013-03-22T10:02:05Z');
later.dayOfYear.name;
// 'day of year'
later.dayOfYear.range;
// 86400
later.dayOfYear.val(d);
// 81
later.dayOfYear.isValid(d, 4);
// false
later.dayOfYear.extent(d);
// [1, 365]
later.dayOfYear.start(d);
// 'Fri, 22 Mar 2013 00:00:00 GMT'
later.dayOfYear.end(d);
// 'Fri, 22 Mar 2013 23:59:59 GMT'
later.dayOfYear.next(d, 256);
// 'Fri, 13 Sep 2013 00:00:00 GMT'
later.dayOfYear.prev(d, 44);
// 'Wed, 13 Feb 2013 23:59:59 GMT'
}
export function week_of_month() {
var d = new Date('2013-03-22T10:02:05Z');
later.weekOfMonth.name;
// 'week of month'
later.weekOfMonth.range;
// 604800
later.weekOfMonth.val(d);
// 4
later.weekOfMonth.isValid(d, 4);
// true
later.weekOfMonth.extent(d);
// [1, 6]
later.weekOfMonth.start(d);
// 'Sun, 17 Mar 2013 00:00:00 GMT'
later.weekOfMonth.end(d);
// 'Sat, 23 Mar 2013 23:59:59 GMT'
later.weekOfMonth.next(d, 1);
// 'Mon, 01 Apr 2013 00:00:00 GMT'
later.weekOfMonth.prev(d, 2);
// 'Sat, 09 Mar 2013 23:59:59 GMT'
}
export function week_of_year() {
var d = new Date('2013-03-22T10:02:05Z');
later.weekOfYear.name;
// 'week of year'
later.weekOfYear.range;
// 604800
later.weekOfYear.val(d);
// 12
later.weekOfYear.isValid(d, 21);
// false
later.weekOfYear.extent(d);
// [1, 52]
later.weekOfYear.start(d);
// 'Mon, 18 Mar 2013 00:00:00 GMT'
later.weekOfYear.end(d);
// 'Sun, 24 Mar 2013 23:59:59 GMT'
later.weekOfYear.next(d, 47);
// 'Mon, 18 Nov 2013 00:00:00 GMT'
later.weekOfYear.prev(d, 52);
// 'Sun, 30 Dec 2012 23:59:59 GMT'
}
export function month() {
var d = new Date('2013-03-22T10:02:05Z');
later.month.name;
// 'month'
later.month.range;
// 2629740
later.month.val(d);
// 3
later.month.isValid(d, 3);
// true
later.month.extent();
// [1, 12]
later.month.start(d);
// 'Fri, 01 Mar 2013 00:00:00 GMT'
later.month.end(d);
// 'Sun, 31 Mar 2013 23:59:59 GMT'
later.month.next(d, 11);
// 'Fri, 01 Nov 2013 00:00:00 GMT'
later.month.prev(d, 2);
// 'Thu, 28 Feb 2013 23:59:59 GMT'
}
export function year() {
var d = new Date('2013-03-22T10:02:05Z');
later.year.name;
// 'year'
later.year.range;
// 31556900
later.year.val(d);
// 2013
later.year.isValid(d, 2013);
// true
later.year.extent();
// [1970, 2099]
later.year.start(d);
// 'Tue, 01 Jan 2013 00:00:00 GMT'
later.year.end(d);
// 'Tue, 31 Dec 2013 23:59:59 GMT'
later.year.next(d, 2014);
// 'Wed, 01 Jan 2014 00:00:00 GMT'
later.year.prev(d, 2012);
// 'Mon, 31 Dec 2012 23:59:59 GMT'
}
export interface IPartOfDayLater extends Later.IStatic {
partOfDay: Later.ITimePeriod;
}
export function custom() {
var customLater = <IPartOfDayLater>later;
customLater.partOfDay = {
name: 'part of day',
range: later.hour.range * 6,
val: function(d: Date): number {
return later.hour.val(d) < 12
? 0
: later.hour.val(d) < 18
? 1
: 2;
},
isValid: function(d: Date, val: any) {
return customLater.partOfDay.val(d) === val;
},
extent: function(date?: Date) {
return [0, 2];
},
start: function(date: Date) {
var hour = customLater.partOfDay.val(date) === 0
? 0
: customLater.partOfDay.val(date) === 1
? 12
: 18;
return later.date.next(
later.year.val(date),
later.month.val(date),
later.day.val(date),
hour
);
},
end: function(date: Date) {
var hour = customLater.partOfDay.val(date) === 0
? 11
: customLater.partOfDay.val(date) === 1
? 5
: 23;
return later.date.prev(
later.year.val(date),
later.month.val(date),
later.day.val(date),
hour
);
},
next: function(date: Date, val: any) {
var hour = val === 0
? 0
: val === 1
? 12
: 18;
return later.date.next(
later.year.val(date),
later.month.val(date),
// increment the day if we already passed the desired time period
later.day.val(date) + (hour < later.hour.val(date) ? 1 : 0),
hour
);
},
prev: function(date: Date, val: any) {
var hour = val === 0
? 11
: val === 1
? 5
: 23;
return later.date.prev(
later.year.val(date),
later.month.val(date),
// decrement the day if we already passed the desired time period
later.day.val(date) + (hour > later.hour.val(date) ? -1 : 0),
hour
);
}
};
}
}
module LaterTest_GenerateRecurences {
export function on_method() {
// fires on the 2nd minute every hour
later.parse.recur().on(2).minute();
// fires every day at 8am and 8pm
later.parse.recur().on(8, 20).hour();
// fires every day at 8am
later.parse.recur().on('08:00:00').time();
}
export function first_method() {
// fires on the 0th minute of every hour
later.parse.recur().first().minute();
}
export function last_method() {
// fires on the last day of every month at 5am
later.parse.recur().on(5).hour().last().dayOfMonth();
}
export function onWeekend_method() {
// fires on the 5th minute of every hour during Sat and Sun
later.parse.recur().on(5).minute().onWeekend();
}
export function onWeekday_method() {
// fires on the 5th minute of every hour during Mon,Tues,Wed,Thur,Fri
later.parse.recur().on(5).minute().onWeekday();
}
export function every_method() {
// fires on the 0th, 10th, 20th, 30th, 40th, and 50th min of every hour
later.parse.recur().every(10).minute();
// fires on first second of Jan, Apr, July, Oct
later.parse.recur().every(3).month();
}
export function after_method() {
// fires on the 55th, 56th, 57th, 58th, and 59th minute
later.parse.recur().after(55).minute();
// fires at 12 noon and 6pm
later.parse.recur().every(6).hour().after('09:00').time();
}
export function before_method() {
// fires on the first second of January and February
later.parse.recur().before(3).month();
// fires at 6am every day
later.parse.recur().every(6).hour().before('09:00').time();
// fires between 9am and 6pm every day
later.parse.recur().after('09:00').time().before('18:00').time();
later.parse.recur().after(9).hour().before(18).hour();
}
export function startingOn_method() {
// fires on the 10th, 25th, 40th, and 55th minute of every hour
later.parse.recur().every(15).minute().startingOn(10);
}
export function between_method() {
// fires on the 10th, 25th, 40th minute of every hour
later.parse.recur().every(15).minute().between(10, 40);
}
export function and_method() {
// fires every 2 hours on the first day of every month
// and 8:00am and 8:00pm on the last day of every month
var sched = later.parse.recur()
.every(2).hour().first().dayOfMonth()
.and()
.on(8, 20).hour().last().dayOfMonth()
}
export function except_method() {
// fires every minute of every hour except on multiples of 2 and 3
var sched = later.parse.recur()
.every().minute()
.except()
.every(2).minute().between(2, 59)
.and()
.every(3).minute().between(3, 59);
}
}
module LaterTest_CalculateOccurences {
// Initialise next variable.
var next: Date[] = [];
// calculate the next 10 occurrences of a recur schedule
var recurSched = later.parse.recur().last().dayOfMonth();
next = later.schedule(recurSched).next(10);
// calculate the previous occurrence starting from March 21, 2013
var cronSched = later.parse.cron('0 0/5 14,18 * * ?');
next = later.schedule(cronSched).prev(1, new Date(2013, 2, 21));
}
module LaterTest_ExecuteCodeUsingSchedule {
// will fire every 5 minutes
var textSched = later.parse.text('every 5 min');
// execute logTime one time on the next occurrence of the text schedule
var timer = later.setTimeout(logTime, textSched);
// execute logTime for each successive occurrence of the text schedule
var timer2 = later.setInterval(logTime, textSched);
// function to execute
function logTime() {
console.log(new Date());
}
// clear the interval timer when you are done
timer2.clear();
}
+673
View File
@@ -0,0 +1,673 @@
// Type definitions for LaterJS
// Project: http://bunkat.github.io/later/
// Definitions by: Jason D Dryhurst-Smith <http://jasonds.co.uk/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module Later {
export interface IScheduleData {
/**
* A list of recurrence information as a composite schedule.
*/
schedules: IRecurrence[];
/**
* A list of exceptions to the composite recurrence information.
*/
exceptions: IRecurrence[];
/**
* A code to identify any errors in the composite schedule and exceptions.
* The number tells you the position of the error within the schedule.
*/
error: number;
}
export interface IRecurrence {
/** Time in seconds from midnight.
*/
t?: number[];
/** Seconds in minute.
*/
s?: number[];
/** Minutes in hour.
*/
m?: number[];
/** Hour in day.
*/
h?: number[];
/** Day of the month.
*/
D?: number[];
/** Day in week.
*/
dw?: number[];
/** Nth day of the week in month.
*/
dc?: number[];
/** Day in year.
*/
dy?: number[];
/** Week in month.
*/
wm?: number[];
/** ISO week in year.
*/
wy?: number[];
/** Month in year.
*/
M?: number[];
/** Year.
*/
Y?: number[];
/** After modifiers.
*/
t_a?: number[];
/** After modifiers.
*/
s_a?: number[];
/** After modifiers.
*/
m_a?: number[];
/** After modifiers.
*/
h_a?: number[];
/** After modifiers.
*/
D_a?: number[];
/** After modifiers.
*/
dw_a?: number[];
/** After modifiers.
*/
dc_a?: number[];
/** After modifiers.
*/
dy_a?: number[];
/** After modifiers.
*/
wm_a?: number[];
/** After modifiers.
*/
wy_a?: number[];
/** After modifiers.
*/
M_a?: number[];
/** After modifiers.
*/
Y_a?: number[];
/** Before modifiers.
*/
t_b?: number[];
/** Before modifiers.
*/
s_b?: number[];
/** Before modifiers.
*/
m_b?: number[];
/** Before modifiers.
*/
h_b?: number[];
/** Before modifiers.
*/
D_b?: number[];
/** Before modifiers.
*/
dw_b?: number[];
/** Before modifiers.
*/
dc_b?: number[];
/** Before modifiers.
*/
dy_b?: number[];
/** Before modifiers.
*/
wm_b?: number[];
/** Before modifiers.
*/
wy_b?: number[];
/** Before modifiers.
*/
M_b?: number[];
/** Before modifiers.
*/
Y_b?: number[];
/*
* Custom Time Periods and Modifiers
* For acces to custom time periods created as extension to the later static type
* and modifiers created on the later modifier static type.
*/
[ timeperiodAndModifierName: string ]: number[];
}
export interface IParseStatic {
/**
* Create a recurrence builder for building schedule data.
*/
recur(): IRecurrenceBuilder;
/**
* Create schedule data by parsing a cron string
*
* @param {string} [input] - A string value to parse.
*/
cron(input?: string): IScheduleData;
/**
* Create schedule data by paring a human readable string.
*
* @param {string} [input] - A string value to parse.
*/
text(input?: string): IScheduleData;
}
export interface ITimer {
/**
* Clear the timer and end execution.
*/
clear(): void;
}
export interface ISchedule {
/**
* Finds the next valid instance or instances of the current schedule,
* optionally between a specified start and end date. Start date is
* Date.now() by default, end date is unspecified. Start date must be
* smaller than end date.
*
* @param {number} numberOfInst: The number of instances to return
* @param {Date} dateFrom: The earliest a valid instance can occur
* @param {Date} dateTo: The latest a valid instance can occur
*/
next(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[];
/**
* Finds the next valid range or ranges of the current schedule,
* optionally between a specified start and end date. Start date is
* Date.now() by default, end date is unspecified. Start date must be
* greater than end date.
*
* @param {number} numberOfInst: The number of ranges to return
* @param {Date} dateFrom: The earliest a valid range can occur
* @param {Date} dateTo: The latest a valid range can occur
*/
nextRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[];
/**
* Finds the previous valid instance or instances of the current schedule,
* optionally between a specified start and end date. Start date is
* Date.now() by default, end date is unspecified. Start date must be
* greater than end date.
*
* @param {number} numberOfInst: The number of instances to return
* @param {Date} dateFrom: The earliest a valid instance can occur
* @param {Date} dateTo: The latest a valid instance can occur
*/
prev(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[];
/**
* Finds the previous valid range or ranges of the current schedule,
* optionally between a specified start and end date. Start date is
* Date.now() by default, end date is unspecified. Start date must be
* greater than end date.
*
* @param {number} numberOfInst: The number of ranges to return
* @param {Date} dateFrom: The earliest a valid range can occur
* @param {Date} dateTo: The latest a valid range can occur
*/
prevRange(numberOfInst: number, dateFrom?: Date, dateTo?: Date): Date[];
}
export interface IRecurrenceBuilder extends IScheduleData {
/** a time period
*/
second(): IRecurrenceBuilder;
/** a time period
*/
minute(): IRecurrenceBuilder;
/** a time period
*/
hour(): IRecurrenceBuilder;
/** a time period
*/
time(): IRecurrenceBuilder;
/** a time period
*/
dayOfWeek(): IRecurrenceBuilder;
/** a time period
*/
dayOfWeekCount(): IRecurrenceBuilder;
/** a time period
*/
dayOfMonth(): IRecurrenceBuilder;
/** a time period
*/
dayOfYear(): IRecurrenceBuilder;
/** a time period
*/
weekOfMonth(): IRecurrenceBuilder;
/** a time period
*/
weekOfYear(): IRecurrenceBuilder;
/** a time period
*/
month(): IRecurrenceBuilder;
/** a time period
*/
year(): IRecurrenceBuilder;
/** a time period
*/
fullDate(): IRecurrenceBuilder;
/**
* Specifies one or more specific vals of a time period information provider.
* When used to specify a time, a string indicating the 24-hour time may be used.
*
* @param {number[]} values - A list of values.
*/
on(...values: number[]): IRecurrenceBuilder;
/**
* Specifies one or more specific vals of a time period information provider.
* When used to specify a time, a string indicating the 24-hour time may be used.
*
* @param {string} value - A string representing your value.
*/
on(value: string): IRecurrenceBuilder;
/**
* Specifies one or more specific vals of a time period information provider.
* When used to specify a time, a string indicating the 24-hour time may be used.
*
* @param {Date} date - A Date representing your value.
*/
on(date: Date): IRecurrenceBuilder;
/**
* Preceed a time period.
*
* @param {number} [value] - A number representing your value.
*/
every(value?: number): IRecurrenceBuilder;
/**
* Preceed a time period.
*
* @param {string} [value] - A string representing your value.
*/
every(value?: string): IRecurrenceBuilder;
/**
* Preceed a time period.
*
* @param {number} start - A number representing your start value.
* @param {number} end - A number representing your end value.
*/
between(start: number, end: number): IRecurrenceBuilder;
/**
* Preceed a time period.
*
* @param {string} start - A string representing your start value.
* @param {string} end - A string representing your end value.
*/
between(start: string, end: string): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {number} value - A number representing your value.
*/
after(value: number): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {string} value - A string representing your value.
*/
after(value: string): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {number} value - A number representing your value.
*/
before(value: number): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {string} value - A string representing your value.
*/
before(value: string): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {number} value - A number representing your value.
*/
startingOn(value: number): IRecurrenceBuilder;
/**
* After a time period.
*
* @param {string} value - A string representing your value.
*/
startingOn(value: string): IRecurrenceBuilder;
/**
* Equivalent to .on(min)
*/
first(): IRecurrenceBuilder;
/**
* Equivalent to .on(max)
*/
last(): IRecurrenceBuilder;
/**
* Equivalent to .on(1,7).dayOfWeek()
*/
onWeekend(): IRecurrenceBuilder;
/**
* Equivalent to .on(2,3,4,5,6).dayOfWeek()
*/
onWeekday(): IRecurrenceBuilder;
/**
* Add a new schedule value to schedules, composite schedule.
*/
and(): IRecurrenceBuilder;
/**
* Add exceptions.
*/
except(): IRecurrenceBuilder;
/**
* Custom Timeperiod Recurrences.
* Using a key as defined by the custom period in any extension to Later.IStatic.
*/
customPeriod(key: string): IRecurrenceBuilder;
/**
* Customise Recurrences.
* Using a key as defined by the custom modifier in any extension to Later.IModifierStatic.
*/
customModifier(key: string, values: number): IRecurrenceBuilder;
}
export interface IDateProvider {
/**
* Set later to use UTC time.
*/
UTC(): void;
/**
* Set later to use local time.
*/
localTime(): void;
/**
* Builds and returns a new Date using the specified values. Date
* returned is either using Local time or UTC based on isLocal.
*
* @param {number} [Y]: Four digit year
* @param {number} [M]: Month between 1 and 12, defaults to 1
* @param {number} [D]: Date between 1 and 31, defaults to 1
* @param {number} [h]: Hour between 0 and 23, defaults to 0
* @param {number} [m]: Minute between 0 and 59, defaults to 0
* @param {number} [s]: Second between 0 and 59, defaults to 0
*/
next(Y?: number, M?: number, D?: number, h?: number, m?: number, s?: number): Date;
/**
* Builds and returns a new Date using the specified values. Date
* returned is either using Local time or UTC based on isLocal.
*
* @param {number} [Y]: Four digit year
* @param {number} [M]: Month between 0 and 11, defaults to 11
* @param {number} [D]: Date between 1 and 31, defaults to last day of month
* @param {number} [h]: Hour between 0 and 23, defaults to 23
* @param {number} [m]: Minute between 0 and 59, defaults to 59
* @param {number} [s]: Second between 0 and 59, defaults to 59
*/
prev(Y?: number, M?: number, D?: number, h?: number, m?: number, s?: number): Date;
/**
* Determines if a value will cause a particular constraint to rollover to the
* next largest time period. Used primarily when a constraint has a
* variable extent.
*
* @param {Date} d: Date
* @param {number} val: Value
* @param {IModifier} constraint: A modifier
* @param {ITimePeriod} period: A time period
*/
nextRollover(d: Date, val: number, constraint: IModifier, period: ITimePeriod): Date;
/**
* Determines if a value will cause a particular constraint to rollover to the
* previous largest time period. Used primarily when a constraint has a
* variable extent.
*
* @param {Date} d: Date
* @param {number} val: Value
* @param {IModifier} constraint: A modifier
* @param {ITimePeriod} period: A time period
*/
prevRollover(d: Date, val: number, constraint: IModifier, period: ITimePeriod): Date;
}
export interface ITimePeriod {
/**
* The name of the time period information provider.
*/
name: string;
/**
* The rough number of seconds that are covered when moving from one instance of this time period to the next instance.
*/
range: number;
/**
* The value of this time period for the date specified.
*
* @param {Date} date - The given date.
*/
val(date: Date): number;
/**
* True if the specified value is valid for the specified date, false otherwise.
*
* @param {Date} date - The given date.
* @param {any} value - The value to test for the date.
*/
isValid(date: Date, value: any): boolean;
/**
* The minimum and maximum valid values for the time period for the specified date.
* If the minimum value is not 0, 0 can be specified in schedules to indicate the maximum value.
* This makes working with non - constant extents(like days in a month) easier.
*
* @param {Date} [date] - The given date.
*/
extent(date?: Date): number[];
/**
* The first second in which the value is the same as the value of the specified date.
* For example, the start of an hour would be the hour with 0 minutes and 0 seconds.
*
* @param {Date} date - The given date.
*/
start(date: Date): Date;
/**
* The last second in which the value is the same as the value of the specified date.
* For example, the end of an hour would be the hour with 59 minutes and 59 seconds.
*
* @param {Date} date - The given date.
*/
end(date: Date): Date;
/**
* Returns the next date where the value is the value specified.
* Sets the value to 1 if value specified is greater than the max allowed value.
*
* @param {Date} date - The given date.
* @param {any} value - The value to test for the date.
*/
next(date: Date, value: any): Date;
/**
* Returns the previous date where the value is the value specified.
* Sets the value to the max allowed value if the value specified is greater than the max allowed value.
*
* @param {Date} date - The given date.
* @param {any} value - The value to test for the date.
*/
prev(date: Date, value: any): Date;
}
export interface IModifier extends ITimePeriod {
/**
* Creates a new modified constraint.
*
* @param {ITimePeriod} constraint: The constraint to be modified
* @param {number} value: The starting value of the after constraint
*/
(constraint: ITimePeriod, value: number): ITimePeriod;
}
export interface IModifierStatic {
/**
* After Modifier
*/
after: IModifier;
/**
* Before Modifier
*/
before: IModifier;
}
export interface IStatic {
/**
* Schedule
* Generates instances from schedule data.
*/
schedule(input: any): ISchedule;
/**
* Parse
* For generating schedule data.
*/
parse: IParseStatic;
/** Date Provider
*/
date: IDateProvider;
/**
* Set timeout on window using given recurrence next.
*
* @param {function} callback - A callback called after first instance of recurrence pattern.
* @param {Later.IReccurence} - A recurrence instance.
*/
setTimeout(callback: () => void, time: IScheduleData): ITimer;
/**
* Set interval on window using given recurrence
*
* @param {function} callback - A callback called after each instance of recurrence pattern.
* @param {Later.IReccurence} - A recurrence instance.
*/
setInterval(callback: () => void, time: IScheduleData): ITimer;
/**
* time period information provider.
*/
time: ITimePeriod;
/**
* Second time period information provider.
*/
second: ITimePeriod;
/**
* Minute time period information provider.
*/
minute: ITimePeriod;
/**
* Hour time period information provider.
*/
hour: ITimePeriod;
/**
* Day time period information provider.
*/
day: ITimePeriod;
/**
* Day of week time period information provider.
*/
dayOfWeek: ITimePeriod;
/**
* Day of week in month time period information provider.
*/
dayOfWeekCount: ITimePeriod;
/**
* Day in year time period information provider.
*/
dayOfYear: ITimePeriod;
/**
* Week of mobth time period information provider.
*/
weekOfMonth: ITimePeriod;
/**
* Week of yearfrom ISO 8601 time period information provider.
*/
weekOfYear: ITimePeriod;
/**
* Month time period information provider.
*/
month: ITimePeriod;
/**
* Year time period information provider.
*/
year: ITimePeriod;
/**
* Later Modifiers:
*
* This type can be easily extended to include any custom IModifiers that you desire.
* These can then be used to create schedules of your own custom type.
*
* interface IGandalfsLaterModifier extends Later.IModifierStatic {
* duringTheThirdAge: IModifier
* }
*
* Be sure to use this interface when dealing with Later.modifier
*/
modifier: IModifierStatic
}
}
/**
* Later Module:
*
* Easily define complex schedules then quickly calculate future or previous schedule occurrences.
*
* This type can be easily extended to include any custom ITimePeriods that you desire.
* These can then be used to create schedules of your own custom type.
*
* interface IGandalfsLater extends Later.IStatic {
* agesOfMiddleEarth: ITimePeriod
* }
*
* Be sure to use this interface when dealing with Later.
*/
declare var later: Later.IStatic;
+1 -1
View File
@@ -156,7 +156,7 @@ obj = fooSequence.toObject();
// ArrayLikeSequence
fooArraySeq = fooArraySeq.concat();
fooArraySeq = fooArraySeq.concat(fooArr);
fooArraySeq = fooArraySeq.first();
fooArraySeq = fooArraySeq.first(num);
foo = fooArraySeq.get(num);
+1 -1
View File
@@ -176,7 +176,7 @@ declare module LazyJS {
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(): ArrayLikeSequence<T>;
concat(var_args: T[]): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
+35
View File
@@ -1096,6 +1096,41 @@ result = <string>_.unescape('Moe, Larry &amp; Curly');
result = <string>_.uniqueId('contact_');
result = <string>_.uniqueId();
/*********
* String
*********/
result = <string>_.camelCase('Foo Bar');
result = <string>_.capitalize('fred');
result = <string>_.deburr('déjà vu');
result = <boolean>_.endsWith('abc', 'c');
result = <string>_.escape('fred, barney, & pebbles');
result = <string>_.escapeRegExp('[lodash](https://lodash.com/)');
result = <string>_.kebabCase('Foo Bar');
result = <string>_.pad('abc', 8);
result = <string>_.pad('abc', 8, '_-');
result = <string>_.padLeft('abc', 6);
result = <string>_.padLeft('abc', 6, '_-');
result = <string>_.padRight('abc', 6);
result = <string>_.padRight('abc', 6, '_-');
result = <string>_.repeat('*', 3);
result = <string>_.snakeCase('Foo Bar');
result = <string>_.startCase('--foo-bar');
result = <boolean>_.startsWith('abc', 'a');
result = <string>_.trim(' abc ');
result = <string>_.trim('-_-abc-_-', '_-');
result = <string>_.trimLeft(' abc ');
result = <string>_.trimLeft('-_-abc-_-', '_-');
result = <string>_.trimRight(' abc ');
result = <string>_.trimRight('-_-abc-_-', '_-');
result = <string>_.trunc('hi-diddly-ho there, neighborino');
result = <string>_.trunc('hi-diddly-ho there, neighborino', 24);
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': ' ' });
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'length': 24, 'separator': /,? +/ });
result = <string>_.trunc('hi-diddly-ho there, neighborino', { 'omission': ' […]' });
result = <string[]>_.words('fred, barney, & pebbles');
result = <string[]>_.words('fred, barney, & pebbles', /[^, ]+/g);
/**********
* Utilities *
***********/
+44 -16
View File
@@ -6133,6 +6133,50 @@ declare module _ {
values(object: any): any[];
}
/**********
* String *
**********/
interface LoDashStatic {
camelCase(str?: string): string;
capitalize(str?: string): string;
deburr(str?: string): string;
endsWith(str?: string, target?: string, position?: number): boolean;
escape(str?: string): string;
escapeRegExp(str?: string): string;
kebabCase(str?: string): string;
pad(str?: string, length?: number, chars?: string): string;
padLeft(str?: string, length?: number, chars?: string): string;
padRight(str?: string, length?: number, chars?: string): string;
repeat(str?: string, n?: number): string;
snakeCase(str?: string): string;
startCase(str?: string): string;
startsWith(str?: string, target?: string, position?: number): boolean;
trim(str?: string, chars?: string): string;
trimLeft(str?: string, chars?: string): string;
trimRight(str?: string, chars?: string): string;
trunc(str?: string, len?: number): string;
trunc(str?: string, options?: { length?: number; omission?: string; separator?: string }): string;
trunc(str?: string, options?: { length?: number; omission?: string; separator?: RegExp }): string;
words(str?: string, pattern?: string): string[];
words(str?: string, pattern?: RegExp): string[];
}
//_.parseInt
interface LoDashStatic {
/**
* Converts the given value into an integer of the specified radix. If radix is undefined or 0 a
* radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used.
*
* Note: This method avoids differences in native ES3 and ES5 parseInt implementations. See
* http://es5.github.io/#E.
* @param value The value to parse.
* @param radix The radix used to interpret the value to parse.
* @return The new integer value.
**/
parseInt(value: string, radix?: number): number;
}
/*************
* Utilities *
*************/
@@ -6174,22 +6218,6 @@ declare module _ {
noConflict(): typeof _;
}
//_.parseInt
interface LoDashStatic {
/**
* Converts the given value into an integer of the specified radix. If radix is undefined or 0 a
* radix of 10 is used unless the value is a hexadecimal, in which case a radix of 16 is used.
*
* Note: This method avoids differences in native ES3 and ES5 parseInt implementations. See
* http://es5.github.io/#E.
* @param value The value to parse.
* @param radix The radix used to interpret the value to parse.
* @return The new integer value.
**/
parseInt(value: string): number;
}
//_.property
interface LoDashStatic {
/**
+9
View File
@@ -0,0 +1,9 @@
/// <reference path="mkpath.d.ts" />
import mkpath = require('mkpath');
mkpath('red/green/violet', function (err) {
if (err) throw err;
console.log('Directory structure red/green/violet created');
});
mkpath.sync('/tmp/blue/orange', 700);
+15
View File
@@ -0,0 +1,15 @@
// Type definitions for mkpath v0.1.0
// Project: https://www.npmjs.com/package/mkpath
// Definitions by: Jared Klopper <https://github.com/optical>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'mkpath' {
module mkpath {
function sync(path: string, mode?: number): void;
}
function mkpath(path: string, callback?: (err: any) => void): void;
function mkpath(path: string, mode?: number, callback?: (err?: any) => void): void;
export = mkpath;
}
+47
View File
@@ -0,0 +1,47 @@
/// <reference path="./node-persist.d.ts" />
// node-persist tests
// compile with --module=common
import nodePersist = require("node-persist");
var opts = Node
nodePersist.init({
dir: __dirname + "/test",
continuous: false
});
nodePersist.setItem("someArray", [1,2,3], (err)=> {
nodePersist.getItem("someArray", (err: any, value: any)=> {
nodePersist.removeItem("someArray", (err) => err);
});
});
nodePersist.setItem("someString", "foo")
.then(() => nodePersist.getItem("someString"))
.then(() => nodePersist.removeItem("someString"))
.then(() => nodePersist.clear())
.then(() => null);
interface TestObject {
foo: string;
two: number;
}
nodePersist.clear((err) => {
var testObject: TestObject = {foo: "bar", two: 2};
nodePersist.setItemSync("someObject", testObject);
testObject = nodePersist.getItemSync("someObject");
nodePersist.removeItem("someObject");
nodePersist.clearSync();
});
var values: Array<any> = nodePersist.values();
var valuesWithKeyMatch: Array<any> = nodePersist.valuesWithKeyMatch("some");
var keys: Array<string> = nodePersist.keys();
var size: number = nodePersist.length();
nodePersist.forEach((val) => {});
try {
nodePersist.persist((err) => err);
nodePersist.persist().then(() => null);
nodePersist.persistSync;
nodePersist.persistKey("this", (err) => null);
nodePersist.persistKey("this").then(() => null);
nodePersist.persistKeySync("this");
} catch(anyError){}
+44
View File
@@ -0,0 +1,44 @@
// Type definitions for node-persist
// Project: https://github.com/simonlast/node-persist
// Definitions by: Spencer Williams <http://spencerwi.com/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../q/Q.d.ts" />
declare module "node-persist" {
type milliseconds = number;
module NodePersist {
export interface InitOptions {
dir?: string;
stringify?: (toSerialize: any)=>string;
parse?: (serialized: string)=>any;
encoding?: string;
logging?: boolean|Function;
continuous?: boolean;
interval?: milliseconds|boolean;
ttl?: milliseconds|boolean;
}
export function init(options?: InitOptions, callback?: Function): Q.Promise<any>;
export function initSync(options?: InitOptions): void;
export function getItem(key: string, callback?: (err: any, value: any)=>any): Q.Promise<any>;
export function getItemSync(key: string): any;
export function setItem(key: string, value: any, callback?: (err: any)=>any): Q.Promise<any>;
export function setItemSync(key: string, value: any): void;
export function removeItem(key: string, callback?: (err: any)=>any): Q.Promise<any>;
export function removeItemSync(key: string): void;
export function clear(callback?: (err: any)=>any): Q.Promise<any>;
export function clearSync(): void;
export function values(): Array<any>;
export function valuesWithKeyMatch(match: string): Array<any>;
export function keys(): Array<string>;
export function length(): number;
export function forEach(callback: (key: string, value: any)=>void): void;
export function persist(callback?: (err: any)=>any): Q.Promise<any>;
export function persistSync(): void;
export function persistKey(key: string, callback?: (err: any)=>any): Q.Promise<any>;
export function persistKeySync(key: string): void;
}
export = NodePersist;
}
+11
View File
@@ -10,6 +10,7 @@ import crypto = require("crypto");
import http = require("http");
import net = require("net");
import dgram = require("dgram");
import querystring = require('querystring');
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
@@ -122,4 +123,14 @@ var ai: dgram.AddressInfo = ds.address();
ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => {
});
////////////////////////////////////////////////////
///Querystring tests : https://gist.github.com/musubu/2202583
////////////////////////////////////////////////////
var original: string = 'http://example.com/product/abcde.html';
var escaped: string = querystring.escape(original);
console.log(escaped);
// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html
var unescaped: string = querystring.unescape(escaped);
console.log(unescaped);
// http://example.com/product/abcde.html
+2 -2
View File
@@ -250,8 +250,8 @@ declare module "buffer" {
declare module "querystring" {
export function stringify(obj: any, sep?: string, eq?: string): string;
export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
export function escape(): any;
export function unescape(): any;
export function escape(str: string): string;
export function unescape(str: string): string;
}
declare module "events" {
+2 -2
View File
@@ -203,8 +203,8 @@ interface Buffer {
declare module "querystring" {
export function stringify(obj: any, sep?: string, eq?: string): string;
export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
export function escape(): any;
export function unescape(): any;
export function escape(str: string): string;
export function unescape(str: string): string;
}
declare module "events" {
+11
View File
@@ -10,6 +10,7 @@ import crypto = require("crypto");
import http = require("http");
import net = require("net");
import dgram = require("dgram");
import querystring = require('querystring');
assert(1 + 1 - 2 === 0, "The universe isn't how it should.");
@@ -165,4 +166,14 @@ var ai: dgram.AddressInfo = ds.address();
ds.send(new Buffer("hello"), 0, 5, 5000, "127.0.0.1", (error: Error, bytes: number): void => {
});
////////////////////////////////////////////////////
///Querystring tests : https://gist.github.com/musubu/2202583
////////////////////////////////////////////////////
var original: string = 'http://example.com/product/abcde.html';
var escaped: string = querystring.escape(original);
console.log(escaped);
// http%3A%2F%2Fexample.com%2Fproduct%2Fabcde.html
var unescaped: string = querystring.unescape(escaped);
console.log(unescaped);
// http://example.com/product/abcde.html
+2 -2
View File
@@ -250,8 +250,8 @@ declare module "buffer" {
declare module "querystring" {
export function stringify(obj: any, sep?: string, eq?: string): string;
export function parse(str: string, sep?: string, eq?: string, options?: { maxKeys?: number; }): any;
export function escape(): any;
export function unescape(): any;
export function escape(str: string): string;
export function unescape(str: string): string;
}
declare module "events" {
+20
View File
@@ -0,0 +1,20 @@
/**
* Maintained by: jbondc <https://github.com/jbondc>
*/
/// <reference path="../node/node.d.ts" />
/// <reference path="nopt.d.ts" />
import nopt = require("nopt");
nopt({"--foo" : String})
nopt({ "--foo": String }, { "-f": "--foo"})
nopt({ "--foo": String }, { "-f": ["--foo", "-d"] })
nopt({ "--foo": String }, { "-f": ["--foo", "-d"] }, ["test me --foo arg"])
var cmd = nopt({ "--foo": String }, { "-f": ["--foo", "-d"] }, ["test me --foo arg"], 2)
console.log(cmd.argv.cooked)
console.log(cmd.argv.original)
console.log(cmd.argv.remain)
+46
View File
@@ -0,0 +1,46 @@
// Type definitions for nopt 3.0.1
// Project: https://github.com/npm/nopt
// Definitions by: jbondc <https://github.com/jbondc>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "nopt" {
interface CommandData {
[key: string]: string
}
interface TypeDefs {
[key: string]: TypeInfo
}
interface TypeInfo {
type: Object
validate: (data: CommandData, k: string, val: string) => boolean
}
module nopt {
export function clean(data: CommandData, types: FlagTypeMap, typeDefs?: TypeDefs): string
export var typeDefs: TypeDefs
}
interface FlagTypeMap {
[k: string]: Object
}
interface ShortFlags {
[k: string]: string[]|string
}
function nopt(types: FlagTypeMap, shorthands?: ShortFlags, args?: string[], slice?: number): OptionsParsed
interface OptionsParsed {
[k: string]: any
argv: {
remain: string[]
cooked: string[]
original: string[]
}
}
export = nopt
}
+1 -1
View File
@@ -28,9 +28,9 @@ interface RaphaelElement {
animateWith(el: RaphaelElement, anim: RaphaelAnimation, params: any, ms: number, easing?: string, callback?: Function): RaphaelElement;
animateWith(el: RaphaelElement, anim: RaphaelAnimation, animation: RaphaelAnimation): RaphaelElement;
attr(attrName: string, value: any): RaphaelElement;
attr(params: any): RaphaelElement;
attr(attrName: string): any;
attr(attrNames: string[]): any[];
attr(params: any): RaphaelElement;
click(handler: Function): RaphaelElement;
clone(): RaphaelElement;
data(key: string): any;
+326
View File
@@ -0,0 +1,326 @@
///<reference path="react-router.d.ts" />
"use strict";
import React = require('react');
import Router = require('react-router');
// Mixin
class NavigationTest<T extends Router.Navigation> {
v: T;
makePath() {
var v1: string = this.v.makePath('to');
var v2: string = this.v.makePath('to', {id: 1});
var v3: string = this.v.makePath('to', {id: 1}, {type: 'json'});
}
makeHref() {
var v1: string = this.v.makeHref('to');
var v2: string = this.v.makeHref('to', {id: 1});
var v3: string = this.v.makeHref('to', {id: 1}, {type: 'json'});
}
transitionTo() {
var v1: void = this.v.transitionTo('to');
var v2: void = this.v.transitionTo('to', {id: 1});
var v3: void = this.v.transitionTo('to', {id: 1}, {type: 'json'});
}
replaceWith() {
var v1: void = this.v.replaceWith('to');
var v2: void = this.v.replaceWith('to', {id: 1});
var v3: void = this.v.replaceWith('to', {id: 1}, {type: 'json'});
}
goBack() {
var v1: void = this.v.goBack();
}
}
class StateTest<T extends Router.State> {
v: T;
getPath() {
var v1: string = this.v.getPath();
}
getRoutes() {
var v1: Router.Route[] = this.v.getRoutes();
}
getPathname() {
var v1: string = this.v.getPathname();
}
getParams() {
var v1: {} = this.v.getParams();
}
getQuery() {
var v1: {} = this.v.getQuery();
}
isActive() {
var v1: boolean = this.v.isActive('to');
var v2: boolean = this.v.isActive('to', {id: 1});
var v3: boolean = this.v.isActive('to', {id: 1}, {type: 'json'});
}
}
class RouteHandlerMixinTest<T extends Router.RouteHandlerMixin> {
v: T;
getRouteDepth() {
var v1: number = this.v.getRouteDepth();
}
createChildRouteHandler() {
var v1: Router.RouteHandler = this.v.createChildRouteHandler({ref: 'hoge'});
}
}
// Location
class LocationTest<T extends Router.LocationBase> {
v: T;
push() {
var v1: void = this.v.push('path/to/hoge');
}
replace() {
var v1: void = this.v.replace('path/to/hoge');
}
pop() {
var v1: void = this.v.pop();
}
getCurrentPath() {
var v1: void = this.v.getCurrentPath();
}
}
new LocationTest<Router.HashLocation>();
new LocationTest<Router.HistoryLocation>();
new LocationTest<Router.RefreshLocation>();
class LocationListenerTest<T extends Router.LocationListener> {
v: T;
addChangeListener() {
var v1: void = this.v.addChangeListener(() => console.log(1));
}
removeChangeListener() {
var v1: void = this.v.removeChangeListener(() => console.log(1));
}
}
new LocationListenerTest<Router.HashLocation>();
new LocationListenerTest<Router.HistoryLocation>();
// Behavior
class ScrollBehaviorTest<T extends Router.ScrollBehaviorBase> {
v: T;
updateScrollPosition() {
var v1: void = this.v.updateScrollPosition({x: 33, y: 102}, 'scrollTop');
}
}
new ScrollBehaviorTest<Router.ImitateBrowserBehavior>();
new ScrollBehaviorTest<Router.ScrollToTopBehavior>();
// Component
class DefaultRouteTest {
v: Router.DefaultRoute;
props() {
var name: string = this.v.props.name;
var handler: React.ComponentClass<any> = this.v.props.handler;
}
createElement() {
var Handler: React.ComponentClass<any>;
React.createElement(Router.DefaultRoute, null);
React.createElement(Router.DefaultRoute, {name: 'name', handler: Handler});
}
}
class LinkTest {
v: Router.Link;
constructor() {
new NavigationTest<Router.Link>();
new StateTest<Router.Link>();
}
props() {
var activeClassName: string = this.v.props.activeClassName;
var to: string = this.v.props.to;
var params: {} = this.v.props.params;
var query: {} = this.v.props.query;
var onClick: Function = this.v.props.onClick;
}
getHref() {
var v1: string = this.v.getHref();
}
getClassName() {
var v1: string = this.v.getClassName();
}
createElement() {
React.createElement(Router.Link, null);
React.createElement(Router.Link, {to: 'home'});
React.createElement(Router.Link, {
activeClassName: 'name',
to: 'home',
params: {},
query: {},
onClick: () => console.log(1)
});
}
}
class NotFoundRouteTest {
v: Router.NotFoundRoute;
props() {
var name: string = this.v.props.name;
var handler: React.ComponentClass<any> = this.v.props.handler;
}
createElement() {
var Handler: React.ComponentClass<any>;
React.createElement(Router.NotFoundRoute, null);
React.createElement(Router.NotFoundRoute, {handler: Handler});
React.createElement(Router.NotFoundRoute, {handler: Handler, name: "home"});
}
}
class RedirectTest {
v: Router.Redirect;
props() {
var path: string = this.v.props.path;
var from: string = this.v.props.from;
var to: string = this.v.props.to;
}
createElement() {
React.createElement(Router.Redirect, null);
React.createElement(Router.Redirect, {});
React.createElement(Router.Redirect, {path: 'a', from: 'a', to: 'b'});
}
}
class RouteTest {
v: Router.Route;
props() {
var name: string = this.v.props.name;
var path: string = this.v.props.path;
var handler: React.ComponentClass<any> = this.v.props.handler;
var ignoreScrollBehavior: boolean = this.v.props.ignoreScrollBehavior;
}
createElement() {
var Handler: React.ComponentClass<any>;
React.createElement(Router.Route, null);
React.createElement(Router.Route, {});
React.createElement(Router.Route, {name: "home", path: "/", handler: Handler, ignoreScrollBehavior: true});
}
}
class RouteHandlerTest {
v: Router.RouteHandler;
constructor() {
new RouteHandlerMixinTest<Router.RouteHandler>();
}
createElement() {
React.createElement(Router.RouteHandler, null);
React.createElement(Router.RouteHandler, {});
}
}
// History
class HistoryTest {
v: Router.History;
length() {
var v1: number = this.v.length;
}
back() {
var v1: void = this.v.back();
}
}
// Router
class CreateTest {
v: Router.Router;
constructor() {
this.v = Router.create({
routes: React.createElement(Router.Route, null)
});
this.v = Router.create({
routes: React.createElement(Router.Route, null),
location: Router.HistoryLocation,
scrollBehavior: Router.ImitateBrowserBehavior
});
}
run() {
this.v.run((Handler) => console.log(Handler));
this.v.run((Handler, state) => console.log(Handler, state));
}
}
class RunTest {
constructor() {
var v1: Router.Router = Router.run(React.createElement(Router.Route, null), (Handler) => {
React.render(React.createElement(Handler, null), document.body);
});
var v2: Router.Router = Router.run(React.createElement(Router.Route, null), Router.HistoryLocation, (Handler, state) => {
React.render(React.createElement(Handler, null), document.body);
});
}
}
// Transition
class TransitionTest {
constructor() {
var v1: Router.TransitionStaticLifecycle = {
willTransitionTo: (transition, params, query, callback) => {
transition.abort();
transition.redirect('to');
transition.redirect('to', {id: 1});
transition.redirect('to', {id: 1}, {type: 'json'});
transition.retry();
},
willTransitionFrom: (transition, component, callback) => {}
};
var v2: Router.TransitionStaticLifecycle = {
willTransitionTo: (transition, params, query) => {},
willTransitionFrom: (transition, component) => {}
};
var v3: Router.TransitionStaticLifecycle = {
willTransitionTo: (transition, params) => {},
willTransitionFrom: (transition) => {}
};
var v4: Router.TransitionStaticLifecycle = {
willTransitionTo: (transition) => {},
willTransitionFrom: () => {}
};
var v5: Router.TransitionStaticLifecycle = {
willTransitionTo: () => {}
};
var v6: Router.TransitionStaticLifecycle = {
willTransitionFrom: () => {}
};
}
}
+278
View File
@@ -0,0 +1,278 @@
// Type definitions for React Router 0.12.0
// Project: https://github.com/rackt/react-router
// Definitions by: Yuichi Murata <https://github.com/mrk21>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path='../react/react.d.ts' />
declare module ReactRouter {
//
// Mixin
// ----------------------------------------------------------------------
interface Navigation {
makePath(to: string, params?: {}, query?: {}): string;
makeHref(to: string, params?: {}, query?: {}): string;
transitionTo(to: string, params?: {}, query?: {}): void;
replaceWith(to: string, params?: {}, query?: {}): void;
goBack(): void;
}
interface RouteHandlerMixin {
getRouteDepth(): number;
createChildRouteHandler(props: {}): RouteHandler;
}
interface State {
getPath(): string;
getRoutes(): Route[];
getPathname(): string;
getParams(): {};
getQuery(): {};
isActive(to: string, params?: {}, query?: {}): boolean;
}
var Navigation: Navigation;
var State: State;
var RouteHandlerMixin: RouteHandlerMixin;
//
// Component
// ----------------------------------------------------------------------
// DefaultRoute
interface DefaultRouteProp {
name?: string;
handler: React.ComponentClass<any>;
}
interface DefaultRoute extends React.ReactElement<DefaultRouteProp> {
__react_router_default_route__: any; // dummy
}
interface DefaultRouteClass extends React.ComponentClass<DefaultRouteProp> {
__react_router_default_route__: any; // dummy
}
// Link
interface LinkProp {
activeClassName?: string;
to: string;
params?: {};
query?: {};
onClick?: Function;
}
interface Link extends React.ReactElement<LinkProp>, Navigation, State {
__react_router_link__: any; // dummy
getHref(): string;
getClassName(): string;
}
interface LinkClass extends React.ComponentClass<LinkProp> {
__react_router_link__: any; // dummy
}
// NotFoundRoute
interface NotFoundRouteProp {
name?: string;
handler: React.ComponentClass<any>;
}
interface NotFoundRoute extends React.ReactElement<NotFoundRouteProp> {
__react_router_not_found_route__: any; // dummy
}
interface NotFoundRouteClass extends React.ComponentClass<NotFoundRouteProp> {
__react_router_not_found_route__: any; // dummy
}
// Redirect
interface RedirectProp {
path?: string;
from?: string;
to?: string;
}
interface Redirect extends React.ReactElement<RedirectProp> {
__react_router_redirect__: any; // dummy
}
interface RedirectClass extends React.ComponentClass<RedirectProp> {
__react_router_redirect__: any; // dummy
}
// Route
interface RouteProp {
name?: string;
path?: string;
handler?: React.ComponentClass<any>;
ignoreScrollBehavior?: boolean;
}
interface Route extends React.ReactElement<RouteProp> {
__react_router_route__: any; // dummy
}
interface RouteClass extends React.ComponentClass<RouteProp> {
__react_router_route__: any; // dummy
}
// RouteHandler
interface RouteHandlerProp {}
interface RouteHandler extends React.ReactElement<RouteHandlerProp>, RouteHandlerMixin {
__react_router_route_handler__: any; // dummy
}
interface RouteHandlerClass extends React.ReactElement<RouteHandlerProp> {
__react_router_route_handler__: any; // dummy
}
var DefaultRoute: DefaultRouteClass;
var Link: LinkClass;
var NotFoundRoute: NotFoundRouteClass;
var Redirect: RedirectClass;
var Route: RouteClass;
var RouteHandler: RouteHandlerClass;
//
// Location
// ----------------------------------------------------------------------
interface LocationBase {
push(path: string): void;
replace(path: string): void;
pop(): void;
getCurrentPath(): void;
}
interface LocationListener {
addChangeListener(listener: Function): void;
removeChangeListener(listener: Function): void;
}
interface HashLocation extends LocationBase, LocationListener {}
interface HistoryLocation extends LocationBase, LocationListener {}
interface RefreshLocation extends LocationBase {}
var HashLocation: HashLocation;
var HistoryLocation: HistoryLocation;
var RefreshLocation: RefreshLocation;
//
// Behavior
// ----------------------------------------------------------------------
interface ScrollBehaviorBase {
updateScrollPosition(position: {x: number; y: number;}, actionType: string): void;
}
interface ImitateBrowserBehavior extends ScrollBehaviorBase {}
interface ScrollToTopBehavior extends ScrollBehaviorBase {}
var ImitateBrowserBehavior: ImitateBrowserBehavior;
var ScrollToTopBehavior: ScrollToTopBehavior;
//
// Router
// ----------------------------------------------------------------------
interface Router extends React.ReactElement<any> {
run(callback: RouterRunCallback): void;
}
interface RouterState {
path: string;
action: string;
pathname: string;
params: {};
query: {};
routes : Route[];
}
interface RouterCreateOption {
routes: Route;
location?: LocationBase;
scrollBehavior?: ScrollBehaviorBase;
}
type RouterRunCallback = (Handler: Router, state: RouterState) => void;
function create(options: RouterCreateOption): Router;
function run(routes: Route, callback: RouterRunCallback): Router;
function run(routes: Route, location: LocationBase, callback: RouterRunCallback): Router;
//
// History
// ----------------------------------------------------------------------
interface History {
back(): void;
length: number;
}
var History: History;
//
// Transition
// ----------------------------------------------------------------------
interface Transition {
abort(): void;
redirect(to: string, params?: {}, query?: {}): void;
retry(): void;
}
interface TransitionStaticLifecycle {
willTransitionTo?(
transition: Transition,
params: {},
query: {},
callback: Function
): void;
willTransitionFrom?(
transition: Transition,
component: React.ReactElement<any>,
callback: Function
): void;
}
}
declare module 'react-router' {
import Export = ReactRouter;
export = Export;
}
declare module React {
interface TopLevelAPI {
// for DefaultRoute
createElement(
type: ReactRouter.DefaultRouteClass,
props: ReactRouter.DefaultRouteProp,
...children: ReactNode[]
): ReactRouter.DefaultRoute;
// for Link
createElement(
type: ReactRouter.LinkClass,
props: ReactRouter.LinkProp,
...children: ReactNode[]
): ReactRouter.Link;
// for NotFoundRoute
createElement(
type: ReactRouter.NotFoundRouteClass,
props: ReactRouter.NotFoundRouteProp,
...children: ReactNode[]
): ReactRouter.NotFoundRoute;
// for Redirect
createElement(
type: ReactRouter.RedirectClass,
props: ReactRouter.RedirectProp,
...children: ReactNode[]
): ReactRouter.Redirect;
// for Route
createElement(
type: ReactRouter.RouteClass,
props: ReactRouter.RouteProp,
...children: ReactNode[]
): ReactRouter.Route;
// for RouteHandler
createElement(
type: ReactRouter.RouteHandlerClass,
props: ReactRouter.RouteHandlerProp,
...children: ReactNode[]
): ReactRouter.RouteHandler;
}
}
+10
View File
@@ -0,0 +1,10 @@
# React v0.13.0-beta Type Definitions
This folder contains the following `.d.ts` files:
* `react-0.13.0.d.ts` declares the external module `"react"`
* `react-addons-0.13.0.d.ts` declares the external module `"react/addons"`
* `react-global-0.13.0.d.ts` declares the internal module `React` in the global namespace
* `react-addons-global-0.13.0.d.ts` extends the global `React` module with `addons`
Interfaces are duplicated between these files; please take care to keep them in sync when making changes. See [#3615](https://github.com/borisyankov/DefinitelyTyped/pull/3615) for relevant discussion.
@@ -1,9 +1,9 @@
/// <reference path="react-0.13.0.d.ts" />
/// <reference path="react-addons-0.13.0.d.ts" />
// requiring react/addons instead of react so react.d.ts doesn't get picked up
import React = require('react/addons');
// TODO: import "react" once 0.13.0 is released
import React = require("react/addons");
interface Props {
interface Props extends React.Props {
hello: string;
world?: string;
foo: number;
@@ -42,36 +42,37 @@ var INPUT_REF: string = "input";
// Top-Level API
// --------------------------------------------------------------------------
var reactClassicClass: React.ClassicComponentClass<Props, State, Context> = React.createClass<Props, State, Context>({
getDefaultProps: () => {
return <Props>{
hello: undefined,
world: "peace",
foo: undefined,
bar: undefined
};
},
getInitialState: () => {
return {
inputValue: this.context.someValue,
seconds: this.props.foo
};
},
reset: () => {
this.replaceState(this.getInitialState());
},
render: () => {
return React.DOM.div(null,
React.DOM.input({
ref: INPUT_REF,
value: this.state.inputValue
}));
}
});
var ClassicComponent: React.ClassicComponentClass<Props, State, Context> =
React.createClass<Props, State, Context>({
getDefaultProps: () => {
return <Props>{
hello: undefined,
world: "peace",
foo: undefined,
bar: undefined
};
},
getInitialState: () => {
return {
inputValue: this.context.someValue,
seconds: this.props.foo
};
},
reset: () => {
this.replaceState(this.getInitialState());
},
render: () => {
return React.DOM.div(null,
React.DOM.input({
ref: INPUT_REF,
value: this.state.inputValue
}));
}
});
var reactClass: React.ComponentClass<Props, State, Context> = reactClassicClass;
class ModernComponent extends React.Component<Props, State, Context>
implements React.ChildContextProvider<ChildContext> {
class ModernComponent extends React.Component<Props, State, Context> implements React.ChildContextProvider<ChildContext> {
constructor(props: Props, context: Context) {
super(props, context);
this.state = {
@@ -80,18 +81,17 @@ class ModernComponent extends React.Component<Props, State, Context> implements
};
}
// this should work but doesn't. Due to TypeScript bug?
//static propTypes = {
// foo: React.PropTypes.number
//}
static propTypes: React.ValidationMap<Props> = {
foo: React.PropTypes.number
}
//static contextTypes = {
// someValue: React.PropTypes.string
//}
static contextTypes: React.ValidationMap<Context> = {
someValue: React.PropTypes.string
}
//static childContextTypes = {
// someOtherValue: React.PropTypes.string
//}
static childContextTypes: React.ValidationMap<ChildContext> = {
someOtherValue: React.PropTypes.string
}
getChildContext() {
return {
@@ -120,66 +120,71 @@ class ModernComponent extends React.Component<Props, State, Context> implements
}
}
ModernComponent.propTypes = {
foo: React.PropTypes.string,
}
// React.createFactory
var factory: React.Factory<Props> =
React.createFactory(ModernComponent);
var factoryElement: React.ReactElement<Props> =
factory(props);
ModernComponent.contextTypes = {
someValue: React.PropTypes.string
}
var classicFactory: React.ClassicFactory<Props> =
React.createFactory(ClassicComponent);
var classicFactoryElement: React.ReactClassicElement<Props> =
classicFactory(props);
ModernComponent.childContextTypes = {
someOtherValue: React.PropTypes.string
}
var domFactory: React.DOMFactory<any> =
React.createFactory("foo");
var domFactoryElement: React.ReactDOMElement<any> =
domFactory();
var reactElement: React.ReactElement<Props>;
reactElement = React.createElement<Props>(reactClass, props);
reactElement = React.createElement(ModernComponent, props);
// React.createElement
var element: React.ReactElement<Props> =
React.createElement(ModernComponent, props);
var classicElement: React.ReactClassicElement<Props> =
React.createElement(ClassicComponent, props);
var domElement: React.ReactHTMLElement =
React.createElement("div");
var reactFactory: React.ComponentFactory<Props>;
reactFactory = React.createFactory<Props>(reactClass);
reactFactory = React.createFactory<Props>(ModernComponent);
var component: React.Component<Props, State, Context> =
React.render<Props, State>(reactElement, container);
// React.render
var component: React.Component<Props, any, any> =
React.render(element, container);
var classicComponent: React.ClassicComponent<Props, any, any> =
React.render(classicElement, container);
var domComponent: React.DOMComponent<any> =
React.render(domElement, container);
// Other Top-Level API
var unmounted: boolean = React.unmountComponentAtNode(container);
var str: string = React.renderToString(reactElement);
var markup: string = React.renderToStaticMarkup(reactElement);
var str: string = React.renderToString(element);
var markup: string = React.renderToStaticMarkup(element);
var notValid: boolean = React.isValidElement(props); // false
var isValid = React.isValidElement(reactElement); // true
var isValid = React.isValidElement(element); // true
React.initializeTouchEvents(true);
var domNode: Element = React.findDOMNode(component);
var reactClassicElement: React.ReactClassicElement<Props>;
reactClassicElement = React.createElement<Props>(reactClassicClass, props);
var classicComponent: React.ClassicComponent<Props, State, Context>;
classicComponent = React.render<Props, State>(reactClassicElement, container);
domNode = React.findDOMNode(domNode);
//
// React Elements
// --------------------------------------------------------------------------
var type = reactElement.type;
var elementProps: Props = reactElement.props;
var key = reactElement.key;
var ref: string = reactElement.ref;
var factoryElement: React.ReactElement<Props> = reactFactory(elementProps);
var type = element.type;
var elementProps: Props = element.props;
var key = element.key;
var ref: string = element.ref;
//
// React Components
// --------------------------------------------------------------------------
var displayName: string = reactClass.displayName;
var defaultProps: Props = reactClass.getDefaultProps();
var propTypes: React.ValidationMap<Props> = reactClass.propTypes;
var displayName: string = ClassicComponent.displayName;
var defaultProps: Props = ClassicComponent.getDefaultProps();
var propTypes: React.ValidationMap<Props> = ClassicComponent.propTypes;
//
// Component API
// --------------------------------------------------------------------------
// modern
var initialState: State = component.state;
var componentState: State = component.state;
component.setState({ inputValue: "!!!" });
component.forceUpdate();
@@ -324,33 +329,28 @@ var onlyChild = React.Children.only([null, [[["Hallo"], true]], false]);
interface TimerState {
secondsElapsed: number;
}
interface Timer extends React.Component<{}, TimerState, any> {
}
var Timer = React.createClass({
displayName: "Timer",
getInitialState: () => {
return { secondsElapsed: 0 };
},
tick: () => {
var me = <Timer>this;
me.setState({
secondsElapsed: me.state.secondsElapsed + 1
});
},
componentDidMount: () => {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: () => {
clearInterval(this.interval);
},
render: () => {
var me = <Timer>this;
class Timer extends React.Component<{}, TimerState, {}> {
static state = {
secondsElapsed: 0
}
private _interval: number;
tick() {
this.setState({ secondsElapsed: this.state.secondsElapsed + 1 });
}
componentDidMount() {
var me = this;
this._interval = setInterval(() => me.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this._interval);
}
render() {
return React.DOM.div(
null,
"Seconds Elapsed: ",
me.state.secondsElapsed
this.state.secondsElapsed
);
}
});
var mountNode: Element;
React.render(React.createElement(Timer, null), mountNode);
}
React.render(React.createElement(Timer), container);
+747
View File
@@ -0,0 +1,747 @@
// Type definitions for React v0.13.0 (external module)
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "react" {
//
// React Elements
// ----------------------------------------------------------------------
interface ReactElementBase<T, P> {
type: T;
props: P;
key: number | string;
ref: string;
}
interface ReactElement<P>
extends ReactElementBase<ComponentClass<P, any, any>, P> {}
interface ReactClassicElement<P>
extends ReactElementBase<ClassicComponentClass<P, any, any> | string, P> {}
interface ReactDOMElement<P> // subtype of ReactClassicElement
extends ReactElementBase<string, P> {}
type ReactHTMLElement = ReactDOMElement<HTMLAttributes>;
type ReactSVGElement = ReactDOMElement<SVGAttributes>;
//
// Factories
// ----------------------------------------------------------------------
interface Factory<P> {
(props?: P, ...children: ReactNode[]): ReactElement<P>;
}
interface ClassicFactory<P> {
(props?: P, ...children: ReactNode[]): ReactClassicElement<P>;
}
interface DOMFactory<P> {
(props?: P, ...children: ReactNode[]): ReactDOMElement<P>;
}
type HTMLFactory = DOMFactory<HTMLAttributes>;
type SVGFactory = DOMFactory<SVGAttributes>;
//
// React Nodes
// http://facebook.github.io/react/docs/glossary.html
// ----------------------------------------------------------------------
type ReactText = string | number;
type ReactChild = ReactElementBase<any, any> | ReactText;
// Should be Array<ReactNode> but type aliases cannot be recursive
type ReactFragment = Array<ReactChild | any[] | boolean>;
type ReactNode = ReactChild | ReactFragment | boolean;
//
// Top Level API
// ----------------------------------------------------------------------
function createClass<P, S, C>(
spec: ComponentSpec<P, S, C>): ClassicComponentClass<P, S, C>;
function createFactory<P>(
type: string): DOMFactory<P>;
function createFactory<P>(
type: ClassicComponentClass<P, any, any> | string): ClassicFactory<P>;
function createFactory<P>(
type: ComponentClass<P, any, any>): Factory<P>;
function createElement<P>(
type: string,
props?: P,
...children: ReactNode[]): ReactDOMElement<P>;
function createElement<P>(
type: ClassicComponentClass<P, any, any> | string,
props?: P,
...children: ReactNode[]): ReactClassicElement<P>;
function createElement<P>(
type: ComponentClass<P, any, any>,
props?: P,
...children: ReactNode[]): ReactElement<P>;
function render<P>(
element: ReactDOMElement<P>,
container: Element,
callback?: () => any): DOMComponent<P>;
function render<P, S>(
element: ReactClassicElement<P>,
container: Element,
callback?: () => any): ClassicComponent<P, S, {}>;
function render<P, S>(
element: ReactElement<P>,
container: Element,
callback?: () => any): Component<P, S, {}>;
function unmountComponentAtNode(container: Element): boolean;
function renderToString(element: ReactElementBase<any, any>): string;
function renderToStaticMarkup(element: ReactElementBase<any, any>): string;
function isValidElement(object: {}): boolean;
function initializeTouchEvents(shouldUseTouch: boolean): void;
function findDOMNode<TElement extends Element>(
componentOrElement: Component<any, any, any> | Element): TElement;
function findDOMNode(
componentOrElement: Component<any, any, any> | Element): Element;
var DOM: ReactDOM;
var PropTypes: ReactPropTypes;
var Children: ReactChildren;
//
// Component API
// ----------------------------------------------------------------------
// Base component for plain JS classes
class Component<P, S, C> implements ComponentLifecycle<P, S, C> {
constructor(props: P, context: C);
setState(state: S, callback?: () => any): void;
forceUpdate(): void;
props: P;
state: S;
context: C;
refs: {
[key: string]: Component<any, any, any>
};
}
interface ClassicComponent<P, S, C> extends Component<P, S, C> {
replaceState(nextState: S, callback?: () => any): void;
getDOMNode<TElement extends Element>(): TElement;
getDOMNode(): Element;
isMounted(): boolean;
getInitialState?(): S;
setProps(nextProps: P, callback?: () => any): void;
replaceProps(nextProps: P, callback?: () => any): void;
}
interface DOMComponent<P> extends ClassicComponent<P, any, any> {
tagName: string;
}
type HTMLComponent = DOMComponent<HTMLAttributes>;
type SVGComponent = DOMComponent<SVGAttributes>;
interface ChildContextProvider<CC> {
getChildContext(): CC;
}
//
// Class Interfaces
// ----------------------------------------------------------------------
interface ComponentClassBase<P, C> {
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<C>;
childContextTypes?: ValidationMap<{}>;
}
interface ComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): Component<P, S, C>;
defaultProps?: P;
}
interface ClassicComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): ClassicComponent<P, S, C>;
getDefaultProps?(): P;
displayName?: string;
}
//
// Component Specs and Lifecycle
// ----------------------------------------------------------------------
interface ComponentLifecycle<P, S, C> {
componentWillMount?(): void;
componentDidMount?(): void;
componentWillReceiveProps?(nextProps: P, nextContext: C): void;
shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: C): boolean;
componentWillUpdate?(nextProps: P, nextState: S, nextContext: C): void;
componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void;
componentWillUnmount?(): void;
}
interface Mixin<P, S, C> extends ComponentLifecycle<P, S, C> {
mixins?: Mixin<P, S, C>;
statics?: {
[key: string]: any;
};
displayName?: string;
propTypes?: ValidationMap<any>;
contextTypes?: ValidationMap<any>;
childContextTypes?: ValidationMap<any>
getInitialState?(): S;
getDefaultProps?(): P;
}
interface ComponentSpec<P, S, C> extends Mixin<P, S, C> {
render(): ReactElementBase<any, any>;
}
//
// Event System
// ----------------------------------------------------------------------
interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: Date;
type: string;
}
interface ClipboardEvent extends SyntheticEvent {
clipboardData: DataTransfer;
}
interface KeyboardEvent extends SyntheticEvent {
altKey: boolean;
charCode: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
key: string;
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
which: number;
}
interface FocusEvent extends SyntheticEvent {
relatedTarget: EventTarget;
}
interface FormEvent extends SyntheticEvent {
}
interface MouseEvent extends SyntheticEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
}
interface TouchEvent extends SyntheticEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
interface UIEvent extends SyntheticEvent {
detail: number;
view: AbstractView;
}
interface WheelEvent extends SyntheticEvent {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
}
//
// Event Handler Types
// ----------------------------------------------------------------------
interface EventHandler<E extends SyntheticEvent> {
(event: E): void;
}
interface ClipboardEventHandler extends EventHandler<ClipboardEvent> {}
interface KeyboardEventHandler extends EventHandler<KeyboardEvent> {}
interface FocusEventHandler extends EventHandler<FocusEvent> {}
interface FormEventHandler extends EventHandler<FormEvent> {}
interface MouseEventHandler extends EventHandler<MouseEvent> {}
interface TouchEventHandler extends EventHandler<TouchEvent> {}
interface UIEventHandler extends EventHandler<UIEvent> {}
interface WheelEventHandler extends EventHandler<WheelEvent> {}
//
// Props / DOM Attributes
// ----------------------------------------------------------------------
interface Props {
children?: ReactNode;
key?: number | string;
ref?: string;
}
interface DOMAttributes extends Props {
onCopy?: ClipboardEventHandler;
onCut?: ClipboardEventHandler;
onPaste?: ClipboardEventHandler;
onKeyDown?: KeyboardEventHandler;
onKeyPress?: KeyboardEventHandler;
onKeyUp?: KeyboardEventHandler;
onFocus?: FocusEventHandler;
onBlur?: FocusEventHandler;
onChange?: FormEventHandler;
onInput?: FormEventHandler;
onSubmit?: FormEventHandler;
onClick?: MouseEventHandler;
onDoubleClick?: MouseEventHandler;
onDrag?: MouseEventHandler;
onDragEnd?: MouseEventHandler;
onDragEnter?: MouseEventHandler;
onDragExit?: MouseEventHandler;
onDragLeave?: MouseEventHandler;
onDragOver?: MouseEventHandler;
onDragStart?: MouseEventHandler;
onDrop?: MouseEventHandler;
onMouseDown?: MouseEventHandler;
onMouseEnter?: MouseEventHandler;
onMouseLeave?: MouseEventHandler;
onMouseMove?: MouseEventHandler;
onMouseOut?: MouseEventHandler;
onMouseOver?: MouseEventHandler;
onMouseUp?: MouseEventHandler;
onTouchCancel?: TouchEventHandler;
onTouchEnd?: TouchEventHandler;
onTouchMove?: TouchEventHandler;
onTouchStart?: TouchEventHandler;
onScroll?: UIEventHandler;
onWheel?: WheelEventHandler;
dangerouslySetInnerHTML?: {
__html: string;
};
}
interface CSSProperties {
columnCount?: number;
flex?: number | string;
flexGrow?: number;
flexShrink?: number;
fontWeight?: number;
lineClamp?: number;
lineHeight?: number;
opacity?: number;
order?: number;
orphans?: number;
widows?: number;
zIndex?: number;
zoom?: number;
// SVG-related properties
fillOpacity?: number;
strokeOpacity?: number;
}
interface HTMLAttributes extends DOMAttributes {
accept?: string;
acceptCharset?: string;
accessKey?: string;
action?: string;
allowFullScreen?: boolean;
allowTransparency?: boolean;
alt?: string;
async?: boolean;
autoComplete?: boolean;
autoFocus?: boolean;
autoPlay?: boolean;
cellPadding?: number | string;
cellSpacing?: number | string;
charSet?: string;
checked?: boolean;
classID?: string;
className?: string;
cols?: number;
colSpan?: number;
content?: string;
contentEditable?: boolean;
contextMenu?: string;
controls?: any;
coords?: string;
crossOrigin?: string;
data?: string;
dateTime?: string;
defer?: boolean;
dir?: string;
disabled?: boolean;
download?: any;
draggable?: boolean;
encType?: string;
form?: string;
formNoValidate?: boolean;
frameBorder?: number | string;
height?: number | string;
hidden?: boolean;
href?: string;
hrefLang?: string;
htmlFor?: string;
httpEquiv?: string;
icon?: string;
id?: string;
label?: string;
lang?: string;
list?: string;
loop?: boolean;
manifest?: string;
max?: number | string;
maxLength?: number;
media?: string;
mediaGroup?: string;
method?: string;
min?: number | string;
multiple?: boolean;
muted?: boolean;
name?: string;
noValidate?: boolean;
open?: boolean;
pattern?: string;
placeholder?: string;
poster?: string;
preload?: string;
radioGroup?: string;
readOnly?: boolean;
rel?: string;
required?: boolean;
role?: string;
rows?: number;
rowSpan?: number;
sandbox?: string;
scope?: string;
scrollLeft?: number;
scrolling?: string;
scrollTop?: number;
seamless?: boolean;
selected?: boolean;
shape?: string;
size?: number;
sizes?: string;
span?: number;
spellCheck?: boolean;
src?: string;
srcDoc?: string;
srcSet?: string;
start?: number;
step?: number | string;
style?: CSSProperties;
tabIndex?: number;
target?: string;
title?: string;
type?: string;
useMap?: string;
value?: string;
width?: number | string;
wmode?: string;
// Non-standard Attributes
autoCapitalize?: boolean;
autoCorrect?: boolean;
property?: string;
itemProp?: string;
itemScope?: boolean;
itemType?: string;
}
interface SVGAttributes extends DOMAttributes {
cx?: SVGLength | SVGAnimatedLength;
cy?: any;
d?: string;
dx?: SVGLength | SVGAnimatedLength;
dy?: SVGLength | SVGAnimatedLength;
fill?: any; // SVGPaint | string
fillOpacity?: number | string;
fontFamily?: string;
fontSize?: number | string;
fx?: SVGLength | SVGAnimatedLength;
fy?: SVGLength | SVGAnimatedLength;
gradientTransform?: SVGTransformList | SVGAnimatedTransformList;
gradientUnits?: string;
markerEnd?: string;
markerMid?: string;
markerStart?: string;
offset?: number | string;
opacity?: number | string;
patternContentUnits?: string;
patternUnits?: string;
points?: string;
preserveAspectRatio?: string;
r?: SVGLength | SVGAnimatedLength;
rx?: SVGLength | SVGAnimatedLength;
ry?: SVGLength | SVGAnimatedLength;
spreadMethod?: string;
stopColor?: any; // SVGColor | string
stopOpacity?: number | string;
stroke?: any; // SVGPaint
strokeDasharray?: string;
strokeLinecap?: string;
strokeOpacity?: number | string;
strokeWidth?: SVGLength | SVGAnimatedLength;
textAnchor?: string;
transform?: SVGTransformList | SVGAnimatedTransformList;
version?: string;
viewBox?: string;
x1?: SVGLength | SVGAnimatedLength;
x2?: SVGLength | SVGAnimatedLength;
x?: SVGLength | SVGAnimatedLength;
y1?: SVGLength | SVGAnimatedLength;
y2?: SVGLength | SVGAnimatedLength
y?: SVGLength | SVGAnimatedLength;
}
//
// React.DOM
// ----------------------------------------------------------------------
interface ReactDOM {
// HTML
a: HTMLFactory;
abbr: HTMLFactory;
address: HTMLFactory;
area: HTMLFactory;
article: HTMLFactory;
aside: HTMLFactory;
audio: HTMLFactory;
b: HTMLFactory;
base: HTMLFactory;
bdi: HTMLFactory;
bdo: HTMLFactory;
big: HTMLFactory;
blockquote: HTMLFactory;
body: HTMLFactory;
br: HTMLFactory;
button: HTMLFactory;
canvas: HTMLFactory;
caption: HTMLFactory;
cite: HTMLFactory;
code: HTMLFactory;
col: HTMLFactory;
colgroup: HTMLFactory;
data: HTMLFactory;
datalist: HTMLFactory;
dd: HTMLFactory;
del: HTMLFactory;
details: HTMLFactory;
dfn: HTMLFactory;
dialog: HTMLFactory;
div: HTMLFactory;
dl: HTMLFactory;
dt: HTMLFactory;
em: HTMLFactory;
embed: HTMLFactory;
fieldset: HTMLFactory;
figcaption: HTMLFactory;
figure: HTMLFactory;
footer: HTMLFactory;
form: HTMLFactory;
h1: HTMLFactory;
h2: HTMLFactory;
h3: HTMLFactory;
h4: HTMLFactory;
h5: HTMLFactory;
h6: HTMLFactory;
head: HTMLFactory;
header: HTMLFactory;
hr: HTMLFactory;
html: HTMLFactory;
i: HTMLFactory;
iframe: HTMLFactory;
img: HTMLFactory;
input: HTMLFactory;
ins: HTMLFactory;
kbd: HTMLFactory;
keygen: HTMLFactory;
label: HTMLFactory;
legend: HTMLFactory;
li: HTMLFactory;
link: HTMLFactory;
main: HTMLFactory;
map: HTMLFactory;
mark: HTMLFactory;
menu: HTMLFactory;
menuitem: HTMLFactory;
meta: HTMLFactory;
meter: HTMLFactory;
nav: HTMLFactory;
noscript: HTMLFactory;
object: HTMLFactory;
ol: HTMLFactory;
optgroup: HTMLFactory;
option: HTMLFactory;
output: HTMLFactory;
p: HTMLFactory;
param: HTMLFactory;
picture: HTMLFactory;
pre: HTMLFactory;
progress: HTMLFactory;
q: HTMLFactory;
rp: HTMLFactory;
rt: HTMLFactory;
ruby: HTMLFactory;
s: HTMLFactory;
samp: HTMLFactory;
script: HTMLFactory;
section: HTMLFactory;
select: HTMLFactory;
small: HTMLFactory;
source: HTMLFactory;
span: HTMLFactory;
strong: HTMLFactory;
style: HTMLFactory;
sub: HTMLFactory;
summary: HTMLFactory;
sup: HTMLFactory;
table: HTMLFactory;
tbody: HTMLFactory;
td: HTMLFactory;
textarea: HTMLFactory;
tfoot: HTMLFactory;
th: HTMLFactory;
thead: HTMLFactory;
time: HTMLFactory;
title: HTMLFactory;
tr: HTMLFactory;
track: HTMLFactory;
u: HTMLFactory;
ul: HTMLFactory;
"var": HTMLFactory;
video: HTMLFactory;
wbr: HTMLFactory;
// SVG
circle: SVGFactory;
defs: SVGFactory;
ellipse: SVGFactory;
g: SVGFactory;
line: SVGFactory;
linearGradient: SVGFactory;
mask: SVGFactory;
path: SVGFactory;
pattern: SVGFactory;
polygon: SVGFactory;
polyline: SVGFactory;
radialGradient: SVGFactory;
rect: SVGFactory;
stop: SVGFactory;
svg: SVGFactory;
text: SVGFactory;
tspan: SVGFactory;
}
//
// React.PropTypes
// ----------------------------------------------------------------------
interface Validator<T> {
(object: T, key: string, componentName: string): Error;
}
interface Requireable<T> extends Validator<T> {
isRequired: Validator<T>;
}
interface ValidationMap<T> {
[key: string]: Validator<T>;
}
interface ReactPropTypes {
any: Requireable<any>;
array: Requireable<any>;
bool: Requireable<any>;
func: Requireable<any>;
number: Requireable<any>;
object: Requireable<any>;
string: Requireable<any>;
node: Requireable<any>;
element: Requireable<any>;
instanceOf(expectedClass: {}): Requireable<any>;
oneOf(types: any[]): Requireable<any>;
oneOfType(types: Validator<any>[]): Requireable<any>;
arrayOf(type: Validator<any>): Requireable<any>;
objectOf(type: Validator<any>): Requireable<any>;
shape(type: ValidationMap<any>): Requireable<any>;
}
//
// React.Children
// ----------------------------------------------------------------------
interface ReactChildren {
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;
}
//
// Browser Interfaces
// https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts
// ----------------------------------------------------------------------
interface AbstractView {
styleMedia: StyleMedia;
document: Document;
}
interface Touch {
identifier: number;
target: EventTarget;
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
interface TouchList {
[index: number]: Touch;
length: number;
item(index: number): Touch;
identifiedTouch(identifier: number): Touch;
}
}
+387
View File
@@ -0,0 +1,387 @@
/// <reference path="react-addons-0.13.0.d.ts" />
import React = require("react/addons");
interface Props extends React.Props {
hello: string;
world?: string;
foo: number;
bar: boolean;
}
interface State {
inputValue?: string;
seconds?: number;
}
interface Context {
someValue?: string;
}
interface ChildContext {
someOtherValue: string;
}
interface MyComponent extends React.Component<Props, State, Context> {
reset(): void;
}
var props: Props = {
key: 42,
ref: "myComponent42",
hello: "world",
foo: 42,
bar: true
};
var container: Element;
var INPUT_REF: string = "input";
//
// Top-Level API
// --------------------------------------------------------------------------
var ClassicComponent: React.ClassicComponentClass<Props, State, Context> =
React.createClass<Props, State, Context>({
getDefaultProps: () => {
return <Props>{
hello: undefined,
world: "peace",
foo: undefined,
bar: undefined
};
},
getInitialState: () => {
return {
inputValue: this.context.someValue,
seconds: this.props.foo
};
},
reset: () => {
this.replaceState(this.getInitialState());
},
render: () => {
return React.DOM.div(null,
React.DOM.input({
ref: INPUT_REF,
value: this.state.inputValue
}));
}
});
class ModernComponent extends React.Component<Props, State, Context>
implements React.ChildContextProvider<ChildContext> {
constructor(props: Props, context: Context) {
super(props, context);
this.state = {
inputValue: context.someValue,
seconds: props.foo
};
}
static propTypes: React.ValidationMap<Props> = {
foo: React.PropTypes.number
}
static contextTypes: React.ValidationMap<Context> = {
someValue: React.PropTypes.string
}
static childContextTypes: React.ValidationMap<ChildContext> = {
someOtherValue: React.PropTypes.string
}
getChildContext() {
return {
someOtherValue: 'foo'
}
}
state = {
inputValue: this.context.someValue,
seconds: this.props.foo
}
reset() {
this.setState({
inputValue: this.context.someValue,
seconds: this.props.foo
});
}
render() {
return React.DOM.div(null,
React.DOM.input({
ref: INPUT_REF,
value: this.state.inputValue
}));
}
}
// React.createFactory
var factory: React.Factory<Props> =
React.createFactory(ModernComponent);
var factoryElement: React.ReactElement<Props> =
factory(props);
var classicFactory: React.ClassicFactory<Props> =
React.createFactory(ClassicComponent);
var classicFactoryElement: React.ReactClassicElement<Props> =
classicFactory(props);
var domFactory: React.DOMFactory<any> =
React.createFactory("foo");
var domFactoryElement: React.ReactDOMElement<any> =
domFactory();
// React.createElement
var element: React.ReactElement<Props> =
React.createElement(ModernComponent, props);
var classicElement: React.ReactClassicElement<Props> =
React.createElement(ClassicComponent, props);
var domElement: React.ReactHTMLElement =
React.createElement("div");
// React.render
var component: React.Component<Props, any, any> =
React.render(element, container);
var classicComponent: React.ClassicComponent<Props, any, any> =
React.render(classicElement, container);
var domComponent: React.DOMComponent<any> =
React.render(domElement, container);
// Other Top-Level API
var unmounted: boolean = React.unmountComponentAtNode(container);
var str: string = React.renderToString(element);
var markup: string = React.renderToStaticMarkup(element);
var notValid: boolean = React.isValidElement(props); // false
var isValid = React.isValidElement(element); // true
React.initializeTouchEvents(true);
var domNode: Element = React.findDOMNode(component);
domNode = React.findDOMNode(domNode);
//
// React Elements
// --------------------------------------------------------------------------
var type = element.type;
var elementProps: Props = element.props;
var key = element.key;
var ref: string = element.ref;
//
// React Components
// --------------------------------------------------------------------------
var displayName: string = ClassicComponent.displayName;
var defaultProps: Props = ClassicComponent.getDefaultProps();
var propTypes: React.ValidationMap<Props> = ClassicComponent.propTypes;
//
// Component API
// --------------------------------------------------------------------------
// modern
var componentState: State = component.state;
component.setState({ inputValue: "!!!" });
component.forceUpdate();
// classic
var htmlElement: Element = classicComponent.getDOMNode();
var divElement: HTMLDivElement = classicComponent.getDOMNode<HTMLDivElement>();
var isMounted: boolean = classicComponent.isMounted();
classicComponent.setProps(elementProps);
classicComponent.replaceProps(props);
classicComponent.replaceState({ inputValue: "???", seconds: 60 });
var inputRef: React.HTMLComponent =
<React.HTMLComponent>component.refs[INPUT_REF];
var value: string = inputRef.getDOMNode<HTMLInputElement>().value;
var myComponent = <MyComponent>component;
myComponent.reset();
//
// Attributes
// --------------------------------------------------------------------------
var children = ["Hello world", [null], React.DOM.span(null)];
var divStyle = { // CSSProperties
flex: "1 1 main-size",
backgroundImage: "url('hello.png')"
};
var htmlAttr: React.HTMLAttributes = {
key: 36,
ref: "htmlComponent",
children: children,
className: "test-attr",
style: divStyle,
onClick: (event: React.MouseEvent) => {
event.preventDefault();
event.stopPropagation();
},
dangerouslySetInnerHTML: {
__html: "<strong>STRONG</strong>"
}
};
React.DOM.div(htmlAttr);
React.DOM.span(htmlAttr);
React.DOM.input(htmlAttr);
//
// React.PropTypes
// --------------------------------------------------------------------------
var PropTypesSpecification: React.ComponentSpec<any, any, any> = {
propTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Date),
optionalEnum: React.PropTypes.oneOf(["News", "Photos"]),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Date)
]),
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
requiredFunc: React.PropTypes.func.isRequired,
requiredAny: React.PropTypes.any.isRequired,
customProp: function(props: any, propName: string, componentName: string) {
if (!/matchme/.test(props[propName])) {
return new Error("Validation failed!");
}
return null;
}
},
render: (): React.ReactHTMLElement => {
return null;
}
};
//
// ContextTypes
// --------------------------------------------------------------------------
var ContextTypesSpecification: React.ComponentSpec<any, any, any> = {
contextTypes: {
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
optionalNode: React.PropTypes.node,
optionalElement: React.PropTypes.element,
optionalMessage: React.PropTypes.instanceOf(Date),
optionalEnum: React.PropTypes.oneOf(["News", "Photos"]),
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Date)
]),
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
requiredFunc: React.PropTypes.func.isRequired,
requiredAny: React.PropTypes.any.isRequired,
customProp: function(props: any, propName: string, componentName: string) {
if (!/matchme/.test(props[propName])) {
return new Error("Validation failed!");
}
return null;
}
},
render: (): React.ReactHTMLElement => {
return null;
}
};
//
// React.Children
// --------------------------------------------------------------------------
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]);
//
// Example from http://facebook.github.io/react/
// --------------------------------------------------------------------------
interface TimerState {
secondsElapsed: number;
}
class Timer extends React.Component<{}, TimerState, {}> {
static state = {
secondsElapsed: 0
}
private _interval: number;
tick() {
this.setState({ secondsElapsed: this.state.secondsElapsed + 1 });
}
componentDidMount() {
var me = this;
this._interval = setInterval(() => me.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this._interval);
}
render() {
return React.DOM.div(
null,
"Seconds Elapsed: ",
this.state.secondsElapsed
);
}
}
React.render(React.createElement(Timer), container);
//
// React.addons
// --------------------------------------------------------------------------
var cx = React.addons.classSet;
var className: string = cx({ a: true, b: false, c: true });
className = cx("a", null, "b");
//
// React.addons (Transitions)
// --------------------------------------------------------------------------
React.createFactory(React.addons.TransitionGroup)({ component: "div" });
React.createFactory(React.addons.CSSTransitionGroup)({
component: React.createClass({
render: (): React.ReactElement<any> => null
}),
childFactory: (c) => c,
transitionName: "transition",
transitionAppear: false,
transitionEnter: true,
transitionLeave: true
});
//
// React.addons.TestUtils
// --------------------------------------------------------------------------
var node: Element;
React.addons.TestUtils.Simulate.click(node);
React.addons.TestUtils.Simulate.change(node);
React.addons.TestUtils.Simulate.keyDown(node, { key: "Enter" });
@@ -1,42 +1,179 @@
// Type definitions for React 0.13.0
// Type definitions for ReactWithAddons v0.13.0 (external module)
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module React {
declare module "react/addons" {
//
// React Elements
// React Elements
// ----------------------------------------------------------------------
type ReactType = ComponentClass<any, any, any> | string;
interface ReactElement<P> {
type: ComponentClass<P, any, any> | string;
interface ReactElementBase<T, P> {
type: T;
props: P;
key: number | string;
ref: string;
}
interface ReactClassicElement<P> extends ReactElement<P> {
}
interface ReactElement<P>
extends ReactElementBase<ComponentClass<P, any, any>, P> {}
interface ReactHTMLElement extends ReactElement<HTMLAttributes> {}
interface ReactSVGElement extends ReactElement<SVGAttributes> {}
interface ReactClassicElement<P>
extends ReactElementBase<ClassicComponentClass<P, any, any> | string, P> {}
interface ReactDOMElement<P> // subtype of ReactClassicElement
extends ReactElementBase<string, P> {}
type ReactHTMLElement = ReactDOMElement<HTMLAttributes>;
type ReactSVGElement = ReactDOMElement<SVGAttributes>;
//
// React Nodes
// Factories
// ----------------------------------------------------------------------
interface Factory<P> {
(props?: P, ...children: ReactNode[]): ReactElement<P>;
}
interface ClassicFactory<P> {
(props?: P, ...children: ReactNode[]): ReactClassicElement<P>;
}
interface DOMFactory<P> {
(props?: P, ...children: ReactNode[]): ReactDOMElement<P>;
}
type HTMLFactory = DOMFactory<HTMLAttributes>;
type SVGFactory = DOMFactory<SVGAttributes>;
//
// React Nodes
// http://facebook.github.io/react/docs/glossary.html
// ----------------------------------------------------------------------
type ReactText = string | number;
type ReactChild = ReactElement<any> | ReactText;
type ReactChild = ReactElementBase<any, 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
// Top Level API
// ----------------------------------------------------------------------
function createClass<P, S, C>(
spec: ComponentSpec<P, S, C>): ClassicComponentClass<P, S, C>;
function createFactory<P>(
type: string): DOMFactory<P>;
function createFactory<P>(
type: ClassicComponentClass<P, any, any> | string): ClassicFactory<P>;
function createFactory<P>(
type: ComponentClass<P, any, any>): Factory<P>;
function createElement<P>(
type: string,
props?: P,
...children: ReactNode[]): ReactDOMElement<P>;
function createElement<P>(
type: ClassicComponentClass<P, any, any> | string,
props?: P,
...children: ReactNode[]): ReactClassicElement<P>;
function createElement<P>(
type: ComponentClass<P, any, any>,
props?: P,
...children: ReactNode[]): ReactElement<P>;
function render<P>(
element: ReactDOMElement<P>,
container: Element,
callback?: () => any): DOMComponent<P>;
function render<P, S>(
element: ReactClassicElement<P>,
container: Element,
callback?: () => any): ClassicComponent<P, S, {}>;
function render<P, S>(
element: ReactElement<P>,
container: Element,
callback?: () => any): Component<P, S, {}>;
function unmountComponentAtNode(container: Element): boolean;
function renderToString(element: ReactElementBase<any, any>): string;
function renderToStaticMarkup(element: ReactElementBase<any, any>): string;
function isValidElement(object: {}): boolean;
function initializeTouchEvents(shouldUseTouch: boolean): void;
function findDOMNode<TElement extends Element>(
componentOrElement: Component<any, any, any> | Element): TElement;
function findDOMNode(
componentOrElement: Component<any, any, any> | Element): Element;
var DOM: ReactDOM;
var PropTypes: ReactPropTypes;
var Children: ReactChildren;
//
// Component API
// ----------------------------------------------------------------------
// Base component for plain JS classes
class Component<P, S, C> implements ComponentLifecycle<P, S, C> {
constructor(props: P, context: C);
setState(state: S, callback?: () => any): void;
forceUpdate(): void;
props: P;
state: S;
context: C;
refs: {
[key: string]: Component<any, any, any>
};
}
interface ClassicComponent<P, S, C> extends Component<P, S, C> {
replaceState(nextState: S, callback?: () => any): void;
getDOMNode<TElement extends Element>(): TElement;
getDOMNode(): Element;
isMounted(): boolean;
getInitialState?(): S;
setProps(nextProps: P, callback?: () => any): void;
replaceProps(nextProps: P, callback?: () => any): void;
}
interface DOMComponent<P> extends ClassicComponent<P, any, any> {
tagName: string;
}
type HTMLComponent = DOMComponent<HTMLAttributes>;
type SVGComponent = DOMComponent<SVGAttributes>;
interface ChildContextProvider<CC> {
getChildContext(): CC;
}
//
// Class Interfaces
// ----------------------------------------------------------------------
interface ComponentClassBase<P, C> {
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<C>;
childContextTypes?: ValidationMap<{}>;
}
interface ComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): Component<P, S, C>;
defaultProps?: P;
}
interface ClassicComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): ClassicComponent<P, S, C>;
getDefaultProps?(): P;
displayName?: string;
}
//
// Component Specs and Lifecycle
// ----------------------------------------------------------------------
interface ComponentLifecycle<P, S, C> {
@@ -48,102 +185,7 @@ declare module React {
componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void;
componentWillUnmount?(): void;
}
// "modern" ES6 classes
class Component<P, S, C> implements ComponentLifecycle<P, S, C> {
constructor(props: P, context: C);
// static members can't be type checked with generics. However, see ComponentClass<P, S, C>
static defaultProps: any;
static propTypes: ValidationMap<any>;
static contextTypes: ValidationMap<any>;
static childContextTypes: ValidationMap<any>;
static displayName: string;
setState(state: S, callback?: () => any): void;
forceUpdate(): void;
props: P;
state: S;
context: C;
refs: {
[key: string]: Component<any, any, any>
};
}
interface ComponentClass<P, S, C> {
new (props: P, context: C): Component<P, S, C>;
// can cast to get type checking for generics if desired
defaultProps: P;
getDefaultProps?(): P;
propTypes: ValidationMap<P>;
contextTypes: ValidationMap<C>;
childContextTypes: ValidationMap<any>;
displayName: string;
}
// "classic" createClass
class ClassicComponent<P, S, C> extends Component<P, S, C> {
replaceState(nextState: S, callback?: () => any): void;
getDOMNode<TElement extends Element>(): TElement;
getDOMNode(): Element;
isMounted(): boolean;
getInitialState(): S;
setProps(nextProps: P, callback?: () => any): void;
replaceProps(nextProps: P, callback?: () => any): void;
}
interface ClassicComponentClass<P, S, C> extends ComponentClass<P, S, C> {
new (props: P, context: C): ClassicComponent<P, S, C>;
}
interface ChildContextProvider<C> {
getChildContext: () => C;
}
//
// ReactElement Factories
// ----------------------------------------------------------------------
interface ComponentFactory<P> {
(props?: P, ...children: ReactNode[]): ReactElement<P>;
}
interface HTMLFactory extends ComponentFactory<HTMLAttributes> {}
interface SVGFactory extends ComponentFactory<SVGAttributes> {}
//
// Top-Level API
// ----------------------------------------------------------------------
interface TopLevelAPI {
createClass<P, S, C>(spec: ComponentSpec<P, S, C>): ClassicComponentClass<P, S, C>;
createElement<P>(type: ClassicComponentClass<P, any, any>, props: P, ...children: ReactNode[]): ReactClassicElement<P>;
createElement<P>(type: ComponentClass<P, any, any> | string, props: P, ...children: ReactNode[]): ReactElement<P>;
createFactory<P>(type: ComponentClass<P, any, any> | string): ComponentFactory<P>;
render<P, S>(element: ReactClassicElement<P>, container: Element, callback?: () => any): ClassicComponent<P, S, any>;
render<P, S>(element: ReactElement<P>, container: Element, callback?: () => any): Component<P, S, any>;
unmountComponentAtNode(container: Element): boolean;
renderToString(element: ReactElement<any>): string;
renderToStaticMarkup(element: ReactElement<any>): string;
isValidElement(object: {}): boolean;
initializeTouchEvents(shouldUseTouch: boolean): void;
findDOMNode(component: Component<any, any, any>): Element;
findDOMNode<TElement extends Element>(component: Component<any, any, any>): TElement;
}
//
// Component API
// ----------------------------------------------------------------------
class DOMComponent<P> extends ClassicComponent<P, any, any> {
tagName: string;
}
interface HTMLComponent extends DOMComponent<HTMLAttributes> {}
interface SVGComponent extends DOMComponent<SVGAttributes> {}
//
// Component Specs and Lifecycle
// ----------------------------------------------------------------------
interface Mixin<P, S, C> extends ComponentLifecycle<P, S, C> {
mixins?: Mixin<P, S, C>;
statics?: {
@@ -154,13 +196,13 @@ declare module React {
propTypes?: ValidationMap<any>;
contextTypes?: ValidationMap<any>;
childContextTypes?: ValidationMap<any>
getInitialState?(): S;
getDefaultProps?(): P;
}
interface ComponentSpec<P, S, C> extends Mixin<P, S, C> {
render(): ReactElement<any>;
render(): ReactElementBase<any, any>;
}
//
@@ -266,15 +308,16 @@ declare module React {
interface WheelEventHandler extends EventHandler<WheelEvent> {}
//
// Attributes
// Props / DOM Attributes
// ----------------------------------------------------------------------
interface ReactAttributes {
interface Props {
children?: ReactNode;
key?: number | string;
ref?: string;
}
// Event Attributes
interface DOMAttributes extends Props {
onCopy?: ClipboardEventHandler;
onCut?: ClipboardEventHandler;
onPaste?: ClipboardEventHandler;
@@ -335,7 +378,7 @@ declare module React {
strokeOpacity?: number;
}
interface HTMLAttributes extends ReactAttributes {
interface HTMLAttributes extends DOMAttributes {
accept?: string;
acceptCharset?: string;
accessKey?: string;
@@ -443,9 +486,9 @@ declare module React {
itemType?: string;
}
interface SVGAttributes extends ReactAttributes {
interface SVGAttributes extends DOMAttributes {
cx?: SVGLength | SVGAnimatedLength;
cy?: any;
cy?: any;
d?: string;
dx?: SVGLength | SVGAnimatedLength;
dy?: SVGLength | SVGAnimatedLength;
@@ -490,7 +533,7 @@ declare module React {
}
//
// React.DOM
// React.DOM
// ----------------------------------------------------------------------
interface ReactDOM {
@@ -677,14 +720,36 @@ declare module React {
// React.addons
// ----------------------------------------------------------------------
interface ClassSet {
[key: string]: boolean;
}
export var addons: {
CSSTransitionGroup: CSSTransitionGroup;
LinkedStateMixin: LinkedStateMixin;
PureRenderMixin: PureRenderMixin;
TransitionGroup: TransitionGroup;
batchedUpdates<A, B>(callback: (a: A, b: B) => any, a: A, b: B): void;
batchedUpdates<A>(callback: (a: A) => any, a: A): void;
batchedUpdates(callback: () => any): void;
// deprecated: use petehunt/react-classset or JedWatson/classnames
classSet(cx: { [key: string]: boolean }): string;
classSet(...classList: string[]): string;
cloneWithProps<P>(element: ReactElement<P>, props: P): ReactElement<P>;
update(value: any[], spec: UpdateArraySpec): any[];
update(value: {}, spec: UpdateSpec): any;
// Development tools
Perf: ReactPerf;
TestUtils: ReactTestUtils;
};
//
// React.addons (Transitions)
// ----------------------------------------------------------------------
type ReactType = ComponentClass<any, any, any> | string;
interface TransitionGroupProps {
component?: ReactType;
childFactory?: (child: ReactElement<any>) => ReactElement<any>;
@@ -697,8 +762,10 @@ declare module React {
transitionLeave?: boolean;
}
interface CSSTransitionGroup extends ComponentClass<CSSTransitionGroupProps, any, any> {}
interface TransitionGroup extends ComponentClass<TransitionGroupProps, any, any> {}
type CSSTransitionGroup =
ComponentClass<CSSTransitionGroupProps, any, any>;
type TransitionGroup =
ComponentClass<TransitionGroupProps, any, any>;
//
// React.addons (Mixins)
@@ -785,28 +852,44 @@ declare module React {
mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils;
isElementOfType(element: ReactElement<any>, type: ReactType): boolean;
isTextComponent(instance: Component<any, any, any>): boolean;
isDOMComponent(instance: Component<any, any, any>): boolean;
isCompositeComponent(instance: Component<any, any, any>): boolean;
isCompositeComponentWithType(instance: Component<any, any, any>, type: ComponentClass<any, any, any>): boolean;
isTextComponent(instance: Component<any, any, any>): boolean;
isCompositeComponentWithType(
instance: Component<any, any, any>,
type: ComponentClass<any, any, any>): boolean;
findAllInRenderedTree(tree: Component<any, any, any>, fn: (i: Component<any, any, any>) => boolean): Component<any, any, any>;
findAllInRenderedTree(
tree: Component<any, any, any>,
fn: (i: Component<any, any, any>) => boolean): Component<any, any, any>;
scryRenderedDOMComponentsWithClass(tree: Component<any, any, any>, className: string): DOMComponent<any>[];
findRenderedDOMComponentWithClass(tree: Component<any, any, any>, className: string): DOMComponent<any>;
scryRenderedDOMComponentsWithClass(
tree: Component<any, any, any>,
className: string): DOMComponent<any>[];
findRenderedDOMComponentWithClass(
tree: Component<any, any, any>,
className: string): DOMComponent<any>;
scryRenderedDOMComponentsWithTag(tree: Component<any, any, any>, tagName: string): DOMComponent<any>[];
findRenderedDOMComponentWithTag(tree: Component<any, any, any>, tagName: string): DOMComponent<any>;
scryRenderedDOMComponentsWithTag(
tree: Component<any, any, any>,
tagName: string): DOMComponent<any>[];
findRenderedDOMComponentWithTag(
tree: Component<any, any, any>,
tagName: string): DOMComponent<any>;
scryRenderedComponentsWithType<P, S, C>(
tree: Component<any, any, any>, type: ComponentClass<P, S, C>): Component<P, S, C>[];
tree: Component<any, any, any>,
type: ComponentClass<P, S, C>): Component<P, S, C>[];
scryRenderedComponentsWithType<C extends Component<any, any, any>>(
tree: Component<any, any, any>, type: ComponentClass<any, any, any>): C[];
tree: Component<any, any, any>,
type: ComponentClass<any, any, any>): C[];
findRenderedComponentWithType<P, S, C>(
tree: Component<any, any, any>, type: ComponentClass<P, S, C>): Component<P, S, C>;
tree: Component<any, any, any>,
type: ComponentClass<P, S, C>): Component<P, S, C>;
findRenderedComponentWithType<C extends Component<any, any, any>>(
tree: Component<any, any, any>, type: ComponentClass<any, any, any>): C;
tree: Component<any, any, any>,
type: ComponentClass<any, any, any>): C;
}
interface SyntheticEventData {
@@ -884,44 +967,6 @@ declare module React {
wheel: EventSimulator;
}
//
// react Exports
// ----------------------------------------------------------------------
interface Exports extends TopLevelAPI {
DOM: ReactDOM;
PropTypes: ReactPropTypes;
Children: ReactChildren;
Component: ComponentClass<any, any, any>;
}
//
// react/addons Exports
// ----------------------------------------------------------------------
interface AddonsExports extends Exports {
addons: {
CSSTransitionGroup: CSSTransitionGroup;
LinkedStateMixin: LinkedStateMixin;
PureRenderMixin: PureRenderMixin;
TransitionGroup: TransitionGroup;
batchedUpdates<A, B>(callback: (a: A, b: B) => any, a: A, b: B): void;
batchedUpdates<A>(callback: (a: A) => any, a: A): void;
batchedUpdates(callback: () => any): void;
classSet(cx: ClassSet): string;
cloneWithProps<P>(element: ReactElement<P>, props: P): ReactElement<P>;
update(value: any[], spec: UpdateArraySpec): any[];
update(value: {}, spec: UpdateSpec): any;
// Development tools
Perf: ReactPerf;
TestUtils: ReactTestUtils;
};
}
//
// Browser Interfaces
// https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts
@@ -951,13 +996,3 @@ declare module React {
}
}
declare module "react" {
var exports: React.Exports;
export = exports;
}
declare module "react/addons" {
var exports: React.AddonsExports;
export = exports;
}
+259
View File
@@ -0,0 +1,259 @@
// Type definitions for ReactWithAddons v0.13.0 (internal module)
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="react-global-0.13.0.d.ts" />
declare module React {
//
// React.addons
// ----------------------------------------------------------------------
export var addons: {
CSSTransitionGroup: CSSTransitionGroup;
LinkedStateMixin: LinkedStateMixin;
PureRenderMixin: PureRenderMixin;
TransitionGroup: TransitionGroup;
batchedUpdates<A, B>(callback: (a: A, b: B) => any, a: A, b: B): void;
batchedUpdates<A>(callback: (a: A) => any, a: A): void;
batchedUpdates(callback: () => any): void;
// deprecated: use petehunt/react-classset or JedWatson/classnames
classSet(cx: { [key: string]: boolean }): string;
classSet(...classList: string[]): string;
cloneWithProps<P>(element: ReactElement<P>, props: P): ReactElement<P>;
update(value: any[], spec: UpdateArraySpec): any[];
update(value: {}, spec: UpdateSpec): any;
// Development tools
Perf: ReactPerf;
TestUtils: ReactTestUtils;
};
//
// React.addons (Transitions)
// ----------------------------------------------------------------------
type ReactType = ComponentClass<any, any, any> | string;
interface TransitionGroupProps {
component?: ReactType;
childFactory?: (child: ReactElement<any>) => ReactElement<any>;
}
interface CSSTransitionGroupProps extends TransitionGroupProps {
transitionName: string;
transitionAppear?: boolean;
transitionEnter?: boolean;
transitionLeave?: boolean;
}
type CSSTransitionGroup =
ComponentClass<CSSTransitionGroupProps, any, any>;
type TransitionGroup =
ComponentClass<TransitionGroupProps, any, any>;
//
// React.addons (Mixins)
// ----------------------------------------------------------------------
interface ReactLink<T> {
value: T;
requestChange(newValue: T): void;
}
interface LinkedStateMixin extends Mixin<any, any, any> {
linkState<T>(key: string): ReactLink<T>;
}
interface PureRenderMixin extends Mixin<any, any, any> {
}
//
// Reat.addons.update
// ----------------------------------------------------------------------
interface UpdateSpec {
$set: any;
$merge: {};
$apply(value: any): any;
// [key: string]: UpdateSpec;
}
interface UpdateArraySpec extends UpdateSpec {
$push?: any[];
$unshift?: any[];
$splice?: any[][];
}
//
// React.addons.Perf
// ----------------------------------------------------------------------
interface ComponentPerfContext {
current: string;
owner: string;
}
interface NumericPerfContext {
[key: string]: number;
}
interface Measurements {
exclusive: NumericPerfContext;
inclusive: NumericPerfContext;
render: NumericPerfContext;
counts: NumericPerfContext;
writes: NumericPerfContext;
displayNames: {
[key: string]: ComponentPerfContext;
};
totalTime: number;
}
interface ReactPerf {
start(): void;
stop(): void;
printInclusive(measurements: Measurements[]): void;
printExclusive(measurements: Measurements[]): void;
printWasted(measurements: Measurements[]): void;
printDOM(measurements: Measurements[]): void;
getLastMeasurements(): Measurements[];
}
//
// React.addons.TestUtils
// ----------------------------------------------------------------------
interface MockedComponentClass {
new(): any;
}
interface ReactTestUtils {
Simulate: Simulate;
renderIntoDocument<P>(element: ReactElement<P>): Component<P, any, any>;
renderIntoDocument<C extends Component<any, any, any>>(element: ReactElement<any>): C;
mockComponent(mocked: MockedComponentClass, mockTagName?: string): ReactTestUtils;
isElementOfType(element: ReactElement<any>, type: ReactType): boolean;
isTextComponent(instance: Component<any, any, any>): boolean;
isDOMComponent(instance: Component<any, any, any>): boolean;
isCompositeComponent(instance: Component<any, any, any>): boolean;
isCompositeComponentWithType(
instance: Component<any, any, any>,
type: ComponentClass<any, any, any>): boolean;
findAllInRenderedTree(
tree: Component<any, any, any>,
fn: (i: Component<any, any, any>) => boolean): Component<any, any, any>;
scryRenderedDOMComponentsWithClass(
tree: Component<any, any, any>,
className: string): DOMComponent<any>[];
findRenderedDOMComponentWithClass(
tree: Component<any, any, any>,
className: string): DOMComponent<any>;
scryRenderedDOMComponentsWithTag(
tree: Component<any, any, any>,
tagName: string): DOMComponent<any>[];
findRenderedDOMComponentWithTag(
tree: Component<any, any, any>,
tagName: string): DOMComponent<any>;
scryRenderedComponentsWithType<P, S, C>(
tree: Component<any, any, any>,
type: ComponentClass<P, S, C>): Component<P, S, C>[];
scryRenderedComponentsWithType<C extends Component<any, any, any>>(
tree: Component<any, any, any>,
type: ComponentClass<any, any, any>): C[];
findRenderedComponentWithType<P, S, C>(
tree: Component<any, any, any>,
type: ComponentClass<P, S, C>): Component<P, S, C>;
findRenderedComponentWithType<C extends Component<any, any, any>>(
tree: Component<any, any, any>,
type: ComponentClass<any, any, any>): C;
}
interface SyntheticEventData {
altKey?: boolean;
button?: number;
buttons?: number;
clientX?: number;
clientY?: number;
changedTouches?: TouchList;
charCode?: boolean;
clipboardData?: DataTransfer;
ctrlKey?: boolean;
deltaMode?: number;
deltaX?: number;
deltaY?: number;
deltaZ?: number;
detail?: number;
getModifierState?(key: string): boolean;
key?: string;
keyCode?: number;
locale?: string;
location?: number;
metaKey?: boolean;
pageX?: number;
pageY?: number;
relatedTarget?: EventTarget;
repeat?: boolean;
screenX?: number;
screenY?: number;
shiftKey?: boolean;
targetTouches?: TouchList;
touches?: TouchList;
view?: AbstractView;
which?: number;
}
interface EventSimulator {
(element: Element, eventData?: SyntheticEventData): void;
(descriptor: Component<any, any, any>, eventData?: SyntheticEventData): void;
}
interface Simulate {
blur: EventSimulator;
change: EventSimulator;
click: EventSimulator;
cut: EventSimulator;
doubleClick: EventSimulator;
drag: EventSimulator;
dragEnd: EventSimulator;
dragEnter: EventSimulator;
dragExit: EventSimulator;
dragLeave: EventSimulator;
dragOver: EventSimulator;
dragStart: EventSimulator;
drop: EventSimulator;
focus: EventSimulator;
input: EventSimulator;
keyDown: EventSimulator;
keyPress: EventSimulator;
keyUp: EventSimulator;
mouseDown: EventSimulator;
mouseEnter: EventSimulator;
mouseLeave: EventSimulator;
mouseMove: EventSimulator;
mouseOut: EventSimulator;
mouseOver: EventSimulator;
mouseUp: EventSimulator;
paste: EventSimulator;
scroll: EventSimulator;
submit: EventSimulator;
touchCancel: EventSimulator;
touchEnd: EventSimulator;
touchMove: EventSimulator;
touchStart: EventSimulator;
wheel: EventSimulator;
}
}
+747
View File
@@ -0,0 +1,747 @@
// Type definitions for React v0.13.0 (internal module)
// Project: http://facebook.github.io/react/
// Definitions by: Asana <https://asana.com>, AssureSign <http://www.assuresign.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module React {
//
// React Elements
// ----------------------------------------------------------------------
interface ReactElementBase<T, P> {
type: T;
props: P;
key: number | string;
ref: string;
}
interface ReactElement<P>
extends ReactElementBase<ComponentClass<P, any, any>, P> {}
interface ReactClassicElement<P>
extends ReactElementBase<ClassicComponentClass<P, any, any> | string, P> {}
interface ReactDOMElement<P> // subtype of ReactClassicElement
extends ReactElementBase<string, P> {}
type ReactHTMLElement = ReactDOMElement<HTMLAttributes>;
type ReactSVGElement = ReactDOMElement<SVGAttributes>;
//
// Factories
// ----------------------------------------------------------------------
interface Factory<P> {
(props?: P, ...children: ReactNode[]): ReactElement<P>;
}
interface ClassicFactory<P> {
(props?: P, ...children: ReactNode[]): ReactClassicElement<P>;
}
interface DOMFactory<P> {
(props?: P, ...children: ReactNode[]): ReactDOMElement<P>;
}
type HTMLFactory = DOMFactory<HTMLAttributes>;
type SVGFactory = DOMFactory<SVGAttributes>;
//
// React Nodes
// http://facebook.github.io/react/docs/glossary.html
// ----------------------------------------------------------------------
type ReactText = string | number;
type ReactChild = ReactElementBase<any, any> | ReactText;
// Should be Array<ReactNode> but type aliases cannot be recursive
type ReactFragment = Array<ReactChild | any[] | boolean>;
type ReactNode = ReactChild | ReactFragment | boolean;
//
// Top Level API
// ----------------------------------------------------------------------
function createClass<P, S, C>(
spec: ComponentSpec<P, S, C>): ClassicComponentClass<P, S, C>;
function createFactory<P>(
type: string): DOMFactory<P>;
function createFactory<P>(
type: ClassicComponentClass<P, any, any> | string): ClassicFactory<P>;
function createFactory<P>(
type: ComponentClass<P, any, any>): Factory<P>;
function createElement<P>(
type: string,
props?: P,
...children: ReactNode[]): ReactDOMElement<P>;
function createElement<P>(
type: ClassicComponentClass<P, any, any> | string,
props?: P,
...children: ReactNode[]): ReactClassicElement<P>;
function createElement<P>(
type: ComponentClass<P, any, any>,
props?: P,
...children: ReactNode[]): ReactElement<P>;
function render<P>(
element: ReactDOMElement<P>,
container: Element,
callback?: () => any): DOMComponent<P>;
function render<P, S>(
element: ReactClassicElement<P>,
container: Element,
callback?: () => any): ClassicComponent<P, S, {}>;
function render<P, S>(
element: ReactElement<P>,
container: Element,
callback?: () => any): Component<P, S, {}>;
function unmountComponentAtNode(container: Element): boolean;
function renderToString(element: ReactElementBase<any, any>): string;
function renderToStaticMarkup(element: ReactElementBase<any, any>): string;
function isValidElement(object: {}): boolean;
function initializeTouchEvents(shouldUseTouch: boolean): void;
function findDOMNode<TElement extends Element>(
componentOrElement: Component<any, any, any> | Element): TElement;
function findDOMNode(
componentOrElement: Component<any, any, any> | Element): Element;
var DOM: ReactDOM;
var PropTypes: ReactPropTypes;
var Children: ReactChildren;
//
// Component API
// ----------------------------------------------------------------------
// Base component for plain JS classes
class Component<P, S, C> implements ComponentLifecycle<P, S, C> {
constructor(props: P, context: C);
setState(state: S, callback?: () => any): void;
forceUpdate(): void;
props: P;
state: S;
context: C;
refs: {
[key: string]: Component<any, any, any>
};
}
interface ClassicComponent<P, S, C> extends Component<P, S, C> {
replaceState(nextState: S, callback?: () => any): void;
getDOMNode<TElement extends Element>(): TElement;
getDOMNode(): Element;
isMounted(): boolean;
getInitialState?(): S;
setProps(nextProps: P, callback?: () => any): void;
replaceProps(nextProps: P, callback?: () => any): void;
}
interface DOMComponent<P> extends ClassicComponent<P, any, any> {
tagName: string;
}
type HTMLComponent = DOMComponent<HTMLAttributes>;
type SVGComponent = DOMComponent<SVGAttributes>;
interface ChildContextProvider<CC> {
getChildContext(): CC;
}
//
// Class Interfaces
// ----------------------------------------------------------------------
interface ComponentClassBase<P, C> {
propTypes?: ValidationMap<P>;
contextTypes?: ValidationMap<C>;
childContextTypes?: ValidationMap<{}>;
}
interface ComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): Component<P, S, C>;
defaultProps?: P;
}
interface ClassicComponentClass<P, S, C> extends ComponentClassBase<P, C> {
new(props?: P, context?: C): ClassicComponent<P, S, C>;
getDefaultProps?(): P;
displayName?: string;
}
//
// Component Specs and Lifecycle
// ----------------------------------------------------------------------
interface ComponentLifecycle<P, S, C> {
componentWillMount?(): void;
componentDidMount?(): void;
componentWillReceiveProps?(nextProps: P, nextContext: C): void;
shouldComponentUpdate?(nextProps: P, nextState: S, nextContext: C): boolean;
componentWillUpdate?(nextProps: P, nextState: S, nextContext: C): void;
componentDidUpdate?(prevProps: P, prevState: S, prevContext: C): void;
componentWillUnmount?(): void;
}
interface Mixin<P, S, C> extends ComponentLifecycle<P, S, C> {
mixins?: Mixin<P, S, C>;
statics?: {
[key: string]: any;
};
displayName?: string;
propTypes?: ValidationMap<any>;
contextTypes?: ValidationMap<any>;
childContextTypes?: ValidationMap<any>
getInitialState?(): S;
getDefaultProps?(): P;
}
interface ComponentSpec<P, S, C> extends Mixin<P, S, C> {
render(): ReactElementBase<any, any>;
}
//
// Event System
// ----------------------------------------------------------------------
interface SyntheticEvent {
bubbles: boolean;
cancelable: boolean;
currentTarget: EventTarget;
defaultPrevented: boolean;
eventPhase: number;
isTrusted: boolean;
nativeEvent: Event;
preventDefault(): void;
stopPropagation(): void;
target: EventTarget;
timeStamp: Date;
type: string;
}
interface ClipboardEvent extends SyntheticEvent {
clipboardData: DataTransfer;
}
interface KeyboardEvent extends SyntheticEvent {
altKey: boolean;
charCode: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
key: string;
keyCode: number;
locale: string;
location: number;
metaKey: boolean;
repeat: boolean;
shiftKey: boolean;
which: number;
}
interface FocusEvent extends SyntheticEvent {
relatedTarget: EventTarget;
}
interface FormEvent extends SyntheticEvent {
}
interface MouseEvent extends SyntheticEvent {
altKey: boolean;
button: number;
buttons: number;
clientX: number;
clientY: number;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
pageX: number;
pageY: number;
relatedTarget: EventTarget;
screenX: number;
screenY: number;
shiftKey: boolean;
}
interface TouchEvent extends SyntheticEvent {
altKey: boolean;
changedTouches: TouchList;
ctrlKey: boolean;
getModifierState(key: string): boolean;
metaKey: boolean;
shiftKey: boolean;
targetTouches: TouchList;
touches: TouchList;
}
interface UIEvent extends SyntheticEvent {
detail: number;
view: AbstractView;
}
interface WheelEvent extends SyntheticEvent {
deltaMode: number;
deltaX: number;
deltaY: number;
deltaZ: number;
}
//
// Event Handler Types
// ----------------------------------------------------------------------
interface EventHandler<E extends SyntheticEvent> {
(event: E): void;
}
interface ClipboardEventHandler extends EventHandler<ClipboardEvent> {}
interface KeyboardEventHandler extends EventHandler<KeyboardEvent> {}
interface FocusEventHandler extends EventHandler<FocusEvent> {}
interface FormEventHandler extends EventHandler<FormEvent> {}
interface MouseEventHandler extends EventHandler<MouseEvent> {}
interface TouchEventHandler extends EventHandler<TouchEvent> {}
interface UIEventHandler extends EventHandler<UIEvent> {}
interface WheelEventHandler extends EventHandler<WheelEvent> {}
//
// Props / DOM Attributes
// ----------------------------------------------------------------------
interface Props {
children?: ReactNode;
key?: number | string;
ref?: string;
}
interface DOMAttributes extends Props {
onCopy?: ClipboardEventHandler;
onCut?: ClipboardEventHandler;
onPaste?: ClipboardEventHandler;
onKeyDown?: KeyboardEventHandler;
onKeyPress?: KeyboardEventHandler;
onKeyUp?: KeyboardEventHandler;
onFocus?: FocusEventHandler;
onBlur?: FocusEventHandler;
onChange?: FormEventHandler;
onInput?: FormEventHandler;
onSubmit?: FormEventHandler;
onClick?: MouseEventHandler;
onDoubleClick?: MouseEventHandler;
onDrag?: MouseEventHandler;
onDragEnd?: MouseEventHandler;
onDragEnter?: MouseEventHandler;
onDragExit?: MouseEventHandler;
onDragLeave?: MouseEventHandler;
onDragOver?: MouseEventHandler;
onDragStart?: MouseEventHandler;
onDrop?: MouseEventHandler;
onMouseDown?: MouseEventHandler;
onMouseEnter?: MouseEventHandler;
onMouseLeave?: MouseEventHandler;
onMouseMove?: MouseEventHandler;
onMouseOut?: MouseEventHandler;
onMouseOver?: MouseEventHandler;
onMouseUp?: MouseEventHandler;
onTouchCancel?: TouchEventHandler;
onTouchEnd?: TouchEventHandler;
onTouchMove?: TouchEventHandler;
onTouchStart?: TouchEventHandler;
onScroll?: UIEventHandler;
onWheel?: WheelEventHandler;
dangerouslySetInnerHTML?: {
__html: string;
};
}
interface CSSProperties {
columnCount?: number;
flex?: number | string;
flexGrow?: number;
flexShrink?: number;
fontWeight?: number;
lineClamp?: number;
lineHeight?: number;
opacity?: number;
order?: number;
orphans?: number;
widows?: number;
zIndex?: number;
zoom?: number;
// SVG-related properties
fillOpacity?: number;
strokeOpacity?: number;
}
interface HTMLAttributes extends DOMAttributes {
accept?: string;
acceptCharset?: string;
accessKey?: string;
action?: string;
allowFullScreen?: boolean;
allowTransparency?: boolean;
alt?: string;
async?: boolean;
autoComplete?: boolean;
autoFocus?: boolean;
autoPlay?: boolean;
cellPadding?: number | string;
cellSpacing?: number | string;
charSet?: string;
checked?: boolean;
classID?: string;
className?: string;
cols?: number;
colSpan?: number;
content?: string;
contentEditable?: boolean;
contextMenu?: string;
controls?: any;
coords?: string;
crossOrigin?: string;
data?: string;
dateTime?: string;
defer?: boolean;
dir?: string;
disabled?: boolean;
download?: any;
draggable?: boolean;
encType?: string;
form?: string;
formNoValidate?: boolean;
frameBorder?: number | string;
height?: number | string;
hidden?: boolean;
href?: string;
hrefLang?: string;
htmlFor?: string;
httpEquiv?: string;
icon?: string;
id?: string;
label?: string;
lang?: string;
list?: string;
loop?: boolean;
manifest?: string;
max?: number | string;
maxLength?: number;
media?: string;
mediaGroup?: string;
method?: string;
min?: number | string;
multiple?: boolean;
muted?: boolean;
name?: string;
noValidate?: boolean;
open?: boolean;
pattern?: string;
placeholder?: string;
poster?: string;
preload?: string;
radioGroup?: string;
readOnly?: boolean;
rel?: string;
required?: boolean;
role?: string;
rows?: number;
rowSpan?: number;
sandbox?: string;
scope?: string;
scrollLeft?: number;
scrolling?: string;
scrollTop?: number;
seamless?: boolean;
selected?: boolean;
shape?: string;
size?: number;
sizes?: string;
span?: number;
spellCheck?: boolean;
src?: string;
srcDoc?: string;
srcSet?: string;
start?: number;
step?: number | string;
style?: CSSProperties;
tabIndex?: number;
target?: string;
title?: string;
type?: string;
useMap?: string;
value?: string;
width?: number | string;
wmode?: string;
// Non-standard Attributes
autoCapitalize?: boolean;
autoCorrect?: boolean;
property?: string;
itemProp?: string;
itemScope?: boolean;
itemType?: string;
}
interface SVGAttributes extends DOMAttributes {
cx?: SVGLength | SVGAnimatedLength;
cy?: any;
d?: string;
dx?: SVGLength | SVGAnimatedLength;
dy?: SVGLength | SVGAnimatedLength;
fill?: any; // SVGPaint | string
fillOpacity?: number | string;
fontFamily?: string;
fontSize?: number | string;
fx?: SVGLength | SVGAnimatedLength;
fy?: SVGLength | SVGAnimatedLength;
gradientTransform?: SVGTransformList | SVGAnimatedTransformList;
gradientUnits?: string;
markerEnd?: string;
markerMid?: string;
markerStart?: string;
offset?: number | string;
opacity?: number | string;
patternContentUnits?: string;
patternUnits?: string;
points?: string;
preserveAspectRatio?: string;
r?: SVGLength | SVGAnimatedLength;
rx?: SVGLength | SVGAnimatedLength;
ry?: SVGLength | SVGAnimatedLength;
spreadMethod?: string;
stopColor?: any; // SVGColor | string
stopOpacity?: number | string;
stroke?: any; // SVGPaint
strokeDasharray?: string;
strokeLinecap?: string;
strokeOpacity?: number | string;
strokeWidth?: SVGLength | SVGAnimatedLength;
textAnchor?: string;
transform?: SVGTransformList | SVGAnimatedTransformList;
version?: string;
viewBox?: string;
x1?: SVGLength | SVGAnimatedLength;
x2?: SVGLength | SVGAnimatedLength;
x?: SVGLength | SVGAnimatedLength;
y1?: SVGLength | SVGAnimatedLength;
y2?: SVGLength | SVGAnimatedLength
y?: SVGLength | SVGAnimatedLength;
}
//
// React.DOM
// ----------------------------------------------------------------------
interface ReactDOM {
// HTML
a: HTMLFactory;
abbr: HTMLFactory;
address: HTMLFactory;
area: HTMLFactory;
article: HTMLFactory;
aside: HTMLFactory;
audio: HTMLFactory;
b: HTMLFactory;
base: HTMLFactory;
bdi: HTMLFactory;
bdo: HTMLFactory;
big: HTMLFactory;
blockquote: HTMLFactory;
body: HTMLFactory;
br: HTMLFactory;
button: HTMLFactory;
canvas: HTMLFactory;
caption: HTMLFactory;
cite: HTMLFactory;
code: HTMLFactory;
col: HTMLFactory;
colgroup: HTMLFactory;
data: HTMLFactory;
datalist: HTMLFactory;
dd: HTMLFactory;
del: HTMLFactory;
details: HTMLFactory;
dfn: HTMLFactory;
dialog: HTMLFactory;
div: HTMLFactory;
dl: HTMLFactory;
dt: HTMLFactory;
em: HTMLFactory;
embed: HTMLFactory;
fieldset: HTMLFactory;
figcaption: HTMLFactory;
figure: HTMLFactory;
footer: HTMLFactory;
form: HTMLFactory;
h1: HTMLFactory;
h2: HTMLFactory;
h3: HTMLFactory;
h4: HTMLFactory;
h5: HTMLFactory;
h6: HTMLFactory;
head: HTMLFactory;
header: HTMLFactory;
hr: HTMLFactory;
html: HTMLFactory;
i: HTMLFactory;
iframe: HTMLFactory;
img: HTMLFactory;
input: HTMLFactory;
ins: HTMLFactory;
kbd: HTMLFactory;
keygen: HTMLFactory;
label: HTMLFactory;
legend: HTMLFactory;
li: HTMLFactory;
link: HTMLFactory;
main: HTMLFactory;
map: HTMLFactory;
mark: HTMLFactory;
menu: HTMLFactory;
menuitem: HTMLFactory;
meta: HTMLFactory;
meter: HTMLFactory;
nav: HTMLFactory;
noscript: HTMLFactory;
object: HTMLFactory;
ol: HTMLFactory;
optgroup: HTMLFactory;
option: HTMLFactory;
output: HTMLFactory;
p: HTMLFactory;
param: HTMLFactory;
picture: HTMLFactory;
pre: HTMLFactory;
progress: HTMLFactory;
q: HTMLFactory;
rp: HTMLFactory;
rt: HTMLFactory;
ruby: HTMLFactory;
s: HTMLFactory;
samp: HTMLFactory;
script: HTMLFactory;
section: HTMLFactory;
select: HTMLFactory;
small: HTMLFactory;
source: HTMLFactory;
span: HTMLFactory;
strong: HTMLFactory;
style: HTMLFactory;
sub: HTMLFactory;
summary: HTMLFactory;
sup: HTMLFactory;
table: HTMLFactory;
tbody: HTMLFactory;
td: HTMLFactory;
textarea: HTMLFactory;
tfoot: HTMLFactory;
th: HTMLFactory;
thead: HTMLFactory;
time: HTMLFactory;
title: HTMLFactory;
tr: HTMLFactory;
track: HTMLFactory;
u: HTMLFactory;
ul: HTMLFactory;
"var": HTMLFactory;
video: HTMLFactory;
wbr: HTMLFactory;
// SVG
circle: SVGFactory;
defs: SVGFactory;
ellipse: SVGFactory;
g: SVGFactory;
line: SVGFactory;
linearGradient: SVGFactory;
mask: SVGFactory;
path: SVGFactory;
pattern: SVGFactory;
polygon: SVGFactory;
polyline: SVGFactory;
radialGradient: SVGFactory;
rect: SVGFactory;
stop: SVGFactory;
svg: SVGFactory;
text: SVGFactory;
tspan: SVGFactory;
}
//
// React.PropTypes
// ----------------------------------------------------------------------
interface Validator<T> {
(object: T, key: string, componentName: string): Error;
}
interface Requireable<T> extends Validator<T> {
isRequired: Validator<T>;
}
interface ValidationMap<T> {
[key: string]: Validator<T>;
}
interface ReactPropTypes {
any: Requireable<any>;
array: Requireable<any>;
bool: Requireable<any>;
func: Requireable<any>;
number: Requireable<any>;
object: Requireable<any>;
string: Requireable<any>;
node: Requireable<any>;
element: Requireable<any>;
instanceOf(expectedClass: {}): Requireable<any>;
oneOf(types: any[]): Requireable<any>;
oneOfType(types: Validator<any>[]): Requireable<any>;
arrayOf(type: Validator<any>): Requireable<any>;
objectOf(type: Validator<any>): Requireable<any>;
shape(type: ValidationMap<any>): Requireable<any>;
}
//
// React.Children
// ----------------------------------------------------------------------
interface ReactChildren {
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;
}
//
// Browser Interfaces
// https://github.com/nikeee/2048-typescript/blob/master/2048/js/touch.d.ts
// ----------------------------------------------------------------------
interface AbstractView {
styleMedia: StyleMedia;
document: Document;
}
interface Touch {
identifier: number;
target: EventTarget;
screenX: number;
screenY: number;
clientX: number;
clientY: number;
pageX: number;
pageY: number;
}
interface TouchList {
[index: number]: Touch;
length: number;
item(index: number): Touch;
identifiedTouch(identifier: number): Touch;
}
}
-68
View File
@@ -1,68 +0,0 @@
/// <reference path="react-0.13.0.d.ts" />
import React = require("react/addons");
var isImportant: boolean;
var isRead: boolean;
var classSet: React.ClassSet = {
"message": true,
"message-important": isImportant,
"message-read": isRead
};
var cx = React.addons.classSet;
var classes: string = cx(classSet);
//
// React.addons (Transitions)
// --------------------------------------------------------------------------
React.createFactory(React.addons.TransitionGroup)({ component: "div" });
React.createFactory(React.addons.CSSTransitionGroup)({
component: React.createClass({
render: (): React.ReactElement<any> => null
}),
childFactory: (c) => c,
transitionName: "transition",
transitionAppear: false,
transitionEnter: true,
transitionLeave: true
});
//
// React.addons.TestUtils
// --------------------------------------------------------------------------
var that: React.Component<any, any, any>;
var node = React.findDOMNode(that.refs["input"]);
React.addons.TestUtils.Simulate.click(node);
React.addons.TestUtils.Simulate.change(node);
React.addons.TestUtils.Simulate.keyDown(node, {key: "Enter"});
interface GreetingProps {
name: string;
}
interface GreetingState {
morning: boolean;
}
interface Greeting extends React.Component<GreetingProps, GreetingState, any> {
}
var Greeting = React.createClass({
displayName: "Greeting",
getInitialState: function() {
return {morning: true};
},
render: function() {
var me = <Greeting>this;
return React.DOM.div(
null,
me.state.morning ? "Hello " : "Goodbye ",
me.props.name);
}
});
var root = React.addons.TestUtils.renderIntoDocument(
React.createElement(Greeting, {name: "John"}));
var greeting = <Greeting>React.addons.TestUtils
.findRenderedComponentWithType(root, Greeting);
greeting.setState({
morning: false
});
+33
View File
@@ -0,0 +1,33 @@
/// <reference path="sanitize-html.d.ts" />
import sanitizeHtml = require('sanitize-html');
var s: string;
var t: string;
t = sanitizeHtml(s);
t = sanitizeHtml(s, {
});
t = sanitizeHtml(s, {
allowedTags: ["a", "br"],
allowedSchemes: ["http"],
allowedAttributes: { "a": ["href"] },
allowedClasses: { "a": ["someclass"] },
transformTags: {
"a": "b",
"br": function(tagName: string, attributes: {[index: string]: string}): { tagName: string; attributes: {[index: string]: string};} {
return { tagName: tagName, attributes: attributes };
}
},
exclusiveFilter: {
"a": function(frame: {
tag: string;
attribs: { [index: string]: string };
text: string;
tagPosition: number;
}): boolean {
return false;
}
}
});
+27
View File
@@ -0,0 +1,27 @@
// Type definitions for sanitize-html 1.6.0
// Project: https://github.com/punkave/sanitize-html
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "sanitize-html" {
function sanitizeHtml(s: string, opts?: {
allowedTags?: string[];
allowedSchemes?: string[];
allowedAttributes?: { [index: string]: string[] };
allowedClasses?: { [index: string]: string[] };
transformTags?: { [index: string]: any };
exclusiveFilter?: {
[index: string]: (frame: {
tag: string;
attribs: { [index: string]: string };
text: string;
tagPosition: number;
}) => boolean
};
}): string;
export = sanitizeHtml;
}
+43
View File
@@ -0,0 +1,43 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="./sax.d.ts" />
import sax = require("sax");
var opts: sax.SAXOptions = {
lowercase: true,
normalize: true,
xmlns: true,
position: true
};
var parser = sax.parser(/*strict=*/true, opts);
parser.onerror = function(e: Error) {
};
parser.ontext = function(text: string) {
};
parser.onopentag = function(tag: sax.Tag) {
};
parser.onattribute = function(attr: { name: string; value: string; }) {
};
parser.onend = function() {
};
parser.write("<xml>Hello, <who name=\"world\">world</who>!</xml>").close();
var saxStream = sax.createStream(/*strict=*/true, opts);
saxStream.on("error", function(e: Error) {
this._parser.error = null;
this._parser.resume();
});
import fs = require("fs");
fs.createReadStream("file.xml")
.pipe(saxStream)
.pipe(fs.createWriteStream("file-copy.xml"));
+78
View File
@@ -0,0 +1,78 @@
// Type definitions for sax js
// Project: https://github.com/isaacs/sax-js
// Definitions by: Asana <https://asana.com>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "sax" {
export var EVENTS: string[];
interface SAXOptions {
trim?: boolean;
normalize?: boolean;
lowercase?: boolean;
xmlns?: boolean;
noscript?: boolean;
position?: boolean;
}
export interface Tag {
name: string;
attributes: { [key: string]: string };
// Available if opt.xmlns
ns?: { [key: string]: string };
prefix?: string;
local?: string;
uri?: string;
}
export function parser(strict: boolean, opt: SAXOptions): SAXParser;
export class SAXParser {
constructor(strict: boolean, opt: SAXOptions);
// Methods
end(): void;
write(s: string): SAXParser;
resume(): SAXParser;
close(): SAXParser;
flush(): void;
// Members
line: number;
column: number;
error: Error;
position: number;
startTagPosition: number;
closed: boolean;
strict: boolean;
opt: SAXOptions;
tag: string;
// Events
onerror(e: Error): void;
ontext(t: string): void;
ondoctype(doctype: string): void;
onprocessinginstruction(node: { name: string; body: string }): void;
onopentag(tag: Tag): void;
onclosetag(tagName: string): void;
onattribute(attr: { name: string; value: string }): void;
oncomment(comment: string): void;
onopencdata(): void;
oncdata(cdata: string): void;
onclosecdata(): void;
onopennamespace(ns: { prefix: string; uri: string }): void;
onclosenamespace(ns: { prefix: string; uri: string }): void;
onend(): void;
onready(): void;
onscript(script: string): void;
}
import stream = require("stream");
export function createStream(strict: boolean, opt: SAXOptions): SAXStream;
export class SAXStream extends stream.Duplex {
constructor(strict: boolean, opt: SAXOptions);
private _parser: SAXParser;
}
}
+214
View File
@@ -0,0 +1,214 @@
/// <reference path="sequelize.d.ts" />
import Sequelize = require('sequelize');
var opts: Sequelize.Options;
var defOpts: Sequelize.DefineOptions = {
indexes: [{
fields: [""],
type: "",
method: ""
}]
};
var attrOpts: Sequelize.AttributeOptions;
var defIndexOpts: Sequelize.DefineIndexOptions;
var indexOpts: Sequelize.IndexOptions;
var dropOpts: Sequelize.DropOptions;
var transOpts: Sequelize.TransactionOptions;
var syncOpts: Sequelize.SyncOptions;
var assocOpts: Sequelize.AssociationOptions;
var schemaOpts: Sequelize.SchemaOptions;
var findOpts: Sequelize.FindOptions
var findCrOpts: Sequelize.FindOrCreateOptions;
var queryOpts: Sequelize.QueryOptions;
var buildOpts: Sequelize.BuildOptions;
var copyOpts: Sequelize.CopyOptions;
var bulkCrOpts: Sequelize.BulkCreateOptions;
var destroyOpts: Sequelize.DestroyOptions;
var destroyInstOpts: Sequelize.DestroyInstanceOptions;
var updateOpts: Sequelize.UpdateOptions;
var saveOpts: Sequelize.SaveOptions;
var valOpts: Sequelize.ValidateOptions;
var incrOpts: Sequelize.IncrementOptions;
var promiseMe: Sequelize.Promise;
var emitMe: Sequelize.EventEmitter;
var sequelize = new Sequelize("", "");
sequelize = new Sequelize("", opts);
sequelize = new Sequelize("", "", "");
sequelize = new Sequelize("", "", opts);
sequelize = new Sequelize("", "", "", opts);
interface modelPojo {
name: string;
}
interface modelInst extends Sequelize.Instance<modelInst, modelPojo>, modelPojo {
};
var myModelInst: modelInst;
var myModelPojo: modelPojo;
sequelize.define<modelInst, modelPojo>("MyTable", attrOpts, defOpts);
var model: Sequelize.Model<modelInst, modelPojo> = sequelize.model<modelInst, modelPojo>("MyTable");
model = sequelize.import<modelInst, modelPojo>("");
emitMe = sequelize.authenticate();
sequelize.cast({}, "");
sequelize.col("myCol");
sequelize.models.MyTable;
emitMe = sequelize.drop(dropOpts);
emitMe = sequelize.createSchema("schema");
emitMe = sequelize.dropAllSchemas();
emitMe = sequelize.dropSchema("dbo");
emitMe = sequelize.fn("upper", sequelize.col("username"));
sequelize.literal("");
sequelize.literal(1234);
sequelize.and("", 1234);
sequelize.or("", 123);
sequelize.where("", "");
sequelize.where("", sequelize.and("", ""));
promiseMe= sequelize.transaction(transOpts);
promiseMe = sequelize.transaction(transOpts, function (t:Sequelize.Transaction): boolean { return true; });
emitMe = sequelize.query<modelInst, modelPojo>("", model).complete(function (err, result) { });
emitMe = sequelize.query("");
var dialect: string = sequelize.getDialect();
emitMe = sequelize.showAllSchemas();
emitMe = sequelize.sync(syncOpts);
model.addHook("", "", function () { });
model.addHook("", function () { });
model.beforeValidate("", function () { });
model.afterValidate("", function () { });
model.beforeCreate("", function () { });
model.afterCreate("", function () { });
model.beforeDestroy("", function () { });
model.afterDestroy("", function () { });
model.beforeUpdate("", function () { });
model.afterUpdate("", function () { });
model.beforeBulkCreate("", function () { });
model.afterBulkCreate("", function () { });
model.beforeBulkDestroy("", function () { });
model.afterBulkDestroy("", function () { });
model.beforeBulkUpdate("", function () { });
model.afterBulkUpdate("", function () { });
model.hasOne<modelInst, modelPojo>(model);
model.hasOne<modelInst, modelPojo>(model, assocOpts);
model.belongsTo<modelInst, modelPojo>(model);
model.belongsTo<modelInst, modelPojo>(model, assocOpts);
model.hasMany<modelInst, modelPojo>(model);
model.hasMany<modelInst, modelPojo>(model, assocOpts);
promiseMe = model.sync();
promiseMe = model.drop(dropOpts);
model.schema("", schemaOpts);
model.getTableName();
model = model.scope({});
model = model.scope("");
model = model.scope([]);
model = model.scope(null);
model.find().then(function () { }, function () { });
model.find().then(function () { });
model.find().then(null, function () { });
model.find().then(function (result: modelInst) { });
model.find().then<modelInst>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1) });
model.find().then<modelInst, any>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1) }, function (): Sequelize.PromiseT<any> { return model.find(1) });
model.find().catch(function () { });
model.find().catch(function (result: modelInst) { });
model.find().catch(function (result: modelInst): Sequelize.Promise { return model.find(1) });
model.find().spread(function () { }, function () { });
model.find().spread(function () { });
model.find().spread(null, function () { });
model.find().spread(function (result: modelInst) { });
model.find().spread(function (result1: modelInst, result2: any) { });
model.find().spread(null, function (result1: any, result2: boolean) { });
model.find().spread(function (result: modelInst): Sequelize.Promise { return model.find(1) });
model.find().spread<modelInst>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1) });
model.find().spread<modelInst>(function (result: modelInst) { }, function (): Sequelize.PromiseT<modelInst> { return model.find(1) });
model.find().spread<modelInst, any>(function (result: modelInst): Sequelize.PromiseT<modelInst> { return model.find(1) }, function (): Sequelize.PromiseT<any> { return model.find(1) });
promiseMe = model.findAll(findOpts, queryOpts);
promiseMe = model.findAll(findOpts);
promiseMe = model.findAll();
promiseMe = model.find(findOpts, queryOpts);
promiseMe = model.find(findOpts);
promiseMe = model.find(1, queryOpts);
promiseMe = model.find(1);
promiseMe = model.find();
promiseMe = model.aggregate<number>("", "", findOpts);
promiseMe = model.count();
promiseMe = model.count(findOpts);
promiseMe = model.findAndCountAll(findOpts, queryOpts);
promiseMe = model.findAndCountAll(findOpts);
promiseMe = model.findAndCountAll();
promiseMe = model.max<number>("", findOpts);
promiseMe = model.max<number>("");
promiseMe = model.min<number>("", findOpts);
promiseMe = model.min<number>("");
promiseMe = model.sum("", findOpts);
promiseMe = model.sum("");
myModelInst = model.build(myModelPojo, buildOpts);
myModelInst = model.build(myModelPojo);
promiseMe = model.create(myModelPojo, copyOpts);
promiseMe = model.create(myModelPojo);
promiseMe = model.findOrInitialize({}, myModelPojo, queryOpts);
promiseMe = model.findOrInitialize({}, myModelPojo);
promiseMe = model.findOrInitialize({});
promiseMe = model.findOrCreate({}, myModelPojo, findCrOpts);
promiseMe = model.findOrCreate({}, myModelPojo);
promiseMe = model.findOrCreate({});
promiseMe = model.bulkCreate([myModelPojo], bulkCrOpts);
promiseMe = model.bulkCreate([myModelPojo]);
promiseMe = model.destroy({}, destroyOpts);
promiseMe = model.destroy({});
promiseMe = model.destroy();
promiseMe = model.update(myModelPojo, {}, updateOpts);
promiseMe = model.update(myModelPojo, {});
promiseMe = model.describe();
model.dataset;
//var isDefined: boolean = sequelize.isDefined("");
model.find().spread(function (arg1: string, arg2: number) {
return model.find();
});
var isBool: boolean;
var strArr: Array<string>;
isBool = myModelInst.isNewRecord;
model = myModelInst.Model;
sequelize = myModelInst.sequelize;
isBool = myModelInst.isDeleted;
myModelPojo = myModelInst.values;
isBool = myModelInst.isDirty;
myModelPojo = myModelInst.primaryKeyValues;
myModelInst.getDataValue("");
myModelInst.setDataValue("", "");
myModelInst.setDataValue("", 123);
myModelInst.get("");
myModelInst.set("", "");
myModelInst.set("", 123);
isBool = myModelInst.changed("");
strArr = myModelInst.changed();
myModelInst.previous("");
promiseMe = myModelInst.save(["", ""], saveOpts);
promiseMe = myModelInst.save(["", ""]);
promiseMe = myModelInst.reload();
promiseMe = myModelInst.reload(findOpts);
promiseMe = myModelInst.validate(valOpts);
promiseMe = myModelInst.validate();
promiseMe = myModelInst.updateAttributes(myModelPojo, saveOpts);
promiseMe = myModelInst.destroy(destroyInstOpts);
promiseMe = myModelInst.destroy();
promiseMe = myModelInst.increment({}, incrOpts);
promiseMe = myModelInst.increment({});
promiseMe = myModelInst.decrement({}, incrOpts);
isBool = myModelInst.equal(myModelInst);
isBool = myModelInst.equalsOneOf([myModelInst]);
myModelPojo = myModelInst.toJSON();
+2780
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,4 +1,4 @@
// Type definitions for Stats.js r11
// Type definitions for Stats.js r12
// Project: http://github.com/mrdoob/stats.js
// Definitions by: Gregory Dalton <https://github.com/gregolai>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
+3 -1
View File
@@ -12,5 +12,7 @@ The WebKit nightly builds try to keep up with the editors draft version of the s
### Adding the reference to your project
/// <reference path="waa.d.ts" />
or
/// <reference path="waa-nightly.d.ts" />
/// <reference path="waa-nightly.d.ts" />
+8
View File
@@ -323,3 +323,11 @@ declare var footstepsBuffer: any;
context.startRendering();
}
// Test automatic type inference of the audio processing event handler
() => {
var context = new AudioContext();
var recorder = context.createScriptProcessor(2048, 1, 1);
recorder.onaudioprocess = function (e) {
e.inputBuffer;
};
}
+5 -1
View File
@@ -601,6 +601,10 @@ interface AudioBufferSourceNode extends AudioNode {
interface MediaElementAudioSourceNode extends AudioNode {
}
interface AudioProcessingEventHandler {
(e: AudioProcessingEvent): void;
}
/**
* This interface is an AudioNode which can generate, process, or analyse audio directly using JavaScript.
*
@@ -617,7 +621,7 @@ interface ScriptProcessorNode extends AudioNode {
/**
* An event listener which is called periodically for audio processing. An event of type AudioProcessingEvent will be passed to the event handler.
*/
onaudioprocess: EventHandler;
onaudioprocess: AudioProcessingEventHandler;
/**
* The size of the buffer (in sample-frames) which needs to be processed each time onprocessaudio is called. Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384).